/* * Checks pairwise effects to identify conflicts. */ int detectConflicts() { int i, j, k, n; // initializations num_BA = 0; num_BB = 0; // test each branch for( i = 0; i < prog.num_procs; i++ ) { proc_t *p = &(prog.procs[i]); inf_proc_t *ip = &(inf_procs[i]); if( !include_proc[i] ) continue; for( j = 0; j < ip->num_bb; j++ ) { inf_node_t *ib = &(ip->inf_cfg[j]); branch_t *br = ib->branch; if( br == NULL ) continue; // printBranch( br, 0 ); // exclude loop branch test if( isLoopBranch( ib->bb )) continue; // check self-effect for( k = 0; k < ib->num_assign; k++ ) { assign_t *as = ib->assignlist[k]; // printf( "- " ); printAssign( as, 0 ); // same tested variable if( streq( br->deritree, as->deritree )) { if( isBAConflict( as, br, br->jump_cond )) { setBAConflict( as, br, JUMP, NULL, 0 ); // printf( ">> BA jump conflict\n" ); num_BA++; } else if( isBAConflict( as, br, neg( br->jump_cond ))) { setBAConflict( as, br, FALL, NULL, 0 ); // printf( ">> BA fall conflict\n" ); num_BA++; } // stop once a match is found (can have at most one match) break; } } // check against effects coming before this node in the CFG //for( k = 0; k < ip->num_bb; k++ ) { for( k = 0; k < j; k++ ) { inf_node_t *ibk = &(ip->inf_cfg[k]); branch_t *brk = ibk->branch; if( j == k ) continue; // isolate effects within loop body if( !loopEqual( ib->bb, ibk->bb )) continue; // check BA conflict for( n = 0; n < ibk->num_assign; n++ ) { assign_t *as = ibk->assignlist[n]; // printf( "- " ); printAssign( as, 0 ); if( streq( as->deritree, br->deritree )) { char res = 0; int num_nullifiers = 0; assign_t **nullifier_list = NULL; // printf( "testBA: %s (%d --> %d)\n", br->deritree, k, j ); testReachableNoCancel( &res, &nullifier_list, &num_nullifiers, p->id, k, j, br->deritree, as, p->cfg, p->num_bb ); if( res ) { if( isBAConflict( as, br, br->jump_cond )) { setBAConflict( as, br, JUMP, nullifier_list, num_nullifiers ); // printf( ">> BA jump conflict\n" ); num_BA++; } else if( isBAConflict( as, br, neg( br->jump_cond ))) { setBAConflict( as, br, FALL, nullifier_list, num_nullifiers ); // printf( ">> BA fall conflict\n" ); num_BA++; } } free( nullifier_list ); // stop once a match is found (can have at most one match) break; } } // check BB conflict if( brk == NULL ) continue; // printf( "- " ); printBranch( brk, 0 ); if( streq( brk->deritree, br->deritree )) { int jump = p->cfg[k].out_t->dst->id; int fall = p->cfg[k].out_n->dst->id; // test all combinations of edge directions char res = 0; int num_nullifiers = 0; assign_t **nullifier_list = NULL; // printf( "testBB: %s (%d,%d --> %d)\n", br->deritree, k, jump, j ); testReachableNoCancel( &res, &nullifier_list, &num_nullifiers, p->id, jump, j, br->deritree, NULL, p->cfg, p->num_bb ); if( res ) { if( isBBConflict( brk, br, brk->jump_cond, br->jump_cond )) { setBBConflict( brk, br, JJ, nullifier_list, num_nullifiers ); // printf( ">> BB jump-jump conflict\n" ); num_BB++; } else if( isBBConflict( brk, br, brk->jump_cond, neg( br->jump_cond ))) { setBBConflict( brk, br, JF, nullifier_list, num_nullifiers ); // printf( ">> BB jump-fall conflict\n" ); num_BB++; } } free( nullifier_list ); res = 0; num_nullifiers = 0; nullifier_list = NULL; // printf( "testBB: %s (%d,%d --> %d)\n", br->deritree, k, fall, j ); testReachableNoCancel( &res, &nullifier_list, &num_nullifiers, p->id, fall, j, br->deritree, NULL, p->cfg, p->num_bb ); if( res ) { if( isBBConflict( brk, br, neg( brk->jump_cond ), br->jump_cond )) { setBBConflict( brk, br, FJ, nullifier_list, num_nullifiers ); // printf( ">> BB fall-jump conflict\n" ); num_BB++; } else if( isBBConflict( brk, br, neg( brk->jump_cond ), neg( br->jump_cond ))) { setBBConflict( brk, br, FF, nullifier_list, num_nullifiers ); // printf( ">> BB fall-fall conflict\n" ); num_BB++; } } free( nullifier_list ); } } // end for each incoming block } // for nodes } // for procs return 0; }
unsigned long csport(register Cs_t* state, const char* type, const char* serv) { unsigned long n; char* t; if (streq(serv, "reserved")) return CS_PORT_RESERVED; if (streq(serv, "normal")) return CS_PORT_NORMAL; n = strtol(serv, &t, 0); if (t > serv && *t == '.') strtol(t + 1, &t, 0); if (*t) { if (strneq(serv, CS_SVC_INET, sizeof(CS_SVC_INET) - 1)) { serv += sizeof(CS_SVC_INET) - 1; #if CS_LIB_SOCKET || CS_LIB_V10 { struct servent* sp; #if CS_LIB_V10 if (sp = in_service(serv, type, 0)) return sp->port; #endif #if CS_LIB_SOCKET if (sp = getservbyname(serv, type)) return ntohs(sp->s_port); #endif } #endif switch (strkey(serv)) { case HASHKEY6('t','c','p','m','u','x'): return 1; case HASHKEY4('e','c','h','o'): return 7; case HASHKEY6('d','i','s','c','a','r'): return 9; case HASHKEY6('s','y','s','t','a','t'): return 11; case HASHKEY6('d','a','y','t','i','m'): return 13; case HASHKEY6('n','e','t','s','t','a'): return 15; case HASHKEY4('q','o','t','d'): return 17; case HASHKEY6('c','h','a','r','g','e'): return 19; case HASHKEY3('f','t','p'): return 21; case HASHKEY6('t','e','l','n','e','t'): return 23; case HASHKEY4('s','m','t','p'): return 25; case HASHKEY4('t','i','m','e'): return 37; case HASHKEY3('r','l','p'): return 39; case HASHKEY4('n','a','m','e'): return 42; case HASHKEY5('w','h','o','i','s'): return 43; case HASHKEY6('d','o','m','a','i','n'): return 53; case HASHKEY3('m','t','p'): return 57; case HASHKEY5('b','o','o','t','p'): return 67; case HASHKEY6('b','o','o','t','p','c'): return 68; case HASHKEY4('t','f','t','p'): return 69; case HASHKEY6('g','o','p','h','e','r'): return 70; case HASHKEY3('r','j','e'): return 77; case HASHKEY6('f','i','n','g','e','r'): return 79; case HASHKEY4('h','t','t','p'): return 80; case HASHKEY4('l','i','n','k'): return 87; case HASHKEY6('s','u','p','d','u','p'): return 95; case HASHKEY6('h','o','s','t','n','a'): return 101; case HASHKEY4('x',HASHKEYN('4'),HASHKEYN('0'),HASHKEYN('0')): return 103; case HASHKEY6('s','u','n','r','p','c'): return 111; case HASHKEY4('a','u','t','h'): return 113; case HASHKEY4('s','f','t','p'): return 115; case HASHKEY4('n','n','t','p'): return 119; case HASHKEY4('e','r','p','c'): return 121; case HASHKEY3('n','t','p'): return 123; case HASHKEY4('i','m','a','p'): return 143; case HASHKEY4('s','n','m','p'): return 161; case HASHKEY5('p','r','o','x','y'): return 402; case HASHKEY3('a','t','x'): if (access("/etc/in.atxd", F_OK)) break; return 512; case HASHKEY4('b','i','f','f'): return 512; case HASHKEY4('e','x','e','c'): return 512; case HASHKEY5('l','o','g','i','n'): return 513; case HASHKEY3('w','h','o'): return 513; case HASHKEY5('s','h','e','l','l'): return 514; case HASHKEY6('s','y','s','l','o','g'): return 514; case HASHKEY6('p','r','i','n','t','e'): return 515; case HASHKEY4('t','a','l','k'): return 517; case HASHKEY5('n','t','a','l','k'): return 518; case HASHKEY5('r','o','u','t','e'): return 520; case HASHKEY5('t','i','m','e','d'): return 525; case HASHKEY5('t','e','m','p','o'): return 526; case HASHKEY4('u','u','c','p'): return 540; } } return CS_PORT_INVALID; } return n; }
// ---------------------------------------------------------------- static char* test_lhmslv() { slls_t* aw = slls_alloc(); slls_add_no_free(aw, "a"); slls_add_no_free(aw, "w"); slls_t* ax = slls_alloc(); slls_add_no_free(ax, "a"); slls_add_no_free(ax, "x"); slls_t* ay = slls_alloc(); slls_add_no_free(ay, "a"); slls_add_no_free(ay, "y"); slls_t* bz = slls_alloc(); slls_add_no_free(bz, "b"); slls_add_no_free(bz, "z"); lhmslv_t *pmap = lhmslv_alloc(); mu_assert_lf(pmap->num_occupied == 0); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, ax)); mu_assert_lf(lhmslv_get(pmap, ax) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, ay)); mu_assert_lf(lhmslv_get(pmap, ay) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, bz)); mu_assert_lf(lhmslv_get(pmap, bz) == NULL); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_put(pmap, ax, "3"); mu_assert_lf(pmap->num_occupied == 1); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf( lhmslv_has_key(pmap, ax)); mu_assert_lf(streq(lhmslv_get(pmap, ax), "3")); mu_assert_lf(!lhmslv_has_key(pmap, ay)); mu_assert_lf(lhmslv_get(pmap, ay) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, bz)); mu_assert_lf(lhmslv_get(pmap, bz) == NULL); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_put(pmap, ay, "5"); mu_assert_lf(pmap->num_occupied == 2); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf( lhmslv_has_key(pmap, ax)); mu_assert_lf(streq(lhmslv_get(pmap, ax), "3")); mu_assert_lf( lhmslv_has_key(pmap, ay)); mu_assert_lf(streq(lhmslv_get(pmap, ay), "5")); mu_assert_lf(!lhmslv_has_key(pmap, bz)); mu_assert_lf(lhmslv_get(pmap, bz) == NULL); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_put(pmap, ax, "4"); mu_assert_lf(pmap->num_occupied == 2); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf( lhmslv_has_key(pmap, ax)); mu_assert_lf(streq(lhmslv_get(pmap, ax), "4")); mu_assert_lf( lhmslv_has_key(pmap, ay)); mu_assert_lf(streq(lhmslv_get(pmap, ay), "5")); mu_assert_lf(!lhmslv_has_key(pmap, bz)); mu_assert_lf(lhmslv_get(pmap, bz) == NULL); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_put(pmap, bz, "7"); mu_assert_lf(pmap->num_occupied == 3); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf( lhmslv_has_key(pmap, ax)); mu_assert_lf(streq(lhmslv_get(pmap, ax), "4")); mu_assert_lf( lhmslv_has_key(pmap, ay)); mu_assert_lf(streq(lhmslv_get(pmap, ay), "5")); mu_assert_lf( lhmslv_has_key(pmap, bz)); mu_assert_lf(streq(lhmslv_get(pmap, bz), "7")); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_remove(pmap, ay); mu_assert_lf(pmap->num_occupied == 2); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf( lhmslv_has_key(pmap, ax)); mu_assert_lf(streq(lhmslv_get(pmap, ax), "4")); mu_assert_lf(!lhmslv_has_key(pmap, ay)); mu_assert_lf(lhmslv_get(pmap, ay) == NULL); mu_assert_lf( lhmslv_has_key(pmap, bz)); mu_assert_lf(streq(lhmslv_get(pmap, bz), "7")); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_clear(pmap); mu_assert_lf(pmap->num_occupied == 0); mu_assert_lf(!lhmslv_has_key(pmap, aw)); mu_assert_lf(lhmslv_get(pmap, aw) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, ax)); mu_assert_lf(lhmslv_get(pmap, ax) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, ay)); mu_assert_lf(lhmslv_get(pmap, ay) == NULL); mu_assert_lf(!lhmslv_has_key(pmap, bz)); mu_assert_lf(lhmslv_get(pmap, bz) == NULL); mu_assert_lf(lhmslv_check_counts(pmap)); lhmslv_free(pmap); return NULL; }
static bool mount_in_initrd(struct mntent *me) { assert(me); return fstab_test_option(me->mnt_opts, "x-initrd.mount\0") || streq(me->mnt_dir, "/usr"); }
int parse_sleep_config(const char *verb, char ***_modes, char ***_states) { _cleanup_strv_free_ char **suspend_mode = NULL, **suspend_state = NULL, **hibernate_mode = NULL, **hibernate_state = NULL, **hybrid_mode = NULL, **hybrid_state = NULL; char **modes, **states; const ConfigTableItem items[] = { { "Sleep", "SuspendMode", config_parse_strv, 0, &suspend_mode }, { "Sleep", "SuspendState", config_parse_strv, 0, &suspend_state }, { "Sleep", "HibernateMode", config_parse_strv, 0, &hibernate_mode }, { "Sleep", "HibernateState", config_parse_strv, 0, &hibernate_state }, { "Sleep", "HybridSleepMode", config_parse_strv, 0, &hybrid_mode }, { "Sleep", "HybridSleepState", config_parse_strv, 0, &hybrid_state }, {} }; int r; _cleanup_fclose_ FILE *f; f = fopen(PKGSYSCONFDIR "/sleep.conf", "re"); if (!f) log_full(errno == ENOENT ? LOG_DEBUG: LOG_WARNING, "Failed to open configuration file " PKGSYSCONFDIR "/sleep.conf: %m"); else { r = config_parse(NULL, PKGSYSCONFDIR "/sleep.conf", f, "Sleep\0", config_item_table_lookup, (void*) items, false, false, NULL); if (r < 0) log_warning("Failed to parse configuration file: %s", strerror(-r)); } if (streq(verb, "suspend")) { /* empty by default */ USE(modes, suspend_mode); if (suspend_state) USE(states, suspend_state); else states = strv_new("mem", "standby", "freeze", NULL); } else if (streq(verb, "hibernate")) { if (hibernate_mode) USE(modes, hibernate_mode); else modes = strv_new("platform", "shutdown", NULL); if (hibernate_state) USE(states, hibernate_state); else states = strv_new("disk", NULL); } else if (streq(verb, "hybrid-sleep")) { if (hybrid_mode) USE(modes, hybrid_mode); else modes = strv_new("suspend", "platform", "shutdown", NULL); if (hybrid_state) USE(states, hybrid_state); else states = strv_new("disk", NULL); } else assert_not_reached("what verb"); if ((!modes && !streq(verb, "suspend")) || !states) { strv_free(modes); strv_free(states); return log_oom(); } *_modes = modes; *_states = states; return 0; }
static void test_parse_env_file(void) { char t[] = "/tmp/test-fileio-in-XXXXXX", p[] = "/tmp/test-fileio-out-XXXXXX"; int fd, r; FILE *f; _cleanup_free_ char *one = NULL, *two = NULL, *three = NULL, *four = NULL, *five = NULL, *six = NULL, *seven = NULL, *eight = NULL, *nine = NULL, *ten = NULL; _cleanup_strv_free_ char **a = NULL, **b = NULL; char **i; unsigned k; assert_se(mktemp(p)); fd = mkostemp(t, O_CLOEXEC); assert_se(fd >= 0); f = fdopen(fd, "w"); assert_se(f); fputs("one=BAR \n" "# comment\n" " # comment \n" " ; comment \n" " two = bar \n" "invalid line\n" "invalid line #comment\n" "three = \"333\n" "xxxx\"\n" "four = \'44\\\"44\'\n" "five = \'55\\\'55\' \"FIVE\" cinco \n" "six = seis sechs\\\n" " sis\n" "seven=\"sevenval\" #nocomment\n" "eight=eightval #nocomment\n" "export nine=nineval\n" "ten=", f); fflush(f); fclose(f); r = load_env_file(t, NULL, &a); assert_se(r >= 0); STRV_FOREACH(i, a) log_info("Got: <%s>", *i); assert_se(streq(a[0], "one=BAR")); assert_se(streq(a[1], "two=bar")); assert_se(streq(a[2], "three=333\nxxxx")); assert_se(streq(a[3], "four=44\"44")); assert_se(streq(a[4], "five=55\'55FIVEcinco")); assert_se(streq(a[5], "six=seis sechs sis")); assert_se(streq(a[6], "seven=sevenval#nocomment")); assert_se(streq(a[7], "eight=eightval #nocomment")); assert_se(streq(a[8], "export nine=nineval")); assert_se(streq(a[9], "ten=")); assert_se(a[10] == NULL); strv_env_clean_log(a, "test"); k = 0; STRV_FOREACH(i, b) { log_info("Got2: <%s>", *i); assert_se(streq(*i, a[k++])); }
static int refresh_one( const char *controller, const char *path, Hashmap *a, Hashmap *b, unsigned iteration, unsigned depth, Group **ret) { _cleanup_closedir_ DIR *d = NULL; Group *ours = NULL; int r; assert(controller); assert(path); assert(a); if (depth > arg_depth) return 0; r = process(controller, path, a, b, iteration, &ours); if (r < 0) return r; r = cg_enumerate_subgroups(controller, path, &d); if (r == -ENOENT) return 0; if (r < 0) return r; for (;;) { _cleanup_free_ char *fn = NULL, *p = NULL; Group *child = NULL; r = cg_read_subgroup(d, &fn); if (r < 0) return r; if (r == 0) break; p = strjoin(path, "/", fn, NULL); if (!p) return -ENOMEM; path_kill_slashes(p); r = refresh_one(controller, p, a, b, iteration, depth + 1, &child); if (r < 0) return r; if (arg_recursive && IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES) && child && child->n_tasks_valid && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) { /* Recursively sum up processes */ if (ours->n_tasks_valid) ours->n_tasks += child->n_tasks; else { ours->n_tasks = child->n_tasks; ours->n_tasks_valid = true; } } } if (ret) *ret = ours; return 1; }
// xsamefile returns whether f1 and f2 are the same file (or dir) int xsamefile(char *f1, char *f2) { return streq(f1, f2); // suffice for now }
int main(int argc, char* argv[]) { int c; extern int optind; extern char* optarg; while ((c = getopt(argc, argv, "c:p:r:")) != -1) switch (c) { case 'b': /* save as b&w */ photometric = PHOTOMETRIC_MINISBLACK; break; case 'c': /* compression scheme */ if (streq(optarg, "none")) compression = COMPRESSION_NONE; else if (streq(optarg, "packbits")) compression = COMPRESSION_PACKBITS; else if (strneq(optarg, "jpeg", 4)) { char* cp = strchr(optarg, ':'); if (cp && isdigit(cp[1])) quality = atoi(cp+1); if (cp && strchr(cp, 'r')) jpegcolormode = JPEGCOLORMODE_RAW; compression = COMPRESSION_JPEG; } else if (strneq(optarg, "lzw", 3)) { char* cp = strchr(optarg, ':'); if (cp) predictor = atoi(cp+1); compression = COMPRESSION_LZW; } else usage(); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) config = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) config = PLANARCONFIG_CONTIG; else usage(); break; case 'r': /* rows/strip */ rowsperstrip = atoi(optarg); break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind != 1 && argc - optind != 5) usage(); xmaxscreen = getgdesc(GD_XPMAX)-1; ymaxscreen = getgdesc(GD_YPMAX)-1; foreground(); noport(); winopen("tiffsv"); if (argc - optind == 5) tiffsv(argv[optind], atoi(argv[optind+1]), atoi(argv[optind+2]), atoi(argv[optind+3]), atoi(argv[optind+4])); else tiffsv(argv[optind], 0, xmaxscreen, 0, ymaxscreen); return (0); }
/* * Recursive file perusal. * * Return FALSE on "?", otherwise TRUE. * * This function could be made much more efficient with the use of "seek" * functionality, especially when moving backwards through a file, or * forwards through a file by less than a page at a time. XXX XXX XXX */ bool show_file(cptr name, cptr what, int line, int mode) { int i, k, n; char ch; /* Number of "real" lines passed by */ int next = 0; /* Number of "real" lines in the file */ int size; /* Backup value for "line" */ int back = 0; /* This screen has sub-screens */ bool menu = FALSE; /* Case sensitive search */ bool case_sensitive = FALSE; /* Current help file */ ang_file *fff = NULL; /* Find this string (if any) */ char *find = NULL; /* Jump to this tag */ cptr tag = NULL; /* Hold a string to find */ char finder[80] = ""; /* Hold a string to show */ char shower[80] = ""; /* Filename */ char filename[1024]; /* Describe this thing */ char caption[128] = ""; /* Path buffer */ char path[1024]; /* General buffer */ char buf[1024]; /* Lower case version of the buffer, for searching */ char lc_buf[1024]; /* Sub-menu information */ char hook[26][32]; int wid, hgt; /* Wipe the hooks */ for (i = 0; i < 26; i++) hook[i][0] = '\0'; /* Get size */ Term_get_size(&wid, &hgt); /* Copy the filename */ my_strcpy(filename, name, sizeof(filename)); n = strlen(filename); /* Extract the tag from the filename */ for (i = 0; i < n; i++) { if (filename[i] == '#') { filename[i] = '\0'; tag = filename + i + 1; break; } } /* Redirect the name */ name = filename; /* Hack XXX XXX XXX */ if (what) { my_strcpy(caption, what, sizeof(caption)); my_strcpy(path, name, sizeof(path)); fff = file_open(path, MODE_READ, -1); } /* Look in "help" */ if (!fff) { strnfmt(caption, sizeof(caption), "Help file '%s'", name); path_build(path, sizeof(path), reposband_DIR_HELP, name); fff = file_open(path, MODE_READ, -1); } /* Look in "info" */ if (!fff) { strnfmt(caption, sizeof(caption), "Info file '%s'", name); path_build(path, sizeof(path), reposband_DIR_INFO, name); fff = file_open(path, MODE_READ, -1); } /* Oops */ if (!fff) { /* Message */ msg_format("Cannot open '%s'.", name); message_flush(); /* Oops */ return (TRUE); } /* Pre-Parse the file */ while (TRUE) { /* Read a line or stop */ if (!file_getl(fff, buf, sizeof(buf))) break; /* XXX Parse "menu" items */ if (prefix(buf, "***** ")) { char b1 = '[', b2 = ']'; /* Notice "menu" requests */ if ((buf[6] == b1) && isalpha((unsigned char)buf[7]) && (buf[8] == b2) && (buf[9] == ' ')) { /* This is a menu file */ menu = TRUE; /* Extract the menu item */ k = A2I(buf[7]); /* Store the menu item (if valid) */ if ((k >= 0) && (k < 26)) my_strcpy(hook[k], buf + 10, sizeof(hook[0])); } /* Notice "tag" requests */ else if (buf[6] == '<') { if (tag) { /* Remove the closing '>' of the tag */ buf[strlen(buf) - 1] = '\0'; /* Compare with the requested tag */ if (streq(buf + 7, tag)) { /* Remember the tagged line */ line = next; } } } /* Skip this */ continue; } /* Count the "real" lines */ next++; } /* Save the number of "real" lines */ size = next; /* Display the file */ while (TRUE) { /* Clear screen */ Term_clear(); /* Restrict the visible range */ if (line > (size - (hgt - 4))) line = size - (hgt - 4); if (line < 0) line = 0; /* Re-open the file if needed */ if (next > line) { /* Close it */ file_close(fff); /* Hack -- Re-Open the file */ fff = file_open(path, MODE_READ, -1); if (!fff) return (TRUE); /* File has been restarted */ next = 0; } /* Goto the selected line */ while (next < line) { /* Get a line */ if (!file_getl(fff, buf, sizeof(buf))) break; /* Skip tags/links */ if (prefix(buf, "***** ")) continue; /* Count the lines */ next++; } /* Dump the next lines of the file */ for (i = 0; i < hgt - 4; ) { /* Hack -- track the "first" line */ if (!i) line = next; /* Get a line of the file or stop */ if (!file_getl(fff, buf, sizeof(buf))) break; /* Hack -- skip "special" lines */ if (prefix(buf, "***** ")) continue; /* Count the "real" lines */ next++; /* Make a copy of the current line for searching */ my_strcpy(lc_buf, buf, sizeof(lc_buf)); /* Make the line lower case */ if (!case_sensitive) string_lower(lc_buf); /* Hack -- keep searching */ if (find && !i && !strstr(lc_buf, find)) continue; /* Hack -- stop searching */ find = NULL; /* Dump the line */ Term_putstr(0, i+2, -1, TERM_WHITE, buf); /* Highlight "shower" */ if (shower[0]) { cptr str = lc_buf; /* Display matches */ while ((str = strstr(str, shower)) != NULL) { int len = strlen(shower); /* Display the match */ Term_putstr(str-lc_buf, i+2, len, TERM_YELLOW, &buf[str-lc_buf]); /* Advance */ str += len; } } /* Count the printed lines */ i++; } /* Hack -- failed search */ if (find) { bell("Search string not found!"); line = back; find = NULL; continue; } /* Show a general "title" */ prt(format("[%s %s, %s, Line %d-%d/%d]", VERSION_NAME, VERSION_STRING, caption, line, line + hgt - 4, size), 0, 0); /* Prompt -- menu screen */ if (menu) { /* Wait for it */ prt("[Press a Number, or ESC to exit.]", hgt - 1, 0); } /* Prompt -- small files */ else if (size <= hgt - 4) { /* Wait for it */ prt("[Press ESC to exit.]", hgt - 1, 0); } /* Prompt -- large files */ else { /* Wait for it */ prt("[Press Space to advance, or ESC to exit.]", hgt - 1, 0); } /* Get a keypress */ ch = inkey(); /* Exit the help */ if (ch == '?') break; /* Toggle case sensitive on/off */ if (ch == '!') { case_sensitive = !case_sensitive; } /* Try showing */ if (ch == '&') { /* Get "shower" */ prt("Show: ", hgt - 1, 0); (void)askfor_aux(shower, sizeof(shower), NULL); /* Make the "shower" lowercase */ if (!case_sensitive) string_lower(shower); } /* Try finding */ if (ch == '/') { /* Get "finder" */ prt("Find: ", hgt - 1, 0); if (askfor_aux(finder, sizeof(finder), NULL)) { /* Find it */ find = finder; back = line; line = line + 1; /* Make the "finder" lowercase */ if (!case_sensitive) string_lower(finder); /* Show it */ my_strcpy(shower, finder, sizeof(shower)); } } /* Go to a specific line */ if (ch == '#') { char tmp[80] = "0"; prt("Goto Line: ", hgt - 1, 0); if (askfor_aux(tmp, sizeof(tmp), NULL)) line = atoi(tmp); } /* Go to a specific file */ if (ch == '%') { char ftmp[80] = "help.hlp"; prt("Goto File: ", hgt - 1, 0); if (askfor_aux(ftmp, sizeof(ftmp), NULL)) { if (!show_file(ftmp, NULL, 0, mode)) ch = ESCAPE; } } /* Back up one line */ if (ch == ARROW_UP || ch == '8') { line = line - 1; } /* Back up one full page */ if ((ch == '9') || (ch == '-')) { line = line - (hgt - 4); } /* Back to the top */ if (ch == '7') { line = 0; } /* Advance one line */ if ((ch == ARROW_DOWN) || (ch == '2') || (ch == '\n') || (ch == '\r')) { line = line + 1; } /* Advance one full page */ if ((ch == '3') || (ch == ' ')) { line = line + (hgt - 4); } /* Advance to the bottom */ if (ch == '1') { line = size; } /* Recurse on letters */ if (menu && isalpha((unsigned char)ch)) { /* Extract the requested menu item */ k = A2I(ch); /* Verify the menu item */ if ((k >= 0) && (k <= 25) && hook[k][0]) { /* Recurse on that file */ if (!show_file(hook[k], NULL, 0, mode)) ch = ESCAPE; } } /* Exit on escape */ if (ch == ESCAPE) break; } /* Close the file */ file_close(fff); /* Done */ return (ch != '?'); }
int do_fc(param_t *param, char *logfile){ int i; FILE *fp_log; double zeff; int config=-1; int ipsp=1; int ifc=1; int iexit=0; int iprint=1; int irel=1; int irelxc=1; int ncore; FILE *fp; char filename[160]; char *rp=report; double temp_eigen[10]; double temp_norm[10]; /* set the log file */ sprintf(filenames_.file_log, "%s", logfile); fp_log = fopen(logfile, "a"); fprintf(fp_log,"\n ======================================================================== \n"); fprintf(fp_log," Begin FC calculation\n"); fprintf(fp_log," ======================================================================== \n"); ipsp = 0; ncore = param->norb-param->nval; fprintf(fp_log," Performing non-relativistic FC calculation... \n" ); fclose(fp_log); if (!strcmp(param->reltype, "nrl")){ /* set up the nlm's ; config=-1 is the reference state */ nrelorbae(param,config,logfile); }else{ relorbae(param,config,logfile); } /* starting guess for the AE potential */ startae(param, aorb_.norb); sprintf(filename, "%s.psi_ae_core", param->name); fp = fopen(filename, "rb"); for (i=0; i<ncore; i++) fread(wfn_.rnl[i], sizeof(double), param->ngrid, fp); fclose(fp); sprintf(filename, "%s.eig_ae_core", param->name); fp = fopen(filename, "rb"); for (i=0; i<ncore; i++) { fread(&adat_.en[i], sizeof(double),1, fp); fread(&adat_.wnl[i], sizeof(double),1, fp); fread(&aorb_.nlm[i], sizeof(int),1, fp); fread(&aorb_.nmax[i], sizeof(int),1, fp); fread(&aorb_.maxim, sizeof(int),1, fp); fread(&adat_.xion, sizeof(double),1, fp); fread(&aval_.ibd[i], sizeof(int),1, fp); fread(&etrial_.etrial[i], sizeof(double),1, fp); printf(" en: %d %lg \n", i,adat_.en[i]); } fclose(fp); zeff=adat_.xion; for (i=0; i<param->nval; i++) { if (aval_.ibd[i]==0) { fp_log = fopen(logfile, "a"); fprintf(fp_log," !NOTE! State: |%3d> marked as unbound, using reference eigenvalue of %6.3f \n", aorb_.nlm[i],etrial_.etrial[i]); fclose(fp_log); } zeff +=adat_.wnl[i]; } if (!strcmp(param->reltype, "nrl")){ irel=0; irelxc=0; }else{ irel=1; if (streq(param->relxc,"rxc")){ irelxc=1; }else{ irelxc=0; } } dftsolve_(¶m->z,¶m->ixc,¶m->exccut,&ipsp,&ifc,&iexit,&irel,&irelxc,&iprint); rp = write_reportfc(param,rp,config,temp_eigen,temp_norm); enfc[0] = aval_.etot; fp_log = fopen(logfile, "a"); fprintf(fp_log,"\n ======================================================================== \n"); fprintf(fp_log," End FC calculation\n"); fprintf(fp_log," ======================================================================== \n"); fclose(fp_log); return 0; }
// initializes user_options void parse_args(int argc, char *argv[], bool debug) { int i; char* a; char* b; // parse arguments for (i = 1; i < argc; i++) { a = argv[i]; b = (i < argc) ? argv[i+1] : NULL; if (streq(a, "-from")) { if (streq(b, "null")) { usage(argv[0]); fprintf(stderr, "Invalid input format. Type %s -help\n", argv[0]); exit(1); } else { gbl.fromtype = format2int(b); } i++; } else if (streq(a, "-to")) { if (streq(b, "null")) { gbl.totype = NONE; } else { gbl.totype = format2int(b); } i++; } else if (streq(a, "-n")) { gbl.maxRecs = strtoll(b, NULL, 10); if (b[strlen(b) - 1] == 'i') { gbl.maxInstrs = gbl.maxRecs; gbl.maxRecs = INT64_MAX; } i++; } else if (streq(a, "-syms")) { if (b == NULL) { usage(argv[0]); fprintf(stderr, "Could not open file for writing: %s\n", b); exit(1); } else { if (gbl.symbol_table.read_symbol_file(b) == false) { fprintf(stderr, "Read of symbol table file '%s' failed\n", b); exit(1); } } gbl.show_syms = true; i++; } else if (streq(a, "-s")) { gbl.skipRecs = strtoll(b, NULL, 10); if (b[strlen(b) - 1] == 'i') { gbl.skipInstrs = gbl.skipRecs; gbl.skipRecs = 0; } i++; } else if (streqprefix(a, "-pc")) { get_range(a, &gbl.frompc, &gbl.topc); } else if (streqprefix(a, "-ea")) { get_range(a, &gbl.fromea, &gbl.toea); } else if (streqprefix(a, "-cpu")) { get_cpu_range(a); } else if (streq(a, "-a")) { gbl.disassembly = false; gbl.record = true; gbl.verbose = false; } else if (streq(a, "-d")) { gbl.disassembly = true; gbl.record = false; gbl.verbose = false; } else if (streq(a, "-x")) { gbl.disassembly = false; gbl.record = false; gbl.verbose = true; } else if (streq(a, "-nid")) { gbl.showIdx = false; } else if (streq(a, "-c")) { gbl.countOnly = true; #ifdef _PRINT_PA } else if (streq(a, "-pa")) { gbl.printPA = true; #endif // _PRINT_PA #ifdef _VALUE_TRACE } else if (streq(a, "-vt")) { gbl.valueTrace = true; #endif // _VALUE_TRACE } else if (streq(a, "-nv")) { gbl.verify = false; } else if (streq(a, "-e")) { gbl.checkError = true; } else if (streq(a, "-fast")) { gbl.fast = true; } else if (streq(a, "-i")) { gbl.onlyIns = true; } else if (streq(a, "-ic")) { gbl.onlyIns = true; gbl.reorderIns = true; } else if (streq(a, "-ni")) { gbl.noIns = true; } else if (streq(a, "-nic")) { gbl.noIns = true; gbl.reorderNoIns = true; } else if (streq(a, "-rstdump") || streq(a, "-r")) { gbl.fromtype = RST; gbl.totype = NONE; } else if (streq(a, "-nobranch")) { gbl.branch = false; } else if (streq(a, "-nopc_pavadiff")) { gbl.pc_pavadiff = false; } else if (streq(a, "-noea_pavadiff")) { gbl.ea_pavadiff = false; } else if (streq(a, "-pstate_am")) { unsigned am = atoi(b) << 3; int j; for (j = 0; j < MAX_CPUID + 1; j++) { gbl.pstate[j] = am; } i++; } else if (streq(a, "-patchcleanrst")) { gbl.clean = true; } else if (streq(a, "-patchihash")) { gbl.genIHash = true; } else if (streq(a, "-stdout")) { gbl.outfp = stdout; } else if (streq(a, "-o")) { gbl.outfp = fopen(b, "w"); if (gbl.outfp == NULL) { usage(argv[0]); fprintf(stderr, "Could not open file for writing: %s\n", b); exit(1); } i++; } else if (streq(a, "-help") || streq(a, "-h")) { usage(argv[0]); exit(0); } else if (streq(a, "-version") || streq(a, "-v")) { fprintf(stderr, "%s %s\n", argv[0], version_string); exit(0); } else if (a[0] == '-') { usage(argv[0]); fprintf(stderr, "Unknown flag: %s\n", a); exit(1); } else if (i < argc - 1) { usage(argv[0]); fprintf(stderr, "Unknown flag: %s\n", a); exit(1); } else if (i == argc - 1) { gbl.infile = a; gbl.infp = fopen(a, "r"); if (gbl.infp == NULL) { usage(argv[0]); fprintf(stderr, "Could not open input file: %s\n", a); exit(1); } } } if (gbl.fast) { gbl.verify = false; gbl.checkError = false; gbl.branch = false; gbl.pc_pavadiff = false; gbl.ea_pavadiff = false; gbl.clean = false; gbl.genIHash = false; gbl.checkIHash = false; } gbl.fromsize = format2size(gbl.fromtype); gbl.tosize = format2size(gbl.totype); if (debug) { for (i = 0; i < argc; i++) { fprintf(gbl.msgfp, "%s ", argv[i]); } fprintf(gbl.msgfp, "\n\n"); // format options fprintf(gbl.msgfp, "fromtype = %d\n", gbl.fromtype); fprintf(gbl.msgfp, "totype = %d\n", gbl.totype); fprintf(gbl.msgfp, "\n"); // selection options fprintf(gbl.msgfp, "maxRecs = %llu\n", gbl.maxRecs); fprintf(gbl.msgfp, "maxInstrs = %llu\n", gbl.maxInstrs); fprintf(gbl.msgfp, "skipRecs = %llu\n", gbl.skipRecs); fprintf(gbl.msgfp, "skipInstrs = %llu\n", gbl.skipInstrs); fprintf(gbl.msgfp, "frompc = 0x%llx\n", gbl.frompc); fprintf(gbl.msgfp, "topc = 0x%llx\n", gbl.topc); fprintf(gbl.msgfp, "fromea = 0x%llx\n", gbl.fromea); fprintf(gbl.msgfp, "toea = 0x%llx\n", gbl.toea); fprintf(gbl.msgfp, "\n"); // priting options fprintf(gbl.msgfp, "record = %d\n", gbl.record); fprintf(gbl.msgfp, "disassembly = %d\n", gbl.disassembly); fprintf(gbl.msgfp, "verbose = %d\n", gbl.verbose); fprintf(gbl.msgfp, "showIdx = %d\n", gbl.showIdx); fprintf(gbl.msgfp, "countOnly = %d\n", gbl.countOnly); #ifdef _PRINT_PA fprintf(gbl.msgfp, "print PA = %d\n", gbl.printPA); #endif // _PRINT_PA #ifdef _VALUE_TRACE fprintf(gbl.msgfp, "valueTrace = %d\n", gbl.valueTrace); #endif // _VALUE_TRACE fprintf(gbl.msgfp, "msgfp = 0x%x\n", gbl.msgfp); fprintf(gbl.msgfp, "\n"); // verification options fprintf(gbl.msgfp, "verify = %d\n", gbl.verify); fprintf(gbl.msgfp, "checkError = %d\n", gbl.checkError); fprintf(gbl.msgfp, "fast = %d\n", gbl.fast); fprintf(gbl.msgfp, "\n"); // rsttrace options fprintf(gbl.msgfp, "onlyIns = %d\n", gbl.onlyIns); fprintf(gbl.msgfp, "reorderIns = %d\n", gbl.reorderIns); fprintf(gbl.msgfp, "noIns = %d\n", gbl.noIns); fprintf(gbl.msgfp, "reorderNoIns = %d\n", gbl.reorderNoIns); fprintf(gbl.msgfp, "branch = %d\n", gbl.branch); fprintf(gbl.msgfp, "pc_pavadiff = %d\n", gbl.pc_pavadiff); fprintf(gbl.msgfp, "ea_pavadiff = %d\n", gbl.ea_pavadiff); fprintf(gbl.msgfp, "\n"); // patching options fprintf(gbl.msgfp, "clean = %d\n", gbl.clean); fprintf(gbl.msgfp, "genIHash = %d\n", gbl.genIHash); fprintf(gbl.msgfp, "\n"); // output options fprintf(gbl.msgfp, "infp = 0x%x\n", gbl.infp); fprintf(gbl.msgfp, "outfp = 0x%x\n", gbl.outfp); fprintf(gbl.msgfp, "\n"); // convenient variables fprintf(gbl.msgfp, "progname = %s\n", gbl.progname); fprintf(gbl.msgfp, "infile = %s\n", gbl.infile); fprintf(gbl.msgfp, "fromsize = %d bytes\n", gbl.fromsize); fprintf(gbl.msgfp, "tosize = %d bytes\n", gbl.tosize); fflush(gbl.msgfp); } } // parse_args
doorid_t dlookup(const char* dname) { for (int i = 0; i < ndoors; ++i) { if (streq(dname, doors[i].name)) return i; } return DOOR_ERROR; }
int main(int argc, char* argv[]) { TIFF *in, *out; int c; extern int optind; extern char *optarg; while ((c = getopt(argc, argv, "c:r:t:bn8")) != -1) switch (c) { case 'b': process_by_block = 1; break; case 'c': if (streq(optarg, "none")) compression = COMPRESSION_NONE; else if (streq(optarg, "packbits")) compression = COMPRESSION_PACKBITS; else if (streq(optarg, "lzw")) compression = COMPRESSION_LZW; else if (streq(optarg, "jpeg")) compression = COMPRESSION_JPEG; else if (streq(optarg, "zip")) compression = COMPRESSION_DEFLATE; else usage(-1); break; case 'r': rowsperstrip = atoi(optarg); break; case 't': rowsperstrip = atoi(optarg); break; case 'n': no_alpha = 1; break; case '8': bigtiff_output = 1; break; case '?': usage(0); /*NOTREACHED*/ } if (argc - optind < 2) usage(-1); out = TIFFOpen(argv[argc-1], bigtiff_output?"w8":"w"); if (out == NULL) return (-2); for (; optind < argc-1; optind++) { in = TIFFOpen(argv[optind], "r"); if (in != NULL) { do { if (!tiffcvt(in, out) || !TIFFWriteDirectory(out)) { (void) TIFFClose(out); (void) TIFFClose(in); return (1); } } while (TIFFReadDirectory(in)); (void) TIFFClose(in); } } (void) TIFFClose(out); return (0); }
struct raw_iface *find_raw_ifaces4(void) { static const int on = TRUE; /* by-reference parameter; constant, we hope */ int j; /* index into buf */ struct ifconf ifconf; struct ifreq *buf = NULL; /* for list of interfaces -- arbitrary limit */ struct raw_iface *rifaces = NULL; int master_sock = safe_socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); /* Get a UDP socket */ /* * Current upper bound on number of interfaces. * Tricky: because this is a static, we won't have to start from * 64 in subsequent calls. */ static int num = 64; /* get list of interfaces with assigned IPv4 addresses from system */ if (master_sock == -1) exit_log_errno((e, "socket() failed in find_raw_ifaces4()")); if (setsockopt(master_sock, SOL_SOCKET, SO_REUSEADDR, (const void *)&on, sizeof(on)) < 0) exit_log_errno((e, "setsockopt() in find_raw_ifaces4()")); /* bind the socket */ { ip_address any; happy(anyaddr(AF_INET, &any)); setportof(htons(pluto_port), &any); if (bind(master_sock, sockaddrof(&any), sockaddrlenof(&any)) < 0) exit_log_errno((e, "bind() failed in find_raw_ifaces4()")); } /* a million interfaces is probably the maximum, ever... */ for (; num < (1024 * 1024); num *= 2) { /* Get num local interfaces. See netdevice(7). */ ifconf.ifc_len = num * sizeof(struct ifreq); buf = realloc(buf, ifconf.ifc_len); if (buf == NULL) { exit_log_errno((e, "realloc of %d in find_raw_ifaces4()", ifconf.ifc_len)); } memset(buf, 0xDF, ifconf.ifc_len); /* stomp */ ifconf.ifc_buf = (void *) buf; if (ioctl(master_sock, SIOCGIFCONF, &ifconf) == -1) exit_log_errno((e, "ioctl(SIOCGIFCONF) in find_raw_ifaces4()")); /* if we got back less than we asked for, we have them all */ if (ifconf.ifc_len < (int)(sizeof(struct ifreq) * num)) break; } /* Add an entry to rifaces for each interesting interface. */ for (j = 0; (j + 1) * sizeof(struct ifreq) <= (size_t)ifconf.ifc_len; j++) { struct raw_iface ri; const struct sockaddr_in *rs = (struct sockaddr_in *) &buf[j].ifr_addr; struct ifreq auxinfo; /* build a NUL-terminated copy of the rname field */ memcpy(ri.name, buf[j].ifr_name, IFNAMSIZ); ri.name[IFNAMSIZ] = '\0'; DBG(DBG_CONTROLMORE, DBG_log("Inspecting interface %s ", ri.name)); /* ignore all but AF_INET interfaces */ if (rs->sin_family != AF_INET) { DBG(DBG_CONTROLMORE, DBG_log("Ignoring non AF_INET interface %s ", ri.name)); continue; /* not interesting */ } /* ignore if our interface names were specified, and this isn't one - for KLIPS/MAST only */ if (pluto_ifn_roof != 0 && (kern_interface == USE_MASTKLIPS || kern_interface == USE_KLIPS)) { int i; DBG(DBG_CONTROLMORE, DBG_log("interfaces= specified, applying filter")); for (i = 0; i != pluto_ifn_roof; i++) if (streq(ri.name, pluto_ifn[i])) { DBG(DBG_CONTROLMORE, DBG_log("interface name '%s' found in interfaces= line", ri.name)); break; } if (i == pluto_ifn_roof) { DBG(DBG_CONTROLMORE, DBG_log("interface name '%s' not present in interfaces= line - skipped", ri.name)); continue; /* not found -- skip */ } } /* Find out stuff about this interface. See netdevice(7). */ zero(&auxinfo); /* paranoia */ memcpy(auxinfo.ifr_name, buf[j].ifr_name, IFNAMSIZ); if (ioctl(master_sock, SIOCGIFFLAGS, &auxinfo) == -1) { exit_log_errno((e, "ioctl(SIOCGIFFLAGS) for %s in find_raw_ifaces4()", ri.name)); } if (!(auxinfo.ifr_flags & IFF_UP)) { DBG(DBG_CONTROLMORE, DBG_log("Ignored interface %s - it is not up", ri.name)); continue; /* ignore an interface that isn't UP */ } if (auxinfo.ifr_flags & IFF_SLAVE) { DBG(DBG_CONTROLMORE, DBG_log("Ignored interface %s - it is a slave interface", ri.name)); continue; /* ignore slave interfaces; they share IPs with their master */ } /* ignore unconfigured interfaces */ if (rs->sin_addr.s_addr == 0) { DBG(DBG_CONTROLMORE, DBG_log("Ignored interface %s - it is unconfigured", ri.name)); continue; } happy(initaddr((const void *)&rs->sin_addr, sizeof(struct in_addr), AF_INET, &ri.addr)); DBG(DBG_CONTROLMORE, { ipstr_buf b; DBG_log("found %s with address %s", ri.name, ipstr(&ri.addr, &b)); }); ri.next = rifaces; rifaces = clone_thing(ri, "struct raw_iface"); }
int zgossip_msg_test (bool verbose) { printf (" * zgossip_msg: "); // @selftest // Simple create/destroy test zgossip_msg_t *self = zgossip_msg_new (0); assert (self); zgossip_msg_destroy (&self); // Create pair of sockets we can send through zsock_t *input = zsock_new (ZMQ_ROUTER); assert (input); zsock_connect (input, "inproc://selftest-zgossip_msg"); zsock_t *output = zsock_new (ZMQ_DEALER); assert (output); zsock_bind (output, "inproc://selftest-zgossip_msg"); // Encode/send/decode and verify each message type int instance; zgossip_msg_t *copy; self = zgossip_msg_new (ZGOSSIP_MSG_HELLO); // Check that _dup works on empty message copy = zgossip_msg_dup (self); assert (copy); zgossip_msg_destroy (©); // Send twice from same object zgossip_msg_send_again (self, output); zgossip_msg_send (&self, output); for (instance = 0; instance < 2; instance++) { self = zgossip_msg_recv (input); assert (self); assert (zgossip_msg_routing_id (self)); zgossip_msg_destroy (&self); } self = zgossip_msg_new (ZGOSSIP_MSG_ANNOUNCE); // Check that _dup works on empty message copy = zgossip_msg_dup (self); assert (copy); zgossip_msg_destroy (©); zgossip_msg_set_endpoint (self, "Life is short but Now lasts for ever"); zgossip_msg_set_service (self, "Life is short but Now lasts for ever"); // Send twice from same object zgossip_msg_send_again (self, output); zgossip_msg_send (&self, output); for (instance = 0; instance < 2; instance++) { self = zgossip_msg_recv (input); assert (self); assert (zgossip_msg_routing_id (self)); assert (streq (zgossip_msg_endpoint (self), "Life is short but Now lasts for ever")); assert (streq (zgossip_msg_service (self), "Life is short but Now lasts for ever")); zgossip_msg_destroy (&self); } self = zgossip_msg_new (ZGOSSIP_MSG_PING); // Check that _dup works on empty message copy = zgossip_msg_dup (self); assert (copy); zgossip_msg_destroy (©); // Send twice from same object zgossip_msg_send_again (self, output); zgossip_msg_send (&self, output); for (instance = 0; instance < 2; instance++) { self = zgossip_msg_recv (input); assert (self); assert (zgossip_msg_routing_id (self)); zgossip_msg_destroy (&self); } self = zgossip_msg_new (ZGOSSIP_MSG_PONG); // Check that _dup works on empty message copy = zgossip_msg_dup (self); assert (copy); zgossip_msg_destroy (©); // Send twice from same object zgossip_msg_send_again (self, output); zgossip_msg_send (&self, output); for (instance = 0; instance < 2; instance++) { self = zgossip_msg_recv (input); assert (self); assert (zgossip_msg_routing_id (self)); zgossip_msg_destroy (&self); } self = zgossip_msg_new (ZGOSSIP_MSG_INVALID); // Check that _dup works on empty message copy = zgossip_msg_dup (self); assert (copy); zgossip_msg_destroy (©); // Send twice from same object zgossip_msg_send_again (self, output); zgossip_msg_send (&self, output); for (instance = 0; instance < 2; instance++) { self = zgossip_msg_recv (input); assert (self); assert (zgossip_msg_routing_id (self)); zgossip_msg_destroy (&self); } zsock_destroy (&input); zsock_destroy (&output); // @end printf ("OK\n"); return 0; }
NULL); assert_se(r >= 0); log_info("one=[%s]", strna(one)); log_info("two=[%s]", strna(two)); log_info("three=[%s]", strna(three)); log_info("four=[%s]", strna(four)); log_info("five=[%s]", strna(five)); log_info("six=[%s]", strna(six)); log_info("seven=[%s]", strna(seven)); log_info("eight=[%s]", strna(eight)); log_info("export nine=[%s]", strna(nine)); log_info("ten=[%s]", strna(nine)); assert_se(streq(one, "BAR")); assert_se(streq(two, "bar")); assert_se(streq(three, "333\nxxxx")); assert_se(streq(four, "44\"44")); assert_se(streq(five, "55\'55FIVEcinco")); assert_se(streq(six, "seis sechs sis")); assert_se(streq(seven, "sevenval#nocomment")); assert_se(streq(eight, "eightval #nocomment")); assert_se(streq(nine, "nineval")); assert_se(ten == NULL); r = write_env_file(p, a); assert_se(r >= 0); r = load_env_file(p, NULL, &b); assert_se(r >= 0);
bool find(string itm, const vector<string> &lst) { for (int i = 0; i < lst.size(); i++) if (streq(lst[i], itm)) return true; return false; }
static int process( const char *controller, const char *path, Hashmap *a, Hashmap *b, unsigned iteration, Group **ret) { Group *g; int r; assert(controller); assert(path); assert(a); g = hashmap_get(a, path); if (!g) { g = hashmap_get(b, path); if (!g) { g = new0(Group, 1); if (!g) return -ENOMEM; g->path = strdup(path); if (!g->path) { group_free(g); return -ENOMEM; } r = hashmap_put(a, g->path, g); if (r < 0) { group_free(g); return r; } } else { r = hashmap_move_one(a, b, path); if (r < 0) return r; g->cpu_valid = g->memory_valid = g->io_valid = g->n_tasks_valid = false; } } if (streq(controller, SYSTEMD_CGROUP_CONTROLLER) && IN_SET(arg_count, COUNT_ALL_PROCESSES, COUNT_USERSPACE_PROCESSES)) { _cleanup_fclose_ FILE *f = NULL; pid_t pid; r = cg_enumerate_processes(controller, path, &f); if (r == -ENOENT) return 0; if (r < 0) return r; g->n_tasks = 0; while (cg_read_pid(f, &pid) > 0) { if (arg_count == COUNT_USERSPACE_PROCESSES && is_kernel_thread(pid) > 0) continue; g->n_tasks++; } if (g->n_tasks > 0) g->n_tasks_valid = true; } else if (streq(controller, "pids") && arg_count == COUNT_PIDS) { _cleanup_free_ char *p = NULL, *v = NULL; r = cg_get_path(controller, path, "pids.current", &p); if (r < 0) return r; r = read_one_line_file(p, &v); if (r == -ENOENT) return 0; if (r < 0) return r; r = safe_atou64(v, &g->n_tasks); if (r < 0) return r; if (g->n_tasks > 0) g->n_tasks_valid = true; } else if (streq(controller, "cpuacct") && cg_unified() <= 0) { _cleanup_free_ char *p = NULL, *v = NULL; uint64_t new_usage; nsec_t timestamp; r = cg_get_path(controller, path, "cpuacct.usage", &p); if (r < 0) return r; r = read_one_line_file(p, &v); if (r == -ENOENT) return 0; if (r < 0) return r; r = safe_atou64(v, &new_usage); if (r < 0) return r; timestamp = now_nsec(CLOCK_MONOTONIC); if (g->cpu_iteration == iteration - 1 && (nsec_t) new_usage > g->cpu_usage) { nsec_t x, y; x = timestamp - g->cpu_timestamp; if (x < 1) x = 1; y = (nsec_t) new_usage - g->cpu_usage; g->cpu_fraction = (double) y / (double) x; g->cpu_valid = true; } g->cpu_usage = (nsec_t) new_usage; g->cpu_timestamp = timestamp; g->cpu_iteration = iteration; } else if (streq(controller, "memory")) { _cleanup_free_ char *p = NULL, *v = NULL; if (cg_unified() <= 0) r = cg_get_path(controller, path, "memory.usage_in_bytes", &p); else r = cg_get_path(controller, path, "memory.current", &p); if (r < 0) return r; r = read_one_line_file(p, &v); if (r == -ENOENT) return 0; if (r < 0) return r; r = safe_atou64(v, &g->memory); if (r < 0) return r; if (g->memory > 0) g->memory_valid = true; } else if ((streq(controller, "io") && cg_unified() > 0) || (streq(controller, "blkio") && cg_unified() <= 0)) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *p = NULL; bool unified = cg_unified() > 0; uint64_t wr = 0, rd = 0; nsec_t timestamp; r = cg_get_path(controller, path, unified ? "io.stat" : "blkio.io_service_bytes", &p); if (r < 0) return r; f = fopen(p, "re"); if (!f) { if (errno == ENOENT) return 0; return -errno; } for (;;) { char line[LINE_MAX], *l; uint64_t k, *q; if (!fgets(line, sizeof(line), f)) break; /* Trim and skip the device */ l = strstrip(line); l += strcspn(l, WHITESPACE); l += strspn(l, WHITESPACE); if (unified) { while (!isempty(l)) { if (sscanf(l, "rbytes=%" SCNu64, &k)) rd += k; else if (sscanf(l, "wbytes=%" SCNu64, &k)) wr += k; l += strcspn(l, WHITESPACE); l += strspn(l, WHITESPACE); } } else { if (first_word(l, "Read")) { l += 4; q = &rd; } else if (first_word(l, "Write")) { l += 5; q = ≀ } else continue; l += strspn(l, WHITESPACE); r = safe_atou64(l, &k); if (r < 0) continue; *q += k; } } timestamp = now_nsec(CLOCK_MONOTONIC); if (g->io_iteration == iteration - 1) { uint64_t x, yr, yw; x = (uint64_t) (timestamp - g->io_timestamp); if (x < 1) x = 1; if (rd > g->io_input) yr = rd - g->io_input; else yr = 0; if (wr > g->io_output) yw = wr - g->io_output; else yw = 0; if (yr > 0 || yw > 0) { g->io_input_bps = (yr * 1000000000ULL) / x; g->io_output_bps = (yw * 1000000000ULL) / x; g->io_valid = true; } } g->io_input = rd; g->io_output = wr; g->io_timestamp = timestamp; g->io_iteration = iteration; } if (ret) *ret = g; return 0; }
static void parseCommandLine(int argc, char ** argv, struct cmdlineInfo * const cmdlineP) { /*---------------------------------------------------------------------------- Note that the file spec array we return is stored in the storage that was passed to us as the argv array. -----------------------------------------------------------------------------*/ optEntry *option_def; /* Instructions to OptParseOptions3 on how to parse our options. */ optStruct3 opt; unsigned int option_def_index; const char * nameOpt; unsigned int nameSpec; MALLOCARRAY(option_def, 100); option_def_index = 0; /* incremented by OPTENTRY */ OPTENT3(0, "alphamask", OPT_STRING, &cmdlineP->alpha_filename, NULL, 0); OPTENT3(0, "name", OPT_STRING, &nameOpt, &nameSpec, 0); OPTENT3(0, "rgb", OPT_STRING, &cmdlineP->rgb, NULL, 0); OPTENT3(0, "hexonly", OPT_FLAG, NULL, &cmdlineP->hexonly, 0); OPTENT3(0, "verbose", OPT_FLAG, NULL, &cmdlineP->verbose, 0); /* Set the defaults */ cmdlineP->alpha_filename = NULL; /* no transparency */ cmdlineP->rgb = NULL; /* no rgb file specified */ opt.opt_table = option_def; opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */ opt.allowNegNum = FALSE; /* We may have parms that are negative numbers */ pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0); /* Uses and sets argc, argv, and some of *cmdlineP and others. */ if (argc-1 == 0) cmdlineP->inputFilename = "-"; else if (argc-1 != 1) pm_error("Program takes zero or one argument (filename). You " "specified %d", argc-1); else cmdlineP->inputFilename = argv[1]; /* If output filename not specified, use input filename as default. */ if (nameSpec) cmdlineP->name = nameOpt; else if (streq(cmdlineP->inputFilename, "-")) cmdlineP->name = "noname"; else { static char name[80+1]; char *cp; STRSCPY(name, cmdlineP->inputFilename); cp = strchr(name, '.'); if (cp) *cp = '\0'; /* remove extension */ cmdlineP->name = name; } }
static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_DEPTH, ARG_CPU_TYPE, ARG_ORDER, ARG_RECURSIVE, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "delay", required_argument, NULL, 'd' }, { "iterations", required_argument, NULL, 'n' }, { "batch", no_argument, NULL, 'b' }, { "raw", no_argument, NULL, 'r' }, { "depth", required_argument, NULL, ARG_DEPTH }, { "cpu", optional_argument, NULL, ARG_CPU_TYPE }, { "order", required_argument, NULL, ARG_ORDER }, { "recursive", required_argument, NULL, ARG_RECURSIVE }, { "machine", required_argument, NULL, 'M' }, {} }; bool recursive_unset = false; int c, r; assert(argc >= 1); assert(argv); while ((c = getopt_long(argc, argv, "hptcmin:brd:kPM:", options, NULL)) >= 0) switch (c) { case 'h': help(); return 0; case ARG_VERSION: return version(); case ARG_CPU_TYPE: if (optarg) { if (streq(optarg, "time")) arg_cpu_type = CPU_TIME; else if (streq(optarg, "percentage")) arg_cpu_type = CPU_PERCENT; else { log_error("Unknown argument to --cpu=: %s", optarg); return -EINVAL; } } else arg_cpu_type = CPU_TIME; break; case ARG_DEPTH: r = safe_atou(optarg, &arg_depth); if (r < 0) { log_error("Failed to parse depth parameter."); return -EINVAL; } break; case 'd': r = parse_sec(optarg, &arg_delay); if (r < 0 || arg_delay <= 0) { log_error("Failed to parse delay parameter."); return -EINVAL; } break; case 'n': r = safe_atou(optarg, &arg_iterations); if (r < 0) { log_error("Failed to parse iterations parameter."); return -EINVAL; } break; case 'b': arg_batch = true; break; case 'r': arg_raw = true; break; case 'p': arg_order = ORDER_PATH; break; case 't': arg_order = ORDER_TASKS; break; case 'c': arg_order = ORDER_CPU; break; case 'm': arg_order = ORDER_MEMORY; break; case 'i': arg_order = ORDER_IO; break; case ARG_ORDER: if (streq(optarg, "path")) arg_order = ORDER_PATH; else if (streq(optarg, "tasks")) arg_order = ORDER_TASKS; else if (streq(optarg, "cpu")) arg_order = ORDER_CPU; else if (streq(optarg, "memory")) arg_order = ORDER_MEMORY; else if (streq(optarg, "io")) arg_order = ORDER_IO; else { log_error("Invalid argument to --order=: %s", optarg); return -EINVAL; } break; case 'k': arg_count = COUNT_ALL_PROCESSES; break; case 'P': arg_count = COUNT_USERSPACE_PROCESSES; break; case ARG_RECURSIVE: r = parse_boolean(optarg); if (r < 0) { log_error("Failed to parse --recursive= argument: %s", optarg); return r; } arg_recursive = r; recursive_unset = r == 0; break; case 'M': arg_machine = optarg; break; case '?': return -EINVAL; default: assert_not_reached("Unhandled option"); } if (optind == argc-1) { if (arg_machine) { log_error("Specifying a control group path together with the -M option is not allowed"); return -EINVAL; } arg_root = argv[optind]; } else if (optind < argc) { log_error("Too many arguments."); return -EINVAL; } if (recursive_unset && arg_count == COUNT_PIDS) { log_error("Non-recursive counting is only supported when counting processes, not tasks. Use -P or -k."); return -EINVAL; } return 1; }
static int parse_argv(int argc, char *argv[], Set *matches) { enum { ARG_VERSION = 0x100, ARG_NO_PAGER, ARG_NO_LEGEND, }; int r, c; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version" , no_argument, NULL, ARG_VERSION }, { "no-pager", no_argument, NULL, ARG_NO_PAGER }, { "no-legend", no_argument, NULL, ARG_NO_LEGEND }, { "output", required_argument, NULL, 'o' }, { "field", required_argument, NULL, 'F' }, {} }; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "ho:F:1", options, NULL)) >= 0) switch(c) { case 'h': arg_action = ACTION_NONE; return help(); case ARG_VERSION: arg_action = ACTION_NONE; puts(PACKAGE_STRING); puts(SYSTEMD_FEATURES); return 0; case ARG_NO_PAGER: arg_no_pager = true; break; case ARG_NO_LEGEND: arg_no_legend = true; break; case 'o': if (output) { log_error("cannot set output more than once"); return -EINVAL; } output = fopen(optarg, "we"); if (!output) { log_error("writing to '%s': %m", optarg); return -errno; } break; case 'F': if (arg_field) { log_error("cannot use --field/-F more than once"); return -EINVAL; } arg_field = optarg; break; case '1': arg_one = true; break; case '?': return -EINVAL; default: assert_not_reached("Unhandled option"); } if (optind < argc) { const char *cmd = argv[optind++]; if (streq(cmd, "list")) arg_action = ACTION_LIST; else if (streq(cmd, "dump")) arg_action = ACTION_DUMP; else if (streq(cmd, "gdb")) arg_action = ACTION_GDB; else if (streq(cmd, "info")) arg_action = ACTION_INFO; else { log_error("Unknown action '%s'", cmd); return -EINVAL; } } if (arg_field && arg_action != ACTION_LIST) { log_error("Option --field/-F only makes sense with list"); return -EINVAL; } while (optind < argc) { r = add_match(matches, argv[optind]); if (r != 0) return r; optind++; } return 0; }
static int add_swap( const char *what, struct mntent *me, bool noauto, bool nofail) { _cleanup_free_ char *name = NULL, *unit = NULL, *lnk = NULL; _cleanup_fclose_ FILE *f = NULL; int r; assert(what); assert(me); if (access("/proc/swaps", F_OK) < 0) { log_info("Swap not supported, ignoring fstab swap entry for %s.", what); return 0; } if (detect_container() > 0) { log_info("Running in a container, ignoring fstab swap entry for %s.", what); return 0; } r = unit_name_from_path(what, ".swap", &name); if (r < 0) return log_error_errno(r, "Failed to generate unit name: %m"); unit = strjoin(arg_dest, "/", name, NULL); if (!unit) return log_oom(); f = fopen(unit, "wxe"); if (!f) { if (errno == EEXIST) log_error("Failed to create swap unit file %s, as it already exists. Duplicate entry in /etc/fstab?", unit); else log_error_errno(errno, "Failed to create unit file %s: %m", unit); return -errno; } fprintf(f, "# Automatically generated by systemd-fstab-generator\n\n" "[Unit]\n" "SourcePath=/etc/fstab\n" "Documentation=man:fstab(5) man:systemd-fstab-generator(8)\n\n" "[Swap]\n" "What=%s\n", what); if (!isempty(me->mnt_opts) && !streq(me->mnt_opts, "defaults")) fprintf(f, "Options=%s\n", me->mnt_opts); r = fflush_and_check(f); if (r < 0) return log_error_errno(r, "Failed to write unit file %s: %m", unit); /* use what as where, to have a nicer error message */ r = generator_write_timeouts(arg_dest, what, what, me->mnt_opts, NULL); if (r < 0) return r; if (!noauto) { lnk = strjoin(arg_dest, "/" SPECIAL_SWAP_TARGET, nofail ? ".wants/" : ".requires/", name, NULL); if (!lnk) return log_oom(); mkdir_parents_label(lnk, 0755); if (symlink(unit, lnk) < 0) return log_error_errno(errno, "Failed to create symlink %s: %m", lnk); } return 0; }
static void cs_fake_client(struct s_client *client, char *usr, int32_t uniq, IN_ADDR_T ip) { /* Uniq = 1: only one connection per user * * Uniq = 2: set (new connected) user only to fake if source * ip is different (e.g. for newcamd clients with * different CAID's -> Ports) * * Uniq = 3: only one connection per user, but only the last * login will survive (old mpcs behavior) * * Uniq = 4: set user only to fake if source ip is * different, but only the last login will survive */ struct s_client *cl; struct s_auth *account; cs_writelock(&fakeuser_lock); for (cl = first_client->next; cl; cl = cl->next) { account = cl->account; if (cl != client && cl->typ == 'c' && !cl->dup && account && streq(account->usr, usr) && uniq < 5 && ((uniq % 2) || !IP_EQUAL(cl->ip, ip))) { char buf[20]; if (uniq == 3 || uniq == 4) { cl->dup = 1; cl->aureader_list = NULL; cs_strncpy(buf, cs_inet_ntoa(cl->ip), sizeof(buf)); cs_log("client(%8lX) duplicate user '%s' from %s (prev %s) set to fake (uniq=%d)", (unsigned long)cl->thread, usr, cs_inet_ntoa(ip), buf, uniq); if (cl->failban & BAN_DUPLICATE) { cs_add_violation(cl, usr); } if (cfg.dropdups){ cs_writeunlock(&fakeuser_lock); cs_sleepms(100); // sleep a bit to prevent against saturation from fast reconnecting clients kill_thread(cl); cs_writelock(&fakeuser_lock); } } else { client->dup = 1; client->aureader_list = NULL; cs_strncpy(buf, cs_inet_ntoa(ip), sizeof(buf)); cs_log("client(%8lX) duplicate user '%s' from %s (current %s) set to fake (uniq=%d)", (unsigned long)pthread_self(), usr, cs_inet_ntoa(cl->ip), buf, uniq); if (client->failban & BAN_DUPLICATE) { cs_add_violation_by_ip(ip, modules[client->ctyp].ptab->ports[client->port_idx].s_port, usr); } if (cfg.dropdups){ cs_writeunlock(&fakeuser_lock); // we need to unlock here as cs_disconnect_client kills the current thread! cs_sleepms(100); // sleep a bit to prevent against saturation from fast reconnecting clients cs_disconnect_client(client); cs_writelock(&fakeuser_lock); } break; } } } cs_writeunlock(&fakeuser_lock); }
/** * Read a monster */ static bool rd_monster(struct chunk *c, struct monster *mon) { byte tmp8u; u16b tmp16u; char race_name[80]; size_t j; /* Read the monster race */ rd_u16b(&tmp16u); mon->midx = tmp16u; rd_string(race_name, sizeof(race_name)); mon->race = lookup_monster(race_name); if (!mon->race) { note(format("Monster race %s no longer exists!", race_name)); return false; } rd_string(race_name, sizeof(race_name)); if (streq(race_name, "none")) { mon->original_race = NULL; } else { mon->original_race = lookup_monster(race_name); } /* Read the other information */ rd_byte(&tmp8u); mon->grid.y = tmp8u; rd_byte(&tmp8u); mon->grid.x = tmp8u; rd_s16b(&mon->hp); rd_s16b(&mon->maxhp); rd_byte(&mon->mspeed); rd_byte(&mon->energy); rd_byte(&tmp8u); for (j = 0; j < tmp8u; j++) rd_s16b(&mon->m_timed[j]); /* Read and extract the flag */ for (j = 0; j < mflag_size; j++) rd_byte(&mon->mflag[j]); for (j = 0; j < of_size; j++) rd_byte(&mon->known_pstate.flags[j]); for (j = 0; j < elem_max; j++) rd_s16b(&mon->known_pstate.el_info[j].res_level); rd_u16b(&tmp16u); if (tmp16u) { /* Find and set the mimicked object */ struct object *square_obj = square_object(c, mon->grid); /* Try and find the mimicked object; if we fail, create a new one */ while (square_obj) { if (square_obj->mimicking_m_idx == tmp16u) break; square_obj = square_obj->next; } if (square_obj) { mon->mimicked_obj = square_obj; } else { mon_create_mimicked_object(c, mon, tmp16u); } } /* Read all the held objects (order is unimportant) */ while (true) { struct object *obj = rd_item(); if (!obj) break; pile_insert(&mon->held_obj, obj); assert(obj->oidx); assert(c->objects[obj->oidx] == NULL); c->objects[obj->oidx] = obj; } /* Read group info */ rd_u16b(&tmp16u); mon->group_info[PRIMARY_GROUP].index = tmp16u; rd_byte(&tmp8u); mon->group_info[PRIMARY_GROUP].role = tmp8u; rd_u16b(&tmp16u); mon->group_info[SUMMON_GROUP].index = tmp16u; rd_byte(&tmp8u); mon->group_info[SUMMON_GROUP].role = tmp8u; return true; }
int bus_creds_add_more(sd_bus_creds *c, uint64_t mask, pid_t pid, pid_t tid) { uint64_t missing; int r; assert(c); assert(c->allocated); if (!(mask & SD_BUS_CREDS_AUGMENT)) return 0; /* Try to retrieve PID from creds if it wasn't passed to us */ if (pid > 0) { c->pid = pid; c->mask |= SD_BUS_CREDS_PID; } else if (c->mask & SD_BUS_CREDS_PID) pid = c->pid; else /* Without pid we cannot do much... */ return 0; /* Try to retrieve TID from creds if it wasn't passed to us */ if (tid <= 0 && (c->mask & SD_BUS_CREDS_TID)) tid = c->tid; /* Calculate what we shall and can add */ missing = mask & ~(c->mask|SD_BUS_CREDS_PID|SD_BUS_CREDS_TID|SD_BUS_CREDS_UNIQUE_NAME|SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_DESCRIPTION|SD_BUS_CREDS_AUGMENT); if (missing == 0) return 0; if (tid > 0) { c->tid = tid; c->mask |= SD_BUS_CREDS_TID; } if (missing & (SD_BUS_CREDS_PPID | SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_SUID | SD_BUS_CREDS_FSUID | SD_BUS_CREDS_GID | SD_BUS_CREDS_EGID | SD_BUS_CREDS_SGID | SD_BUS_CREDS_FSGID | SD_BUS_CREDS_SUPPLEMENTARY_GIDS | SD_BUS_CREDS_EFFECTIVE_CAPS | SD_BUS_CREDS_INHERITABLE_CAPS | SD_BUS_CREDS_PERMITTED_CAPS | SD_BUS_CREDS_BOUNDING_CAPS)) { _cleanup_fclose_ FILE *f = NULL; const char *p; p = procfs_file_alloca(pid, "status"); f = fopen(p, "re"); if (!f) { if (errno == ENOENT) return -ESRCH; else if (!IN_SET(errno, EPERM, EACCES)) return -errno; } else { char line[LINE_MAX]; FOREACH_LINE(line, f, return -errno) { truncate_nl(line); if (missing & SD_BUS_CREDS_PPID) { p = startswith(line, "PPid:"); if (p) { p += strspn(p, WHITESPACE); /* Explicitly check for PPID 0 (which is the case for PID 1) */ if (!streq(p, "0")) { r = parse_pid(p, &c->ppid); if (r < 0) return r; } else c->ppid = 0; c->mask |= SD_BUS_CREDS_PPID; continue; } } if (missing & (SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_SUID|SD_BUS_CREDS_FSUID)) { p = startswith(line, "Uid:"); if (p) { unsigned long uid, euid, suid, fsuid; p += strspn(p, WHITESPACE); if (sscanf(p, "%lu %lu %lu %lu", &uid, &euid, &suid, &fsuid) != 4) return -EIO; if (missing & SD_BUS_CREDS_UID) c->uid = (uid_t) uid; if (missing & SD_BUS_CREDS_EUID) c->euid = (uid_t) euid; if (missing & SD_BUS_CREDS_SUID) c->suid = (uid_t) suid; if (missing & SD_BUS_CREDS_FSUID) c->fsuid = (uid_t) fsuid; c->mask |= missing & (SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_SUID|SD_BUS_CREDS_FSUID); continue; } } if (missing & (SD_BUS_CREDS_GID|SD_BUS_CREDS_EGID|SD_BUS_CREDS_SGID|SD_BUS_CREDS_FSGID)) { p = startswith(line, "Gid:"); if (p) { unsigned long gid, egid, sgid, fsgid; p += strspn(p, WHITESPACE); if (sscanf(p, "%lu %lu %lu %lu", &gid, &egid, &sgid, &fsgid) != 4) return -EIO; if (missing & SD_BUS_CREDS_GID) c->gid = (gid_t) gid; if (missing & SD_BUS_CREDS_EGID) c->egid = (gid_t) egid; if (missing & SD_BUS_CREDS_SGID) c->sgid = (gid_t) sgid; if (missing & SD_BUS_CREDS_FSGID) c->fsgid = (gid_t) fsgid; c->mask |= missing & (SD_BUS_CREDS_GID|SD_BUS_CREDS_EGID|SD_BUS_CREDS_SGID|SD_BUS_CREDS_FSGID); continue; } } if (missing & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) { p = startswith(line, "Groups:"); if (p) { size_t allocated = 0; for (;;) { unsigned long g; int n = 0; p += strspn(p, WHITESPACE); if (*p == 0) break; if (sscanf(p, "%lu%n", &g, &n) != 1) return -EIO; if (!GREEDY_REALLOC(c->supplementary_gids, allocated, c->n_supplementary_gids+1)) return -ENOMEM; c->supplementary_gids[c->n_supplementary_gids++] = (gid_t) g; p += n; } c->mask |= SD_BUS_CREDS_SUPPLEMENTARY_GIDS; continue; } } if (missing & SD_BUS_CREDS_EFFECTIVE_CAPS) { p = startswith(line, "CapEff:"); if (p) { r = parse_caps(c, CAP_OFFSET_EFFECTIVE, p); if (r < 0) return r; c->mask |= SD_BUS_CREDS_EFFECTIVE_CAPS; continue; } } if (missing & SD_BUS_CREDS_PERMITTED_CAPS) { p = startswith(line, "CapPrm:"); if (p) { r = parse_caps(c, CAP_OFFSET_PERMITTED, p); if (r < 0) return r; c->mask |= SD_BUS_CREDS_PERMITTED_CAPS; continue; } } if (missing & SD_BUS_CREDS_INHERITABLE_CAPS) { p = startswith(line, "CapInh:"); if (p) { r = parse_caps(c, CAP_OFFSET_INHERITABLE, p); if (r < 0) return r; c->mask |= SD_BUS_CREDS_INHERITABLE_CAPS; continue; } } if (missing & SD_BUS_CREDS_BOUNDING_CAPS) { p = startswith(line, "CapBnd:"); if (p) { r = parse_caps(c, CAP_OFFSET_BOUNDING, p); if (r < 0) return r; c->mask |= SD_BUS_CREDS_BOUNDING_CAPS; continue; } } } } }
// ---------------------------------------------------------------- static char* test_lhms2v() { lhms2v_t *pmap = lhms2v_alloc(); mu_assert_lf(pmap->num_occupied == 0); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(lhms2v_get(pmap, "a", "x") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(lhms2v_get(pmap, "a", "y") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(lhms2v_get(pmap, "b", "z") == NULL); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_put(pmap, "a", "x", "3"); mu_assert_lf(pmap->num_occupied == 1); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf( lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "x"), "3")); mu_assert_lf(!lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(lhms2v_get(pmap, "a", "y") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(lhms2v_get(pmap, "b", "z") == NULL); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_put(pmap, "a", "y", "5"); mu_assert_lf(pmap->num_occupied == 2); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf( lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "x"), "3")); mu_assert_lf( lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "y"), "5")); mu_assert_lf(!lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(lhms2v_get(pmap, "b", "z") == NULL); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_put(pmap, "a", "x", "4"); mu_assert_lf(pmap->num_occupied == 2); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf( lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "x"), "4")); mu_assert_lf( lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "y"), "5")); mu_assert_lf(!lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(lhms2v_get(pmap, "b", "z") == NULL); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_put(pmap, "b", "z", "7"); mu_assert_lf(pmap->num_occupied == 3); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf( lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "x"), "4")); mu_assert_lf( lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "y"), "5")); mu_assert_lf( lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(streq(lhms2v_get(pmap, "b", "z"), "7")); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_remove(pmap, "a", "y"); mu_assert_lf(pmap->num_occupied == 2); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf( lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(streq(lhms2v_get(pmap, "a", "x"), "4")); mu_assert_lf(!lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(lhms2v_get(pmap, "a", "y") == NULL); mu_assert_lf( lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(streq(lhms2v_get(pmap, "b", "z"), "7")); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_clear(pmap); mu_assert_lf(pmap->num_occupied == 0); mu_assert_lf(!lhms2v_has_key(pmap, "a", "w")); mu_assert_lf(lhms2v_get(pmap, "a", "w") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "a", "x")); mu_assert_lf(lhms2v_get(pmap, "a", "x") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "a", "y")); mu_assert_lf(lhms2v_get(pmap, "a", "y") == NULL); mu_assert_lf(!lhms2v_has_key(pmap, "b", "z")); mu_assert_lf(lhms2v_get(pmap, "b", "z") == NULL); mu_assert_lf(lhms2v_check_counts(pmap)); lhms2v_free(pmap); return NULL; }
static void printbody(proc_list *proc) { decl_list *l; bool_t args2 = (proc->arg_num > 1); /* * For new style with multiple arguments, need a structure in which * to stuff the arguments. */ if (newstyle && args2) { f_print(fout, "\t%s", proc->args.argname); f_print(fout, " arg;\n"); } if (!mtflag) { f_print(fout, "\tstatic "); if (streq(proc->res_type, "void")) { f_print(fout, "char "); } else { ptype(proc->res_prefix, proc->res_type, 0); } f_print(fout, "%s;\n", RESULT); f_print(fout, "\n"); f_print(fout, "\tmemset((char *)%s%s, 0, sizeof (%s));\n", ampr(proc->res_type), RESULT, RESULT); } if (newstyle && !args2 && (streq(proc->args.decls->decl.type, "void"))) { /* newstyle, 0 arguments */ if (mtflag) f_print(fout, "\t return "); else f_print(fout, "\t if "); f_print(fout, "(clnt_call(clnt, %s,\n\t\t(xdrproc_t) xdr_void, ", proc->proc_name); f_print(fout, "(caddr_t) NULL,\n\t\t(xdrproc_t) xdr_%s, (caddr_t) %s%s,", stringfix(proc->res_type), (mtflag)?"":ampr(proc->res_type), RESULT); if (mtflag) f_print(fout, "\n\t\tTIMEOUT));\n"); else f_print(fout, "\n\t\tTIMEOUT) != RPC_SUCCESS) {\n"); } else if (newstyle && args2) { /* * Newstyle, multiple arguments * stuff arguments into structure */ for (l = proc->args.decls; l != NULL; l = l->next) { f_print(fout, "\targ.%s = %s;\n", l->decl.name, l->decl.name); } if (mtflag) f_print(fout, "\treturn "); else f_print(fout, "\tif "); f_print(fout, "(clnt_call(clnt, %s,\n\t\t(xdrproc_t) xdr_%s", proc->proc_name,proc->args.argname); f_print(fout, ", (caddr_t) &arg,\n\t\t(xdrproc_t) xdr_%s, (caddr_t) %s%s,", stringfix(proc->res_type), (mtflag)?"":ampr(proc->res_type), RESULT); if (mtflag) f_print(fout, "\n\t\tTIMEOUT));\n"); else f_print(fout, "\n\t\tTIMEOUT) != RPC_SUCCESS) {\n"); } else { /* single argument, new or old style */ if (!mtflag) f_print(fout, "\tif (clnt_call(clnt, %s,\n\t\t(xdrproc_t) xdr_%s, (caddr_t) %s%s,\n\t\t(xdrproc_t) xdr_%s, (caddr_t) %s%s,\n\t\tTIMEOUT) != RPC_SUCCESS) {\n", proc->proc_name, stringfix(proc->args.decls->decl.type), (newstyle ? "&" : ""), (newstyle ? proc->args.decls->decl.name : "argp"), stringfix(proc->res_type), ampr(proc->res_type), RESULT); else f_print(fout, "\treturn (clnt_call(clnt, %s,\n\t\t(xdrproc_t) xdr_%s, (caddr_t) %s%s,\n\t\t(xdrproc_t) xdr_%s, (caddr_t) %s%s,\n\t\tTIMEOUT));\n", proc->proc_name, stringfix(proc->args.decls->decl.type), (newstyle ? "&" : ""), (newstyle ? proc->args.decls->decl.name : "argp"), stringfix(proc->res_type), "", RESULT); } if (!mtflag) { f_print(fout, "\t\treturn (NULL);\n"); f_print(fout, "\t}\n"); if (streq(proc->res_type, "void")) { f_print(fout, "\treturn ((void *)%s%s);\n", ampr(proc->res_type), RESULT); } else { f_print(fout, "\treturn (%s%s);\n", ampr(proc->res_type), RESULT); } } }
// ---------------------------------------------------------------- static char* test_sllv() { sllv_t* pa = sllv_alloc(); sllv_add(pa, "a"); sllv_add(pa, "b"); sllv_add(pa, "c"); mu_assert_lf(pa->length == 3); sllve_t* pe = pa->phead; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "a")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "b")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "c")); pe = pe->pnext; mu_assert_lf(pe == NULL); sllv_t* pb = sllv_alloc(); sllv_add(pb, "d"); sllv_add(pb, "e"); mu_assert_lf(pb->length == 2); pe = pb->phead; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "d")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "e")); pe = pe->pnext; mu_assert_lf(pe == NULL); pa = sllv_append(pa, pb); mu_assert_lf(pa->length == 5); mu_assert_lf(pb->length == 2); pe = pa->phead; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "a")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "b")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "c")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "d")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "e")); pe = pe->pnext; mu_assert_lf(pe == NULL); pe = pb->phead; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "d")); pe = pe->pnext; mu_assert_lf(pe != NULL); mu_assert_lf(streq(pe->pvdata, "e")); pe = pe->pnext; mu_assert_lf(pe == NULL); return NULL; }
int main(int argc, char *argv[]) { database_t *db; char *uri; int session_id; bool start, success; /* enable attest debugging hook */ dbg = stderr_dbg; atexit(library_deinit); /* initialize library */ if (!library_init(NULL, "imv_policy_manager")) { exit(SS_RC_LIBSTRONGSWAN_INTEGRITY); } if (!lib->plugins->load(lib->plugins, lib->settings->get_str(lib->settings, "imv_policy_manager.load", "sqlite"))) { exit(SS_RC_INITIALIZATION_FAILED); } if (argc < 3) { usage(); exit(SS_RC_INITIALIZATION_FAILED); } if (streq(argv[1], "start")) { start = TRUE; } else if (streq(argv[1], "stop")) { start = FALSE; } else { usage(); exit(SS_RC_INITIALIZATION_FAILED); } session_id = atoi(argv[2]); /* attach IMV database */ uri = lib->settings->get_str(lib->settings, "imv_policy_manager.database", lib->settings->get_str(lib->settings, "charon.imcv.database", lib->settings->get_str(lib->settings, "libimcv.database", NULL))); if (!uri) { fprintf(stderr, "database uri not defined.\n"); exit(SS_RC_INITIALIZATION_FAILED); } db = lib->db->create(lib->db, uri); if (!db) { fprintf(stderr, "opening database failed.\n"); exit(SS_RC_INITIALIZATION_FAILED); } if (start) { success = policy_start(db, session_id); } else { success = policy_stop(db, session_id); } db->destroy(db); fprintf(stderr, "imv_policy_manager %s %s\n", start ? "start" : "stop", success ? "successful" : "failed"); exit(EXIT_SUCCESS); }