bool doCmd(const char* path, enum CmdType cmd_type, enum FileType file_type, CacheStat* pStat){ int fd = 0; DIR *dir = NULL; DIR *soft_dir = NULL; struct dirent *dp = NULL; char file_name[256]; char link_name[256]; char real_path[256]; void *pbase = NULL; char *vec = NULL; struct stat st; int in_cache = 0; int str_len = 0; int page_index; int page_count; int pagesize = getpagesize(); int time_used = 0; struct timeval begin, end; if(realpath(path, real_path) == NULL){ goto ERROR; } if(file_type == REGFILE){ fd = open(real_path, O_RDONLY); if(fd<0){ goto ERROR; } if(stat(real_path, &st)<0){ goto ERROR; } switch(cmd_type){ case CLEAR: if(posix_fadvise(fd, 0, st.st_size, POSIX_FADV_DONTNEED) != 0){ goto ERROR; } fprintf(stdout, "Release:%s\n", real_path); break; case STAT: if(st.st_size == 0) goto EMPTYFILE; pbase = mmap((void *)0, st.st_size, PROT_NONE, MAP_SHARED, fd, 0); if(pbase == MAP_FAILED){ goto ERROR; } page_count = (st.st_size+pagesize-1)/pagesize; vec = (char*)calloc(1, page_count); if(mincore(pbase, st.st_size, (unsigned char *)vec) != 0){ goto ERROR; } for(page_index=0; page_index<page_count; page_index++){ if(vec[page_index]&1 != 0){ ++in_cache; } } pStat->page_count += page_count; pStat->in_cache += in_cache; EMPTYFILE: if(pStat->is_print == true){ fprintf(stdout, "Stat:%s size:%s cached:%s\n", real_path, sizeFit(st.st_size, buf1), sizeFit(in_cache*(pagesize), buf2)); } break; case LOCK: if(st.st_size == 0){ fprintf(stderr, "Empty file %s\n", real_path); return true; } pbase = mmap((void *)0, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if(pbase == MAP_FAILED){ goto ERROR; } if(mlock(pbase, st.st_size) == 0){ fprintf(stdout, "Lock %s succeed, size:%s\n", real_path, sizeFit(st.st_size, buf1)); return true; }else{ goto ERROR; } case WARM: gettimeofday(&begin, NULL); if(posix_fadvise(fd, 0, st.st_size, POSIX_FADV_WILLNEED) != 0){ goto ERROR; } gettimeofday(&end, NULL); time_used = getUsedTime(&begin, &end); fprintf(stdout, "Warmup File:%s TimeUsed:%d ms\n", real_path, time_used); break; default: fprintf(stderr, "do not support cmd type %d\n", cmd_type); goto ERROR; } close(fd); if(vec) free(vec); if(pbase) munmap(pbase, st.st_size); return true; }else if(file_type == DIRECTORY){ if((dir = opendir(real_path)) == NULL){ goto ERROR; } gettimeofday(&begin, NULL); while((dp = readdir(dir)) != NULL){ if(strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0){ memset(file_name, 0, sizeof(file_name)); strcat(file_name, real_path); strcat(file_name, "/"); strcat(file_name, dp->d_name); if(dp->d_type == DT_REG){ doCmd(file_name, cmd_type, REGFILE, pStat); }else if(dp->d_type == DT_DIR){ doCmd(file_name, cmd_type, DIRECTORY, pStat); }else if(dp->d_type == DT_LNK){ if(realpath(file_name, link_name) != NULL){ if(stat(link_name, &st)<0){ goto ERROR; } if(st.st_mode & S_IFREG){ doCmd(file_name, cmd_type, REGFILE, pStat); }else if(st.st_mode & S_IFDIR){ doCmd(file_name, cmd_type, DIRECTORY, pStat); } } }else{ fprintf(stdout, "%s:%c type unsupported!\n", dp->d_name, dp->d_type); } } } gettimeofday(&end, NULL); time_used = getUsedTime(&begin, &end); if(cmd_type == WARM){ fprintf(stdout, "Warmup Dir:%s TimeUsed:%d ms\n", real_path, time_used); } closedir(dir); return true; } ERROR: fprintf(stderr, "File:%s %s\n", real_path, strerror(errno)); if(fd) close(fd); if(dir) closedir(dir); if(vec) free(vec); if(pbase) munmap(pbase, st.st_size); return false; }
int filebrowser_init (MBDesktop *mb, MBDesktopFolderModule *folder_module, char *arg_str) { DIR *dp; struct dirent *dir_entry; struct stat stat_info; MBDotDesktop *dd; BrowserData *data = NULL; /* XXX args can be location of user def config folder */ if (arg_str == NULL) arg_str = PKGDATADIR "/mbdesktop_filebrowser"; if ((dp = opendir(arg_str)) == NULL) { fprintf(stderr, "simplefilebrowser: failed to open %s\n", arg_str); return -1; } while((dir_entry = readdir(dp)) != NULL) { char buf[512]; if (strcmp(dir_entry->d_name+strlen(dir_entry->d_name)-8, ".desktop")) continue; snprintf(buf, 512, "%s/%s", arg_str, dir_entry->d_name); lstat(buf, &stat_info); if (!(S_ISDIR(stat_info.st_mode))) { dd = mb_dotdesktop_new_from_file(buf); if (dd) { MBDesktopItem *folder = NULL; data = malloc(sizeof(BrowserData)); /* Defualts */ data->BrowserPath = "/"; data->BrowserMatchStr = "*"; data->BrowserIcon = "mbnoapp.png"; data->BrowserExecWith = "cat"; data->BrowserFolderName = "files"; data->BrowserFolderIcon = "mbfolder.png"; if (mb_dotdesktop_get(dd, "Path")) data->BrowserPath = strdup(mb_dotdesktop_get(dd, "Path")); if (mb_dotdesktop_get(dd, "Match")) data->BrowserMatchStr = strdup(mb_dotdesktop_get(dd, "Match")); if (mb_dotdesktop_get(dd, "FileIcon")) data->BrowserIcon = strdup(mb_dotdesktop_get(dd, "FileIcon")); if (mb_dotdesktop_get(dd, "ExecWith")) data->BrowserExecWith = strdup(mb_dotdesktop_get(dd, "ExecWith")); if (mb_dotdesktop_get(dd, "FolderName")) data->BrowserFolderName = strdup(mb_dotdesktop_get(dd, "FolderName")); if (mb_dotdesktop_get(dd, "FolderIcon")) data->BrowserFolderIcon = strdup(mb_dotdesktop_get(dd, "FolderIcon")); folder = mbdesktop_module_folder_create (mb, data->BrowserFolderName, data->BrowserFolderIcon); mbdesktop_item_set_user_data (mb, folder, (void *)data); mbdesktop_item_set_extended_name(mb, folder, data->BrowserFolderName); mbdesktop_items_append_to_top_level (mb, folder); mbdesktop_item_folder_set_view (mb, folder, VIEW_LIST); mbdesktop_item_set_activate_callback (mb, folder, filebrowser_open_cb); mb_dotdesktop_free(dd); } } } closedir(dp); return 1; }
#include <errno.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <dirent.h> void DEFUN(test, (name), CONST char *name) { DIR *dirp; struct dirent *entp; puts(name); dirp = opendir(name); if (dirp == NULL) { perror("opendir"); return; } errno = 0; while ((entp = readdir(dirp)) != NULL) printf("%s\tfile number %lu\n", entp->d_name, (unsigned long int) entp->d_fileno); if (errno) perror ("readdir"); if (closedir(dirp) < 0)
static int copy_event_system(const char *sys, struct tracepoint_path *tps) { struct dirent *dent; struct stat st; char *format; DIR *dir; int count = 0; int ret; int err; dir = opendir(sys); if (!dir) { pr_debug("can't read directory '%s'", sys); return -errno; } while ((dent = readdir(dir))) { if (dent->d_type != DT_DIR || strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0 || !name_in_tp_list(dent->d_name, tps)) continue; format = malloc(strlen(sys) + strlen(dent->d_name) + 10); if (!format) { err = -ENOMEM; goto out; } sprintf(format, "%s/%s/format", sys, dent->d_name); ret = stat(format, &st); free(format); if (ret < 0) continue; count++; } if (write(output_fd, &count, 4) != 4) { err = -EIO; pr_debug("can't write count\n"); goto out; } rewinddir(dir); while ((dent = readdir(dir))) { if (dent->d_type != DT_DIR || strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0 || !name_in_tp_list(dent->d_name, tps)) continue; format = malloc(strlen(sys) + strlen(dent->d_name) + 10); if (!format) { err = -ENOMEM; goto out; } sprintf(format, "%s/%s/format", sys, dent->d_name); ret = stat(format, &st); if (ret >= 0) { err = record_file(format, 8); if (err) { free(format); goto out; } } free(format); } err = 0; out: closedir(dir); return err; }
static int dev_pci_slot(struct udev_device *dev, struct netnames *names) { struct udev *udev = udev_device_get_udev(names->pcidev); unsigned domain, bus, slot, func, dev_id = 0; size_t l; char *s; const char *attr; struct udev_device *pci = NULL; char slots[256], str[256]; _cleanup_closedir_ DIR *dir = NULL; struct dirent *dent; int hotplug_slot = 0, err = 0; if (sscanf(udev_device_get_sysname(names->pcidev), "%x:%x:%x.%u", &domain, &bus, &slot, &func) != 4) return -ENOENT; /* kernel provided port index for multiple ports on a single PCI function */ attr = udev_device_get_sysattr_value(dev, "dev_id"); if (attr) { dev_id = strtol(attr, NULL, 16); if (dev_id == 0) { attr = udev_device_get_sysattr_value(dev, "dev_port"); if (attr) dev_id = strtol(attr, NULL, 16); } } /* compose a name based on the raw kernel's PCI bus, slot numbers */ s = names->pci_path; l = sizeof(names->pci_path); if (domain > 0) l = strpcpyf(&s, l, "P%u", domain); l = strpcpyf(&s, l, "p%us%u", bus, slot); if (func > 0 || is_pci_multifunction(names->pcidev)) l = strpcpyf(&s, l, "f%d", func); if (dev_id > 0) l = strpcpyf(&s, l, "d%d", dev_id); if (l == 0) names->pci_path[0] = '\0'; /* ACPI _SUN -- slot user number */ pci = udev_device_new_from_subsystem_sysname(udev, "subsystem", "pci"); if (!pci) { err = -ENOENT; goto out; } snprintf(slots, sizeof(slots), "%s/slots", udev_device_get_syspath(pci)); dir = opendir(slots); if (!dir) { err = -errno; goto out; } for (dent = readdir(dir); dent != NULL; dent = readdir(dir)) { int i; char *rest; char *address; if (dent->d_name[0] == '.') continue; i = strtol(dent->d_name, &rest, 10); if (rest[0] != '\0') continue; if (i < 1) continue; snprintf(str, sizeof(str), "%s/%s/address", slots, dent->d_name); if (read_one_line_file(str, &address) >= 0) { /* match slot address with device by stripping the function */ if (strneq(address, udev_device_get_sysname(names->pcidev), strlen(address))) hotplug_slot = i; free(address); } if (hotplug_slot > 0) break; } if (hotplug_slot > 0) { s = names->pci_slot; l = sizeof(names->pci_slot); if (domain > 0) l = strpcpyf(&s, l, "P%d", domain); l = strpcpyf(&s, l, "s%d", hotplug_slot); if (func > 0 || is_pci_multifunction(names->pcidev)) l = strpcpyf(&s, l, "f%d", func); if (dev_id > 0) l = strpcpyf(&s, l, "d%d", dev_id); if (l == 0) names->pci_slot[0] = '\0'; } out: udev_device_unref(pci); return err; }
/** * lt_ext_modules_load: * * Load all of the modules on the system, including the internal accessor. * This has to be invoked before processing something with #lt_extension_t. * or lt_db_initialize() does. */ void lt_ext_modules_load(void) { #if ENABLE_MODULE const char *env = getenv("LANGTAG_EXT_MODULE_PATH"); char *path_list, *s, *p, *path; size_t suffix_len = strlen(LT_MODULE_SUFFIX) + 1; if (__lt_ext_module_initialized) return; if (!env) { path_list = strdup( #ifdef GNOME_ENABLE_DEBUG BUILDDIR LT_DIR_SEPARATOR_S "extensions" LT_SEARCHPATH_SEPARATOR_S BUILDDIR LT_DIR_SEPARATOR_S "extensions" LT_DIR_SEPARATOR_S ".libs" LT_SEARCHPATH_SEPARATOR_S #endif LANGTAG_EXT_MODULE_PATH); } else { path_list = strdup(env); } s = path_list; do { DIR *dir; if (!s) break; p = strchr(s, LT_SEARCHPATH_SEPARATOR); if (s == p) { s++; continue; } path = s; if (p) { *p = 0; p++; } s = p; dir = opendir(path); if (dir) { struct dirent dent, *dresult; size_t len; while (1) { if (readdir_r(dir, &dent, &dresult) || dresult == NULL) break; len = strlen(dent.d_name); if (len > suffix_len && lt_strcmp0(&dent.d_name[len - suffix_len], "." LT_MODULE_SUFFIX) == 0) { lt_ext_module_new(dent.d_name); } } closedir(dir); } } while (1); free(path_list); #else /* !ENABLE_MODULE */ const lt_ext_module_funcs_t *f; int c; #define REGISTER(_ext_) \ f = LT_MODULE_SYMBOL_ (lt_module_ext_##_ext_, get_funcs) (); \ c = lt_ext_module_singleton_char_to_int(f->get_singleton()); \ __lt_ext_modules[c] = lt_ext_module_new_with_data(#_ext_, f); \ lt_mem_add_weak_pointer(&__lt_ext_modules[c]->parent, \ (lt_pointer_t *)&__lt_ext_modules[c]); REGISTER (t); REGISTER (u); #undef REGISTER #endif /* ENABLE_MODULE */ __lt_ext_default_handler = lt_ext_module_new_with_data("default", &__default_funcs); lt_mem_add_weak_pointer(&__lt_ext_default_handler->parent, (lt_pointer_t *)&__lt_ext_default_handler); __lt_ext_modules[LT_MAX_EXT_MODULES - 2] = lt_ext_module_new_with_data("empty", &__empty_and_wildcard_funcs); lt_mem_add_weak_pointer(&__lt_ext_modules[LT_MAX_EXT_MODULES - 2]->parent, (lt_pointer_t *)&__lt_ext_modules[LT_MAX_EXT_MODULES - 2]); __lt_ext_modules[LT_MAX_EXT_MODULES - 1] = lt_ext_module_new_with_data("wildcard", &__empty_and_wildcard_funcs); lt_mem_add_weak_pointer(&__lt_ext_modules[LT_MAX_EXT_MODULES - 1]->parent, (lt_pointer_t *)&__lt_ext_modules[LT_MAX_EXT_MODULES - 1]); __lt_ext_module_initialized = TRUE; }
int x509_crt_parse_path( x509_crt *chain, const char *path ) { int ret = 0; #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) int w_ret; WCHAR szDir[MAX_PATH]; char filename[MAX_PATH]; char *p; int len = (int) strlen( path ); WIN32_FIND_DATAW file_data; HANDLE hFind; if( len > MAX_PATH - 3 ) return( POLARSSL_ERR_X509_BAD_INPUT_DATA ); memset( szDir, 0, sizeof(szDir) ); memset( filename, 0, MAX_PATH ); memcpy( filename, path, len ); filename[len++] = '\\'; p = filename + len; filename[len++] = '*'; w_ret = MultiByteToWideChar( CP_ACP, 0, filename, len, szDir, MAX_PATH - 3 ); hFind = FindFirstFileW( szDir, &file_data ); if (hFind == INVALID_HANDLE_VALUE) return( POLARSSL_ERR_X509_FILE_IO_ERROR ); len = MAX_PATH - len; do { memset( p, 0, len ); if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) continue; w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName, lstrlenW(file_data.cFileName), p, len - 1, NULL, NULL ); w_ret = x509_crt_parse_file( chain, filename ); if( w_ret < 0 ) ret++; else ret += w_ret; } while( FindNextFileW( hFind, &file_data ) != 0 ); if (GetLastError() != ERROR_NO_MORE_FILES) ret = POLARSSL_ERR_X509_FILE_IO_ERROR; FindClose( hFind ); #else /* _WIN32 */ int t_ret; struct stat sb; struct dirent *entry; char entry_name[255]; DIR *dir = opendir( path ); if( dir == NULL) return( POLARSSL_ERR_X509_FILE_IO_ERROR ); #if defined(POLARSSL_THREADING_PTHREAD) if( ( ret = polarssl_mutex_lock( &readdir_mutex ) ) != 0 ) return( ret ); #endif while( ( entry = readdir( dir ) ) != NULL ) { snprintf( entry_name, sizeof entry_name, "%s/%s", path, entry->d_name ); if( stat( entry_name, &sb ) == -1 ) { closedir( dir ); ret = POLARSSL_ERR_X509_FILE_IO_ERROR; goto cleanup; } if( !S_ISREG( sb.st_mode ) ) continue; // Ignore parse errors // t_ret = x509_crt_parse_file( chain, entry_name ); if( t_ret < 0 ) ret++; else ret += t_ret; } closedir( dir ); cleanup: #if defined(POLARSSL_THREADING_PTHREAD) if( polarssl_mutex_unlock( &readdir_mutex ) != 0 ) ret = POLARSSL_ERR_THREADING_MUTEX_ERROR; #endif #endif /* _WIN32 */ return( ret ); }
/* Function: main * * Description: Main function to extract frames from 2 video files and runs the * rest of the program using them. Takes at least 10 commandline arguments, * in the order: * <number of camera pairs> * <pair 1 camera 1 filename> * <pair 1 camera 1 frame number> * <pair 1 camera 2 filename> * <pair 1 camera 2 frame number> * <pair 1 view name> * <pair 1 camera coefficients filename> * ... * <TPS smoothing parameter> * <feature detector> * <output directory> * * Parameters: * argc: number of commandline arguments * argv: string array of commandline arguments * * Returns: 0 on success, 1 on error. */ int main (int argc, char *argv[]) { // check for minimum number of commandline arguments if (argc < 11) { printf("Usage:\nvideos\n\t<number of camera pairs>\n\t<pair 1 camera 1 filename>\n\t<pair 1 camera 1 frame number>\n\t<pair 1 camera 2 filename>\n\t<pair 1 camera 2 frame number>\n\t<pair 1 view name>\n\t<pair 1 camera coefficients filename>\n\t...\n\t<TPS smoothing parameter>\n\t<feature detector>\n\t<output directory>\n"); exit(1); } // get the number of camera pairs int numCameraPairs = atoi(argv[1]); if (numCameraPairs <= 0) { printf("Invalid number of camera pairs.\n"); exit(1); } // number of commandline arguments should be numCameraPairs*6 + 5 if (argc != numCameraPairs*6 + 5) { printf("Usage:\nvideos\n\t<number of camera pairs>\n\t<pair 1 camera 1 filename>\n\t<pair 1 camera 1 frame number>\n\t<pair 1 camera 2 filename>\n\t<pair 1 camera 2 frame number>\n\t<pair 1 view name>\n\t<pair 1 camera coefficients filename>\n\t...\n\t<TPS smoothing parameter>\n\t<feature detector>\n\t<output directory>\n"); exit(1); } // allocate memory to store information for camera pairs char **camera1Filenames = (char **)malloc(numCameraPairs * sizeof(char *)); int *camera1Frames = (int *)malloc(numCameraPairs * sizeof(int)); if (camera1Filenames == NULL || camera1Frames == NULL) { printf("Out of memory error.\n"); exit(1); } char **camera2Filenames = (char **)malloc(numCameraPairs * sizeof(char *)); int *camera2Frames = (int *)malloc(numCameraPairs * sizeof(int)); if (camera2Filenames == NULL || camera2Frames == NULL) { printf("Out of memory error.\n"); exit(1); } char **cameraNames = (char **)malloc(numCameraPairs * sizeof(char *)); if (cameraNames == NULL) { printf("Out of memory error.\n"); exit(1); } char **cameraCoefficientsFilenames = (char **)malloc(numCameraPairs * sizeof(char *)); if (cameraCoefficientsFilenames == NULL) { printf("Out of memory error.\n"); exit(1); } int argIndex = 2; for (int i = 0; i < numCameraPairs; i++) { camera1Filenames[i] = argv[argIndex]; camera1Frames[i] = atoi(argv[argIndex+1]); camera2Filenames[i] = argv[argIndex+2]; camera2Frames[i] = atoi(argv[argIndex+3]); cameraNames[i] = argv[argIndex+4]; cameraCoefficientsFilenames[i] = argv[argIndex+5]; // make sure input video frames are valid if (camera1Frames[i] <= 0) { printf("Invalid frame number for pair %d camera 1.\n", i+1); exit(1); } if (camera2Frames[i] <= 0) { printf("Invalid frame number for pair %d camera 1.\n", i+1); exit(1); } // make sure input filenames are valid if (!fileExists(camera1Filenames[i])) { printf("Could not open pair %d camera 1 video file.\n", i+1); exit(1); } if (!fileExists(camera2Filenames[i])) { printf("Could not open pair %d camera 2 video file.\n", i+1); exit(1); } if (!fileExists(cameraCoefficientsFilenames[i])) { printf("Could not open pair %d camera coefficients file.\n", i+1); exit(1); } argIndex += 6; } double regularization = atof(argv[argIndex]); char *featureDetector = argv[argIndex+1]; char *outputDirectory = argv[argIndex+2]; // make sure input feature dectector is recognized if (strcasecmp(featureDetector, FAST_FEATURE_DETECTOR) && strcasecmp(featureDetector, GFTT_FEATURE_DETECTOR) && strcasecmp(featureDetector, SURF_FEATURE_DETECTOR) && strcasecmp(featureDetector, SIFT_FEATURE_DETECTOR) && strcasecmp(featureDetector, SPEEDSIFT_FEATURE_DETECTOR)) { printf("Feature Detector not recognized. Please select from the following:\n\t%s\n\t%s\n\t%s\n\t%s\n\t%s\n", FAST_FEATURE_DETECTOR, GFTT_FEATURE_DETECTOR, SURF_FEATURE_DETECTOR, SIFT_FEATURE_DETECTOR, SPEEDSIFT_FEATURE_DETECTOR); exit(1); } // make sure regularization parameter for TPS is valid if (regularization <= 0.0 || regularization == HUGE_VAL) { printf("Invalid smoothing parameter value.\n"); exit(1); } // if output directory doesn't end with '/' char, append '/' to the string. // this is so we can later append a filename to the directory when we want // to write the file to that directory if (outputDirectory[strlen(outputDirectory)-1] != '/') { strcat(outputDirectory, "/"); } DIR *dir = opendir(outputDirectory); // if output directory does not exist, create it with correct permissions if (dir == NULL) { printf("Output directory does not exist.\n"); if (mkdir(outputDirectory, S_IRWXO | S_IRWXG | S_IRWXU)) { printf("Could not create output directory.\n"); exit(1); } else { printf("Created output directory.\n"); } } else { closedir(dir); } // string for the MATLAB commands char command[500]; Engine *matlabEngine; // open MATLAB engine if (!(matlabEngine = engOpen("\0"))) { printf("Can't start MATLAB engine\n"); exit(1); } // create MATLAB arrays to retrieve values from MATLAB workspace mxArray **c1ImageData = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c1ImageDimensions = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c1ImagePaddedWidths = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); if (c1ImageData == NULL || c1ImageDimensions == NULL || c1ImagePaddedWidths == NULL) { printf("Out of memory error.\n"); exit(1); } mxArray **c2ImageData = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c2ImageDimensions = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); mxArray **c2ImagePaddedWidths = (mxArray **)malloc(numCameraPairs * sizeof(mxArray *)); if (c2ImageData == NULL || c2ImageDimensions == NULL || c2ImagePaddedWidths == NULL) { printf("Out of memory error.\n"); exit(1); } // create IplImage arrays for camera 1 and 2 images for all camera pairs IplImage **c1Images = (IplImage **)malloc(numCameraPairs * sizeof(IplImage *)); IplImage **c2Images = (IplImage **)malloc(numCameraPairs * sizeof(IplImage *)); if (c1Images == NULL || c2Images == NULL) { printf("Out of memory error.\n"); exit(1); } // for each camera pair, get the specified frames from cameras 1 and 2, using // MATLAB functions for (int i = 0; i < numCameraPairs; i++) { char video1Extension[6]; // get the video file extension for the first video file if (getVideoFileExtension(camera1Filenames[i], video1Extension) == INVALID_VIDEO_FILE_EXTENSION_ERROR) { printf("Video files must be of extension .mrf or .cine.\n"); exit(1); } // call appropriate MATLAB function depending on whether video file is .cine // or .mrf to extract the frame as a MATLAB image. If neither, error. if ((strcasecmp(video1Extension, ".cine") == 0) || (strcasecmp(video1Extension, ".cin") == 0)) { sprintf(command, "c1 = cineRead('%s', %d);", camera1Filenames[i], camera1Frames[i]); engEvalString(matlabEngine, command); } else if (strcasecmp(video1Extension, ".mrf") == 0) { sprintf(command, "c1 = mrfRead('%s', %d);", camera1Filenames[i], camera1Frames[i]); engEvalString(matlabEngine, command); } else { printf("Videos must be of extension .mrf or .cine.\n"); exit(1); } char video2Extension[6]; // get the video file extension for the second video file if (getVideoFileExtension(camera2Filenames[i], video2Extension) == INVALID_VIDEO_FILE_EXTENSION_ERROR) { printf("Video files must be of extension .mrf or .cine.\n"); exit(1); } // call appropriate MATLAB function depending on whether video file is .cine // or .mrf to extract the frame as a MATLAB image. If neither, error. if ((strcasecmp(video2Extension, ".cine") == 0) || (strcasecmp(video2Extension, ".cin") == 0)) { sprintf(command, "c2 = cineRead('%s', %d);", camera2Filenames[i], camera2Frames[i]); engEvalString(matlabEngine, command); } else if (strcasecmp(video2Extension, ".mrf") == 0) { sprintf(command, "c2 = mrfRead('%s', %d);", camera2Filenames[i], camera2Frames[i]); engEvalString(matlabEngine, command); } else { printf("Videos must be of extension .mrf or .cine.\n"); exit(1); } // call MATLAB function convert_image_matlab2cv_gs on MATLAB images to convert // them into a format that will be compatible with the IplImages of OpenCV sprintf(command, "[c1_img c1_dim c1_padded_width] = convert_image_matlab2cv_gs(c1);"); engEvalString(matlabEngine, command); sprintf(command, "[c2_img c2_dim c2_padded_width] = convert_image_matlab2cv_gs(c2);"); engEvalString(matlabEngine, command); // retrieve the image data, image dimensions, and image padded width variables // from MATLAB for both camera images c1ImageData[i] = engGetVariable(matlabEngine, "c1_img"); c1ImageDimensions[i] = engGetVariable(matlabEngine, "c1_dim"); c1ImagePaddedWidths[i] = engGetVariable(matlabEngine, "c1_padded_width"); c2ImageData[i] = engGetVariable(matlabEngine, "c2_img"); c2ImageDimensions[i] = engGetVariable(matlabEngine, "c2_dim"); c2ImagePaddedWidths[i] = engGetVariable(matlabEngine, "c2_padded_width"); if (c1ImageData[i] == NULL || c1ImageDimensions[i] == NULL || c1ImagePaddedWidths[i] == NULL) { printf("Could not retrieve all necessary information for pair %d camera 1 frame %d from MATLAB.\n", i+1, camera1Frames[i]); exit(1); } if (c2ImageData[i] == NULL || c2ImageDimensions[i] == NULL || c2ImagePaddedWidths[i] == NULL) { printf("Could not retrieve all necessary information for pair %d camera 2 frame %d from MATLAB.\n", i+1, camera2Frames[i]); exit(1); } int c1Status, c2Status; ImageInfo c1ImageInfo, c2ImageInfo; // extract the image information from the MATLAB variables in the form of // mxArrays, and store in ImageInfo structs c1Status = getInputImageInfo(&c1ImageInfo, c1ImageData[i], c1ImageDimensions[i], c1ImagePaddedWidths[i]); c2Status = getInputImageInfo(&c2ImageInfo, c2ImageData[i], c2ImageDimensions[i], c2ImagePaddedWidths[i]); if (c1Status == IMAGE_INFO_DATA_ERROR) { printf("Pair %d camera 1: Images must have two dimensions.\n", i+1); exit(1); } if (c2Status == IMAGE_INFO_DATA_ERROR) { printf("Pair %d camera 2: Images must have two dimensions.\n", i+1); exit(1); } if (c1Status == IMAGE_INFO_DIMENSIONS_ERROR) { printf("Pair %d camera 1: Image dimension vectors must contain two elements: [width, height].\n", i+1); exit(1); } if (c2Status == IMAGE_INFO_DIMENSIONS_ERROR) { printf("Pair %d camera 2: Image dimension vectors must contain two elements: [width, height].\n", i+1); exit(1); } if (c1Status == IMAGE_INFO_PADDED_WIDTH_ERROR) { printf("Pair %d camera 1: Padded image widths must be scalars.\n", i+1); exit(1); } if (c2Status == IMAGE_INFO_PADDED_WIDTH_ERROR) { printf("Pair %d camera 2: Padded image widths must be scalars.\n", i+1); exit(1); } if (c1Status == IMAGE_DEPTH_ERROR) { printf("Pair %d camera 1: Images must be represented by 8 or 16-bit integers.\n", i+1); exit(1); } if (c2Status == IMAGE_DEPTH_ERROR) { printf("Pair %d camera 2: Images must be represented by 8 or 16-bit integers.\n", i+1); exit(1); } // create IplImages using values in ImageInfo structs c1Status = createIplImageFromImageInfo(&(c1Images[i]), c1ImageInfo); c2Status = createIplImageFromImageInfo(&(c2Images[i]), c2ImageInfo); if (c1Status == OUT_OF_MEMORY_ERROR || c2Status == OUT_OF_MEMORY_ERROR) { printf("Out of memory error.\n"); exit(1); } // flip the images over the y-axis to compensate for the differences in axial // labels between MATLAB and OpenCV (camera coefficients would not correctly // correspond to image otherwise) cvFlip(c1Images[i], NULL, 1); cvFlip(c2Images[i], NULL, 1); } char errorMessage[500]; int numContours; char **contourNames; CvPoint3D32f **features3D; char **validFeatureIndicator; int *numFeaturesInContours; char contoursFilename[MAX_FILENAME_LENGTH]; // for each camera pair, run features and triangulation for (int i = 0; i < numCameraPairs; i++) { // create the output 2D features filename as "frame<frame number>_features2D_<camera name>.txt" char features2DFilename[MAX_FILENAME_LENGTH]; sprintf(features2DFilename, "%sframe%d_features2D_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]); // create the output contours filename as "frame<frame number>_contours_<camera name>.txt" char tempContoursFilename[MAX_FILENAME_LENGTH]; sprintf(tempContoursFilename, "%sframe%d_contours_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]); printf("Camera pair for %s view:\n", cameraNames[i]); // run the features program to extract matching 2D features from the 2 // images within user defined contour if (features(c1Images[i], c2Images[i], features2DFilename, tempContoursFilename, featureDetector, errorMessage)) { printf("Features: %s\n", errorMessage); exit(1); } // we only need to save the contour(s) for the first camera pair, as that // is the one we will use to create the meshes, and we only use the contours // with the same name(s) in subsequent camera pairs if (i == 0) { strcpy(contoursFilename, tempContoursFilename); // get the contour names of the contours selected in features function for // output file naming and contour matching in other camera pairs int status = readContourNamesFromInputFile(&numContours, &contourNames, contoursFilename); if (status == INPUT_FILE_OPEN_ERROR) { printf("Could not open contour vertices file.\n"); exit(1); } if (status == INCORRECT_INPUT_FILE_FORMAT_ERROR) { printf("Contour vertices file has incorrect format.\n"); exit(1); } if (status == OUT_OF_MEMORY_ERROR) { printf("Out of memory error.\n"); exit(1); } // allocate memory for 3D features features3D = (CvPoint3D32f **)malloc(numContours * sizeof(CvPoint3D32f *)); validFeatureIndicator = (char **)malloc(numContours * sizeof(char *)); numFeaturesInContours = (int *)malloc(numContours * sizeof(int)); if (features3D == NULL || numFeaturesInContours == NULL || validFeatureIndicator == NULL) { printf("Out of memory error.\n"); exit(1); } for (int j = 0; j < numContours; j++) { features3D[j] = (CvPoint3D32f *)malloc(MAX_FEATURES_IN_CONTOUR * sizeof(CvPoint3D32f)); validFeatureIndicator[j] = (char *)malloc(MAX_FEATURES_IN_CONTOUR * sizeof(char)); if (features3D[j] == NULL || validFeatureIndicator[j] == NULL) { printf("Out of memory error.\n"); exit(1); } numFeaturesInContours[j] = 0; } } // create the output 3D features filename as "frame<frame number>_features3D_<camera name>.txt" char features3DFilename[MAX_FILENAME_LENGTH]; sprintf(features3DFilename, "%sframe%d_features3D_%s.txt", outputDirectory, camera1Frames[i], cameraNames[i]); // triangulate the matching 2D features between cameras to find the 3D coordinates // of the features, and remove invalid features if (triangulation(cameraCoefficientsFilenames[i], features2DFilename, features3DFilename, c1Images[i], errorMessage)) { printf("Triangulation: %s\n", errorMessage); exit(1); } // if features from triangulation lie within contours that have the same // names as those defined for the first camera pair, add them to the // 3D features array for mesh creation int status = read3DFeaturesFromFileForMatchingContours(features3DFilename, features3D, numFeaturesInContours, numContours, contourNames); if (status == INPUT_FILE_OPEN_ERROR) { printf("Could not open 3D features file.\n"); exit(1); } if (status == INVALID_NUM_CONTOURS_ERROR) { printf("At least 1 contour region required.\n"); exit(1); } if (status == INCORRECT_INPUT_FILE_FORMAT_ERROR) { printf("3D features file has incorrect format.\n"); exit(1); } } // for each contour (defined for the first camera pair), perform RANSAC on // the cumulative 3D features from all camera pairs that lie within the contour for (int i = 0; i < numContours; i++) { memset(validFeatureIndicator[i], 1, numFeaturesInContours[i] * sizeof(char)); // perform RANSAC to remove points that lie too far off a best-fit surface if (ransac(features3D[i], validFeatureIndicator[i], numFeaturesInContours[i], errorMessage)) { printf("RANSAC: %s\n", errorMessage); exit(1); } int numValidFeatures = 0; for (int j = 0; j < numFeaturesInContours[i]; j++) { if (validFeatureIndicator[i][j]) { numValidFeatures++; } } printf("Total valid features after RANSAC for contour %s: %d\n", contourNames[i], numValidFeatures); } // create the output 3D features filename for all camera pairs as // "frame<frame number>_features3D.txt", and write the result of RANSAC to // the file char features3DFilename[MAX_FILENAME_LENGTH]; sprintf(features3DFilename, "%sframe%d_features3D.txt", outputDirectory, camera1Frames[0]); int status = write3DFeaturesToFile(features3D, validFeatureIndicator, numFeaturesInContours, contourNames, numContours, features3DFilename); if (status == OUTPUT_FILE_OPEN_ERROR) { sprintf(errorMessage, "Could not open output file."); return 1; } char **meshFilenames = (char **)malloc(numContours * sizeof(char *)); if (meshFilenames == NULL) { printf("Out of memory error.\n"); exit(1); } // for each contour, create a different mesh output file for (int i = 0; i < numContours; i++) { meshFilenames[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char)); if (meshFilenames[i] == NULL) { printf("Out of memory error.\n"); exit(1); } // create the output mesh filename as "frame<frame number>_mesh_<contour name>_<camera name>.txt" sprintf(meshFilenames[i], "%sframe%d_mesh_%s.txt", outputDirectory, camera1Frames[0], contourNames[i]); } // create the wing meshes from the triangulated 3D points and the user-selected // contours, and write each mesh to a different file for each contour if (mesh(features3DFilename, contoursFilename, cameraCoefficientsFilenames[0], meshFilenames, numContours, regularization, errorMessage)) { printf("Mesh: %s\n", errorMessage); exit(1); } // we only calculate the flow of a wing mesh if there is a mesh file with the // same contour name in the output directory for the previous video frame char **flowFilenames = (char **)malloc(numContours * sizeof(char *)); if (flowFilenames == NULL) { printf("Out of memory error.\n"); exit(1); } for (int i = 0; i < numContours; i++) { flowFilenames[i] = NULL; } int numFilesInDirectory; char **filenamesInDirectory = (char **)malloc(MAX_FILES_IN_DIRECTORY * sizeof(char *)); if (filenamesInDirectory == NULL) { printf("Out of memory error.\n"); exit(1); } for (int i = 0; i < MAX_FILES_IN_DIRECTORY; i++) { filenamesInDirectory[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char)); if (filenamesInDirectory[i] == NULL) { printf("Out of memory error.\n"); exit(1); } } // get all files in the output directory getAllFilenamesInDirectory(outputDirectory, &numFilesInDirectory, filenamesInDirectory); // for each contour check if previous frame mesh file for same contour exists // in output directory for (int i = 0; i < numContours; i++) { // set substring indicating match to be "frame<previous frame number>_mesh_<contour name>.txt" char filenameToMatch[MAX_FILENAME_LENGTH]; sprintf(filenameToMatch, "frame%d_mesh_%s.txt", camera1Frames[0]-1, contourNames[i]); // try to find a filename from the output directory that contains the // substring indicating a match for a previous frame mesh for the same // contour int fileExists = getIndexOfMatchingString(filenamesInDirectory, numFilesInDirectory, filenameToMatch); // if filename was found, create a flow output file for current contour // and call flow to calculate the flow between previous contour mesh and // current contour mesh if (fileExists != -1) { flowFilenames[i] = (char *)malloc(MAX_FILENAME_LENGTH * sizeof(char)); if (flowFilenames[i] == NULL) { printf("Out of memory error.\n"); exit(1); } // create the output flow filename as "frame<frame number>_flow_<contour name>_<camera name>.txt" sprintf(flowFilenames[i], "%sframe%d_flow_%s.txt", outputDirectory, camera1Frames[0], contourNames[i]); // add the output directory name to the beginning of the previous mesh // filename char prevFrameMeshFile[MAX_FILENAME_LENGTH]; sprintf(prevFrameMeshFile, "%s%s", outputDirectory, filenameToMatch); // call flow to find the flow between the previous mesh file and the // current mesh file for each mesh point current contour if (flow(prevFrameMeshFile, meshFilenames[i], flowFilenames[i], errorMessage)) { printf("Flow: %s\n", errorMessage); exit(1); } } else { printf("Mesh points file for previous frame not found for contour %s. Unable to calculate flow.\n", contourNames[i]); } } sprintf(command, "hold on;"); engEvalString(matlabEngine, command); // for each contour, display MATLAB 3D plot of the mesh, as well as the flow // for the mesh, if applicable for (int i = 0; i < numContours; i++) { if (flowFilenames[i] != NULL) { sprintf(command, "flows = load('%s');", flowFilenames[i]); engEvalString(matlabEngine, command); // plot the flows of the mesh points sprintf(command, "quiver3(flows(:,1), flows(:,2), flows(:,3), flows(:,4), flows(:,5), flows(:,6), 4, 'r-');"); engEvalString(matlabEngine, command); } sprintf(command, "mesh = importdata('%s', ' ', 1);", meshFilenames[i]); engEvalString(matlabEngine, command); // plot the mesh points sprintf(command, "plot3(mesh.data(:,1), mesh.data(:,2), mesh.data(:,3), 'b.');"); engEvalString(matlabEngine, command); } // reverse the z and y coordinates in the display sprintf(command, "set(gca,'zdir','reverse','ydir','reverse');"); engEvalString(matlabEngine, command); // scale the axes to be equal sprintf(command, "axis equal"); engEvalString(matlabEngine, command); // wait for the user to hit enter printf("Hit return to continue.\n"); fgetc(stdin); // close MATLAB engine engClose(matlabEngine); // cleanup free(camera1Filenames); free(camera1Frames); free(camera2Filenames); free(camera2Frames); free(cameraNames); free(cameraCoefficientsFilenames); for (int i = 0; i < numCameraPairs; i++) { mxDestroyArray(c1ImageData[i]); mxDestroyArray(c1ImageDimensions[i]); mxDestroyArray(c1ImagePaddedWidths[i]); mxDestroyArray(c2ImageData[i]); mxDestroyArray(c2ImageDimensions[i]); mxDestroyArray(c2ImagePaddedWidths[i]); free(c1Images[i]->imageData); cvReleaseImageHeader(&c1Images[i]); free(c2Images[i]->imageData); cvReleaseImageHeader(&c2Images[i]); } free(c1ImageData); free(c1ImageDimensions); free(c1ImagePaddedWidths); free(c2ImageData); free(c2ImageDimensions); free(c2ImagePaddedWidths); free(c1Images); free(c2Images); for (int i = 0; i < MAX_FILES_IN_DIRECTORY; i++) { free(filenamesInDirectory[i]); } free(filenamesInDirectory); for (int i = 0; i < numContours; i++) { free(contourNames[i]); free(features3D[i]); free(validFeatureIndicator[i]); free(meshFilenames[i]); if (flowFilenames[i] != NULL) { free(flowFilenames[i]); } } free(contourNames); free(features3D); free(validFeatureIndicator); free(numFeaturesInContours); free(meshFilenames); free(flowFilenames); exit(0); }
static int check_dir_contents(const char *path, const char **contents) { int i; int res; int err = 0; int found[MAX_ENTRIES]; const char *cont[MAX_ENTRIES]; DIR *dp; for (i = 0; contents[i]; i++) { assert(i < MAX_ENTRIES - 3); found[i] = 0; cont[i] = contents[i]; } found[i] = 0; cont[i++] = "."; found[i] = 0; cont[i++] = ".."; cont[i] = NULL; dp = opendir(path); if (dp == NULL) { PERROR("opendir"); return -1; } memset(found, 0, sizeof(found)); while(1) { struct dirent *de; errno = 0; de = readdir(dp); if (de == NULL) { if (errno) { PERROR("readdir"); closedir(dp); return -1; } break; } for (i = 0; cont[i] != NULL; i++) { assert(i < MAX_ENTRIES); if (strcmp(cont[i], de->d_name) == 0) { if (found[i]) { ERROR("duplicate entry <%s>", de->d_name); err--; } else found[i] = 1; break; } } if (!cont[i]) { ERROR("unexpected entry <%s>", de->d_name); err --; } } for (i = 0; cont[i] != NULL; i++) { if (!found[i]) { ERROR("missing entry <%s>", cont[i]); err--; } } res = closedir(dp); if (res == -1) { PERROR("closedir"); return -1; } if (err) return -1; return 0; }
int processdir(int level, const char *base, const char *dirname, struct stat *sb, struct filenode *dir, struct filenode *root, int curroffset) { DIR *dirfd; struct dirent *dp; struct filenode *n, *link; struct excludes *pe; if (level <= 1) { /* Ok, to make sure . and .. are handled correctly * we add them first. Note also that we alloc them * first to get to know the real name */ link = newnode(base, ".", curroffset); if (!lstat(link->realname, sb)) { setnode(link, sb->st_dev, sb->st_ino, sb->st_mode); append(&dir->dirlist, link); /* special case for root node - '..'s in subdirs should link to * '.' of root node, not root node itself. */ dir->dirlist.owner = link; curroffset = alignnode(link, curroffset, 0) + spaceneeded(link); n = newnode(base, "..", curroffset); if (!lstat(n->realname, sb)) { setnode(n, sb->st_dev, sb->st_ino, sb->st_mode); append(&dir->dirlist, n); n->orig_link = link; curroffset = alignnode(n, curroffset, 0) + spaceneeded(n); } } } dirfd = opendir(dir->realname); while((dp = readdir(dirfd))) { /* don't process main . and .. twice */ if (level <= 1 && (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)) continue; n = newnode(base, dp->d_name, curroffset); /* Process exclude list. */ for (pe = excludelist; pe; pe = pe->next) { if (!nodematch(pe->pattern, n)) { freenode(n); break; } } if (pe) continue; if (lstat(n->realname, sb)) { fprintf(stderr, "ignoring '%s' (lstat failed)\n", n->realname); freenode(n); continue; } /* Handle special names */ if ( n->name[0] == '@' ) { if (S_ISLNK(sb->st_mode)) { /* this is a link to follow at build time */ n->name = n->name + 1; /* strip off the leading @ */ memset(bigbuf, 0, sizeof(bigbuf)); readlink(n->realname, bigbuf, sizeof(bigbuf)); n->realname = strdup(bigbuf); if (lstat(n->realname, sb)) { fprintf(stderr, "ignoring '%s' (lstat failed)\n", n->realname); freenode(n); continue; } } else if (S_ISREG(sb->st_mode) && sb->st_size == 0) { /* * special file @name,[bcp..],major,minor */ char devname[32]; char type; int major; int minor; if (sscanf(n->name, "@%[a-zA-Z0-9],%c,%d,%d", devname, &type, &major, &minor) == 4 ) { strcpy(n->name, devname); sb->st_rdev = makedev(major, minor); sb->st_mode &= ~S_IFMT; switch (type) { case 'c': case 'u': sb->st_mode |= S_IFCHR; break; case 'b': sb->st_mode |= S_IFBLK; break; case 'p': sb->st_mode |= S_IFIFO; break; default: fprintf(stderr, "Invalid special device type '%c' " "for file %s\n", type, n->realname); freenode(n); continue; } } } } setnode(n, sb->st_dev, sb->st_ino, sb->st_mode); /* Skip unreadable files/dirs */ if (!S_ISLNK(n->modes) && access(n->realname, R_OK)) { fprintf(stderr, "ignoring '%s' (access failed)\n", n->realname); freenode(n); continue; } /* Look up old links */ if ( strcmp(n->name, ".") == 0 ) { append(&dir->dirlist, n); link = n->parent; } else if (strcmp(n->name, "..") == 0) { append(&dir->dirlist, n); link = n->parent->parent; } else { link = findnode(root, n->ondev, n->onino); append(&dir->dirlist, n); } if (link) { n->orig_link = link; curroffset = alignnode(n, curroffset, 0) + spaceneeded(n); continue; } if (S_ISREG(sb->st_mode)) { curroffset = alignnode(n, curroffset, spaceneeded(n)); n->size = sb->st_size; } else curroffset = alignnode(n, curroffset, 0); if (S_ISLNK(sb->st_mode)) { n->size = sb->st_size; } curroffset += spaceneeded(n); if (S_ISCHR(sb->st_mode) || S_ISBLK(sb->st_mode)) { n->devnode = sb->st_rdev; } if (S_ISDIR(sb->st_mode)) { if (!strcmp(n->name, "..")) { curroffset = processdir(level+1, dir->realname, dp->d_name, sb, dir, root, curroffset); } else { curroffset = processdir(level+1, n->realname, dp->d_name, sb, n, root, curroffset); } } } closedir(dirfd); return curroffset; }
int main(int argc, char *argv[]) { extern double probNDE; char *oldFormatDir = (char *) de_malloc(kMaxPathLength); char *newPathFormatDir = (char*) de_malloc(kMaxPathLength); /* alternate pathway input mode*/ char *dirName = (char *) de_malloc(kMaxPathLength); char *deName = (char *) de_malloc(kMaxPathLength); /* differential expression, file */ char *arrName = (char *) de_malloc(kMaxPathLength); /* list of all genes tested, file */ char *betaCoeffFile = (char *) de_malloc(kMaxPathLength); /* user specified beta coefficients */ srand(time(NULL)); gatherOptions(argc, argv, &oldFormatDir, &deName, &arrName, &newPathFormatDir, &betaCoeffFile); if (betaCoeffFile[0] != '\0') { readBetaCoeffFile(betaCoeffFile); // printBetaCoeffs(); } verbose("Opening differetially expressed (DE) genes file: `%s'\n", deName); readDETab(deName); verbose("Opening array file: `%s'\n", arrName); readArrayTab(arrName); /*** Get the pathway dir name, regardless of the format ***/ DIR *dip; struct dirent *dit; if (oldFormatDir[0] != '\0') { verbose("Opening pathway dir (oldFormat): `%s'\n", oldFormatDir); strcpy(dirName, oldFormatDir); } else if (newPathFormatDir != '\0') { verbose("Opening pathway dir (newFormat): `%s'\n", newPathFormatDir); strcpy(dirName, newPathFormatDir); } int i = 0; int leng = 0; char fullPath[kMaxPathLength]; char tmpPath[kMaxPathLength]; struct stat buffer; strcpy(fullPath, dirName); if ((dip = opendir(dirName)) == NULL) { fprintf(stderr, "Error while openning directory `%s'!\n", dirName); exit(EXIT_FAILURE); } double tA; // this is the sum of pert factors for our observed data. double tAc; // median corrected pert factor value. double pPERT; // probability of perturbation. int szMat; // this is the size (# uniq genes) of the pathway. int Nde; // number of diff expr genes that are in the pathway int status = 0; while ((dit = readdir(dip)) != NULL) { i++; strcpy(tmpPath, fullPath); strcat(tmpPath, dit->d_name); leng = strlen(dit->d_name); stat(tmpPath, &buffer); cleanup(); if (!S_ISREG(buffer.st_mode)) { // Is it a regular file? continue; // if not, bail on this file } if (!endsIn_tab(tmpPath)) { continue; // if it does not end in .tab, bail on this file } // printf("%s\n", dit->d_name); // print name of pathway if (oldFormatDir) szMat = readOldPathway(tmpPath); if (newPathFormatDir) szMat = readNewPathway(tmpPath); if (szMat == 0) { fprintf(stderr, "Unable to process pathway `%s', nothing read from " "pathway file.\n", tmpPath); continue; } status = 0; printf("\n####################\nPathway: %s\n", tmpPath); tA = processPathway(&status); verbose("Pathway processed.\n"); if (status != 0) { if (status == -1) fprintf(stderr, "Unable to process pathway `%s', beta matrix is " "EMPTY (this is a pathway issue).\n", tmpPath); if (status == -2) fprintf(stderr, "Unable to process pathway `%s', beta matrix is " "SINGULAR (this as a pathway issue).\n", tmpPath); continue; } if (nBoots) { // if bootstrapping is turned 'on' verbose("Bootstrapping...\n"); Nde = countIntersect_de_path(); double *totalAcc; // T_A from Tarca et al. totalAcc = zerosVec(nBoots); int k; if (Nde == 0) { fprintf(stderr, "Unable to process pathway `%s', number of " "differentially expressed genes, Nde = 0 (None of the genes " "in your DE file are present in this pathway).\n", tmpPath); } else { for (k = 0; k < nBoots; ++k) { populateBootGenes(Nde); totalAcc[k] = calcBootPerterb(); deleteAllBootGenes(); } qsort(totalAcc, nBoots, sizeof(double), compare_dbls); double median = correctTA(totalAcc, nBoots); tAc = tA - median; printf("%6s = %f\n", "t_Ac", tAc); if (tAc >= 0.) pPERT = pPERTcalc(tAc, totalAcc, nBoots, 1); else pPERT = pPERTcalc(tAc, totalAcc, nBoots, 0); printf("%6s = %e\n", "pPERT", pPERT); double pG = combPValue(pPERT, probNDE); if ((probNDE > -1) && pG != -1 ) { printf("%6s = %e\n", "pG", pG); int pSize = countIntersect_array_path(); addPGlobal(pG, dit->d_name, pSize , Nde, tAc, pPERT, probNDE); } else printf("%6s = NaN\n", "pG"); } } // end bootstrapping loop } // end file reading while loop if (closedir(dip) != 0) { fprintf(stderr, "Error while closing directory `%s'!\n", dirName); exit(EXIT_FAILURE); } /*** Now, having processed all pathways, we take the results, sort them, perform the appropriate corrections, and report them. ta-da! ***/ extern pGlobal *pGlist; if (HASH_COUNT(pGlist) > 0) { sort_by_pValue(); bonferrPGlobal(); fdrPGlobal(); printPValues(); } exit(EXIT_SUCCESS); }
int main(int argc, char *argv[]) { int i; BIFF8_STRING_ENCODING encoding = BIFF8_STRING_ENCODING_UTF8; char delimiter = ','; char textDelimiter = '"'; char replacement = '?'; BIFF8_WORKSHEET_SAVE_MODE saveMode = BIFF8_WORKSHEET_SAVE_PRESERVE; int crlf = 0; int enclose = 0; char fileExt[] = FILE_EXTENSION_CSV; int srcIsDir = 1; char src[FILENAME_MAX + 1] = "./"; char dest[FILENAME_MAX + 1] = "./"; char fileName[FILENAME_MAX + 1]; char srcFile[FILENAME_MAX * 2]; char destFile[FILENAME_MAX * 2]; char destFileTemp[FILENAME_MAX * 3]; struct stat statStruct; if(argc > 1) { int len, index; int encodingSet = 0; int delimiterSet = 0; int saveModeSet = 0; int srcSet = 0; int destSet = 0; for(i = 1; i < argc; i++) { len = strlen(argv[i]); if(!strcmp(argv[i], OPTION_HELP)) help(); if(!strcmp(argv[i], OPTION_ENCODING_UTF8)) { if(encodingSet) error(ERROR_ENCODING, 0); encodingSet = 1; continue; } if(!strcmp(argv[i], OPTION_ENCODING_UTF16)) { if(encodingSet) error(ERROR_ENCODING, 0); encoding = BIFF8_STRING_ENCODING_UTF16; encodingSet = 1; continue; } if(!memcmp(argv[i], OPTION_ENCODING_ASCII, OPTION_ENCODING_ASCII_MIN_SIZE)) { if(encodingSet) error(ERROR_ENCODING, 0); index = OPTION_ENCODING_ASCII_MIN_SIZE; if((replacement = optionValueGet(argv[i], &index, 0)) == -1 || index) error (ERROR_ENCODING, 0); encoding = BIFF8_STRING_ENCODING_ASCII; encodingSet = 1; continue; } if(!strcmp(argv[i], OPTION_DELIMITER_CSV)) { if(delimiterSet) error(ERROR_DELIMITER, 0); delimiterSet = 1; continue; } if(!strcmp(argv[i], OPTION_DELIMITER_TSV)) { if(delimiterSet) error(ERROR_DELIMITER, 0); delimiter = '\t'; fileExt[1] = 't'; delimiterSet = 1; continue; } if(!memcmp(argv[i], OPTION_DELIMITER_DSV, OPTION_DELIMITER_DSV_MIN_SIZE)) { if(delimiterSet) error(ERROR_DELIMITER, 0); index = OPTION_DELIMITER_DSV_MIN_SIZE; if((delimiter = optionValueGet(argv[i], &index, 0)) == -1 || !index) error(ERROR_DELIMITER, 0); if(delimiter == ',' || delimiter == '\t') error(ERROR_DELIMITER, 0); if((textDelimiter = optionValueGet(argv[i], &index, 0)) == -1 || !index) error(ERROR_DELIMITER, 0); if((fileExt[1] = optionValueGet(argv[i], &index, 1)) == -1 || index) error(ERROR_DELIMITER, 0); if(fileExt[1] == 'c' || fileExt[1] == 't') error(ERROR_DELIMITER, 0); delimiterSet = 1; continue; } if(!memcmp(argv[i], OPTION_COMPACT, OPTION_COMPACT_MIN_SIZE)) { if(saveModeSet) error(ERROR_COMPACT, 0); if(len != (OPTION_COMPACT_MIN_SIZE + 1)) error(ERROR_COMPACT, 0); switch((saveMode = argv[i][OPTION_COMPACT_MIN_SIZE] - '0')) { case 0: case 1: case 2: case 3: break; default: error(ERROR_COMPACT, 0); } saveModeSet = 1; continue; } if(!strcmp(argv[i], OPTION_CRLF)) { crlf = 1; continue; } if(!strcmp(argv[i], OPTION_ENCLOSE)) { enclose = 1; continue; } if(!srcSet) { if(stat(argv[i], &statStruct)) error(ERROR_SOURCE, (void *)argv[i]); if(!S_ISDIR(statStruct.st_mode)) { if(!S_ISREG(statStruct.st_mode)) error(ERROR_SOURCE, (void *)argv[i]); if(!isXls(argv[i])) error(ERROR_SOURCE, (void *)argv[i]); srcIsDir = 0; } strcpy(src, argv[i]); if(src[len - 1] != '/' && srcIsDir) strcat(src, "/"); strcpy(dest, src); if(!srcIsDir) { len = strlen(dest); while(len && dest[--len] != '/'); if(dest[len] == '/') dest[len + 1] = 0; else strcpy(dest, "./"); } srcSet = 1; continue; } if(!destSet) { if(stat(argv[i], &statStruct)) error(ERROR_DESTINATION, (void *)argv[i]); if(!S_ISDIR(statStruct.st_mode)) error(ERROR_DESTINATION, (void *)argv[i]); strcpy(dest, argv[i]); if(dest[len - 1] != '/') strcat(dest, "/"); destSet = 1; continue; } error(ERROR_UNKNOWN, (void *)argv[i]); } } printf("\n[xls2dsv]\n"); printf(">> encoding: "); switch(encoding) { case BIFF8_STRING_ENCODING_ASCII: printf("ASCII; non-ASCII characters will be replaced by "); iscntrl(replacement) ? printf("0x%.2x", replacement) : printf("'%c' (0x%.2x)", replacement, replacement); printf("\n"); break; case BIFF8_STRING_ENCODING_UTF16: printf("UTF-16BE (no BOM)\n"); break; default: printf("UTF-8\n"); break; } printf(">> delimiter: "); iscntrl(delimiter) ? printf("0x%.2x", delimiter) : printf("0x%.2x=%c", delimiter, delimiter); printf("\n"); printf(">> text delimiter: "); if(delimiter == '\t') printf("none"); else iscntrl(textDelimiter) ? printf("0x%.2x", textDelimiter) : printf("0x%.2x=%c", textDelimiter, textDelimiter); printf("\n"); printf(">> file extension: \"%s\"\n", fileExt); printf(">> save mode: "); switch(saveMode) { case BIFF8_WORKSHEET_SAVE_PRESERVE: printf("preserve original dimension\n"); break; case BIFF8_WORKSHEET_SAVE_COMPACT_0: printf("discard empty rows and columns after non-empty ones\n"); break; case BIFF8_WORKSHEET_SAVE_COMPACT_1: printf("discard empty rows and columns before and after non-empty ones\n"); break; default: printf("discard all empty cells\n"); break; } printf(">> source %s: %s\n", srcIsDir ? "directory" : "file", src); printf(">> destination directory: %s\n", dest); printf("\n"); DIR *dir = opendir(src); struct dirent *dirent = (struct dirent *)-1; FILE *ifile; FILE *ofile; COMPOUND_DOCUMENT_INFO compDocInfo = COMPOUND_DOCUMENT_INFO_INITIALIZER; BIFF8_WORKBOOK_GLOBALS globals = BIFF8_WORKBOOK_GLOBALS_INITIALIZER; BIFF8_WORKSHEET worksheet = BIFF8_WORKSHEET_INITIALIZER; unsigned char *workbook = 0; int workbookDirID; while(1) { strcpy(srcFile, src); strcpy(destFile, dest); if(dir) { errno = 0; if(!(dirent = readdir(dir))) { if(errno) { printf("%s", src); perror(": readdir: "); } break; } strcpy(fileName, dirent->d_name); if(!isXls(fileName)) continue; strcat(srcFile, fileName); } else { for(i = strlen(srcFile); i && srcFile[--i] != '/'; ); strcpy(fileName, &srcFile[i + (srcFile[i] == '/')]); } if(stat(srcFile, &statStruct)) { printf("%s", srcFile); perror(": stat: "); continue; } if(!S_ISREG(statStruct.st_mode)) continue; strcat(destFile, fileName); printf("[%s]\n", srcFile); if(!(ifile = fopen(srcFile, "r"))) { printf("ERROR: unable to open input file\n"); continue; } do { if(compoundDocumentFileInfoGet(ifile, &compDocInfo)) break; if((workbookDirID = biff8WorkbookLocate(&compDocInfo)) < 0) break; if(!(workbook = (unsigned char *)malloc(compDocInfo.dirEntryTbl[workbookDirID].info.totalSize))) break; if(compoundDocumentFileStreamRead(ifile, &compDocInfo, workbookDirID, workbook, 0, compDocInfo.dirEntryTbl[workbookDirID].info.totalSize) != compDocInfo.dirEntryTbl[workbookDirID].info.totalSize) break; if(biff8WorkbookGlobalsInfoBuild(&compDocInfo, workbook, compDocInfo.dirEntryTbl[workbookDirID].info.totalSize, &globals)) break; for(i = strlen(destFile) - 1; i && destFile[i] != '.'; i--); if(destFile[i] == '.') destFile[i] = 0; else i = strlen(destFile); strcat(destFile, "_"); for(i = 0; i < globals.numSheets; i++, biff8WorksheetInfoDestroy(&worksheet)) { if(biff8WorksheetInfoBuild(&compDocInfo, &globals, workbook, compDocInfo.dirEntryTbl[workbookDirID].info.totalSize, i, &worksheet)) { printf("--> warning: unable to parse worksheet %d\n", i + 1); continue; } strcpy(destFileTemp, destFile); strcat(destFileTemp, (char *)globals.sheet[i].name->string); strcat(destFileTemp, fileExt); printf("--> %s ", destFileTemp); if(!(ofile = fopen(destFileTemp, "w"))) { printf("[ERROR: unable to open output file]\n"); continue; } if(biff8WorksheetSaveToFile(ofile, &compDocInfo, &globals, &worksheet, delimiter, textDelimiter, encoding, replacement, crlf, enclose, saveMode)) printf("[ERROR: cannot save worksheet]\n"); else printf("[OK]\n"); fclose(ofile); } } while(0); printf("\n"); if(workbook) { free(workbook); workbook = 0; } biff8WorksheetInfoDestroy(&worksheet); biff8WorkbookGlobalsInfoDestroy(&globals); compoundDocumentFileTableDestroy(&compDocInfo); fclose(ifile); if(!dir) break; } if(dir) closedir(dir); return 0; }
/* adopted from r.colors */ char *icon_files(void) { char **list, *ret; char buf[GNAME_MAX], path[GPATH_MAX], path_i[GPATH_MAX]; int i, count; size_t len; DIR *dir, *dir_i; struct dirent *d, *d_i; list = NULL; len = 0; sprintf(path, "%s/etc/symbol", G_gisbase()); dir = opendir(path); if (!dir) return NULL; count = 0; /* loop over etc/symbol */ while ((d = readdir(dir))) { if (d->d_name[0] == '.') continue; sprintf(path_i, "%s/etc/symbol/%s", G_gisbase(), d->d_name); dir_i = opendir(path_i); if (!dir_i) continue; /* loop over each directory in etc/symbols */ while ((d_i = readdir(dir_i))) { if (d_i->d_name[0] == '.') continue; list = G_realloc(list, (count + 1) * sizeof(char *)); sprintf(buf, "%s/%s", d->d_name, d_i->d_name); list[count++] = G_store(buf); len += strlen(d->d_name) + strlen(d_i->d_name) + 2; /* '/' + ',' */ } closedir(dir_i); } closedir(dir); qsort(list, count, sizeof(char *), cmp); if (len > 0) { ret = G_malloc((len + 1) * sizeof(char)); /* \0 */ *ret = '\0'; for (i = 0; i < count; i++) { if (i > 0) strcat(ret, ","); strcat(ret, list[i]); G_free(list[i]); } G_free(list); } else { ret = G_store(""); } return ret; }
void pfile_scan( bool count ) { DIR *dp; struct dirent *dentry; CLAN_DATA *clan; DEITY_DATA *deity; char directory_name[100]; short alpha_loop; short cou = 0; deleted = 0; now_time = time( 0 ); // nice( 20 ); /* * Reset all clans to 0 members prior to scan - Samson 7-26-00 */ if( !count ) for( clan = first_clan; clan; clan = clan->next ) clan->members = 0; /* * Reset all deities to 0 worshippers prior to scan - Samson 7-26-00 */ if( !count ) for( deity = first_deity; deity; deity = deity->next ) deity->worshippers = 0; for( alpha_loop = 0; alpha_loop <= 25; alpha_loop++ ) { snprintf( directory_name, 100, "%s%c", PLAYER_DIR, 'a' + alpha_loop ); /* * log_string( directory_name ); */ dp = opendir( directory_name ); dentry = readdir( dp ); while( dentry ) { /* * Added by Tarl 3 Dec 02 because we are now using CVS */ if( !str_cmp( dentry->d_name, "CVS" ) ) { dentry = readdir( dp ); continue; } if( dentry->d_name[0] != '.' ) { if( !count ) read_pfile( directory_name, dentry->d_name, count ); cou++; } dentry = readdir( dp ); } closedir( dp ); } if( !count ) log_string( "Pfile cleanup completed." ); else log_string( "Pfile count completed." ); snprintf( log_buf, MAX_STRING_LENGTH, "Total pfiles scanned: %d", cou ); log_string( log_buf ); if( !count ) { snprintf( log_buf, MAX_STRING_LENGTH, "Total pfiles deleted: %d", deleted ); log_string( log_buf ); snprintf( log_buf, MAX_STRING_LENGTH, "Total pfiles remaining: %d", cou - deleted ); num_pfiles = cou - deleted; log_string( log_buf ); for( clan = first_clan; clan; clan = clan->next ) save_clan( clan ); for( deity = first_deity; deity; deity = deity->next ) save_deity( deity ); } else num_pfiles = cou; return; }
/* * Modified : 01.20.2002 Author : Dark0n3 * * Description : Parses file entries from sfv file and store them in a file. * * Todo : Add dupefile remover. * * Totally rewritten by js on 08.02.2005 */ int copysfv(const char *source, const char *target, struct VARS *raceI) { int infd, outfd, i, retval = 0; short int music, rars, video, others, type; char *ptr, fbuf[2048]; FILE *insfv; DIR *dir; SFVDATA sd; //#if ( sfv_dupecheck == TRUE ) int skip = 0; SFVDATA tempsd; //#endif #if ( sfv_cleanup == TRUE ) int tmpfd; char crctmp[16]; if ((tmpfd = open(".tmpsfv", O_CREAT | O_TRUNC | O_RDWR, 0644)) == -1) d_log("copysfv: open(.tmpsfv): %s\n", strerror(errno)); #endif if ((infd = open(source, O_RDONLY)) == -1) { d_log("copysfv: open(%s): %s\n", source, strerror(errno)); remove_lock(raceI); exit(EXIT_FAILURE); } if ((outfd = open(target, O_CREAT | O_TRUNC | O_RDWR, 0666)) == -1) { d_log("copysfv: open(%s): %s\n", target, strerror(errno)); remove_lock(raceI); exit(EXIT_FAILURE); } video = music = rars = others = type = 0; dir = opendir("."); if (!update_lock(raceI, 1, 0)) { d_log("copysfv: Lock is suggested removed. Will comply and exit\n"); remove_lock(raceI); exit(EXIT_FAILURE); } if ((insfv = fdopen(infd, "r")) == NULL) { d_log("copysfv: Unable to fdopen %s: %s\n", source, strerror(errno)); remove_lock(raceI); exit(EXIT_FAILURE); } while ((fgets(fbuf, sizeof(fbuf), insfv))) { /* remove comment */ if ((ptr = find_first_of(fbuf, ";"))) *ptr = '\0'; tailstrip_chars(fbuf, WHITESPACE_STR); ptr = prestrip_chars(fbuf, WHITESPACE_STR); if (ptr != fbuf) d_log("copysfv: prestripped whitespaces (%d chars)\n", ptr - fbuf); if (strlen(ptr) == 0) continue; #if (sfv_cleanup_lowercase == TRUE) for (; *ptr; ptr++) *ptr = tolower(*ptr); #endif sd.crc32 = 0; bzero(sd.fname, sizeof(sd.fname)); if ((ptr = find_last_of(fbuf, " \t"))) { /* pass the " \t" */ ptr++; /* what we have now is hopefully a crc */ for (i = 0; isxdigit(*ptr) != 0; i++) ptr++; ptr -= i; if (i > 8 || i < 6) { /* we didn't get an 8 digit crc number */ #if (sfv_cleanup == TRUE) /* do stuff */ d_log("copysfv: We did not get a 8 digit crc number for %s - trying to continue anyway\n", sd.fname); #else retval = 1; goto END; #endif } else { sd.crc32 = hexstrtodec(ptr); /* cut off crc string */ *ptr = '\0'; /* nobody should be stupid enough to have spaces * at the end of the file name */ tailstrip_chars(fbuf, WHITESPACE_STR); } } else { /* we have a filename only. */ #if (sfv_cleanup == TRUE) /* do stuff */ d_log("copysfv: We did not find a crc number for %s - trying to continue anyway\n", sd.fname); #else retval = 1; goto END; #endif } /* we assume what's left is a filename */ ptr = prestrip_chars(fbuf, WHITESPACE_STR); if (ptr != fbuf) d_log("copysfv: prestripped whitespaces (%d chars)\n", ptr - fbuf); #if (allow_slash_in_sfv == TRUE) if (ptr != find_last_of(ptr, "/")) { ptr = find_last_of(ptr, "/") + 1; d_log("copysfv: found '/' in filename - adjusting.\n"); } if (ptr != find_last_of(ptr, "\\")) { ptr = find_last_of(ptr, "\\") + 1; d_log("copysfv: found '\\' in filename - adjusting.\n"); } #endif if (strlen(ptr) > 0 && strlen(ptr) < NAME_MAX-9 ) { strlcpy(sd.fname, ptr, NAME_MAX-9); if (sd.fname != find_last_of(sd.fname, "\t") || sd.fname != find_last_of(sd.fname, "\\") || sd.fname != find_last_of(sd.fname, "/")) { d_log("copysfv: found '/', '\\' or <TAB> as part of filename in sfv - logging file as bad.\n"); retval = 1; break; } if (sd.crc32 == 0) { #if (sfv_calc_single_fname == TRUE || create_missing_sfv == TRUE) sd.crc32 = match_lenient(dir, sd.fname); d_log("copysfv: Got filename (%s) without crc, calculated to %X.\n", sd.fname, sd.crc32); #else d_log("copysfv: Got filename (%s) without crc - ignoring file.\n", sd.fname); continue; #endif } /* get file extension */ ptr = find_last_of(fbuf, "."); if (*ptr == '.') ptr++; if (!strcomp(ignored_types, ptr) && !(strcomp(allowed_types, ptr) && !matchpath(allowed_types_exemption_dirs, raceI->misc.current_path)) && !strcomp("sfv", ptr) && !strcomp("nfo", ptr)) { skip = 0; //#if ( sfv_dupecheck == TRUE ) /* read from sfvdata - no parsing */ lseek(outfd, 0L, SEEK_SET); while (read(outfd, &tempsd, sizeof(SFVDATA))) // if (!strcmp(sd.fname, tempsd.fname) || (sd.crc32 == tempsd.crc32 && sd.crc32)) if (!strcmp(sd.fname, tempsd.fname)) skip = 1; lseek(outfd, 0L, SEEK_END); #if ( sfv_dupecheck == TRUE ) if (skip) continue; #endif d_log("copysfv: File in sfv: '%s' (%x)\n", sd.fname, sd.crc32); #if ( sfv_cleanup == TRUE ) /* write good stuff to .tmpsfv */ if (tmpfd != -1) { sprintf(crctmp, "%.8x", sd.crc32); if (write(tmpfd, sd.fname, strlen(sd.fname)) != (int)strlen(sd.fname)) d_log("copysfv: write failed: %s\n", strerror(errno)); if (write(tmpfd, " ", 1) != 1) d_log("copysfv: write failed: %s\n", strerror(errno)); if (write(tmpfd, crctmp, 8) != 8) d_log("copysfv: write failed: %s\n", strerror(errno)); #if (sfv_cleanup_crlf == TRUE ) if (write(tmpfd, "\r", 1) != 1) d_log("copysfv: write failed: %s\n", strerror(errno)); #endif if (write(tmpfd, "\n", 1) != 1) d_log("copysfv: write failed: %s\n", strerror(errno)); } #endif if (strcomp(audio_types, ptr)) music++; else if (israr(ptr)) rars++; else if (strcomp(video_types, ptr)) video++; else others++; #if ( create_missing_files == TRUE ) if (!findfile(dir, sd.fname) && !(matchpath(allowed_types_exemption_dirs, raceI->misc.current_path) && strcomp(allowed_types, ptr))) create_missing(sd.fname, raceI); #endif if (write(outfd, &sd, sizeof(SFVDATA)) != sizeof(SFVDATA)) d_log("copysfv: write failed: %s\n", strerror(errno)); } } } if (music > rars) { if (video > music) type = (video >= others ? 4 : 2); else type = (music >= others ? 3 : 2); } else { if (video > rars) type = (video >= others ? 4 : 2); else type = (rars >= others ? 1 : 2); } #if ( sfv_cleanup == FALSE ) END: #endif close(infd); #if ( sfv_cleanup == TRUE ) if (tmpfd != -1) { close(tmpfd); unlink(source); rename(".tmpsfv", source); #ifdef USING_EBFTPD if (ebftpd_chown(source, raceI->user.uid, raceI->user.gid) < 0) d_log("copysfv: ebftpd_chown(%s,%i,%i): %s\n", source, raceI->user.uid, raceI->user.gid, strerror(errno)); #endif } #endif closedir(dir); close(outfd); if (!update_lock(raceI, 1, type)) { d_log("copysfv: Lock is suggested removed. Will comply and exit\n"); remove_lock(raceI); exit(EXIT_FAILURE); } raceI->data_type = type; return retval; }
/// @brief Responds to a List command MavlinkFTP::ErrorCode MavlinkFTP::_workList(PayloadHeader* payload) { char dirPath[kMaxDataLength]; strncpy(dirPath, _data_as_cstring(payload), kMaxDataLength); DIR *dp = opendir(dirPath); if (dp == nullptr) { warnx("FTP: can't open path '%s'", dirPath); return kErrFailErrno; } #ifdef MAVLINK_FTP_DEBUG warnx("FTP: list %s offset %d", dirPath, payload->offset); #endif ErrorCode errorCode = kErrNone; struct dirent entry, *result = nullptr; unsigned offset = 0; // move to the requested offset seekdir(dp, payload->offset); for (;;) { // read the directory entry if (readdir_r(dp, &entry, &result)) { warnx("FTP: list %s readdir_r failure\n", dirPath); errorCode = kErrFailErrno; break; } // no more entries? if (result == nullptr) { if (payload->offset != 0 && offset == 0) { // User is requesting subsequent dir entries but there were none. This means the user asked // to seek past EOF. errorCode = kErrEOF; } // Otherwise we are just at the last directory entry, so we leave the errorCode at kErrorNone to signal that break; } uint32_t fileSize = 0; char buf[256]; char direntType; // Determine the directory entry type switch (entry.d_type) { case DTYPE_FILE: // For files we get the file size as well direntType = kDirentFile; snprintf(buf, sizeof(buf), "%s/%s", dirPath, entry.d_name); struct stat st; if (stat(buf, &st) == 0) { fileSize = st.st_size; } break; case DTYPE_DIRECTORY: if (strcmp(entry.d_name, ".") == 0 || strcmp(entry.d_name, "..") == 0) { // Don't bother sending these back continue; } direntType = kDirentDir; break; default: // We only send back file and diretory entries, skip everything else continue; } if (entry.d_type == DTYPE_FILE) { // Files send filename and file length snprintf(buf, sizeof(buf), "%s\t%d", entry.d_name, fileSize); } else { // Everything else just sends name strncpy(buf, entry.d_name, sizeof(buf)); buf[sizeof(buf)-1] = 0; } size_t nameLen = strlen(buf); // Do we have room for the name, the one char directory identifier and the null terminator? if ((offset + nameLen + 2) > kMaxDataLength) { break; } // Move the data into the buffer payload->data[offset++] = direntType; strcpy((char *)&payload->data[offset], buf); #ifdef MAVLINK_FTP_DEBUG printf("FTP: list %s %s\n", dirPath, (char *)&payload->data[offset-1]); #endif offset += nameLen + 1; } closedir(dp); payload->size = offset; return errorCode; }
int searcher(char *path, int n_bytes) { DIR *d; int ok; int n=0; char path_new[2048]; char buffer[1024]; //char* buffer = (char*)malloc(1024); int fd, nr; ok = stat(path, &s); // busco el status del path if (ok < 0){ exit(EXIT_FAILURE); } if((s.st_mode & S_IFMT) == S_IFDIR){ // compruebo si es un directorio d = opendir(path); if(d == NULL) exit(EXIT_FAILURE); for(;;) { reg_dir=readdir(d); if (reg_dir == NULL) break; if (reg_dir->d_name[0] == '.'){ // paso de los directorios raiz continue; }else{ memset(path_new, 0, 2048); strcat(path_new, path); strcat(path_new, "/"); strcat(path_new, reg_dir->d_name); ok=stat(path_new, &s); // compruebo el path construido if(ok<0) exit(EXIT_FAILURE); if((s.st_mode & S_IFMT) == S_IFDIR){ // si me encuentro otro directorio lo hago recursivo n = n + searcher(path_new, n_bytes); }else if((s.st_mode & S_IFMT) == S_IFREG){ // si es un fichero compruebo si es un txt if(ok_txt(path_new)){ // aqui miro para imprimir los bytes fd = open(path_new, O_RDONLY); if (fd < 0){ fprintf(stderr, "%s %s\n", "Fallo al abrir el fichero: ", path_new); } if (n_bytes != 0) lseek(fd, -n_bytes, SEEK_END); nr = read(fd, buffer, sizeof buffer); if(nr < 0){ fprintf(stderr, "%s %s\n", "Fallo al leer el fichero: ", path_new); } write(1, buffer, nr); printf("\n"); close(fd); n++; } } } } } return n; }
//---------------------------------------------------------- int ofxDirList::listDir(string directory){ directory = ofToDataPath(directory); nameArray.clear(); pathArray.clear(); if(directory.length() <= 0)return 0; //if the trailing slash was not added - then add it if( directory[directory.length()-1] != '/'){ directory = directory + "/"; } DIR *dir = NULL; struct dirent *entry; //open the directory ofLog(OF_LOG_VERBOSE, "ofxDirList - attempting to open %s", directory.c_str()); dir = opendir(directory.c_str()); if(dir == NULL){ ofLog(OF_LOG_ERROR, "ofxDirList - error opening directory"); return 0; }else{ ofLog(OF_LOG_VERBOSE, "ofxDirList - success opening directory"); } string entry_name = ""; string ext = ""; bool skip = false; while ((entry = readdir(dir)) != NULL){ //turn it into a C++ string entry_name = entry->d_name; //lets get the length of the string here as we query it again int fileLen = entry_name.length(); if(fileLen <= 0)continue; //if the name is not existant if(entry_name[0] == '.')continue; //ignore invisible files, ./ and ../ //by default we don't skip files unless we are checking extensions skip = false; if(allowedFileExt.size() > 0){ //we will skip this files unless it has an allowed extension skip = true; for(int i = 0; i < (int)allowedFileExt.size(); i++){ //if the wildecard * has been entered for an ext type then don't check any extensions if( allowedFileExt[i] == "*"){ skip = false; break; } int extLen = allowedFileExt[i].length(); //the extension has to be shorter than the filename - simple check if(extLen >= fileLen) continue; //lets get the ext as lowercase ext = strToLower( getExt(entry_name) ); //if no ext - then skip this ext check if( ext == "" )continue; //if we find a match then stop checking and approve this file if(ext == allowedFileExt[i]){ skip = false; break; } } } if(skip) continue; //finally we store the result pathArray.push_back(directory + entry_name); nameArray.push_back(entry_name); // ofLog(OF_LOG_VERBOSE, "ofxDirList - listing %s ", nameArray.back().c_str()); } if(dir != NULL) closedir(dir); // ofLog(OF_LOG_VERBOSE, "ofxDirList - listed %i files in %s", nameArray.size(), directory.c_str()); return nameArray.size(); }
main(int argc, char *argv[]){ int sockfd; char buffer[BUFSIZE+1]; int bytereceive = 0; struct sockaddr_in serv_addr; char createname[20]; char deletename[20]; static struct sigaction act; void catchin(int); act.sa_handler = catchin; sigfillset(&(act.sa_mask)); sigaction(SIGINT, &act, (void *) 0); if(argc <= 1){ printf("How to use : %s remoteIPaddress [example: ./client 127.0.0.1]\n", argv[0]); exit(1); } bzero( (char*) &serv_addr, sizeof(serv_addr) ); serv_addr.sin_family = AF_INET ; serv_addr.sin_port = htons (SERV_TCP_PORT); inet_pton (AF_INET, argv[1], &serv_addr.sin_addr); if( (sockfd = socket(AF_INET, SOCK_STREAM, 0) ) < 0) { perror("Client: socket() error \n"); exit(1); } if(connect (sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) <0 ) { perror("Client: connect() error\n"); exit(1);} /* Get the user name */ char *buf; buf=(char *)malloc(10*sizeof(char)); buf=getlogin(); /* set the 'client_file' path */ char str[30]; strcpy(str, "/home/"); strcat(str, buf); strcat(str, "/client_file/"); /* Check the path exist or not, if not, create one */ struct stat s; if(stat(str, &s) == -1){ mkdir(str, 0700); } do{ bzero( buffer, sizeof(buffer)); recv(sockfd, buffer, BUFSIZE, 0); printf("\n%s\n", buffer); gets(buffer); send(sockfd,buffer, BUFSIZE, 0); if(!strcmp(buffer, "1")) { bzero( buffer, sizeof(buffer)); recv(sockfd, buffer, BUFSIZE, 0); printf("\n%s\n", buffer); gets(buffer); send(sockfd,buffer, BUFSIZE, 0); char filename[30]; strcpy(filename, "/home/"); strcat(filename, buf); strcat(filename, "/client_file/"); strcat(filename, buffer); FILE *fp; fp = fopen(filename, "ab"); if(NULL == fp) { printf("Error opening file"); } bzero( buffer, sizeof(buffer)); bytereceive = recv(sockfd, buffer, BUFSIZE, 0); fwrite(buffer,1,bytereceive,fp); } else if(!strcmp(buffer, "2")) { DIR *dir; struct dirent *ent; char directoryName[30]; strcpy(directoryName, "/home/"); strcat(directoryName, buf); strcat(directoryName, "/client_file/"); if ((dir = opendir (directoryName)) != NULL) { printf("\n[List of files in Client Directory]\n"); // print all the files and directories within directory while ((ent = readdir (dir)) != NULL) { printf("%s\n", ent->d_name); } closedir (dir); } printf("\nPlease enter one of the filename from above including extension\n"); bzero( buffer, sizeof(buffer)); gets(buffer); send(sockfd,buffer, BUFSIZE, 0); char filename[30]; strcpy(filename, "/home/"); strcat(filename, buf); strcat(filename, "/client_file/"); strcat(filename, buffer); FILE *fp; fp = fopen(filename, "r"); bzero( buffer, sizeof(buffer)); int nread = fread(buffer,1,256,fp); send(sockfd, buffer, nread, 0); } else if(!strcmp(buffer, "3")) { printf("Enter directory name that you want to create: "); scanf("%s", createname); /* set the path/name of the directory that want to create */ char createDirectory[30]; strcpy(createDirectory, "/home/"); strcat(createDirectory, buf); strcat(createDirectory, "/"); strcat(createDirectory, createname); /* Check the path exist or not, if not, create one */ struct stat s; if(stat(createDirectory, &s) == -1){ mkdir(createDirectory, 0700); } } else if(!strcmp(buffer, "4")) { printf("Enter directory name that you want to delete: "); scanf("%s", deletename); /* set the path of the directory that want to delete */ char deleteDirectory[30]; strcpy(deleteDirectory, "/home/"); strcat(deleteDirectory, buf); strcat(deleteDirectory, "/"); strcat(deleteDirectory, deletename); /* select all the files inside the directory that want to delete */ char selectSubDirectory[50]; strcpy(selectSubDirectory, "exec rm -r "); strcat(selectSubDirectory, "/home/"); strcat(selectSubDirectory, buf); strcat(selectSubDirectory, "/"); strcat(selectSubDirectory, deletename); strcat(selectSubDirectory, "/*"); /* Check the path exist or not, if exist, delete it */ struct stat s; if(stat(deleteDirectory, &s) != -1){ system(selectSubDirectory); rmdir(deleteDirectory); } } }while (strcmp(buffer, "/q")); close(sockfd); }
static void BroadcastSetThreadSandbox(SandboxType aType) { int signum; pid_t pid, tid, myTid; DIR *taskdp; struct dirent *de; SandboxFilter filter(&sSetSandboxFilter, aType, getenv("MOZ_SANDBOX_VERBOSE")); static_assert(sizeof(mozilla::Atomic<int>) == sizeof(int), "mozilla::Atomic<int> isn't represented by an int"); pid = getpid(); myTid = syscall(__NR_gettid); taskdp = opendir("/proc/self/task"); if (taskdp == nullptr) { SANDBOX_LOG_ERROR("opendir /proc/self/task: %s\n", strerror(errno)); MOZ_CRASH(); } signum = FindFreeSignalNumber(); if (signum == 0) { SANDBOX_LOG_ERROR("No available signal numbers!"); MOZ_CRASH(); } void (*oldHandler)(int); oldHandler = signal(signum, SetThreadSandboxHandler); if (oldHandler != SIG_DFL) { // See the comment on FindFreeSignalNumber about race conditions. SANDBOX_LOG_ERROR("signal %d in use by handler %p!\n", signum, oldHandler); MOZ_CRASH(); } // In case this races with a not-yet-deprivileged thread cloning // itself, repeat iterating over all threads until we find none // that are still privileged. bool sandboxProgress; do { sandboxProgress = false; // For each thread... while ((de = readdir(taskdp))) { char *endptr; tid = strtol(de->d_name, &endptr, 10); if (*endptr != '\0' || tid <= 0) { // Not a task ID. continue; } if (tid == myTid) { // Drop this thread's privileges last, below, so we can // continue to signal other threads. continue; } // Reset the futex cell and signal. sSetSandboxDone = 0; if (syscall(__NR_tgkill, pid, tid, signum) != 0) { if (errno == ESRCH) { SANDBOX_LOG_ERROR("Thread %d unexpectedly exited.", tid); // Rescan threads, in case it forked before exiting. sandboxProgress = true; continue; } SANDBOX_LOG_ERROR("tgkill(%d,%d): %s\n", pid, tid, strerror(errno)); MOZ_CRASH(); } // It's unlikely, but if the thread somehow manages to exit // after receiving the signal but before entering the signal // handler, we need to avoid blocking forever. // // Using futex directly lets the signal handler send the wakeup // from an async signal handler (pthread mutex/condvar calls // aren't allowed), and to use a relative timeout that isn't // affected by changes to the system clock (not possible with // POSIX semaphores). // // If a thread doesn't respond within a reasonable amount of // time, but still exists, we crash -- the alternative is either // blocking forever or silently losing security, and it // shouldn't actually happen. static const int crashDelay = 10; // seconds struct timespec timeLimit; clock_gettime(CLOCK_MONOTONIC, &timeLimit); timeLimit.tv_sec += crashDelay; while (true) { static const struct timespec futexTimeout = { 0, 10*1000*1000 }; // 10ms // Atomically: if sSetSandboxDone == 0, then sleep. if (syscall(__NR_futex, reinterpret_cast<int*>(&sSetSandboxDone), FUTEX_WAIT, 0, &futexTimeout) != 0) { if (errno != EWOULDBLOCK && errno != ETIMEDOUT && errno != EINTR) { SANDBOX_LOG_ERROR("FUTEX_WAIT: %s\n", strerror(errno)); MOZ_CRASH(); } } // Did the handler finish? if (sSetSandboxDone > 0) { if (sSetSandboxDone == 2) { sandboxProgress = true; } break; } // Has the thread ceased to exist? if (syscall(__NR_tgkill, pid, tid, 0) != 0) { if (errno == ESRCH) { SANDBOX_LOG_ERROR("Thread %d unexpectedly exited.", tid); } // Rescan threads, in case it forked before exiting. // Also, if it somehow failed in a way that wasn't ESRCH, // and still exists, that will be handled on the next pass. sandboxProgress = true; break; } struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); if (now.tv_sec > timeLimit.tv_nsec || (now.tv_sec == timeLimit.tv_nsec && now.tv_nsec > timeLimit.tv_nsec)) { SANDBOX_LOG_ERROR("Thread %d unresponsive for %d seconds." " Killing process.", tid, crashDelay); MOZ_CRASH(); } } } rewinddir(taskdp); } while (sandboxProgress); oldHandler = signal(signum, SIG_DFL); if (oldHandler != SetThreadSandboxHandler) { // See the comment on FindFreeSignalNumber about race conditions. SANDBOX_LOG_ERROR("handler for signal %d was changed to %p!", signum, oldHandler); MOZ_CRASH(); } unused << closedir(taskdp); // And now, deprivilege the main thread: SetThreadSandbox(); }
int btFiles::_btf_recurses_directory(const char *cur_path, BTFILE* lastnode) { char full_cur[MAXPATHLEN]; char fn[MAXPATHLEN]; struct stat sb; struct dirent *dirp; DIR *dp; BTFILE *pbf; #if HAVE_GETCWD if( !getcwd(full_cur,MAXPATHLEN) ) return -1; #else if( !getwd(full_cur) ) return -1; #endif if( cur_path ){ strcpy(fn, full_cur); if( MAXPATHLEN <= snprintf(full_cur, MAXPATHLEN, "%s%c%s", fn, PATH_SP, cur_path)) return -1; } if( (DIR*) 0 == (dp = opendir(full_cur))){ fprintf(stderr,"error, open directory %s failed, %s\n",cur_path,strerror(errno)); return -1; } while( (struct dirent*) 0 != (dirp = readdir(dp)) ){ if( 0 == strcmp(dirp->d_name, ".") || 0 == strcmp(dirp->d_name, "..") ) continue; if( cur_path ){ if(MAXPATHLEN < snprintf(fn, MAXPATHLEN, "%s%c%s", cur_path, PATH_SP, dirp->d_name)){ fprintf(stderr,"error, pathname too long\n"); return -1; } }else{ strcpy(fn, dirp->d_name); } if( stat(fn, &sb) < 0 ){ fprintf(stderr,"error, stat %s failed, %s\n",fn,strerror(errno)); return -1; } if( S_IFREG & sb.st_mode ){ pbf = _new_bfnode(); #ifndef WINDOWS if( !pbf ) return -1; #endif pbf->bf_filename = new char[strlen(fn) + 1]; #ifndef WINDOWS if( !pbf->bf_filename ){ closedir(dp); return -1;} #endif strcpy(pbf->bf_filename, fn); pbf->bf_length = sb.st_size; m_total_files_length += sb.st_size; if( lastnode ) lastnode->bf_next = pbf; else m_btfhead = pbf; lastnode = pbf; }else if( S_IFDIR & sb.st_mode ){ if(_btf_recurses_directory(fn, lastnode) < 0){closedir(dp); return -1;} }else{ fprintf(stderr,"error, %s is not a directory or regular file.\n",fn); closedir(dp); return -1; } } // end while closedir(dp); return 0; }
/* load and sort directory into dircache. returns NULL on failure. */ int ft_load(struct tree_context* c, const char* tempdir) { int i; int name_buffer_used = 0; bool (*callback_show_item)(char *, int, struct tree_context *) = NULL; DIR *dir; if (tempdir) dir = opendir(tempdir); else { dir = opendir(c->currdir); callback_show_item = c->browse? c->browse->callback_show_item: NULL; } if(!dir) return -1; /* not a directory */ c->dirsindir = 0; c->dirfull = false; for ( i=0; i < global_settings.max_files_in_dir; i++ ) { int len; struct dirent *entry = readdir(dir); struct dirinfo info; struct entry* dptr = (struct entry*)(c->dircache + i * sizeof(struct entry)); if (!entry) break; info = dir_get_info(dir, entry); len = strlen((char *)entry->d_name); /* skip directories . and .. */ if ((info.attribute & ATTR_DIRECTORY) && (((len == 1) && (!strncmp((char *)entry->d_name, ".", 1))) || ((len == 2) && (!strncmp((char *)entry->d_name, "..", 2))))) { i--; continue; } /* Skip FAT volume ID */ if (info.attribute & ATTR_VOLUME_ID) { i--; continue; } /* filter out dotfiles and hidden files */ if (*c->dirfilter != SHOW_ALL && ((entry->d_name[0]=='.') || (info.attribute & ATTR_HIDDEN))) { i--; continue; } dptr->attr = info.attribute; /* check for known file types */ if ( !(dptr->attr & ATTR_DIRECTORY) ) dptr->attr |= filetype_get_attr((char *)entry->d_name); /* filter out non-visible files */ if ((!(dptr->attr & ATTR_DIRECTORY) && ( (*c->dirfilter == SHOW_PLAYLIST && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_M3U) || ((*c->dirfilter == SHOW_MUSIC && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_AUDIO) && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_M3U) || (*c->dirfilter == SHOW_SUPPORTED && !filetype_supported(dptr->attr)))) || (*c->dirfilter == SHOW_WPS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_WPS) || #ifdef HAVE_LCD_BITMAP (*c->dirfilter == SHOW_FONT && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_FONT) || (*c->dirfilter == SHOW_SBS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_SBS) || #if CONFIG_TUNER (*c->dirfilter == SHOW_FMS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_FMS) || #endif #endif #ifdef HAVE_REMOTE_LCD (*c->dirfilter == SHOW_RWPS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_RWPS) || (*c->dirfilter == SHOW_RSBS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_RSBS) || #if CONFIG_TUNER (*c->dirfilter == SHOW_RFMS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_RFMS) || #endif #endif #if CONFIG_TUNER (*c->dirfilter == SHOW_FMR && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_FMR) || #endif (*c->dirfilter == SHOW_M3U && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_M3U) || (*c->dirfilter == SHOW_CFG && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_CFG) || (*c->dirfilter == SHOW_LNG && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_LNG) || (*c->dirfilter == SHOW_MOD && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_MOD) || (*c->dirfilter == SHOW_PLUGINS && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_ROCK && (dptr->attr & FILE_ATTR_MASK) != FILE_ATTR_LUA) || (callback_show_item && !callback_show_item(entry->d_name, dptr->attr, c))) { i--; continue; } if (len > c->name_buffer_size - name_buffer_used - 1) { /* Tell the world that we ran out of buffer space */ c->dirfull = true; break; } dptr->name = &c->name_buffer[name_buffer_used]; dptr->time_write = (long)info.wrtdate<<16 | (long)info.wrttime; /* in one # */ strcpy(dptr->name, (char *)entry->d_name); name_buffer_used += len + 1; if (dptr->attr & ATTR_DIRECTORY) /* count the remaining dirs */ c->dirsindir++; } c->filesindir = i; c->dirlength = i; closedir(dir); compare_sort_dir = c->sort_dir; qsort(c->dircache,i,sizeof(struct entry),compare); /* If thumbnail talking is enabled, make an extra run to mark files with associated thumbnails, so we don't do unsuccessful spinups later. */ if (global_settings.talk_file_clip) check_file_thumbnails(c); /* map .talk to ours */ return 0; }
static int record_event_files(struct tracepoint_path *tps) { struct dirent *dent; struct stat st; char *path; char *sys; DIR *dir; int count = 0; int ret; int err; path = get_tracing_file("events"); if (!path) { pr_debug("can't get tracing/events"); return -ENOMEM; } dir = opendir(path); if (!dir) { err = -errno; pr_debug("can't read directory '%s'", path); goto out; } while ((dent = readdir(dir))) { if (dent->d_type != DT_DIR || strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0 || strcmp(dent->d_name, "ftrace") == 0 || !system_in_tp_list(dent->d_name, tps)) continue; count++; } if (write(output_fd, &count, 4) != 4) { err = -EIO; pr_debug("can't write count\n"); goto out; } rewinddir(dir); while ((dent = readdir(dir))) { if (dent->d_type != DT_DIR || strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0 || strcmp(dent->d_name, "ftrace") == 0 || !system_in_tp_list(dent->d_name, tps)) continue; sys = malloc(strlen(path) + strlen(dent->d_name) + 2); if (!sys) { err = -ENOMEM; goto out; } sprintf(sys, "%s/%s", path, dent->d_name); ret = stat(sys, &st); if (ret >= 0) { ssize_t size = strlen(dent->d_name) + 1; if (write(output_fd, dent->d_name, size) != size || copy_event_system(sys, tps) < 0) { err = -EIO; free(sys); goto out; } } free(sys); } err = 0; out: closedir(dir); put_tracing_file(path); return err; }
int create_tmpdir ( int tracing ) { int fixedname = is_ipa && ( ld_ipa_opt[LD_IPA_KEEP_TEMPS].flag ); if (tmpdir) { return 0; } if ( is_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, "/"); if ((filename = strrchr(outfilename, '/')) != 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; #ifndef __sun struct direct *entryp; #else struct dirent *entryp; #endif 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: */ #ifdef _D_EXACT_NAMLEN if (_D_EXACT_NAMLEN(entryp) > 2) #elif defined(__sun) if ( entryp->d_reclen > 2 ) #else if ( entryp->d_namlen > 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 */
void filebrowser_open_cb (void *data1, void *data2) { DIR *dp; BrowserData *mod_data; struct dirent **namelist; char orig_wd[512] = { 0 }; regex_t re; int n, i = 0; char *current_path = NULL, *current_path_stripped = NULL; MBDesktopItem *subfolder = NULL; MBDesktopItem *item_new = NULL; MBDesktop *mb = (MBDesktop *)data1; MBDesktopItem *item_folder = (MBDesktopItem *)data2; Bool is_subfolder = False; mod_data = (BrowserData*)mbdesktop_item_get_user_data (mb, item_folder); if (!strcmp(mbdesktop_item_get_name(mb, item_folder), mod_data->BrowserFolderName)) { /* Is top level */ current_path = strdup(mod_data->BrowserPath); current_path_stripped = strdup(""); } else { /* Is sub folder */ /* Figure out the 'real' directory path from name etc */ char *base_path = mbdesktop_item_get_extended_name(mb, item_folder) + (strlen(mod_data->BrowserFolderName) +1) ; int len = strlen(mod_data->BrowserPath) + strlen(mbdesktop_item_get_extended_name(mb, item_folder)) + strlen(mod_data->BrowserFolderName); current_path = malloc(sizeof(char)*len); current_path_stripped = malloc(sizeof(char)*(strlen(base_path)+3)); snprintf(current_path, len, "%s/%s", mod_data->BrowserPath, base_path); sprintf(current_path_stripped, "%s/", base_path); is_subfolder = True; } if (mbdesktop_item_folder_has_contents(mb, item_folder)) mbdesktop_item_folder_contents_free(mb, item_folder); if (regcomp(&re, mod_data->BrowserMatchStr, REG_EXTENDED|REG_ICASE|REG_NOSUB) != 0) { fprintf(stderr, "mbdesktop-filebrowser: failed to compile re: %s\n", mod_data->BrowserMatchStr); return; } if ((dp = opendir(current_path)) == NULL) { fprintf(stderr, "mbdesktop-filebrowser: failed to open %s\n", mod_data->BrowserPath); return; } if (getcwd(orig_wd, 255) == (char *)NULL) { fprintf(stderr, "mbdesktop-filebrowser: cant get current directory\n"); return; } chdir(current_path); n = scandir(".", &namelist, 0, alphasort); while (i < n && n > 0) { struct stat stat_buf; if (!strcmp(namelist[i]->d_name, "..") || !strcmp(namelist[i]->d_name, ".")) goto end; /* Check for directory */ if (stat(namelist[i]->d_name, &stat_buf) == 0 && S_ISDIR(stat_buf.st_mode)) { char *subfolderlongname = NULL; int l = strlen(mod_data->BrowserFolderName) + strlen(current_path) + strlen(namelist[i]->d_name); subfolderlongname = malloc(sizeof(char)*l); sprintf(subfolderlongname, "%s/%s%s", mod_data->BrowserFolderName, current_path_stripped, namelist[i]->d_name); subfolder = mbdesktop_module_folder_create (mb, namelist[i]->d_name, mod_data->BrowserFolderIcon); mbdesktop_item_set_extended_name (mb, subfolder, subfolderlongname); mbdesktop_item_set_user_data (mb, subfolder, (void *)mod_data); mbdesktop_items_append_to_folder (mb, item_folder, subfolder); mbdesktop_item_folder_set_view (mb, subfolder, VIEW_LIST); mbdesktop_item_set_activate_callback (mb, subfolder, filebrowser_open_cb); free(subfolderlongname); goto end; } if (regexec(&re, namelist[i]->d_name, 0, NULL, REG_NOTBOL) == 0) { item_new = mbdesktop_item_new_with_params( mb, namelist[i]->d_name, mod_data->BrowserIcon, NULL, ITEM_TYPE_MODULE_ITEM ); mbdesktop_item_set_user_data (mb, item_new, (void *)mod_data); mbdesktop_item_set_extended_name (mb, item_new, current_path); mbdesktop_item_set_activate_callback (mb, item_new, filebrowser_file_activate_cb); mbdesktop_items_append_to_folder( mb, item_folder, item_new ); } end: free(namelist[i]); ++i; } regfree(&re); free(namelist); closedir(dp); chdir(orig_wd); free(current_path); mbdesktop_item_folder_activate_cb(data1, data2); }
char * search_lib_dir(char *dir, char *name, int *majorp, int *minorp, int do_dot_a) { size_t namelen; DIR *dd; struct dirent *dp; int best_dewey[MAXDEWEY]; int best_ndewey; char dot_a_name[MAXNAMLEN+1]; char dot_so_name[MAXNAMLEN+1]; if((dd = opendir(dir)) == NULL) return NULL; namelen = strlen(name); best_ndewey = 0; dot_a_name[0] = '\0'; dot_so_name[0] = '\0'; while((dp = readdir(dd)) != NULL) { char *extension; if(strlen(dp->d_name) < 3 + namelen + 2 || /* lib+xxx+.a */ strncmp(dp->d_name, "lib", 3) != 0 || strncmp(dp->d_name + 3, name, namelen) != 0 || dp->d_name[3+namelen] != '.') continue; extension = dp->d_name + 3 + namelen + 1; /* a or so.* */ if(strncmp(extension, "so.", 3) == 0) { int cur_dewey[MAXDEWEY]; int cur_ndewey; cur_ndewey = getdewey(cur_dewey, extension+3); if(cur_ndewey < 2) /* Too few version numbers */ continue; if(*majorp != -1) { /* Need exact match on major */ if(cur_dewey[0] != *majorp) continue; if(*minorp != -1) { /* Need minor >= minimum */ if(cur_dewey[1] < *minorp) continue; } } if(cmpndewey(cur_dewey, cur_ndewey, best_dewey, best_ndewey) <= 0) /* No better than prior match */ continue; /* We found a better match */ strcpy(dot_so_name, dp->d_name); bcopy(cur_dewey, best_dewey, cur_ndewey * sizeof best_dewey[0]); best_ndewey = cur_ndewey; } else if(do_dot_a && strcmp(extension, "a") == 0) strcpy(dot_a_name, dp->d_name); } closedir(dd); if(dot_so_name[0] != '\0') { *majorp = best_dewey[0]; *minorp = best_dewey[1]; return concat(dir, "/", dot_so_name); } if(dot_a_name[0] != '\0') return concat(dir, "/", dot_a_name); return NULL; }
int getiflist(char **ifacelist, int showspeed) { uint32_t speed; char temp[64]; #if defined(__linux__) char interface[32]; FILE *fp; DIR *dp; struct dirent *di; char procline[512]; #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__FreeBSD_kernel__) struct ifaddrs *ifap, *ifa; #endif /* initialize list */ *ifacelist = malloc(sizeof(char)); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } *ifacelist[0] = '\0'; #if defined(__linux__) if ((fp=fopen(PROCNETDEV, "r"))!=NULL) { /* make list of interfaces */ while (fgets(procline, 512, fp)!=NULL) { sscanf(procline, "%63s", temp); if (strlen(temp)>0 && (isdigit(temp[(strlen(temp)-1)]) || temp[(strlen(temp)-1)]==':')) { sscanf(temp, "%31[^':']s", interface); *ifacelist = realloc(*ifacelist, ( ( strlen(*ifacelist) + strlen(interface) + 2 ) * sizeof(char)) ); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } strncat(*ifacelist, interface, strlen(interface)); strcat(*ifacelist, " "); if (!showspeed) { continue; } speed = getifspeed(interface); if (speed > 0) { snprintf(temp, 64, "(%u Mbit) ", speed); *ifacelist = realloc(*ifacelist, ( ( strlen(*ifacelist) + strlen(temp) + 1 ) * sizeof(char)) ); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } strncat(*ifacelist, temp, strlen(temp)); } } } fclose(fp); return 1; } else { if ((dp=opendir(SYSCLASSNET))!=NULL) { /* make list of interfaces */ while ((di=readdir(dp))) { if (di->d_name[0] == '.' || strlen(di->d_name) > 31) { continue; } *ifacelist = realloc(*ifacelist, ( ( strlen(*ifacelist) + strlen(di->d_name) + 2 ) * sizeof(char)) ); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } strncat(*ifacelist, di->d_name, strlen(di->d_name)); strcat(*ifacelist, " "); if (!showspeed) { continue; } speed = getifspeed(di->d_name); if (speed > 0) { snprintf(temp, 64, "(%u Mbit) ", speed); *ifacelist = realloc(*ifacelist, ( ( strlen(*ifacelist) + strlen(temp) + 1 ) * sizeof(char)) ); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } strncat(*ifacelist, temp, strlen(temp)); } } closedir(dp); return 1; } } #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__FreeBSD_kernel__) if (getifaddrs(&ifap) >= 0) { /* make list of interfaces */ for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family != AF_LINK || strlen(ifa->ifa_name) > 31) { continue; } *ifacelist = realloc(*ifacelist, ( ( strlen(*ifacelist) + strlen(ifa->ifa_name) + 2 ) * sizeof(char)) ); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } strncat(*ifacelist, ifa->ifa_name, strlen(ifa->ifa_name)); strcat(*ifacelist, " "); if (!showspeed) { continue; } speed = getifspeed(ifa->ifa_name); if (speed > 0) { snprintf(temp, 64, "(%u Mbit) ", speed); *ifacelist = realloc(*ifacelist, ( ( strlen(*ifacelist) + strlen(temp) + 1 ) * sizeof(char)) ); if (*ifacelist == NULL) { panicexit(__FILE__, __LINE__); } strncat(*ifacelist, temp, strlen(temp)); } } freeifaddrs(ifap); return 1; } #endif return 0; }
/* * check_zipfile - check rarfile for pw protection and strips zip for banned files, and extracts .nfo * psxc r2126 (v1) */ int check_zipfile(const char *dirname, const char *zipfile, int do_nfo) { int ret = 0; char path_buf[PATH_MAX], target[PATH_MAX]; #if (extract_nfo) char nfo_buf[NAME_MAX]; time_t t = 0; struct stat filestat; char *ext; #endif DIR *dir; struct dirent *dp; if (!(dir = opendir(dirname))) return 0; while ((dp = readdir(dir))) { sprintf(path_buf, "%s/%s", dirname, dp->d_name); #if (test_for_password) if (!ret) ret = check_rarfile(path_buf); #endif if (!strncasecmp("file_id.diz", dp->d_name, 11)) { // make lowercase sprintf(path_buf, "%s/%s", dirname, dp->d_name); rename(path_buf, "file_id.diz"); if (chmod("file_id.diz", 0644)) d_log("check_zipfile: Failed to chmod %s: %s\n", "file_id.diz", strerror(errno)); continue; } #if (zip_clean) if (filebanned_match(dp->d_name)) { d_log("check_zipfile: banned file detected: %s\n", dp->d_name); if (!fileexists(zip_bin)) d_log("check_zipfile: ERROR! Not able to remove banned file from zip - zip_bin (%s) does not exist!\n", zip_bin); else { sprintf(target, "%s -qqd \"%s\" \"%s\"", zip_bin, zipfile, dp->d_name); if (execute(target)) d_log("check_zipfile: Failed to remove banned (%s) file from zip.\n", dp->d_name); } continue; } #endif #if (extract_nfo) ext = find_last_of(dp->d_name, "."); if (*ext == '.') ext++; if (strcomp("nfo", ext)) { stat(path_buf, &filestat); if ((t && filestat.st_ctime < t) || !t) { strlcpy(nfo_buf, dp->d_name, NAME_MAX); t = filestat.st_ctime; continue; } } #endif } #if (extract_nfo) if (t) { if (!do_nfo) { sprintf(path_buf, "%s/%s", dirname, nfo_buf); strtolower(nfo_buf); rename(path_buf, nfo_buf); if (chmod(nfo_buf, 0644)) d_log("check_zipfile: Failed to chmod %s: %s\n", nfo_buf, strerror(errno)); d_log("check_zipfile: nfo extracted - %s\n", nfo_buf); } else d_log("check_zipfile: nfo NOT extracted - a nfo already exist in dir\n"); } #endif rewinddir(dir); while ((dp = readdir(dir))) { sprintf(path_buf, "%s/%s", dirname, dp->d_name); unlink(path_buf); } closedir(dir); rmdir(dirname); return ret; }
int runner_start (runner_t *runner) { int pi[3][2] = {{-1, -1}, {-1, -1}, {-1, -1}}; int xpi[2]; int ret = 0; int errno_priv = 0; int i = 0; sigset_t set; if (runner->runerr) { errno = runner->runerr; return -1; } GF_ASSERT (runner->argv[0]); /* set up a channel to child to communicate back * possible execve(2) failures */ ret = pipe(xpi); if (ret != -1) ret = fcntl (xpi[1], F_SETFD, FD_CLOEXEC); for (i = 0; i < 3; i++) { if (runner->chfd[i] != -2) continue; ret = pipe (pi[i]); if (ret != -1) { runner->chio[i] = fdopen (pi[i][i ? 0 : 1], i ? "r" : "w"); if (!runner->chio[i]) ret = -1; } } if (ret != -1) runner->chpid = fork (); switch (runner->chpid) { case -1: errno_priv = errno; close (xpi[0]); close (xpi[1]); for (i = 0; i < 3; i++) { close (pi[i][0]); close (pi[i][1]); } errno = errno_priv; return -1; case 0: for (i = 0; i < 3; i++) close (pi[i][i ? 0 : 1]); close (xpi[0]); ret = 0; for (i = 0; i < 3; i++) { if (ret == -1) break; switch (runner->chfd[i]) { case -1: /* no redir */ break; case -2: /* redir to pipe */ ret = dup2 (pi[i][i ? 1 : 0], i); break; default: /* redir to file */ ret = dup2 (runner->chfd[i], i); } } if (ret != -1 ) { DIR *d = NULL; struct dirent *de = NULL; char *e = NULL; d = opendir ("/proc/self/fd"); if (d) { while ((de = readdir (d))) { i = strtoul (de->d_name, &e, 10); if (*e == '\0' && i > 2 && i != dirfd (d) && i != xpi[1]) close (i); } closedir (d); } else ret = -1; struct rlimit rl; ret = getrlimit (RLIMIT_NOFILE, &rl); GF_ASSERT (ret == 0); for (i = 3; i < rl.rlim_cur; i++) { if (i != xpi[1]) close (i); } } if (ret != -1) { /* save child from inheriting our singal handling */ sigemptyset (&set); sigprocmask (SIG_SETMASK, &set, NULL); execvp (runner->argv[0], runner->argv); } ret = write (xpi[1], &errno, sizeof (errno)); _exit (1); } errno_priv = errno; for (i = 0; i < 3; i++) close (pi[i][i ? 1 : 0]); close (xpi[1]); if (ret == -1) { for (i = 0; i < 3; i++) { if (runner->chio[i]) { fclose (runner->chio[i]); runner->chio[i] = NULL; } } } else { ret = read (xpi[0], (char *)&errno_priv, sizeof (errno_priv)); close (xpi[0]); if (ret <= 0) return 0; GF_ASSERT (ret == sizeof (errno_priv)); } errno = errno_priv; return -1; }
/* * CMDmodules * Obtains a list of modules by looking at what files are present in the * module directory. */ static BAT * TBL_getdir(void) { BAT *b = BATnew(TYPE_void, TYPE_str, 100, TRANSIENT); int i = 0; char *mod_path; size_t extlen = strlen(MAL_EXT); size_t len; struct dirent *dent; DIR *dirp = NULL; if ( b == 0) return 0; BATseqbase(b,0); mod_path = GDKgetenv("monet_mod_path"); if (mod_path == NULL) return b; while (*mod_path == PATH_SEP) mod_path++; if (*mod_path == 0) return b; while (mod_path || dirp) { if (dirp == NULL) { char *cur_dir; char *p; size_t l; if ((p = strchr(mod_path, PATH_SEP)) != NULL) { l = p - mod_path; } else { l = strlen(mod_path); } cur_dir = GDKmalloc(l + 1); if ( cur_dir == NULL){ GDKsyserror("mdb.modules"MAL_MALLOC_FAIL); return b; } strncpy(cur_dir, mod_path, l); cur_dir[l] = 0; if ((mod_path = p) != NULL) { while (*mod_path == PATH_SEP) mod_path++; } dirp = opendir(cur_dir); GDKfree(cur_dir); if (dirp == NULL) continue; } if ((dent = readdir(dirp)) == NULL) { closedir(dirp); dirp = NULL; continue; } len = strlen(dent->d_name); if (len < extlen || strcmp(dent->d_name + len - extlen, MAL_EXT) != 0) continue; dent->d_name[len - extlen] = 0; BUNappend(b, dent->d_name, FALSE); i++; } return b; }