/* * helper function that searches for a specific block device and returns * it's busid * dev: <major>:<minor> of the device * busid: buffer in which the busid string will be returned * returns 0 for successful operation and -1 in case of an error. */ static int find_busid_in_sysfs(char *dev, char *busid) { DIR *blockdir, *diskdir; struct dirent *blockde, *diskde; int found = 0; char namebuffer[PATH_BUFFER_LENGTH]; char *blockend, *diskend = NULL, *partend; /* everything, including the other helper functions, works on the * same buffer area 'namebuffer'. The pointers blockend, diskend * and partend point to the end of the various names. * Example: * "/sys/block/dasda/dasda1/" * ^ blockend * ^ diskend * ^ partend */ strcpy(namebuffer,BLOCKPATH); blockdir = opendir(namebuffer); if (!blockdir) return -1; blockend = namebuffer + strlen(namebuffer); /* check each entry in /sys/block */ while ((blockde = readdir(blockdir))) { diskend = append_if_directory(namebuffer, blockend, blockde); if (!diskend) continue; found = check_directory(namebuffer, dev); if (found) break; diskdir = opendir(namebuffer); if (!diskdir) continue; /* check each entry in /sys/block/<disk name> */ while ((diskde = readdir(diskdir))) { partend = append_if_directory( namebuffer, diskend, diskde); if (!partend) continue; found = check_directory(namebuffer, dev); if (found) break; } closedir(diskdir); if (found) break; } closedir(blockdir); if (found) { *diskend = 0; /* remove partition directory from name */ return extract_busid(namebuffer, busid); } else return -1; }
static void mapper_set_playlist_dir(const char *path) { check_directory(path); playlist_dir = g_strdup(path); }
int main(int argc, char *argv[]) { struct hooks_t hooks; struct files_t files; //int c; /* TODO: Parse command line arguments */ parse_commandline(argc, argv); /* TODO: Initialize hooks and files lists */ TAILQ_INIT(&hooks); TAILQ_INIT(&files); /* TODO: Load hooks */ set_hooks(&hooks); // TODO: Continuously check directory and timestamps //while(true){ char *timestamp = timestamp_string(); check_directory(directory, &hooks, &files, recursive,(time_t) timestamp); sleep(1); //} return (EXIT_SUCCESS); }
int main(int argc, char* argv[]) { std::string errmsg; if (!mooon::utils::parse_arguments(argc, argv, &errmsg)) { fprintf(stderr, "%s\n", errmsg.c_str()); return false; } try { int ret = 0; if (mooon::sys::CUtils::is_file(mooon::argument::sqllog->c_value())) ret = check_file(mooon::argument::sqllog->c_value()); else ret = check_directory(mooon::argument::sqllog->c_value()); fprintf(stdout, "lines: %d\n", sg_lines); return ret; } catch (mooon::sys::CSyscallException& ex) { fprintf(stderr, "%s\n", ex.str().c_str()); exit(1); } }
char* InliningDatabase::index_file_name() { char* name = NEW_RESOURCE_ARRAY(char, 1024); if (!check_directory(directory())) return NULL; strcpy(name, directory()); strcat(name, "\\index.txt"); return name; }
krb5_boolean KRB5_LIB_FUNCTION krb5_kuserok (krb5_context context, krb5_principal principal, const char *luser) { char *buf; size_t buflen; struct passwd *pwd; krb5_error_code ret; krb5_boolean result = FALSE; krb5_boolean found_file = FALSE; #ifdef POSIX_GETPWNAM_R char pwbuf[2048]; struct passwd pw; if(getpwnam_r(luser, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) return FALSE; #else pwd = getpwnam (luser); #endif if (pwd == NULL) return FALSE; #define KLOGIN "/.k5login" buflen = strlen(pwd->pw_dir) + sizeof(KLOGIN) + 2; /* 2 for .d */ buf = malloc(buflen); if(buf == NULL) return FALSE; /* check user's ~/.k5login */ strlcpy(buf, pwd->pw_dir, buflen); strlcat(buf, KLOGIN, buflen); ret = check_one_file(context, buf, pwd, principal, &result); if(ret == 0 && result == TRUE) { free(buf); return TRUE; } if(ret != ENOENT) found_file = TRUE; strlcat(buf, ".d", buflen); ret = check_directory(context, buf, pwd, principal, &result); free(buf); if(ret == 0 && result == TRUE) return TRUE; if(ret != ENOENT && ret != ENOTDIR) found_file = TRUE; /* finally if no files exist, allow all principals matching <localuser>@<LOCALREALM> */ if(found_file == FALSE) return match_local_principals(context, principal, luser); return FALSE; }
//! //! Validate and initialize the Eucalyptus and hook directories to use. //! //! @param[in] euca_dir a string containing the Eucalyptus directory to use //! @param[in] hooks_dir a string containing the hook directory to use //! //! @return EUCA_OK if the operation is successful or proper error code. Known error //! code returned include EUCA_ERROR. //! int init_hooks(const char *euca_dir, const char *hooks_dir) { assert(euca_dir); assert(hooks_dir); euca_strncpy(euca_path, euca_dir, sizeof(euca_path)); if (check_directory(euca_path)) return (EUCA_ERROR); euca_strncpy(hooks_path, hooks_dir, sizeof(hooks_path)); if (check_directory(hooks_path)) return (EUCA_ERROR); LOGINFO("using hooks directory %s\n", hooks_path); initialized = TRUE; return (EUCA_OK); }
static void mapper_set_music_dir(const char *path) { check_directory(path); music_dir = strdup_chop_slash(path); music_dir_length = strlen(music_dir); }
int scInitConfig (void) { struct stat mystat; char config [BUFSIZE]; char * s; if (scConfigInit) { return 0; } if ((sc_sem = sem_alloc (1, "eucalyptus-storage-semaphore")) == NULL) { /* TODO: use this semaphore to fix the race */ logprintfl (EUCAERROR, "failed to create and initialize a semaphore\n"); return 1; } /* read in configuration */ char * home = getenv (EUCALYPTUS_ENV_VAR_NAME); if (!home) { home = strdup(""); /* root by default */ } snprintf(config, BUFSIZE, EUCALYPTUS_CONF_LOCATION, home); if (stat(config, &mystat)==0) { logprintfl (EUCAINFO, "SC is looking for configuration in %s\n", config); if (get_conf_var(config, INSTANCE_PATH, &s)>0){ sc_instance_path = strdup (s); free (s); } if (get_conf_var(config, CONFIG_NC_CACHE_SIZE, &s)>0){ cache_size_mb = atoll (s); cache_free_mb = cache_size_mb; free (s); } if (get_conf_var(config, CONFIG_NC_SWAP_SIZE, &s)>0){ swap_size_mb = atoll (s); free (s); } } snprintf(add_key_command_path, BUFSIZE, EUCALYPTUS_ADD_KEY, home, home, home); /* we need to have valid path */ if (check_directory(sc_instance_path)) { logprintfl (EUCAERROR, "ERROR: INSTANCE_PATH (%s) does not exist!\n", sc_instance_path); return(1); } if (euca_init_cert ()) { logprintfl (EUCAFATAL, "failed to find cryptographic certificates\n"); return 1; } snprintf (disk_convert_command_path, BUFSIZE, EUCALYPTUS_DISK_CONVERT, home, home); scConfigInit=1; return(0); }
int init_backing_store (const char * conf_instances_path, unsigned int conf_work_size_mb, unsigned int conf_cache_size_mb) { logprintfl (EUCAINFO, "initializing backing store...\n"); if (conf_instances_path == NULL) { logprintfl (EUCAERROR, "error: INSTANCE_PATH not specified\n"); return ERROR; } safe_strncpy (instances_path, conf_instances_path, sizeof (instances_path)); if (check_directory (instances_path)) { logprintfl (EUCAERROR, "error: INSTANCE_PATH (%s) does not exist!\n", instances_path); return ERROR; } char cache_path [MAX_PATH]; snprintf (cache_path, sizeof (cache_path), "%s/cache", instances_path); if (ensure_directories_exist (cache_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1) return ERROR; char work_path [MAX_PATH]; snprintf (work_path, sizeof (work_path), "%s/work", instances_path); if (ensure_directories_exist (work_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1) return ERROR; unsigned long long cache_limit_blocks = conf_cache_size_mb * 2048; // convert MB to blocks unsigned long long work_limit_blocks = conf_work_size_mb * 2048; if (work_limit_blocks==0) { // we take 0 as unlimited work_limit_blocks = ULLONG_MAX; } // by default we let blobstore pick the snapshot policy, which // will use device mapper if available, which is faster than copying blobstore_snapshot_t snapshot_policy = BLOBSTORE_SNAPSHOT_ANY; if (nc_state.disable_snapshots) { logprintfl (EUCAINFO, "if allocating storage, will avoid using snapshots\n"); snapshot_policy = BLOBSTORE_SNAPSHOT_NONE; } blobstore_set_error_function ( &bs_errors ); if (cache_limit_blocks) { cache_bs = blobstore_open (cache_path, cache_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_DIRECTORY, BLOBSTORE_REVOCATION_LRU, snapshot_policy); if (cache_bs==NULL) { logprintfl (EUCAERROR, "ERROR: failed to open/create cache blobstore: %s\n", blobstore_get_error_str(blobstore_get_error())); return ERROR; } } work_bs = blobstore_open (work_path, work_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_FILES, BLOBSTORE_REVOCATION_NONE, snapshot_policy); if (work_bs==NULL) { logprintfl (EUCAERROR, "ERROR: failed to open/create work blobstore: %s\n", blobstore_get_error_str(blobstore_get_error())); logprintfl (EUCAERROR, "ERROR: %s\n", blobstore_get_last_trace()); blobstore_close (cache_bs); return ERROR; } // set the initial value of the semaphore to the number of // disk-intensive operations that can run in parallel on this node if (nc_state.concurrent_disk_ops && (disk_sem = sem_alloc (nc_state.concurrent_disk_ops, "mutex")) == NULL) { logprintfl (EUCAERROR, "failed to create and initialize disk semaphore\n"); return ERROR; } return OK; }
char* InliningDatabase::compute_file_name(LookupKey* outer, LookupKey* inner, bool create_directories) { char* name = NEW_RESOURCE_ARRAY(char, 1024); // Outer key char* outer_klass_name = mangle_name(klass_string(outer->klass())); char* outer_selector_name = mangle_name(selector_string(outer->selector())); if (create_directories) { if (!check_directory(directory())) return NULL; } strcpy(name, directory()); strcat(name, "\\"); strcat(name, outer_klass_name); if (create_directories) { if (!check_directory(name)) return NULL; } strcat(name, "\\"); strcat(name, outer_selector_name); if (inner) { // Inner key char* inner_klass_name = mangle_name(klass_string(inner->klass())); char* inner_method_name = mangle_name(method_string(inner->method())); if (create_directories) { if (!check_directory(name)) return NULL; } strcat(name, "\\"); strcat(name, inner_klass_name); if (create_directories) { if (!check_directory(name)) return NULL; } strcat(name, "\\"); strcat(name, inner_method_name); } strcat(name, ".txt"); return name; }
/** Check the directory for new file events. * * Note: * If any directory entries are sub-directories and the recursive flag is set, * then this function recurses on the sub-directories. */ void check_directory(const char *path, struct hooks_t *hooks, struct files_t *files, bool recursive, const time_t timestamp) { //struct dirent **entries; struct dirent *entry; DIR *dp; char fullpath[PATH_MAX]; dp=opendir(path); if(dp == NULL){ fprintf(stderr,"Could not open directory: %s\n", path); return; } while((entry = readdir(dp)) != NULL){ if(streq(entry->d_name, ".") || streq(entry->d_name, "..")){ continue; } snprintf(fullpath, PATH_MAX, "%s/%s", path, entry->d_name); //printf("%s\n", fullpath); struct stat st; lstat(fullpath, &st); if(S_ISDIR(st.st_mode) && recursive){ printf("DIRECTORY: %s\n", entry->d_name); if(strcmp(entry->d_name,"..") != 0 && strcmp(entry->d_name, ".") != 0){ check_directory(fullpath, hooks, files, recursive, timestamp); } }else{ printf("\t%s\n", entry->d_name); printf("\t\t FILE\n"); if(search_files(files, fullpath) == NULL){ add_file(files, fullpath, st.st_mtime, timestamp); printf("CREATE EVENT"); //CREATE EVENT } else{ printf("We have a file match? WTF"); // compare mtime // check timestamp } //look at hooks and files //use n as count of files? } } closedir(dp); }
// This function is used to check the data directory path for safety. // We check that every sub-directory is owned by the 'system' user // and exists and is not a symlink. We also check that the full directory // path is properly owned by the user ID. static bool check_data_path(const char* data_path, uid_t uid) { // The path should be absolute. if (data_path[0] != '/') return false; // Look for all sub-paths, we do that by finding // directory separators in the input path and // checking each sub-path independently. for (int nn = 1; data_path[nn] != '\0'; nn++) { char subpath[PATH_MAX]; /* skip non-separator characters */ if (data_path[nn] != '/') continue; /* handle trailing separator case */ if (data_path[nn+1] == '\0') break; /* found a separator, check that data_path is not too long. */ if (nn >= (int)(sizeof subpath)) return false; /* reject any '..' subpath */ if (nn >= 3 && data_path[nn-3] == '/' && data_path[nn-2] == '.' && data_path[nn-1] == '.') { return false; } /* copy to 'subpath', then check ownership */ memcpy(subpath, data_path, nn); subpath[nn] = '\0'; if (!check_directory(subpath, AID_SYSTEM)) return false; } // All sub-paths were checked, now verify that the full data // directory is owned by the application uid. return check_directory(data_path, uid); }
void chk_bogohome(void) { if (!check_directory(bogohome)) { (void)fprintf(stderr, "%s: cannot find bogofilter directory.\n" "You must specify a directory on the command line, in the config file,\n" #ifndef __riscos__ "or by using the BOGOFILTER_DIR or HOME environment variables.\n" #else "or by ensuring that <Bogofilter$Dir> is set correctly.\n" #endif "Program aborting.\n", progname); exit(EX_ERROR); } }
bool initialize(void) { init_default(); check_directory(); if (!load_proxy_config()) return false; if (file_exist(Config.config_file)) { return load_config(Config.config_file); } return true; }
void e2fsck_pass3(e2fsck_t ctx) { ext2_filsys fs = ctx->fs; struct dir_info_iter *iter; #ifdef RESOURCE_TRACK struct resource_track rtrack; #endif struct problem_context pctx; struct dir_info *dir; unsigned long maxdirs, count; init_resource_track(&rtrack, ctx->fs->io); clear_problem_context(&pctx); #ifdef MTRACE mtrace_print("Pass 3"); #endif if (!(ctx->options & E2F_OPT_PREEN)) fix_problem(ctx, PR_3_PASS_HEADER, &pctx); /* * Allocate some bitmaps to do loop detection. */ pctx.errcode = e2fsck_allocate_inode_bitmap(fs, _("inode done bitmap"), EXT2FS_BMAP64_AUTODIR, "inode_done_map", &inode_done_map); if (pctx.errcode) { pctx.num = 2; fix_problem(ctx, PR_3_ALLOCATE_IBITMAP_ERROR, &pctx); ctx->flags |= E2F_FLAG_ABORT; goto abort_exit; } print_resource_track(ctx, _("Peak memory"), &ctx->global_rtrack, NULL); check_root(ctx); if (ctx->flags & E2F_FLAG_SIGNAL_MASK) goto abort_exit; ext2fs_mark_inode_bitmap2(inode_done_map, EXT2_ROOT_INO); maxdirs = e2fsck_get_num_dirinfo(ctx); count = 1; if (ctx->progress) if ((ctx->progress)(ctx, 3, 0, maxdirs)) goto abort_exit; iter = e2fsck_dir_info_iter_begin(ctx); while ((dir = e2fsck_dir_info_iter(ctx, iter)) != 0) { if (ctx->flags & E2F_FLAG_SIGNAL_MASK) goto abort_exit; if (ctx->progress && (ctx->progress)(ctx, 3, count++, maxdirs)) goto abort_exit; if (ext2fs_test_inode_bitmap2(ctx->inode_dir_map, dir->ino)) if (check_directory(ctx, dir->ino, &pctx)) goto abort_exit; } e2fsck_dir_info_iter_end(ctx, iter); /* * Force the creation of /lost+found if not present */ if ((ctx->flags & E2F_OPT_READONLY) == 0) e2fsck_get_lost_and_found(ctx, 1); /* * If there are any directories that need to be indexed or * optimized, do it here. */ e2fsck_rehash_directories(ctx); abort_exit: e2fsck_free_dir_info(ctx); if (inode_loop_detect) { ext2fs_free_inode_bitmap(inode_loop_detect); inode_loop_detect = 0; } if (inode_done_map) { ext2fs_free_inode_bitmap(inode_done_map); inode_done_map = 0; } print_resource_track(ctx, _("Pass 3"), &rtrack, ctx->fs->io); }
int *parsing_file(char *file_name, int *counter, llist l_args) { FILE *fp; FILE *np; char *line = NULL; size_t len = 0; ssize_t read; int i = 1; int comment_count = 0; DIR *d; char *directory = make_directory(l_args->directory, file_name); int sub_dir = l_args->pr_s; char *org_dir = l_args->directory; struct dirent *dir; if (nmatch(file_name, "*/..") == 1 || nmatch(file_name, "*/.") == 1 || nmatch(file_name, ".") == 1 || nmatch(file_name, "..") == 1 || nmatch(file_name, "no_comment") == 1) return (counter); counter[3] = counter[3] + 1; if (is_directory(file_name) == 1 && nmatch(file_name, org_dir) == 0) { d = opendir(file_name); if (d && sub_dir == 1) { printf(ANSI_COLOR_BLUE"!---> Reading directory '%s':\n"ANSI_COLOR_RESET, file_name); while ((dir = readdir(d)) != NULL) { check_directory(directory, 1); counter = parsing_file(make_directory(file_name, dir->d_name), counter, l_args); } printf(ANSI_COLOR_BLUE"End of directory '%s' <---!\n"ANSI_COLOR_RESET, file_name); return (counter); closedir(d); } return (counter); } printf("\n> Reading file: '%s'\n", file_name); printf("Destination: '%s'\n", directory); if ((fp = fopen(file_name, "r")) == NULL) { printf(ANSI_COLOR_RED"! Error while reading file '%s'\n" ANSI_COLOR_RESET , (file_name ? file_name : " ")); counter[1] = counter[1] + 1; return (counter); } if ((np = fopen(directory, "w+")) == NULL) { printf(ANSI_COLOR_RED"! Error while creating file '%s'\n"ANSI_COLOR_RESET , (file_name ? file_name : " ")); counter[1] = counter[1] + 1; return (counter); } counter[0] = counter[0] + 1; while ((read = getline(&line, &len, fp)) != -1) comment_count = write_file(np, line, comment_count); printf("Total of comments deleted: %d\n", comment_count); printf(ANSI_COLOR_GREEN "--> Done for %s\n\n"ANSI_COLOR_RESET, file_name); counter[2] = counter[2] + comment_count; return (counter); fclose(fp); fclose (np); }
/************************** *** MAIN **************************/ int main(int argc, char **argv) { /* ** INIT SIGNALS */ set_signals(); /* ** INIT / SETTINGS VARS */ client_count = 0; int port; /* ** ARGS MANAGEMENT */ if(argc != 3 || !is_number(argv[2])) { CRITIC("Can't launch with these arguments.", "\tUsage: ./executable <directory> <port>"); } port = atoi(argv[2]); if(port > 65535 || port < 1024) { CRITIC("Can't launch with this port.", "\tPort must be between 1024 and 65535."); } switch(check_directory(argv[1])) { case 0: strncpy(dir_path, argv[1], MAX_PATH - 1); if(dir_path[strlen(dir_path) - 1] != '/') strncat(dir_path, "/", 1); dir_path[MAX_PATH - 1] = '\0'; break; case 1: // Ask to create directory INFO("Directory does not exist, do you want to create it? (yes/no)"); char buffer[MAX_BUF]; fgets(buffer, MAX_BUF, stdin); // If user said yes if(strcmp(buffer, "YES\n") == 0 || strcmp(buffer, "yes\n") == 0) { // Create directory and set full path create_directory(argv[1]); strncpy(dir_path, argv[1], MAX_PATH - 1); if(dir_path[strlen(dir_path) - 1] != '/') strncat(dir_path, "/", 1); dir_path[MAX_PATH - 1] = '\0'; } else { CRITIC("Can't launch with this directory.", "\tDirectory must exists."); } break; case 2: CRITIC("ERRNO ON STAT", strerror(errno)); break; case 3: CRITIC("Can't launch with this directory.", "\tThe given path is not a directory."); break; case 4: CRITIC("Can't launch with this directory.", "\tYou don't have the required permissions."); default: CRITIC("Something impossible happened!", "Wrong switch value"); break; } // INIT MUTEX if(pthread_mutex_init(&client_count_mutex, NULL) != 0) { CRITIC("Can't create client mutex", "MUTEX INIT ERROR"); } if(pthread_mutex_init(&client_list_mutex, NULL) != 0) { CRITIC("Can't create list mutex", "MUTEX INIT ERROR"); } /* ** SERVER MANAGEMENT */ return start_server(port); } // int main(int, char**)
/** * Recursive iteration for file finding * * @param __dir - directory to search file in * @param __rel_dir - relative director name to search file in * @param __options - finding options * @param __res_wnd - window with results * @return zero on success, non-zero otherwise */ static int find_iteration (const wchar_t *__dir, const wchar_t *__rel_dir, const action_find_options_t *__options, action_find_res_wnd_t *__res_wnd) { int i, j, count; vfs_dirent_t **eps = NULL; size_t fn_len; wchar_t *format, *full_name; vfs_stat_t stat; vfs_stat_proc stat_proc; deque_t *dirs; wchar_t **dir_data; __res_wnd->dir_opened = FALSE; /* Get listing of directory */ /* * TODO: Add separately displaying of directories and files */ count = vfs_scandir (__dir, &eps, 0, vfs_alphasort); if (count < 0) { /* Error getting listing */ return ACTION_ERR; } if (TEST_FLAG(__options->flags, AFF_FIND_RECURSIVELY)) { dirs = deque_create (); } /* Get function for stat'ing */ if (TEST_FLAG(__options->flags, AFF_FOLLOW_SYMLINKS)) { stat_proc = vfs_stat; } else { stat_proc = vfs_lstat; } /* Allocate memory for full file name */ fn_len = wcslen (__dir) + MAX_FILENAME_LEN + 1; full_name = malloc ((fn_len + 1) * sizeof (wchar_t)); /* Get format mask for correct directory drilling */ if (__dir[wcslen (__dir) - 1] == '/') { format = L"%ls%ls"; } else { format = L"%ls/%ls"; } for (i = 0; i < count; ++i) { if (IS_PSEUDODIR (eps[i]->name)) { vfs_free_dirent (eps[i]); continue; } set_searching_status (__res_wnd, L"Searching in", __rel_dir); /* Get full file name */ swprintf (full_name, fn_len, format, __dir, eps[i]->name); /* Stat current node of FS */ if (!stat_proc (full_name, &stat) == VFS_OK) { /* Error getting status of file */ vfs_free_dirent (eps[i]); continue; } if (S_ISREG (stat.st_mode)) { if (check_regular_file (eps[i]->name, full_name, __options, __res_wnd)) { append_result (__rel_dir, eps[i]->name, stat, __res_wnd); ++__res_wnd->found_files; } } else if (S_ISDIR (stat.st_mode)) { /* Of user wants directories to be found... */ if (TEST_FLAG(__options->flags, AFF_FIND_DIRECTORIES)) { if (check_directory (eps[i]->name, full_name, __options, __res_wnd)) { append_result (__rel_dir, eps[i]->name, stat, __res_wnd); ++__res_wnd->found_dirs; } } if (TEST_FLAG(__options->flags, AFF_FIND_RECURSIVELY)) { dir_data = malloc (2 * sizeof (wchar_t)); dir_data[0] = wcsdup (eps[i]->name); dir_data[1] = wcsdup (full_name); deque_push_back (dirs, (void*)dir_data); } } else { if (check_special_file (eps[i]->name, full_name, __options, __res_wnd)) { append_result (__rel_dir, eps[i]->name, stat, __res_wnd); ++__res_wnd->found_files; } } vfs_free_dirent (eps[i]); hook_call (L"switch-task-hook", NULL); if (ACTION_PERFORMED (__res_wnd)) { /* Free remain dirents */ for (j = i + 1; j < count; ++j) { vfs_free_dirent (eps[j]); } break; } } SAFE_FREE (eps); free (full_name); if (TEST_FLAG(__options->flags, AFF_FIND_RECURSIVELY) && !ACTION_PERFORMED (__res_wnd)) { void *data; wchar_t *rel_name; if (__rel_dir[wcslen (__rel_dir) - 1] == '/') { format = L"%ls%ls"; } else { format = L"%ls/%ls"; } fn_len = wcslen (__dir) + MAX_FILENAME_LEN + 1; rel_name = malloc ((fn_len + 1) * sizeof (wchar_t)); deque_foreach (dirs, data); /* Drill relative file name */ dir_data = data; if (!ACTION_PERFORMED (__res_wnd)) { swprintf (rel_name, fn_len, format, __rel_dir, dir_data[0]); find_iteration (dir_data[1], rel_name, __options, __res_wnd); } free (dir_data); deque_foreach_done }
int main(int argc, char *argv[]) { int sock_control; boolean has_quit = 0; struct sockaddr_in address; if (argc != 3) { fprintf(stderr, "USAGE: a2client <ip_address> <port_number>\n"); exit(1); } //create a tcp socket if ((sock_control = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { perror("\nError in socket()"); exit(1); } //construct the struct memset(&address, 0, sizeof(address)); /* Clear struct */ address.sin_family = AF_INET; /* Internet/IP */ address.sin_addr.s_addr = inet_addr(argv[1]); /* IP address */ address.sin_port = htons(atoi(argv[2])); /* server port */ //connect to the server if (connect(sock_control, (struct sockaddr *) &address, sizeof(address)) < 0) { perror("\nError in connect()"); exit(1); } //keep getting input from client until they enter QUIT command //these input from client will be sent as commands to server while(has_quit == FALSE){ char command[MAX_LENGTH]; char command_temp[MAX_LENGTH]; fgets(command, MAX_LENGTH, stdin); //get input from user strcat(command, "\r\n"); strcpy(command_temp, command); boolean has_write = TRUE; //if doing a PUT command, check if the file in your directory does in fact exist //if the file does not exists on our (client) directory, do not bother sending //this PUT command to the server //(since on a PUT, the server actually makes an empty file in its directory assuming that //it is going to get data to put in it) if(strncmp("PUT", command, 3) == 0){ has_write = check_directory(command_temp); } if(has_write == TRUE){ //send command to server if(write(sock_control, command, strlen(command)) < 0){ perror("\nError in write()"); exit(1); } char response[MAX_LENGTH]; int n; //read response from server if((n = read(sock_control, response, MAX_LENGTH-1))){ response[n] = '\0'; fprintf(stderr, "%s", response); } //if user enters GET, LIST or PUT //will not make a data connection if a response is anything other //than 103 Command okay if(strncmp("103", response, 3) == 0){ //if the command is ok, the client will connect to the server to form //a tcp data connection create_data_connect(command, argv[1], argv[2]); } if(strncmp("QUIT", command, 4) == 0){ has_quit = TRUE; } } } //when client enters QUIT we quit here printf("\n\nProcessing complete\n\n"); exit(0); }
int main() { /* Declare automatic variables. */ size_t cmdlen = 0; char * cmdline = NULL; int retval; /* Display the banner. */ print_banner(); /* Display the usage information if the command line is empty. */ cmdlen = _bgetcmd( NULL, 0 ); if( cmdlen == 0 ) { print_usage(); return( EXIT_FAILURE ); } /* Include space for the terminating null character. */ cmdlen++; /* Get the command line. */ cmdline = malloc( cmdlen ); if( cmdline == NULL ) { return( EXIT_FAILURE ); } cmdlen = _bgetcmd( cmdline, cmdlen ); /* Initialize the globals. */ initialize_globals(); res_initialize_globals(); /* Initialize the statics, which should be globals in gendev. */ cur_file = (file_info *) malloc( sizeof( file_info ) ); cur_file->filebuf = (char * ) malloc( BUF_SIZE ); cur_file->buflen = BUF_SIZE; cur_file->scanptr = NULL; cur_file->usedlen = 0; cur_token = (token *) malloc( sizeof( token ) ); /* Parse the command line: allocates and sets tgt_path. */ retval = parse_cmdline( cmdline ); if( retval == FAILURE ) { free( cmdline ); return( EXIT_FAILURE ); } /* Free the memory held by cmdline and reset it. */ free( cmdline ); cmdline = NULL; /* Check all files in current directory. */ retval = check_directory(); /* Free the memory held by tgt_path and the statics. */ free( tgt_path ); tgt_path = NULL; free( cur_file->filebuf ); cur_file->filebuf = NULL; free( cur_file ); cur_file = NULL; free( cur_token ); cur_token = NULL; /* Print the useage if the process failed. */ if( retval == FAILURE ) { print_usage(); return( EXIT_FAILURE ); } return( EXIT_SUCCESS ); }
//! //! Defines the thread that does the actual reboot of an instance. //! //! @param[in] arg a transparent pointer to the argument passed to this thread handler //! //! @return Always return NULL //! static void *rebooting_thread(void *arg) { char *xml = NULL; char resourceName[1][MAX_SENSOR_NAME_LEN] = { "" }; char resourceAlias[1][MAX_SENSOR_NAME_LEN] = { "" }; // ncInstance *instance = ((ncInstance *) arg); ncInstance *instance = NULL; struct nc_state_t *nc = NULL; virDomainPtr dom = NULL; virConnectPtr conn = NULL; rebooting_thread_params *params = ((rebooting_thread_params *) arg); instance = &(params->instance); nc = &(params->nc); LOGDEBUG("[%s] spawning rebooting thread\n", instance->instanceId); if ((conn = lock_hypervisor_conn()) == NULL) { LOGERROR("[%s] cannot connect to hypervisor to restart instance, giving up\n", instance->instanceId); EUCA_FREE(params); return NULL; } dom = virDomainLookupByName(conn, instance->instanceId); if (dom == NULL) { LOGERROR("[%s] cannot locate instance to reboot, giving up\n", instance->instanceId); unlock_hypervisor_conn(); EUCA_FREE(params); return NULL; } // obtain the most up-to-date XML for domain from libvirt xml = virDomainGetXMLDesc(dom, 0); if (xml == NULL) { LOGERROR("[%s] cannot obtain metadata for instance to reboot, giving up\n", instance->instanceId); virDomainFree(dom); // release libvirt resource unlock_hypervisor_conn(); EUCA_FREE(params); return NULL; } virDomainFree(dom); // release libvirt resource unlock_hypervisor_conn(); // try shutdown first, then kill it if uncooperative if (shutdown_then_destroy_domain(instance->instanceId, TRUE) != EUCA_OK) { LOGERROR("[%s] failed to shutdown and destroy the instance to reboot, giving up\n", instance->instanceId); EUCA_FREE(params); return NULL; } // Add a shift to values of three of the metrics: ones that // drop back to zero after a reboot. The shift, which is based // on the latest value, ensures that values sent upstream do // not go backwards . sensor_shift_metric(instance->instanceId, "CPUUtilization"); sensor_shift_metric(instance->instanceId, "NetworkIn"); sensor_shift_metric(instance->instanceId, "NetworkOut"); if ((conn = lock_hypervisor_conn()) == NULL) { LOGERROR("[%s] cannot connect to hypervisor to restart instance, giving up\n", instance->instanceId); EUCA_FREE(params); return NULL; } // domain is now shut down, create a new one with the same XML LOGINFO("[%s] rebooting\n", instance->instanceId); if (!strcmp(nc->pEucaNet->sMode, NETMODE_VPCMIDO)) { // need to sleep to allow midolman to update the VM interface sleep(10); } dom = virDomainCreateLinux(conn, xml, 0); if (dom == NULL) { LOGERROR("[%s] failed to restart instance\n", instance->instanceId); change_state(instance, SHUTOFF); } else { euca_strncpy(resourceName[0], instance->instanceId, MAX_SENSOR_NAME_LEN); sensor_refresh_resources(resourceName, resourceAlias, 1); // refresh stats so we set base value accurately virDomainFree(dom); if (!strcmp(nc->pEucaNet->sMode, NETMODE_VPCMIDO)) { char iface[16], cmd[EUCA_MAX_PATH], obuf[256], ebuf[256], sPath[EUCA_MAX_PATH]; int rc; snprintf(iface, 16, "vn_%s", instance->instanceId); // If this device does not have a 'brport' path, this isn't a bridge device snprintf(sPath, EUCA_MAX_PATH, "/sys/class/net/%s/brport/", iface); if (!check_directory(sPath)) { LOGDEBUG("[%s] removing instance interface %s from host bridge\n", instance->instanceId, iface); snprintf(cmd, EUCA_MAX_PATH, "%s brctl delif %s %s", nc->rootwrap_cmd_path, instance->params.guestNicDeviceName, iface); rc = timeshell(cmd, obuf, ebuf, 256, 10); if (rc) { LOGERROR("unable to remove instance interface from bridge after launch: instance will not be able to connect to midonet (will not connect to network): check bridge/libvirt/kvm health\n"); } } // Repeat process for secondary interfaces as well for (int i=0; i < EUCA_MAX_NICS; i++) { if (strlen(instance->secNetCfgs[i].interfaceId) == 0) continue; snprintf(iface, 16, "vn_%s", instance->secNetCfgs[i].interfaceId); // If this device does not have a 'brport' path, this isn't a bridge device snprintf(sPath, EUCA_MAX_PATH, "/sys/class/net/%s/brport/", iface); if (!check_directory(sPath)) { LOGDEBUG("[%s] removing instance interface %s from host bridge\n", instance->instanceId, iface); snprintf(cmd, EUCA_MAX_PATH, "%s brctl delif %s %s", nc->rootwrap_cmd_path, instance->params.guestNicDeviceName, iface); rc = timeshell(cmd, obuf, ebuf, 256, 10); if (rc) { LOGERROR("unable to remove instance interface from bridge after launch: instance will not be able to connect to midonet (will not connect to network): check bridge/libvirt/kvm health\n"); } } } } } EUCA_FREE(xml); unlock_hypervisor_conn(); unset_corrid(get_corrid()); EUCA_FREE(params); return NULL; }
static krb5_error_code KRB5_LIB_CALL kuserok_user_k5login_plug_f(void *plug_ctx, krb5_context context, const char *rule, unsigned int flags, const char *k5login_dir, const char *luser, krb5_const_principal principal, krb5_boolean *result) { #ifdef _WIN32 return KRB5_PLUGIN_NO_HANDLE; #else char *path; char *path_exp; const char *profile_dir = NULL; krb5_error_code ret; krb5_boolean found_file = FALSE; struct passwd pw, *pwd = NULL; char pwbuf[2048]; if (strcmp(rule, "USER-K5LOGIN") != 0) return KRB5_PLUGIN_NO_HANDLE; profile_dir = k5login_dir; if (profile_dir == NULL) { /* Don't deadlock with gssd or anything of the sort */ if (!_krb5_homedir_access(context)) return KRB5_PLUGIN_NO_HANDLE; if (getpwnam_r(luser, &pw, pwbuf, sizeof(pwbuf), &pwd) != 0) { krb5_set_error_message(context, errno, "User unknown (getpwnam_r())"); return KRB5_PLUGIN_NO_HANDLE; } if (pwd == NULL) { krb5_set_error_message(context, errno, "User unknown (getpwnam())"); return KRB5_PLUGIN_NO_HANDLE; } profile_dir = pwd->pw_dir; } #define KLOGIN "/.k5login" if (asprintf(&path, "%s/.k5login.d", profile_dir) == -1) return krb5_enomem(context); ret = _krb5_expand_path_tokensv(context, path, 1, &path_exp, "luser", luser, NULL); free(path); if (ret) return ret; path = path_exp; /* check user's ~/.k5login */ path[strlen(path) - strlen(".d")] = '\0'; ret = check_one_file(context, path, luser, FALSE, principal, result); /* * A match in ~/.k5login is sufficient. A non-match, falls through to the * .k5login.d code below. */ if (ret == 0 && *result == TRUE) { free(path); return 0; } if (ret != ENOENT) found_file = TRUE; /* * A match in ~/.k5login.d/somefile is sufficient. A non-match, falls * through to the code below that handles negative results. * * XXX: put back the .d; clever|hackish? you decide */ path[strlen(path)] = '.'; ret = check_directory(context, path, luser, FALSE, principal, result); free(path); if (ret == 0 && *result == TRUE) return 0; if (ret != ENOENT && ret != ENOTDIR) found_file = TRUE; /* * When either ~/.k5login or ~/.k5login.d/ exists, but neither matches * and we're authoritative, we're done. Otherwise, give other plugins * a chance. */ *result = FALSE; if (found_file && (flags & KUSEROK_K5LOGIN_IS_AUTHORITATIVE)) return 0; return KRB5_PLUGIN_NO_HANDLE; #endif }
int main(int argc, const char **argv) { int res = 0; int optCount = 0; dbgIn = stdin; conOut = stdout; (void)conIn; (void)dbgOut; memset(&cache, 0, sizeof(LIST)); memset(&sources, 0, sizeof(LIST)); stat_clear(&summ); memset(&revinfo, 0, sizeof(REVINFO)); clearLastLine(); optionInit(argc, argv); optCount = optionParse(argc, argv); if (optCount < 0) { return optCount; } argc -= optCount; if (opt_Revision && (strcmp(opt_Revision, "update") == 0)) { res = updateSvnlog(); return res; } if (check_directory(opt_force)) return 3; create_cache(opt_force, 0); if (opt_exit) return 0; read_cache(); l2l_dbg(4, "Cache read complete\n"); if (set_LogFile(&logFile)) return 2; l2l_dbg(4, "opt_logFile processed\n"); if (opt_Pipe) { l2l_dbg(3, "Command line: \"%s\"\n",opt_Pipe); if (!(dbgIn = POPEN(opt_Pipe, "r"))) { dbgIn = stdin; //restore l2l_dbg(0, "Could not popen '%s' (%s)\n", opt_Pipe, strerror(errno)); free(opt_Pipe); opt_Pipe = NULL; } } l2l_dbg(4, "opt_Pipe processed\n"); if (argc > 1) { // translate {<exefile> <offset>} int i = 1; const char *exefile = NULL; const char *offset = NULL; char Line[LINESIZE + 1]; while (i < argc) { Line[0] = '\0'; offset = argv[optCount + i++]; if (isOffset(offset)) { if (exefile) { l2l_dbg(2, "translating %s %s\n", exefile, offset); translate_file(exefile, my_atoi(offset), Line); printf("%s\n", Line); report(conOut); } else { l2l_dbg(0, "<exefile> expected\n"); res = 3; break; } } else { // Not an offset so must be an exefile: exefile = offset; } } } else { // translate logging from stdin translate_files(dbgIn, conOut); } if (logFile) fclose(logFile); if (opt_Pipe) PCLOSE(dbgIn); return res; }
static int inode_callback(sam_perm_inode_t *ip, void *arg) { inode_cb_arg_t *cb_arg = (inode_cb_arg_t *)arg; boolean_t retry_inode; /* Inodes that shouldn't be checked */ if (!IS_DB_INODE(ip->di.id.ino) || !IS_DB_INODE(ip->di.parent_id.ino)) { return (0); } retry: retry_inode = FALSE; if (ip->di.id.ino == cur_check.inode.ino) { if (ip->di.mode == 0 || S_ISEXT(ip->di.mode)) { QUIET_PRINT(stderr, "Inactive inode %d " "found in database.\n", ip->di.id.ino); add_repair_entry(ip->di.id, ip->di.parent_id, TRUE); } else { /* * Check the inode and directory. Repair reason * is printed in the corresponding check method. */ if (check_inode(ip) < 0) { add_repair_entry(ip->di.id, ip->di.parent_id, FALSE); } else if (!fast_scan && S_ISDIR(ip->di.mode)) { if (check_directory(cb_arg->dir_con, cb_arg->dir_stmt, ip) < 0) { add_repair_entry(ip->di.id, ip->di.parent_id, TRUE); } } } } else if (ip->di.id.ino < cur_check.inode.ino) { /* In-use inodes should be in database */ if (!(ip->di.mode == 0 || S_ISEXT(ip->di.mode))) { QUIET_PRINT(stderr, "Inode %d does " "not exist in database.\n", ip->di.id.ino); add_repair_entry(ip->di.id, ip->di.parent_id, TRUE); } return (0); } else { /* ip->di.id.ino > cur_check.inode.ino */ /* Database is incorrect, parent unknown */ QUIET_PRINT(stderr, "Erroneous inode %d " "found in database.\n", cur_check.inode.ino); sam_id_t id = {cur_check.inode.ino, cur_check.inode.gen}; sam_id_t pid = {0, 0}; add_repair_entry(id, pid, TRUE); retry_inode = TRUE; } /* Get next inode to check from database. */ if (next_check_ino(cb_arg->check_stmt) < 0) { fprintf(stderr, "Error getting check value.\n"); return (-1); } if (retry_inode) { goto retry; } return (0); }
//! //! Initialize the backing store. Called during initialization of node controller. //! //! @param[in] conf_instances_path path to where the instances information are stored //! @param[in] conf_work_size_mb the work blobstore size limit in MB (if 0 then unlimitted) //! @param[in] conf_cache_size_mb the cache blobstore size limit in MB (if 0 then cache isn't used) //! //! @return EUCA_OK on success or the following error codes: //! \li EUCA_INVALID_ERROR: if any parameter does not meet the preconditions //! \li EUCA_ACCESS_ERROR: if we fail to access our cache and work directories //! \li EUCA_PERMISSION_ERROR: if we fail to create the cache or work stores. //! //! @pre The conf_instances_path field must not be NULL //! //! @post On success, the backing store module is initialized and the following happened: //! \li our global instance_path variable is set with the given conf_instance_path //! \li the work blobstore is created and our global work_bs variable is set //! \li the cache blobstore is created if necessary and the cache_bs variable is set //! \li the disk semaphore is created if necessary //! int init_backing_store(const char *conf_instances_path, unsigned int conf_work_size_mb, unsigned int conf_cache_size_mb) { char cache_path[EUCA_MAX_PATH] = ""; char work_path[EUCA_MAX_PATH] = ""; unsigned long long cache_limit_blocks = 0; unsigned long long work_limit_blocks = 0; blobstore_snapshot_t snapshot_policy = BLOBSTORE_SNAPSHOT_ANY; LOGINFO("initializing backing store...\n"); // Make sure we have a valid intance path passed to us if (conf_instances_path == NULL) { LOGERROR("INSTANCE_PATH not specified\n"); return (EUCA_INVALID_ERROR); } // Set our global instance_path variable with the content of conf_instance_path euca_strncpy(instances_path, conf_instances_path, sizeof(instances_path)); if (check_directory(instances_path)) { LOGERROR("INSTANCE_PATH (%s) does not exist!\n", instances_path); return (EUCA_ACCESS_ERROR); } // Check if our cache path exist. If not it should get crated snprintf(cache_path, sizeof(cache_path), "%s/cache", instances_path); if (ensure_directories_exist(cache_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1) return (EUCA_ACCESS_ERROR); // Check if our work path exist. If not it should get crated snprintf(work_path, sizeof(work_path), "%s/work", instances_path); if (ensure_directories_exist(work_path, 0, NULL, NULL, BACKING_DIRECTORY_PERM) == -1) return (EUCA_ACCESS_ERROR); // convert MB to blocks cache_limit_blocks = (unsigned long long)conf_cache_size_mb *2048; work_limit_blocks = (unsigned long long)conf_work_size_mb *2048; // we take 0 as unlimited if (work_limit_blocks == 0) { work_limit_blocks = ULLONG_MAX; } // by default we let blobstore pick the snapshot policy, which // will use device mapper if available, which is faster than copying snapshot_policy = BLOBSTORE_SNAPSHOT_ANY; if (nc_state.disable_snapshots) { LOGINFO("if allocating storage, will avoid using snapshots\n"); snapshot_policy = BLOBSTORE_SNAPSHOT_NONE; } // Set the backing store error callback function blobstore_set_error_function(&bs_errors); // Do we need to create a cache blobstore if (cache_limit_blocks) { cache_bs = blobstore_open(cache_path, cache_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_DIRECTORY, BLOBSTORE_REVOCATION_LRU, snapshot_policy); if (cache_bs == NULL) { LOGERROR("failed to open/create cache blobstore: %s\n", blobstore_get_error_str(blobstore_get_error())); return (EUCA_PERMISSION_ERROR); } } // Lets open the work blobstore work_bs = blobstore_open(work_path, work_limit_blocks, BLOBSTORE_FLAG_CREAT, BLOBSTORE_FORMAT_FILES, BLOBSTORE_REVOCATION_NONE, snapshot_policy); if (work_bs == NULL) { LOGERROR("failed to open/create work blobstore: %s\n", blobstore_get_error_str(blobstore_get_error())); LOGERROR("%s\n", blobstore_get_last_trace()); BLOBSTORE_CLOSE(cache_bs); return (EUCA_PERMISSION_ERROR); } // set the initial value of the semaphore to the number of // disk-intensive operations that can run in parallel on this node if (nc_state.concurrent_disk_ops && ((disk_sem = sem_alloc(nc_state.concurrent_disk_ops, IPC_MUTEX_SEMAPHORE)) == NULL)) { LOGERROR("failed to create and initialize disk semaphore\n"); return (EUCA_PERMISSION_ERROR); } return (EUCA_OK); }
static UINT search_directory( MSIPACKAGE *package, MSISIGNATURE *sig, const WCHAR *path, int depth, WCHAR **appValue ) { UINT rc; DWORD attr; LPWSTR val = NULL; TRACE("%p, %p, %s, %d, %p\n", package, sig, debugstr_w(path), depth, appValue); if (is_full_path( path )) { if (sig->File) rc = recurse_search_directory( package, &val, sig, path, depth ); else { /* Recursively searching a directory makes no sense when the * directory to search is the thing you're trying to find. */ rc = check_directory( package, path, &val ); } } else { WCHAR pathWithDrive[MAX_PATH] = { 'C',':','\\',0 }; DWORD drives = GetLogicalDrives(); int i; rc = ERROR_SUCCESS; for (i = 0; rc == ERROR_SUCCESS && !val && i < 26; i++) { if (!(drives & (1 << i))) continue; pathWithDrive[0] = 'A' + i; if (GetDriveTypeW(pathWithDrive) != DRIVE_FIXED) continue; lstrcpynW(pathWithDrive + 3, path, ARRAY_SIZE(pathWithDrive) - 3); if (sig->File) rc = recurse_search_directory( package, &val, sig, pathWithDrive, depth ); else rc = check_directory( package, pathWithDrive, &val ); } } attr = msi_get_file_attributes( package, val ); if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) && val && val[lstrlenW(val) - 1] != '\\') { val = msi_realloc(val, (lstrlenW(val) + 2) * sizeof(WCHAR)); if (!val) rc = ERROR_OUTOFMEMORY; else PathAddBackslashW(val); } *appValue = val; TRACE("returning %d\n", rc); return rc; }