static void unlink2(const char *pathname) { set_profile(0, "file::unlink"); unlink(pathname); set_profile(3, "file::unlink"); errno = 0; }
static void rmdir2(const char *pathname) { set_profile(0, "file::rmdir"); rmdir(pathname); set_profile(3, "file::rmdir"); errno = 0; }
static void mkfifo2(const char *pathname) { set_profile(0, "file::mkfifo"); mkfifo(pathname, 0600); set_profile(3, "file::mkfifo"); errno = 0; }
static void window_changed_cb(RoccatEventhandlerHost *host, gchar const *title, gpointer user_data) { PyraEventhandler *eventhandler = PYRA_EVENTHANDLER(user_data); PyraEventhandlerPrivate *priv = eventhandler->priv; guint profile_index; guint game_file_index; gchar *pattern; for (profile_index = 0; profile_index < PYRA_PROFILE_NUM; ++profile_index) { if (priv->rmp[profile_index] == NULL) continue; for (game_file_index = 0; game_file_index < PYRA_GAMEFILE_NUM; ++game_file_index) { pattern = pyra_rmp_get_game_file_name(priv->rmp[profile_index], game_file_index); if (strcmp(pattern, "") == 0) { g_free(pattern); continue; } if (g_regex_match_simple(pattern, title, 0, 0)) { set_profile(eventhandler, profile_index + 1); g_free(pattern); return; } g_free(pattern); } } set_profile(eventhandler, pyra_configuration_get_default_profile_number(priv->config)); return; }
static void create2(const char *pathname) { set_profile(0, "file::create"); set_profile(0, "file::open"); close(creat(pathname, 0600)); set_profile(3, "file::create"); set_profile(3, "file::open"); errno = 0; }
int main(int argc, char *argv[]) { tomoyo_test_init(); fprintf(profile_fp, "255-PREFERENCE::learning={ verbose=no }\n"); fprintf(profile_fp, "255-PREFERENCE::enforcing={ verbose=no }\n"); fprintf(profile_fp, "255-PREFERENCE::permissive={ verbose=no }\n"); fprintf(profile_fp, "255-PREFERENCE::disabled={ verbose=no }\n"); set_profile(0, "file"); fprintf(profile_fp, "255-PREFERENCE::learning={ max_entry=2048 }\n"); { int append_loop; for (append_loop = 0; append_loop < 2; append_loop++) { int truncate_loop; for (truncate_loop = 0; truncate_loop < 2; truncate_loop++) { int create_loop; for (create_loop = 0; create_loop < 3; create_loop++) { int rw_loop; for (rw_loop = 0; rw_loop < 4; rw_loop++) test(rw_loop, truncate_loop, append_loop, create_loop); } } } } fprintf(profile_fp, "255-CONFIG::file=disabled\n"); printf("Done\n"); clear_status(); return 0; }
int main(int argc, char *argv[]) { int i; tomoyo_test_init(); for (i = 0; tests[i].do_test; i++) { int trial; for (trial = 0; trial < 2; trial++) { int should_fail; for (should_fail = 0; should_fail < 2; should_fail++) { if (tests[i].do_setup) tests[i].do_setup(); if (!should_fail) write_domain_policy(tests[i].policy, 0); set_profile(3, tests[i].name); tests[i].do_test(); show_result(tests[i].policy, !should_fail); set_profile(0, tests[i].name); if (tests[i].do_cleanup) tests[i].do_cleanup(); if (!should_fail) write_domain_policy(tests[i].policy, 1); } } } for (i = 0; tests[i].do_test; i++) { int mode; for (mode = 0; mode < 4; mode++) { if (tests[i].do_setup) tests[i].do_setup(); set_profile(mode, tests[i].name); tests[i].do_test(); show_result(tests[i].name, 1); set_profile(0, tests[i].name); if (tests[i].do_cleanup) tests[i].do_cleanup(); } } fprintf(domain_fp, "delete %s\n", self_domain); return 0; }
/* PROTO */ void input_reload_profile(char *arg) { if (conn->conn == NULL) return; printf("\n"); b_echostr_s(); printf("Reloading away messages and profile.\n"); set_profile(conn->conn); read_away_messages(); }
/** \brief Setup the socket_itor_t with a socket_itor_arg_t */ socket_err_t socket_itor_t::setup(const socket_itor_arg_t &arg , socket_itor_cb_t *callback, void *userptr) throw() { socket_err_t socket_err; socket_addr_t local_addr; // sanity check - the socket_itor_arg_t MUST be valid DBG_ASSERT( arg.is_valid() ); // if the local address is present in the arg, copy it if( arg.local_addr_present() ) local_addr = arg.local_addr(); // setup the socket_itor_t socket_err = setup(arg.domain(), arg.type(), local_addr, arg.remote_addr(),callback,userptr); if( socket_err.failed() ) return socket_err; // add the profile if present if( arg.profile_present() ) set_profile(arg.profile()); // return noerror return socket_err_t::OK; }
static char * handle_profile ( int argc, char * argv[]) { int i; char *profile_pathname = NULL; for (i = 1; i < argc; ++i) { if ((strcmp (argv[i], "-npro") == 0) || (strcmp (argv[i], "--ignore-profile") == 0) || (strcmp (argv[i], "+ignore-profile") == 0)) { break; } } if (i >= argc) { profile_pathname = set_profile (); } return profile_pathname; }
static void set_file_enforce(int enforce) { if (enforce) { set_profile(3, "file::execute"); set_profile(3, "file::open"); set_profile(3, "file::create"); set_profile(3, "file::unlink"); set_profile(3, "file::mkdir"); set_profile(3, "file::rmdir"); set_profile(3, "file::mkfifo"); set_profile(3, "file::mksock"); set_profile(3, "file::truncate"); set_profile(3, "file::symlink"); set_profile(3, "file::rewrite"); set_profile(3, "file::mkblock"); set_profile(3, "file::mkchar"); set_profile(3, "file::link"); set_profile(3, "file::rename"); set_profile(3, "file::chmod"); set_profile(3, "file::chown"); set_profile(3, "file::chgrp"); set_profile(3, "file::ioctl"); set_profile(3, "file::chroot"); set_profile(3, "file::mount"); set_profile(3, "file::umount"); set_profile(3, "file::pivot_root"); } else { set_profile(0, "file::execute"); set_profile(0, "file::open"); set_profile(0, "file::create"); set_profile(0, "file::unlink"); set_profile(0, "file::mkdir"); set_profile(0, "file::rmdir"); set_profile(0, "file::mkfifo"); set_profile(0, "file::mksock"); set_profile(0, "file::truncate"); set_profile(0, "file::symlink"); set_profile(0, "file::rewrite"); set_profile(0, "file::mkblock"); set_profile(0, "file::mkchar"); set_profile(0, "file::link"); set_profile(0, "file::rename"); set_profile(0, "file::chmod"); set_profile(0, "file::chown"); set_profile(0, "file::chgrp"); set_profile(0, "file::ioctl"); set_profile(0, "file::chroot"); set_profile(0, "file::mount"); set_profile(0, "file::umount"); set_profile(0, "file::pivot_root"); } }
int main(int argc, char **argv) { int dec_ind; /* current indentation for declarations */ int di_stack[20]; /* a stack of structure indentation levels */ int flushed_nl; /* used when buffering up comments to remember * that a newline was passed over */ int force_nl; /* when true, code must be broken */ int hd_type = 0; /* used to store type of stmt for if (...), * for (...), etc */ int i; /* local loop counter */ int scase; /* set to true when we see a case, so we will * know what to do with the following colon */ int sp_sw; /* when true, we are in the expression of * if(...), while(...), etc. */ int squest; /* when this is positive, we have seen a ? * without the matching : in a <c>?<s>:<s> * construct */ const char *t_ptr; /* used for copying tokens */ int tabs_to_var; /* true if using tabs to indent to var name */ int type_code; /* the type of token, returned by lexi */ int last_else = 0; /* true iff last keyword was an else */ /*-----------------------------------------------*\ | INITIALIZATION | \*-----------------------------------------------*/ found_err = 0; ps.p_stack[0] = stmt; /* this is the parser's stack */ ps.last_nl = true; /* this is true if the last thing scanned was * a newline */ ps.last_token = semicolon; combuf = (char *) malloc(bufsize); if (combuf == NULL) err(1, NULL); labbuf = (char *) malloc(bufsize); if (labbuf == NULL) err(1, NULL); codebuf = (char *) malloc(bufsize); if (codebuf == NULL) err(1, NULL); tokenbuf = (char *) malloc(bufsize); if (tokenbuf == NULL) err(1, NULL); l_com = combuf + bufsize - 5; l_lab = labbuf + bufsize - 5; l_code = codebuf + bufsize - 5; l_token = tokenbuf + bufsize - 5; combuf[0] = codebuf[0] = labbuf[0] = ' '; /* set up code, label, and * comment buffers */ combuf[1] = codebuf[1] = labbuf[1] = '\0'; ps.else_if = 1; /* Default else-if special processing to on */ s_lab = e_lab = labbuf + 1; s_code = e_code = codebuf + 1; s_com = e_com = combuf + 1; s_token = e_token = tokenbuf + 1; in_buffer = (char *) malloc(10); if (in_buffer == NULL) err(1, NULL); in_buffer_limit = in_buffer + 8; buf_ptr = buf_end = in_buffer; line_no = 1; had_eof = ps.in_decl = ps.decl_on_line = break_comma = false; sp_sw = force_nl = false; ps.in_or_st = false; ps.bl_line = true; dec_ind = 0; di_stack[ps.dec_nest = 0] = 0; ps.want_blank = ps.in_stmt = ps.ind_stmt = false; scase = ps.pcase = false; squest = 0; sc_end = 0; bp_save = 0; be_save = 0; output = 0; tabs_to_var = 0; /*--------------------------------------------------*\ | COMMAND LINE SCAN | \*--------------------------------------------------*/ #ifdef undef max_col = 78; /* -l78 */ lineup_to_parens = 1; /* -lp */ ps.ljust_decl = 0; /* -ndj */ ps.com_ind = 33; /* -c33 */ star_comment_cont = 1; /* -sc */ ps.ind_size = 8; /* -i8 */ verbose = 0; ps.decl_indent = 16; /* -di16 */ ps.local_decl_indent = -1; /* if this is not set to some nonnegative value * by an arg, we will set this equal to * ps.decl_ind */ ps.indent_parameters = 1; /* -ip */ ps.decl_com_ind = 0; /* if this is not set to some positive value * by an arg, we will set this equal to * ps.com_ind */ btype_2 = 1; /* -br */ cuddle_else = 1; /* -ce */ ps.unindent_displace = 0; /* -d0 */ ps.case_indent = 0; /* -cli0 */ format_block_comments = 1; /* -fcb */ format_col1_comments = 1; /* -fc1 */ procnames_start_line = 1; /* -psl */ proc_calls_space = 0; /* -npcs */ comment_delimiter_on_blankline = 1; /* -cdb */ ps.leave_comma = 1; /* -nbc */ #endif for (i = 1; i < argc; ++i) if (strcmp(argv[i], "-npro") == 0) break; set_defaults(); if (i >= argc) set_profile(); for (i = 1; i < argc; ++i) { /* * look thru args (if any) for changes to defaults */ if (argv[i][0] != '-') {/* no flag on parameter */ if (input == NULL) { /* we must have the input file */ in_name = argv[i]; /* remember name of input file */ input = fopen(in_name, "r"); if (input == NULL) /* check for open error */ err(1, "%s", in_name); continue; } else if (output == NULL) { /* we have the output file */ out_name = argv[i]; /* remember name of output file */ if (strcmp(in_name, out_name) == 0) { /* attempt to overwrite * the file */ errx(1, "input and output files must be different"); } output = fopen(out_name, "w"); if (output == NULL) /* check for create error */ err(1, "%s", out_name); continue; } errx(1, "unknown parameter: %s", argv[i]); } else set_option(argv[i]); } /* end of for */ if (input == NULL) input = stdin; if (output == NULL) { if (troff || input == stdin) output = stdout; else { out_name = in_name; bakcopy(); } } if (ps.com_ind <= 1) ps.com_ind = 2; /* dont put normal comments before column 2 */ if (troff) { if (bodyf.font[0] == 0) parsefont(&bodyf, "R"); if (scomf.font[0] == 0) parsefont(&scomf, "I"); if (blkcomf.font[0] == 0) blkcomf = scomf, blkcomf.size += 2; if (boxcomf.font[0] == 0) boxcomf = blkcomf; if (stringf.font[0] == 0) parsefont(&stringf, "L"); if (keywordf.font[0] == 0) parsefont(&keywordf, "B"); writefdef(&bodyf, 'B'); writefdef(&scomf, 'C'); writefdef(&blkcomf, 'L'); writefdef(&boxcomf, 'X'); writefdef(&stringf, 'S'); writefdef(&keywordf, 'K'); } if (block_comment_max_col <= 0) block_comment_max_col = max_col; if (ps.local_decl_indent < 0) /* if not specified by user, set this */ ps.local_decl_indent = ps.decl_indent; if (ps.decl_com_ind <= 0) /* if not specified by user, set this */ ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind; if (continuation_indent == 0) continuation_indent = ps.ind_size; fill_buffer(); /* get first batch of stuff into input buffer */ parse(semicolon); { char *p = buf_ptr; int col = 1; while (1) { if (*p == ' ') col++; else if (*p == '\t') col = ((col - 1) & ~7) + 9; else break; p++; } if (col > ps.ind_size) ps.ind_level = ps.i_l_follow = col / ps.ind_size; } if (troff) { const char *p = in_name, *beg = in_name; while (*p) if (*p++ == '/') beg = p; fprintf(output, ".Fn \"%s\"\n", beg); } /* * START OF MAIN LOOP */ while (1) { /* this is the main loop. it will go until we * reach eof */ int is_procname; type_code = lexi(); /* lexi reads one token. The actual * characters read are stored in "token". lexi * returns a code indicating the type of token */ is_procname = ps.procname[0]; /* * The following code moves everything following an if (), while (), * else, etc. up to the start of the following stmt to a buffer. This * allows proper handling of both kinds of brace placement. */ flushed_nl = false; while (ps.search_brace) { /* if we scanned an if(), while(), * etc., we might need to copy stuff * into a buffer we must loop, copying * stuff into save_com, until we find * the start of the stmt which follows * the if, or whatever */ switch (type_code) { case newline: ++line_no; flushed_nl = true; case form_feed: break; /* form feeds and newlines found here will be * ignored */ case lbrace: /* this is a brace that starts the compound * stmt */ if (sc_end == 0) { /* ignore buffering if a comment wasnt * stored up */ ps.search_brace = false; goto check_type; } if (btype_2) { save_com[0] = '{'; /* we either want to put the brace * right after the if */ goto sw_buffer; /* go to common code to get out of * this loop */ } case comment: /* we have a comment, so we must copy it into * the buffer */ if (!flushed_nl || sc_end != 0) { if (sc_end == 0) { /* if this is the first comment, we * must set up the buffer */ save_com[0] = save_com[1] = ' '; sc_end = &(save_com[2]); } else { *sc_end++ = '\n'; /* add newline between * comments */ *sc_end++ = ' '; --line_no; } *sc_end++ = '/'; /* copy in start of comment */ *sc_end++ = '*'; for (;;) { /* loop until we get to the end of the comment */ *sc_end = *buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); if (*sc_end++ == '*' && *buf_ptr == '/') break; /* we are at end of comment */ if (sc_end >= &(save_com[sc_size])) { /* check for temp buffer * overflow */ diag2(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever"); fflush(output); exit(1); } } *sc_end++ = '/'; /* add ending slash */ if (++buf_ptr >= buf_end) /* get past / in buffer */ fill_buffer(); break; } default: /* it is the start of a normal statement */ if (flushed_nl) /* if we flushed a newline, make sure it is * put back */ force_nl = true; if ((type_code == sp_paren && *token == 'i' && last_else && ps.else_if) || (type_code == sp_nparen && *token == 'e' && e_code != s_code && e_code[-1] == '}')) force_nl = false; if (sc_end == 0) { /* ignore buffering if comment wasnt * saved up */ ps.search_brace = false; goto check_type; } if (force_nl) { /* if we should insert a nl here, put it into * the buffer */ force_nl = false; --line_no; /* this will be re-increased when the nl is * read from the buffer */ *sc_end++ = '\n'; *sc_end++ = ' '; if (verbose && !flushed_nl) /* print error msg if the line * was not already broken */ diag2(0, "Line broken"); flushed_nl = false; } for (t_ptr = token; *t_ptr; ++t_ptr) *sc_end++ = *t_ptr; /* copy token into temp buffer */ ps.procname[0] = 0; sw_buffer: ps.search_brace = false; /* stop looking for start of * stmt */ bp_save = buf_ptr; /* save current input buffer */ be_save = buf_end; buf_ptr = save_com; /* fix so that subsequent calls to * lexi will take tokens out of * save_com */ *sc_end++ = ' ';/* add trailing blank, just in case */ buf_end = sc_end; sc_end = 0; break; } /* end of switch */ if (type_code != 0) /* we must make this check, just in case there * was an unexpected EOF */ type_code = lexi(); /* read another token */ /* if (ps.search_brace) ps.procname[0] = 0; */ if ((is_procname = ps.procname[0]) && flushed_nl && !procnames_start_line && ps.in_decl && type_code == ident) flushed_nl = 0; } /* end of while (search_brace) */ last_else = 0; check_type: if (type_code == 0) { /* we got eof */ if (s_lab != e_lab || s_code != e_code || s_com != e_com) /* must dump end of line */ dump_line(); if (ps.tos > 1) /* check for balanced braces */ diag2(1, "Stuff missing from end of file"); if (verbose) { printf("There were %d output lines and %d comments\n", ps.out_lines, ps.out_coms); printf("(Lines with comments)/(Lines with code): %6.3f\n", (1.0 * ps.com_lines) / code_lines); } fflush(output); exit(found_err); } if ( (type_code != comment) && (type_code != newline) && (type_code != preesc) && (type_code != form_feed)) { if (force_nl && (type_code != semicolon) && (type_code != lbrace || !btype_2)) { /* we should force a broken line here */ if (verbose && !flushed_nl) diag2(0, "Line broken"); flushed_nl = false; dump_line(); ps.want_blank = false; /* dont insert blank at line start */ force_nl = false; } ps.in_stmt = true; /* turn on flag which causes an extra level of * indentation. this is turned off by a ; or * '}' */ if (s_com != e_com) { /* the turkey has embedded a comment * in a line. fix it */ *e_code++ = ' '; for (t_ptr = s_com; *t_ptr; ++t_ptr) { CHECK_SIZE_CODE; *e_code++ = *t_ptr; } *e_code++ = ' '; *e_code = '\0'; /* null terminate code sect */ ps.want_blank = false; e_com = s_com; } } else if (type_code != comment) /* preserve force_nl thru a comment */ force_nl = false; /* cancel forced newline after newline, form * feed, etc */ /*-----------------------------------------------------*\ | do switch on type of token scanned | \*-----------------------------------------------------*/ CHECK_SIZE_CODE; switch (type_code) { /* now, decide what to do with the token */ case form_feed: /* found a form feed in line */ ps.use_ff = true; /* a form feed is treated much like a newline */ dump_line(); ps.want_blank = false; break; case newline: if (ps.last_token != comma || ps.p_l_follow > 0 || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) { dump_line(); ps.want_blank = false; } ++line_no; /* keep track of input line number */ break; case lparen: /* got a '(' or '[' */ ++ps.p_l_follow; /* count parens to make Healy happy */ if (ps.want_blank && *token != '[' && (ps.last_token != ident || proc_calls_space || (ps.its_a_keyword && (!ps.sizeof_keyword || Bill_Shannon)))) *e_code++ = ' '; if (ps.in_decl && !ps.block_init) if (troff && !ps.dumped_decl_indent && !is_procname && ps.last_token == decl) { ps.dumped_decl_indent = 1; sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token); e_code += strlen(e_code); } else { while ((e_code - s_code) < dec_ind) { CHECK_SIZE_CODE; *e_code++ = ' '; } *e_code++ = token[0]; } else *e_code++ = token[0]; ps.paren_indents[ps.p_l_follow - 1] = e_code - s_code; if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent && ps.paren_indents[0] < 2 * ps.ind_size) ps.paren_indents[0] = 2 * ps.ind_size; ps.want_blank = false; if (ps.in_or_st && *token == '(' && ps.tos <= 2) { /* * this is a kluge to make sure that declarations will be * aligned right if proc decl has an explicit type on it, i.e. * "int a(x) {..." */ parse(semicolon); /* I said this was a kluge... */ ps.in_or_st = false; /* turn off flag for structure decl or * initialization */ } if (ps.sizeof_keyword) ps.sizeof_mask |= 1 << ps.p_l_follow; break; case rparen: /* got a ')' or ']' */ rparen_count--; if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.sizeof_mask) { ps.last_u_d = true; ps.cast_mask &= (1 << ps.p_l_follow) - 1; ps.want_blank = false; } else ps.want_blank = true; ps.sizeof_mask &= (1 << ps.p_l_follow) - 1; if (--ps.p_l_follow < 0) { ps.p_l_follow = 0; diag3(0, "Extra %c", *token); } if (e_code == s_code) /* if the paren starts the line */ ps.paren_level = ps.p_l_follow; /* then indent it */ *e_code++ = token[0]; if (sp_sw && (ps.p_l_follow == 0)) { /* check for end of if * (...), or some such */ sp_sw = false; force_nl = true;/* must force newline after if */ ps.last_u_d = true; /* inform lexi that a following * operator is unary */ ps.in_stmt = false; /* dont use stmt continuation * indentation */ parse(hd_type); /* let parser worry about if, or whatever */ } ps.search_brace = btype_2; /* this should insure that constructs * such as main(){...} and int[]{...} * have their braces put in the right * place */ break; case unary_op: /* this could be any unary operation */ if (ps.want_blank) *e_code++ = ' '; if (troff && !ps.dumped_decl_indent && ps.in_decl && !is_procname) { sprintf(e_code, "\n.Du %dp+\200p \"%s\"\n", dec_ind * 7, token); ps.dumped_decl_indent = 1; e_code += strlen(e_code); } else { const char *res = token; if (ps.in_decl && !ps.block_init) { /* if this is a unary op * in a declaration, we * should indent this * token */ for (i = 0; token[i]; ++i); /* find length of token */ while ((e_code - s_code) < (dec_ind - i)) { CHECK_SIZE_CODE; *e_code++ = ' '; /* pad it */ } } if (troff && token[0] == '-' && token[1] == '>') res = "\\(->"; for (t_ptr = res; *t_ptr; ++t_ptr) { CHECK_SIZE_CODE; *e_code++ = *t_ptr; } } ps.want_blank = false; break; case binary_op: /* any binary operation */ if (ps.want_blank) *e_code++ = ' '; { const char *res = token; if (troff) switch (token[0]) { case '<': if (token[1] == '=') res = "\\(<="; break; case '>': if (token[1] == '=') res = "\\(>="; break; case '!': if (token[1] == '=') res = "\\(!="; break; case '|': if (token[1] == '|') res = "\\(br\\(br"; else if (token[1] == 0) res = "\\(br"; break; } for (t_ptr = res; *t_ptr; ++t_ptr) { CHECK_SIZE_CODE; *e_code++ = *t_ptr; /* move the operator */ } } ps.want_blank = true; break; case postop: /* got a trailing ++ or -- */ *e_code++ = token[0]; *e_code++ = token[1]; ps.want_blank = true; break; case question: /* got a ? */ squest++; /* this will be used when a later colon * appears so we can distinguish the * <c>?<n>:<n> construct */ if (ps.want_blank) *e_code++ = ' '; *e_code++ = '?'; ps.want_blank = true; break; case casestmt: /* got word 'case' or 'default' */ scase = true; /* so we can process the later colon properly */ goto copy_id; case colon: /* got a ':' */ if (squest > 0) { /* it is part of the <c>?<n>: <n> construct */ --squest; if (ps.want_blank) *e_code++ = ' '; *e_code++ = ':'; ps.want_blank = true; break; } if (ps.in_or_st) { *e_code++ = ':'; ps.want_blank = false; break; } ps.in_stmt = false; /* seeing a label does not imply we are in a * stmt */ for (t_ptr = s_code; *t_ptr; ++t_ptr) *e_lab++ = *t_ptr; /* turn everything so far into a label */ e_code = s_code; *e_lab++ = ':'; *e_lab++ = ' '; *e_lab = '\0'; force_nl = ps.pcase = scase; /* ps.pcase will be used by * dump_line to decide how to * indent the label. force_nl * will force a case n: to be * on a line by itself */ scase = false; ps.want_blank = false; break; case semicolon: /* got a ';' */ ps.in_or_st = false;/* we are not in an initialization or * structure declaration */ scase = false; /* these will only need resetting in an error */ squest = 0; if (ps.last_token == rparen && rparen_count == 0) ps.in_parameter_declaration = 0; ps.cast_mask = 0; ps.sizeof_mask = 0; ps.block_init = 0; ps.block_init_level = 0; ps.just_saw_decl--; if (ps.in_decl && s_code == e_code && !ps.block_init) while ((e_code - s_code) < (dec_ind - 1)) { CHECK_SIZE_CODE; *e_code++ = ' '; } ps.in_decl = (ps.dec_nest > 0); /* if we were in a first level * structure declaration, we * arent any more */ if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) { /* * This should be true iff there were unbalanced parens in the * stmt. It is a bit complicated, because the semicolon might * be in a for stmt */ diag2(1, "Unbalanced parens"); ps.p_l_follow = 0; if (sp_sw) { /* this is a check for an if, while, etc. with * unbalanced parens */ sp_sw = false; parse(hd_type); /* dont lose the if, or whatever */ } } *e_code++ = ';'; ps.want_blank = true; ps.in_stmt = (ps.p_l_follow > 0); /* we are no longer in the * middle of a stmt */ if (!sp_sw) { /* if not if for (;;) */ parse(semicolon); /* let parser know about end of stmt */ force_nl = true;/* force newline after an end of stmt */ } break; case lbrace: /* got a '{' */ ps.in_stmt = false; /* dont indent the {} */ if (!ps.block_init) force_nl = true;/* force other stuff on same line as '{' onto * new line */ else if (ps.block_init_level <= 0) ps.block_init_level = 1; else ps.block_init_level++; if (s_code != e_code && !ps.block_init) { if (!btype_2) { dump_line(); ps.want_blank = false; } else if (ps.in_parameter_declaration && !ps.in_or_st) { ps.i_l_follow = 0; if (function_brace_split) { /* dump the line prior to the * brace ... */ dump_line(); ps.want_blank = false; } else /* add a space between the decl and brace */ ps.want_blank = true; } } if (ps.in_parameter_declaration) prefix_blankline_requested = 0; if (ps.p_l_follow > 0) { /* check for preceding unbalanced * parens */ diag2(1, "Unbalanced parens"); ps.p_l_follow = 0; if (sp_sw) { /* check for unclosed if, for, etc. */ sp_sw = false; parse(hd_type); ps.ind_level = ps.i_l_follow; } } if (s_code == e_code) ps.ind_stmt = false; /* dont put extra indentation on line * with '{' */ if (ps.in_decl && ps.in_or_st) { /* this is either a structure * declaration or an init */ di_stack[ps.dec_nest++] = dec_ind; /* ? dec_ind = 0; */ } else { ps.decl_on_line = false; /* we cant be in the middle of * a declaration, so dont do * special indentation of * comments */ if (blanklines_after_declarations_at_proctop && ps.in_parameter_declaration) postfix_blankline_requested = 1; ps.in_parameter_declaration = 0; } dec_ind = 0; parse(lbrace); /* let parser know about this */ if (ps.want_blank) /* put a blank before '{' if '{' is not at * start of line */ *e_code++ = ' '; ps.want_blank = false; *e_code++ = '{'; ps.just_saw_decl = 0; break; case rbrace: /* got a '}' */ if (ps.p_stack[ps.tos] == decl && !ps.block_init) /* semicolons can be * omitted in * declarations */ parse(semicolon); if (ps.p_l_follow) {/* check for unclosed if, for, else. */ diag2(1, "Unbalanced parens"); ps.p_l_follow = 0; sp_sw = false; } ps.just_saw_decl = 0; ps.block_init_level--; if (s_code != e_code && !ps.block_init) { /* '}' must be first on * line */ if (verbose) diag2(0, "Line broken"); dump_line(); } *e_code++ = '}'; ps.want_blank = true; ps.in_stmt = ps.ind_stmt = false; if (ps.dec_nest > 0) { /* we are in multi-level structure * declaration */ dec_ind = di_stack[--ps.dec_nest]; if (ps.dec_nest == 0 && !ps.in_parameter_declaration) ps.just_saw_decl = 2; ps.in_decl = true; } prefix_blankline_requested = 0; parse(rbrace); /* let parser know about this */ ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead && ps.il[ps.tos] >= ps.ind_level; if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0) postfix_blankline_requested = 1; break; case swstmt: /* got keyword "switch" */ sp_sw = true; hd_type = swstmt; /* keep this for when we have seen the * expression */ goto copy_id; /* go move the token into buffer */ case sp_paren: /* token is if, while, for */ sp_sw = true; /* the interesting stuff is done after the * expression is scanned */ hd_type = (*token == 'i' ? ifstmt : (*token == 'w' ? whilestmt : forstmt)); /* * remember the type of header for later use by parser */ goto copy_id; /* copy the token into line */ case sp_nparen: /* got else, do */ ps.in_stmt = false; if (*token == 'e') { if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) { if (verbose) diag2(0, "Line broken"); dump_line();/* make sure this starts a line */ ps.want_blank = false; } force_nl = true;/* also, following stuff must go onto new line */ last_else = 1; parse(elselit); } else { if (e_code != s_code) { /* make sure this starts a line */ if (verbose) diag2(0, "Line broken"); dump_line(); ps.want_blank = false; } force_nl = true;/* also, following stuff must go onto new line */ last_else = 0; parse(dolit); } goto copy_id; /* move the token into line */ case decl: /* we have a declaration type (int, register, * etc.) */ parse(decl); /* let parser worry about indentation */ if (ps.last_token == rparen && ps.tos <= 1) { ps.in_parameter_declaration = 1; if (s_code != e_code) { dump_line(); ps.want_blank = 0; } } if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) { ps.ind_level = ps.i_l_follow = 1; ps.ind_stmt = 0; } ps.in_or_st = true; /* this might be a structure or initialization * declaration */ ps.in_decl = ps.decl_on_line = true; if ( /* !ps.in_or_st && */ ps.dec_nest <= 0) ps.just_saw_decl = 2; prefix_blankline_requested = 0; for (i = 0; token[i++];); /* get length of token */ if (ps.ind_level == 0 || ps.dec_nest > 0) { /* global variable or struct member in local variable */ dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i; tabs_to_var = (use_tabs ? ps.decl_indent > 0 : 0); } else { /* local variable */ dec_ind = ps.local_decl_indent > 0 ? ps.local_decl_indent : i; tabs_to_var = (use_tabs ? ps.local_decl_indent > 0 : 0); } goto copy_id; case ident: /* got an identifier or constant */ if (ps.in_decl) { /* if we are in a declaration, we must indent * identifier */ if (is_procname == 0 || !procnames_start_line) { if (!ps.block_init) { if (troff && !ps.dumped_decl_indent) { if (ps.want_blank) *e_code++ = ' '; ps.want_blank = false; sprintf(e_code, "\n.De %dp+\200p\n", dec_ind * 7); ps.dumped_decl_indent = 1; e_code += strlen(e_code); } else { int cur_dec_ind; int pos, startpos; /* * in order to get the tab math right for * indentations that are not multiples of 8 we * need to modify both startpos and dec_ind * (cur_dec_ind) here by eight minus the * remainder of the current starting column * divided by eight. This seems to be a * properly working fix */ startpos = e_code - s_code; cur_dec_ind = dec_ind; pos = startpos; if ((ps.ind_level * ps.ind_size) % 8 != 0) { pos += (ps.ind_level * ps.ind_size) % 8; cur_dec_ind += (ps.ind_level * ps.ind_size) % 8; } if (tabs_to_var) { while ((pos & ~7) + 8 <= cur_dec_ind) { CHECK_SIZE_CODE; *e_code++ = '\t'; pos = (pos & ~7) + 8; } } while (pos < cur_dec_ind) { CHECK_SIZE_CODE; *e_code++ = ' '; pos++; } if (ps.want_blank && e_code - s_code == startpos) *e_code++ = ' '; ps.want_blank = false; } } } else { if (ps.want_blank) *e_code++ = ' '; ps.want_blank = false; if (dec_ind && s_code != e_code) dump_line(); dec_ind = 0; } } else if (sp_sw && ps.p_l_follow == 0) { sp_sw = false; force_nl = true; ps.last_u_d = true; ps.in_stmt = false; parse(hd_type); } copy_id: if (ps.want_blank) *e_code++ = ' '; if (troff && ps.its_a_keyword) { e_code = chfont(&bodyf, &keywordf, e_code); for (t_ptr = token; *t_ptr; ++t_ptr) { CHECK_SIZE_CODE; *e_code++ = keywordf.allcaps && islower(*t_ptr) ? toupper(*t_ptr) : *t_ptr; } e_code = chfont(&keywordf, &bodyf, e_code); } else for (t_ptr = token; *t_ptr; ++t_ptr) { CHECK_SIZE_CODE; *e_code++ = *t_ptr; } ps.want_blank = true; break; case period: /* treat a period kind of like a binary * operation */ *e_code++ = '.'; /* move the period into line */ ps.want_blank = false; /* dont put a blank after a period */ break; case comma: ps.want_blank = (s_code != e_code); /* only put blank after comma * if comma does not start the * line */ if (ps.in_decl && is_procname == 0 && !ps.block_init) while ((e_code - s_code) < (dec_ind - 1)) { CHECK_SIZE_CODE; *e_code++ = ' '; } *e_code++ = ','; if (ps.p_l_follow == 0) { if (ps.block_init_level <= 0) ps.block_init = 0; if (break_comma && (!ps.leave_comma || compute_code_target() + (e_code - s_code) > max_col - 8)) force_nl = true; } break; case preesc: /* got the character '#' */ if ((s_com != e_com) || (s_lab != e_lab) || (s_code != e_code)) dump_line(); *e_lab++ = '#'; /* move whole line to 'label' buffer */ { int in_comment = 0; int com_start = 0; char quote = 0; int com_end = 0; while (*buf_ptr == ' ' || *buf_ptr == '\t') { buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); } while (*buf_ptr != '\n' || (in_comment && !had_eof)) { CHECK_SIZE_LAB; *e_lab = *buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); switch (*e_lab++) { case BACKSLASH: if (troff) *e_lab++ = BACKSLASH; if (!in_comment) { *e_lab++ = *buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); } break; case '/': if (*buf_ptr == '*' && !in_comment && !quote) { in_comment = 1; *e_lab++ = *buf_ptr++; com_start = e_lab - s_lab - 2; } break; case '"': if (quote == '"') quote = 0; break; case '\'': if (quote == '\'') quote = 0; break; case '*': if (*buf_ptr == '/' && in_comment) { in_comment = 0; *e_lab++ = *buf_ptr++; com_end = e_lab - s_lab; } break; } } while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t')) e_lab--; if (e_lab - s_lab == com_end && bp_save == 0) { /* comment on * preprocessor line */ if (sc_end == 0) /* if this is the first comment, we * must set up the buffer */ sc_end = &(save_com[0]); else { *sc_end++ = '\n'; /* add newline between * comments */ *sc_end++ = ' '; --line_no; } bcopy(s_lab + com_start, sc_end, com_end - com_start); sc_end += com_end - com_start; if (sc_end >= &save_com[sc_size]) abort(); e_lab = s_lab + com_start; while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t')) e_lab--; bp_save = buf_ptr; /* save current input buffer */ be_save = buf_end; buf_ptr = save_com; /* fix so that subsequent calls to * lexi will take tokens out of * save_com */ *sc_end++ = ' '; /* add trailing blank, just in case */ buf_end = sc_end; sc_end = 0; } *e_lab = '\0'; /* null terminate line */ ps.pcase = false; } if (strncmp(s_lab, "#if", 3) == 0) { if (blanklines_around_conditional_compilation) { int c; prefix_blankline_requested++; while ((c = getc(input)) == '\n'); ungetc(c, input); } if ((size_t)ifdef_level < sizeof(state_stack)/sizeof(state_stack[0])) { match_state[ifdef_level].tos = -1; state_stack[ifdef_level++] = ps; } else diag2(1, "#if stack overflow"); } else if (strncmp(s_lab, "#else", 5) == 0) if (ifdef_level <= 0) diag2(1, "Unmatched #else"); else { match_state[ifdef_level - 1] = ps; ps = state_stack[ifdef_level - 1]; } else if (strncmp(s_lab, "#endif", 6) == 0) { if (ifdef_level <= 0) diag2(1, "Unmatched #endif"); else { ifdef_level--; #ifdef undef /* * This match needs to be more intelligent before the * message is useful */ if (match_state[ifdef_level].tos >= 0 && bcmp(&ps, &match_state[ifdef_level], sizeof ps)) diag2(0, "Syntactically inconsistent #ifdef alternatives"); #endif } if (blanklines_around_conditional_compilation) { postfix_blankline_requested++; n_real_blanklines = 0; } } break; /* subsequent processing of the newline * character will cause the line to be printed */ case comment: /* we have gotten a / followed by * this is a biggie */ if (flushed_nl) { /* we should force a broken line here */ flushed_nl = false; dump_line(); ps.want_blank = false; /* dont insert blank at line start */ force_nl = false; } pr_comment(); break; } /* end of big switch stmt */ *e_code = '\0'; /* make sure code section is null terminated */ if (type_code != comment && type_code != newline && type_code != preesc) ps.last_token = type_code; } /* end of main while (1) loop */ }
static void stage_file_test(void) { static int name[] = { CTL_NET, NET_IPV4, NET_IPV4_LOCAL_PORT_RANGE }; int buffer[2] = { 32768, 61000 }; size_t size = sizeof(buffer); int pipe_fd[2] = { EOF, EOF }; int error = 0; int fd; char pbuffer[1024]; struct stat sbuf; struct sockaddr_un addr; struct ifreq ifreq; char *filename = ""; set_profile(3, "file::execute"); set_profile(3, "file::open"); set_profile(3, "file::create"); set_profile(3, "file::unlink"); set_profile(3, "file::mkdir"); set_profile(3, "file::rmdir"); set_profile(3, "file::mkfifo"); set_profile(3, "file::mksock"); set_profile(3, "file::truncate"); set_profile(3, "file::symlink"); set_profile(3, "file::rewrite"); set_profile(3, "file::mkblock"); set_profile(3, "file::mkchar"); set_profile(3, "file::link"); set_profile(3, "file::rename"); set_profile(3, "file::chmod"); set_profile(3, "file::chown"); set_profile(3, "file::chgrp"); set_profile(3, "file::ioctl"); set_profile(3, "file::chroot"); set_profile(3, "file::mount"); set_profile(3, "file::umount"); set_profile(3, "file::pivot_root"); policy = "allow_read /proc/sys/net/ipv4/ip_local_port_range"; write_domain_policy(policy, 0); show_result(sysctl(name, 3, buffer, &size, 0, 0), 1); write_domain_policy(policy, 1); show_result(sysctl(name, 3, buffer, &size, 0, 0), 0); policy = "allow_write /proc/sys/net/ipv4/ip_local_port_range"; write_domain_policy(policy, 0); show_result(sysctl(name, 3, 0, 0, buffer, size), 1); write_domain_policy(policy, 1); show_result(sysctl(name, 3, 0, 0, buffer, size), 0); policy = "allow_read/write /proc/sys/net/ipv4/ip_local_port_range"; write_domain_policy(policy, 0); show_result(sysctl(name, 3, buffer, &size, buffer, size), 1); write_domain_policy(policy, 1); show_result(sysctl(name, 3, buffer, &size, buffer, size), 0); policy = "allow_read /bin/true"; write_domain_policy(policy, 0); show_result(uselib("/bin/true"), 1); write_domain_policy(policy, 1); show_result(uselib("/bin/true"), 0); policy = "allow_execute /bin/true"; write_domain_policy(policy, 0); fflush(stdout); fflush(stderr); if (pipe(pipe_fd) == -1) err(1, "pipe"); if (fork() == 0) { execl("/bin/true", "/bin/true", NULL); if (write(pipe_fd[1], &errno, sizeof(errno)) == -1) err(1, "write"); exit(0); } close(pipe_fd[1]); (void)read(pipe_fd[0], &error, sizeof(error)); close(pipe_fd[0]); wait(NULL); errno = error; show_result(error ? EOF : 0, 1); write_domain_policy(policy, 1); fflush(stdout); fflush(stderr); if (pipe(pipe_fd) == -1) err(1, "pipe"); if (fork() == 0) { execl("/bin/true", "/bin/true", NULL); if (write(pipe_fd[1], &errno, sizeof(errno)) == -1) err(1, "write"); _exit(0); } close(pipe_fd[1]); (void)read(pipe_fd[0], &error, sizeof(error)); close(pipe_fd[0]); wait(NULL); errno = error; show_result(errno ? EOF : 0, 0); policy = "allow_read /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_RDONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_RDONLY); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_read /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_RDONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_RDONLY); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_read /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_RDONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_RDONLY); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_read /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_RDONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_RDONLY); show_result(fd, 0); if (fd != EOF) close(fd); set_profile(3, "file::mkfifo"); policy = "allow_mkfifo /tmp/mknod_fifo_test 0644"; write_domain_policy(policy, 0); filename = "/tmp/mknod_fifo_test"; show_result(mknod(filename, S_IFIFO | 0644, 0), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(mknod(filename, S_IFIFO | 0644, 0), 0); memset(pbuffer, 0, sizeof(pbuffer)); memset(&sbuf, 0, sizeof(sbuf)); filename = "/dev/null"; stat(filename, &sbuf); snprintf(pbuffer, sizeof(pbuffer) - 1, "allow_write %s", filename); policy = pbuffer; write_domain_policy(policy, 0); fd = open(filename, O_WRONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open(filename, O_WRONLY); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_read/write /tmp/fifo"; mkfifo2("/tmp/fifo"); write_domain_policy(policy, 0); fd = open("/tmp/fifo", O_RDWR); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/tmp/fifo", O_RDWR); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_read /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_RDONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_RDONLY); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_write /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_WRONLY); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_WRONLY); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_read/write /dev/null"; write_domain_policy(policy, 0); fd = open("/dev/null", O_RDWR); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open("/dev/null", O_RDWR); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_create /tmp/open_test 0644"; write_domain_policy(policy, 0); policy = "allow_write /tmp/open_test"; write_domain_policy(policy, 0); fd = open("/tmp/open_test", O_WRONLY | O_CREAT | O_EXCL, 0644); show_result(fd, 1); if (fd != EOF) close(fd); unlink2("/tmp/open_test"); write_domain_policy(policy, 1); fd = open("/tmp/open_test", O_WRONLY | O_CREAT | O_EXCL, 0644); show_result(fd, 0); if (fd != EOF) close(fd); unlink2("/tmp/open_test"); policy = "allow_create /tmp/open_test 0644"; write_domain_policy(policy, 1); policy = "allow_write /tmp/open_test"; write_domain_policy(policy, 0); policy = "allow_create /tmp/open_test 0644"; write_domain_policy(policy, 0); fd = open("/tmp/open_test", O_WRONLY | O_CREAT | O_EXCL, 0644); show_result(fd, 1); if (fd != EOF) close(fd); unlink2("/tmp/open_test"); write_domain_policy(policy, 1); fd = open("/tmp/open_test", O_WRONLY | O_CREAT | O_EXCL, 0644); show_result(fd, 0); if (fd != EOF) close(fd); unlink2("/tmp/open_test"); policy = "allow_write /tmp/open_test"; write_domain_policy(policy, 1); filename = "/tmp/truncate_test"; create2(filename); policy = "allow_truncate /tmp/truncate_test"; write_domain_policy(policy, 0); policy = "allow_write /tmp/truncate_test"; write_domain_policy(policy, 0); fd = open(filename, O_WRONLY | O_TRUNC); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open(filename, O_WRONLY | O_TRUNC); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_truncate /tmp/truncate_test"; write_domain_policy(policy, 1); policy = "allow_write /tmp/truncate_test"; write_domain_policy(policy, 0); policy = "allow_truncate /tmp/truncate_test"; write_domain_policy(policy, 0); fd = open(filename, O_WRONLY | O_TRUNC); show_result(fd, 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); fd = open(filename, O_WRONLY | O_TRUNC); show_result(fd, 0); if (fd != EOF) close(fd); policy = "allow_write /tmp/truncate_test"; write_domain_policy(policy, 1); policy = "allow_truncate /tmp/truncate_test"; write_domain_policy(policy, 0); show_result(truncate(filename, 0), 1); write_domain_policy(policy, 1); show_result(truncate(filename, 0), 0); policy = "allow_truncate /tmp/truncate_test"; write_domain_policy(policy, 0); set_profile(0, "file::open"); fd = open(filename, O_WRONLY); set_profile(3, "file::open"); show_result(ftruncate(fd, 0), 1); write_domain_policy(policy, 1); show_result(ftruncate(fd, 0), 0); if (fd != EOF) close(fd); unlink2(filename); policy = "allow_create /tmp/mknod_reg_test 0644"; write_domain_policy(policy, 0); filename = "/tmp/mknod_reg_test"; show_result(mknod(filename, S_IFREG | 0644, 0), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(mknod(filename, S_IFREG | 0644, 0), 0); policy = "allow_mkchar /tmp/mknod_chr_test 0644 1 3"; write_domain_policy(policy, 0); filename = "/tmp/mknod_chr_test"; show_result(mknod(filename, S_IFCHR | 0644, MKDEV(1, 3)), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(mknod(filename, S_IFCHR | 0644, MKDEV(1, 3)), 0); policy = "allow_mkblock /tmp/mknod_blk_test 0644 1 0"; write_domain_policy(policy, 0); filename = "/tmp/mknod_blk_test"; show_result(mknod(filename, S_IFBLK | 0644, MKDEV(1, 0)), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(mknod(filename, S_IFBLK | 0644, MKDEV(1, 0)), 0); policy = "allow_mkfifo /tmp/mknod_fifo_test 0644"; write_domain_policy(policy, 0); filename = "/tmp/mknod_fifo_test"; show_result(mknod(filename, S_IFIFO | 0644, 0), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(mknod(filename, S_IFIFO | 0644, 0), 0); policy = "allow_mksock /tmp/mknod_sock_test 0644"; write_domain_policy(policy, 0); filename = "/tmp/mknod_sock_test"; show_result(mknod(filename, S_IFSOCK | 0644, 0), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(mknod(filename, S_IFSOCK | 0644, 0), 0); policy = "allow_mkdir /tmp/mkdir_test/ 0600"; write_domain_policy(policy, 0); filename = "/tmp/mkdir_test"; show_result(mkdir(filename, 0600), 1); write_domain_policy(policy, 1); rmdir2(filename); show_result(mkdir(filename, 0600), 0); policy = "allow_rmdir /tmp/rmdir_test/"; write_domain_policy(policy, 0); filename = "/tmp/rmdir_test"; mkdir2(filename); show_result(rmdir(filename), 1); write_domain_policy(policy, 1); mkdir2(filename); show_result(rmdir(filename), 0); rmdir2(filename); policy = "allow_unlink /tmp/unlink_test"; write_domain_policy(policy, 0); filename = "/tmp/unlink_test"; create2(filename); show_result(unlink(filename), 1); write_domain_policy(policy, 1); create2(filename); show_result(unlink(filename), 0); unlink2(filename); policy = "allow_symlink /tmp/symlink_source_test"; write_domain_policy(policy, 0); filename = "/tmp/symlink_source_test"; show_result(symlink("/tmp/symlink_dest_test", filename), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(symlink("/tmp/symlink_dest_test", filename), 0); policy = "allow_symlink /tmp/symlink_source_test"; write_domain_policy(policy, 0); filename = "/tmp/symlink_source_test"; show_result(symlink("/tmp/symlink_dest_test", filename), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(symlink("/tmp/symlink_dest_test", filename), 0); policy = "allow_symlink /tmp/symlink_source_test"; write_domain_policy(policy, 0); filename = "/tmp/symlink_source_test"; show_result(symlink("/tmp/symlink_dest_test", filename), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(symlink("/tmp/symlink_dest_test", filename), 0); policy = "allow_symlink /tmp/symlink_source_test"; write_domain_policy(policy, 0); filename = "/tmp/symlink_source_test"; show_result(symlink("/tmp/symlink_dest_test", filename), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(symlink("/tmp/symlink_dest_test", filename), 0); policy = "allow_symlink /tmp/symlink_source_test"; write_domain_policy(policy, 0); filename = "/tmp/symlink_source_test"; show_result(symlink("/tmp/symlink_dest_test", filename), 1); write_domain_policy(policy, 1); unlink2(filename); show_result(symlink("/tmp/symlink_dest_test", filename), 0); policy = "allow_link /tmp/link_source_test /tmp/link_dest_test"; write_domain_policy(policy, 0); filename = "/tmp/link_source_test"; create2(filename); show_result(link(filename, "/tmp/link_dest_test"), 1); write_domain_policy(policy, 1); unlink2("/tmp/link_dest_test"); show_result(link(filename, "/tmp/link_dest_test"), 0); unlink2(filename); policy = "allow_rename /tmp/rename_source_test /tmp/rename_dest_test"; write_domain_policy(policy, 0); filename = "/tmp/rename_source_test"; create2(filename); show_result(rename(filename, "/tmp/rename_dest_test"), 1); write_domain_policy(policy, 1); unlink2("/tmp/rename_dest_test"); create2(filename); show_result(rename(filename, "/tmp/rename_dest_test"), 0); unlink2(filename); policy = "allow_mksock /tmp/socket_test 0755"; write_domain_policy(policy, 0); filename = "/tmp/socket_test"; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, filename, sizeof(addr.sun_path) - 1); fd = socket(AF_UNIX, SOCK_STREAM, 0); show_result(bind(fd, (struct sockaddr *) &addr, sizeof(addr)), 1); if (fd != EOF) close(fd); write_domain_policy(policy, 1); unlink2(filename); fd = socket(AF_UNIX, SOCK_STREAM, 0); show_result(bind(fd, (struct sockaddr *) &addr, sizeof(addr)), 0); if (fd != EOF) close(fd); filename = "/tmp/rewrite_test"; create2(filename); policy = "allow_read/write /tmp/rewrite_test"; write_domain_policy(policy, 0); write_exception_policy("deny_rewrite /tmp/rewrite_test", 0); policy = "allow_truncate /tmp/rewrite_test"; write_domain_policy(policy, 0); fd = open(filename, O_RDONLY); show_result(fd, 1); if (fd != EOF) close(fd); fd = open(filename, O_WRONLY | O_APPEND); show_result(fd, 1); if (fd != EOF) close(fd); fd = open(filename, O_WRONLY); show_result(fd, 0); if (fd != EOF) close(fd); fd = open(filename, O_WRONLY | O_TRUNC); show_result(fd, 0); if (fd != EOF) close(fd); fd = open(filename, O_WRONLY | O_TRUNC | O_APPEND); show_result(fd, 0); if (fd != EOF) close(fd); show_result(truncate(filename, 0), 0); set_profile(0, "file::open"); fd = open(filename, O_WRONLY | O_APPEND); set_profile(3, "file::open"); show_result(ftruncate(fd, 0), 0); show_result(fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_APPEND), 0); if (fd != EOF) close(fd); write_domain_policy(policy, 1); policy = "allow_read/write /tmp/rewrite_test"; write_domain_policy(policy, 1); write_exception_policy("deny_rewrite /tmp/rewrite_test", 1); unlink2(filename); policy = "allow_ioctl socket:[family=2:type=2:protocol=17] " "35122-35124"; write_domain_policy(policy, 0); fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); memset(&ifreq, 0, sizeof(ifreq)); snprintf(ifreq.ifr_name, sizeof(ifreq.ifr_name) - 1, "lo"); show_result(ioctl(fd, 35123, &ifreq), 1); write_domain_policy(policy, 1); policy = "allow_ioctl " "socket:[family=2:type=2:protocol=17] 0-35122"; write_domain_policy(policy, 0); show_result(ioctl(fd, 35123, &ifreq), 0); write_domain_policy(policy, 1); if (fd != EOF) close(fd); }
static void set_level(const int i) { set_profile(i, "file::execute"); set_profile(i, "file::open"); set_profile(i, "file::create"); set_profile(i, "file::unlink"); set_profile(i, "file::mkdir"); set_profile(i, "file::rmdir"); set_profile(i, "file::mkfifo"); set_profile(i, "file::mksock"); set_profile(i, "file::truncate"); set_profile(i, "file::symlink"); set_profile(i, "file::rewrite"); set_profile(i, "file::mkblock"); set_profile(i, "file::mkchar"); set_profile(i, "file::link"); set_profile(i, "file::rename"); set_profile(i, "file::chmod"); set_profile(i, "file::chown"); set_profile(i, "file::chgrp"); set_profile(i, "file::ioctl"); set_profile(i, "file::chroot"); set_profile(i, "file::mount"); set_profile(i, "file::umount"); set_profile(i, "file::pivot_root"); }
int main(int argc, char *argv[]) { uint8_t *tab_rp_bits; uint16_t *tab_rp_registers; uint16_t *rd_position_registers; uint16_t *tab_rp_registers_bad; modbus_t *ctx; /*********************************************************************** * feedback is used to store the return value of every called function * rc is used to store the return value of the modbus command * resend is used to define the resend times if the command is failed * i is used for the loop parameter * insert_bit is used to indicate the calibarate function if there is value to set * num is used to store the number of data blocks in database * use_backend is used to indicate the modbus mode is rtu * next_option is used to take the command options * pre_step, curr_step are used to indicate the previous step number and current position step number * pre_length and value indicate the latest posiotion in database and current position * SLEN is a kind of struct used to store the database blocks ************************************************************************/ int feedback,i; int insert_bit, nb_points,num =0; int next_option; long curr_step; long pystep = -1; double value; double pdepth,pspacing,pdwell,pinterval; double profiled,stopped; double depth,dwell,spacing,interval; double last_position; int profilebit =0,feedback1,feedback2; int modbus=0; int motor_stop = 0; char * command_arg = ""; char * return_value; double in_position = 0; SLEN *examp; ARF *config, *profile,*off_set; modbus_mapping_t *mb_mapping; int ShmID; int *ShmPTR; int stop_indicator = 0; key_t MyKey; MyKey = ftok(".", 's'); ShmID = shmget(MyKey, sizeof(int), IPC_CREAT | 0666); ShmPTR = (int *) shmat(ShmID, NULL, 0); tab_rp_registers = (uint16_t *) malloc(4 * sizeof(uint16_t)); rd_position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t)); tab_rp_registers_bad = (uint16_t *) malloc(2 * sizeof(uint16_t)); config = (ARF*)malloc( 10 * sizeof(ARF) ); if ( config == NULL ) { printf("Error: Out of Memory, use ./master reset to reset memory\n"); exit(1); } const char *const short_options = "hd::u::l:p::cD::w::s::i::gSmt::"; const struct option long_options[] = { { "help", 0,NULL, 'h'}, { "down", 2,NULL, 'd'}, { "up", 2,NULL, 'u'}, { "length", 1,NULL, 'l'}, { "position", 2,NULL, 'p'}, { "count", 0,NULL, 'c'}, { "Depth", 2,NULL, 'D'}, { "well", 2,NULL, 'w'}, { "spacing", 2,NULL, 's'}, { "interval", 2,NULL, 'i'}, { "go", 0,NULL, 'g'}, { "System", 0,NULL, 'S'}, { "motor", 0,NULL, 'm'}, { "time", 2,NULL, 't'}, { NULL, 0, NULL, 0 }, }; if (argc < 2) { print_comusage (stderr, 1); return_value = json_option("status:",-1); return return_value; } program_name = argv[0]; /*Get the first argument that passed through main function but does not contain*/ command_name = argv[1]; if(argc > 2) { command_arg = argv[2]; } /******************************************************************************************* * The next three command_name are used to control the motor through modbus (need modbus) * ********************************************************************************************/ if ( strcmp(command_name, "go") == 0 ) { double curr_position; char *recd = (char*)malloc(10*sizeof(char)); double offset; int re_send = 0; *ShmPTR = 0; modbus = 0; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if (next_option == -1) print_comusage (stderr, 1); while (next_option != -1) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'd': godown: enable(0); initbus(1); /* sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = godown(ctx); if((feedback == -1)&&(re_send <1)) { enable(0); initbus(0); re_send++; goto godown; } return_value = json_option("status",feedback); printf("%s\n",return_value); */ feedback = process_go_down(1); if((feedback == 0) && (re_send < 1)) { printf("get false recycle power\n"); enable(0); initbus(0); re_send++; goto godown; } return_value = json_option("status",feedback); printf("%s\n",return_value); break; case 'u': goup: enable(0); initbus(1); /* sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = goup(ctx); if((feedback == -1)&&(re_send <1)) { enable(0); initbus(0); re_send++; goto goup; } */ feedback = process_go_up(1); if((feedback == 0) && (re_send < 1)) { printf("Get false recycle power\n"); enable(0); initbus(0); re_send++; goto goup; } return_value = json_option("status",feedback); printf("%s\n",return_value); break; case 'p': enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; in_position = atof(optarg); off_set = (ARF*)malloc(15*sizeof(ARF)); off_set = getconfig(&num,off_set); offset = off_set[10].value; in_position = in_position - offset; //printf("inposition is %f offset is %f\n",in_position,offset); free(off_set); //system("/home/sampler/kingkong.sh"); gotoposition: if (in_position <= 0) { if( process_read_home_switch(1) == 0) { feedback = process_go_home(1); } else feedback = 1; } else { pystep = process_read_step(1); curr_position = process_position(pystep); if ( !(( (in_position -0.1) <= curr_position ) && ( curr_position <= (in_position + 0.1) )) ) { feedback = process_go_position(1,in_position); return_value = json_option("status",feedback); } } if((feedback == 0)&&(re_send <1)) { printf("get false recycle power"); enable(0); initbus(0); enable(0); initbus(1); re_send++; goto gotoposition; } break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } //If the go command is failed, then exit the current process and power off the controller if(feedback == 0) { printf("1\n"); //*ShmPTR = 1; enable(0); initbus(0); return_value = json_option("status",-1); return return_value; } do{ usleep(5000); stop_indicator = process_check(1); }while(stop_indicator != 0); //printf("stop\n"); sleep(1); pystep = process_read_step(1); curr_position = process_position(pystep); //printf("cur position is %f\n",curr_position); if(curr_position != -1) { login("Go to command set last position"); curr_position = curr_position + offset; setconfig(9,curr_position); // In order to avoid "Read status command shutdown the power by accident enable(0); initbus(0); return_value = json_option("status",1); } else return_value = json_option("status",-1); } if ( strcmp(command_name, "stop") == 0 ) { if(check_power() == 1) { /*sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = stop(ctx); if(feedback == -1)stop(ctx); */ process_stop(1); } } if ( strcmp(command_name, "position") == 0 ) { login("Check position command"); int resend = 0; double temp_position,offset; char *rec = (char*)malloc(10*sizeof(char)); stop_indicator = *ShmPTR; uint16_t * position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t)); off_set = (ARF*)malloc(15*sizeof(ARF)); off_set = getconfig(&num,off_set); offset = off_set[10].value; checkposition: if (check_power()== 1) { ctx = modbusconnection(ctx); modbus = 1; temp_position = checkposition(ctx,position_registers); sprintf(rec,"The position read is %f",temp_position); login(rec); if(temp_position != -1) { login("Check position set last position"); //This sentence is used to show the position with offset temp_position = temp_position + offset; feedback = setconfig(9,temp_position); } else { if(resend < 2) { resend++; goto checkposition; } else return -100; } } else { config = getconfig(&num,config); temp_position = config[8].value; } return_value = json_float_option("status",temp_position); printf("%s\n",return_value); } /*********************************************************************** * 0: motor is stopped * * 1: motor is going down * * 2: motor is going up * * 3: motor is ramp up * * 4: motor is ramp down * * (need modbus) * * * ************************************************************************/ if(strcmp(command_name, "status") == 0) { stop_indicator = *ShmPTR; if (check_power()== 1) { sleep(1); ctx = modbusconnection(ctx); modbus = 1; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if(next_option == -1) print_comusage (stderr, 1); while(next_option != -1) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'S': feedback = checksystemstatus(ctx,tab_rp_registers); return_value = json_option("status",feedback); break; case 'm': feedback = checkmotorstatus(ctx,tab_rp_registers); return_value = json_option("status",feedback); break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } if(feedback == -1) { return_value = json_option("status",0); } } else { return_value = json_option("status",0); //login("Check status from database"); } printf("%s\n",return_value); } /**************************************************************************************** * The next three command_name are used to control the database through sqlite3 * *****************************************************************************************/ if ( strcmp(command_name, "factory_default") == 0 ) { feedback1 = reset(0); feedback2 = dbinit(0); if ( (feedback1 == 1) && (feedback2 == 1)) { return_value = json_float_option("status",1); printf("%s\n",return_value); } else { return_value = json_float_option("status",-1); printf("%s\n",return_value); } } if ( strcmp(command_name, "reset") == 0 ) { feedback = reset(0); if(feedback == 1) { feedback = expected_time_reset(); } return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name, "init") == 0 ) { feedback = -1; if ( strcmp(command_arg, "all") == 0 ) { feedback = dbinit(0); if(feedback == 1) { feedback = expected_time_init(); } } if ( strcmp(command_arg, "calibrate" ) == 0 ) { setconfig(6,0); feedback = dbinit(1); } if ( strcmp(command_arg, "configure" ) == 0 ) { feedback = dbinit(2); } if ( feedback == -1 ) { return_value = json_float_option("status",-1); print_comusage (stderr, 1); } else return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name,"get") == 0 ) { examp = getall(&num,examp); return_value = json_array_option(num,examp); free(examp); printf("%s",return_value); } if ( strcmp(command_name,"set_offset") == 0 ) { double offset; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if ( next_option == -1 ) print_comusage (stderr, 1); while( next_option != -1 ) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'l': if(optarg!=0)offset = strtod(optarg,NULL); insert_bit = 1; break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } feedback = setconfig(11,offset); return_value = json_option("status",feedback); printf("%s",return_value); } if ( strcmp(command_name,"get_offset") == 0 ) { double offset; off_set = (ARF*)malloc(15*sizeof(ARF)); off_set = getconfig(&num,off_set); offset = off_set[10].value; return_value = json_float_option("status",offset); printf("%s",return_value); free(off_set); } /************************************************************************** * The next three command_name are used to calibrate (need modbus) * ***************************************************************************/ if ( strcmp(command_name, "calibrate") == 0 ) { double calibrate; enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if ( next_option == -1 ) print_comusage (stderr, 1); config = getconfig(&num,config); calibrate = config[5].value; if ( calibrate == 0 ) { reset(1); setconfig(6,1.0); set(num,0,0); } while( next_option != -1 ) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'l': if(optarg!=0)value = atof(optarg); insert_bit = 1; break; case 'c': getall(&num,examp); return_value = json_option("status",num); printf("%s\n",return_value); break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } if ( insert_bit == 1 ) { curr_step = checksteps(ctx,rd_position_registers); if ( curr_step < 0 ) curr_step =0;//do not need feedback = checkvalue(curr_step,value); if ( feedback == 1 ) { feedback = set(num,curr_step,value); return_value = json_option("status",feedback); } else { return_value = json_option("status",-1); } } /*if ( checkmotorstatus(ctx,tab_rp_registers) == 0 ) { enable(0); initbus(0); }*/ printf("%s\n",return_value); } /*********************************************************************** * The following functions are used for profile * * * ************************************************************************/ if ( strcmp(command_name, "profile") == 0 ) { next_option = getopt_long (argc, argv, short_options, long_options, NULL); if ( next_option == -1 ) print_comusage (stderr, 1); while ( next_option != -1 ) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'd': if(optarg!=0)depth = atof(optarg); profilebit = 1; break; case 's': if(optarg!=0)spacing = atof(optarg); profilebit = 1; break; case 'w': if(optarg!=0)dwell = atof(optarg); profilebit = 1; break; case 'i': //if(optarg!=0)interval = atof(optarg); if(optarg!=0)interval = strtod(optarg,NULL); profilebit = 1; break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } if ( profilebit == 1 ) { feedback = set_profile(depth,spacing,dwell,interval); } //Want to get the expected profile time and save it in database profile_time_check(interval); return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name, "profileget" ) == 0) { profile = getconfig(&num,config); return_value = json_profile_option(num-2,profile); free(profile); printf("%s",return_value); } if ( strcmp(command_name, "profile_check" ) == 0) { int *expected_profile_time; long remain_profile_time; config = getconfig(&num,config); pinterval = config[3].value; if(pinterval == 0) { printf("-999\n"); return -999; } expected_profile_time = (int*)malloc(10*sizeof(int)); if(expected_profile_time == NULL){printf("error\n");exit(1);} expected_time_get(expected_profile_time); remain_profile_time = auto_run(0,expected_profile_time); if(remain_profile_time <=0 )remain_profile_time = 0; printf("%d\n",remain_profile_time); free(expected_profile_time); return remain_profile_time; } if ( strcmp(command_name, "profile_reset") == 0 ) { //feedback = dbinit(2); //reading_hourly(); system("ps aux | grep -e 'master profilego' | grep -v grep | awk '{print $2}' | xargs -i kill {}"); feedback = set_profile(0,0,0,0); return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name, "profilego") == 0 ) { double stayposition, curr_position,tmp,cal_position; double sdl_read,offset; long wait_time,motor_status; int year; time_t fail_time; int stop_check = -1; int count,fini_count,re_try1 = 0,re_power1 =0,re_try = 0,re_send=0; int i=1,sample = 0,profile_times,sample_indicator; int * expected_tm, *curr_time,inter_val; setconfig(10,0); profile: /* The following eight lines are used to get profile arguments from database */ config = getconfig(&num,config); pdepth = config[0].value; pspacing = config[1].value; pdwell = config[2].value; pinterval = config[3].value; profiled = config[4].value; sample = config[9].value; offset = config[10].value; profile_times = 1+(pdepth - offset)/pspacing; // Caculate the profile times inter_val = (int)pinterval; if(pinterval == 0){schedule_reading();goto profile;} if(profiled == 0 ) { config = getconfig(&num,config); pdepth = config[0].value; pspacing = config[1].value; pdwell = config[2].value; pinterval = config[3].value; profiled = config[4].value; sample = config[9].value; /* The following part are used to get the expected profile time and compare with current time */ expected_tm = (int*)malloc(10*sizeof(int)); curr_time = (int*)malloc(10*sizeof(int)); if(curr_time == NULL){printf("error\n");exit(1);} if(expected_tm == NULL){printf("error\n");exit(1);} do{ config = getconfig(&num,config); sample = config[9].value; expected_time_get(expected_tm); wait_time= auto_run(0,expected_tm); curr_time = check_time(curr_time); sample_indicator = curr_time[3]%inter_val; printf("Wait for next profile\n"); //because the board will boot up 3 minutes after clock time if(wait_time < -600) { profile_time_check(pinterval); goto profile; } sleep(1); }while(wait_time>0); free(expected_tm); four_minute_delay: sleep(1); curr_time = check_time(curr_time); if((curr_time[4]>=4) &&(curr_time[4]<=10))goto start_profile; if(curr_time[4]<4)goto four_minute_delay; if(curr_time[4]>10)goto profile; } start_profile: enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); if(ctx == NULL)goto profile; modbus = 1; sleep(9); if ( profiled == 0 ) { if (process_syncclock() == 0) { login("Failed in connectting with SDL"); return; } if (process_expression(3,1,profile_times,0) == 0) { login("Failed in send profile to SDL"); return; } login("Start Profiling"); if( process_read_home_switch(1) == 0) { gotoposition(ctx, 0,rd_position_registers); //Do not need to check if it is home because we want it home anyway do{ usleep(5000); stop_check = process_check(1); }while(stop_check != 0); if(process_pass_through_check() == 0)initbus(0); setconfig(5,1); //Set the profile flag sleep(pdwell); } else { setconfig(5,1); sleep(pdwell); } } enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); /* This following part is used to determine where is destination */ curr_position = checkposition(ctx,tab_rp_registers) + offset; cal_position = i*pspacing + offset; if ( cal_position < pdepth ) { stayposition = cal_position; } else stayposition = pdepth; i++; stayposition = stayposition - offset; gotoposition(ctx,stayposition,tab_rp_registers); position1: sleep(1); ctx = modbusconnection(ctx); curr_position = checkposition(ctx,tab_rp_registers) + offset; if(curr_position == -1) { if(re_power1 < 3) { if(re_try1 < 2) { sleep(3); re_try1++; goto position1; } else { re_try1 = 0; enable(0); initbus(0); sleep(3); initbus(1); sleep(1); re_power1++; goto position1; } } else { enable(0); initbus(0); enable(1); re_power1 = 0; return -1; } } if (!((stayposition -0.1) <= curr_position ) && (curr_position <= (stayposition + 0.1)))goto position1; wait_for_stop(ctx, tab_rp_registers); //Here check position in order to determine if it is destination now curr_position = checkposition(ctx,tab_rp_registers)+offset; setconfig(9,curr_position); printf("Go to sleep for dwell time\n"); if(process_pass_through_check() == 0)initbus(0); // Add this part to check if it is passing command sleep(pdwell); if (((pdepth -0.1) <= curr_position) && (curr_position <= (pdepth + 0.1))) { setconfig(5,0); //Set profile flag here to avoid reprofile if something wrong happens during following profile_time_check(pinterval); // Set next profile time enable(0); initbus(1); ctx = modbusconnection(ctx); gotoposition(ctx,0,rd_position_registers); // After finish profile, go home wait_for_stop(ctx, tab_rp_registers); sleep(1); enable(0); if(process_pass_through_check() == 0) initbus(0); //Check is pass through enable(1); setconfig(9,offset); //Save the position 0 sleep(40); goto profile; } goto profile; } /*********************************************************************** * The next three command_name are used * * to control the date and time * ************************************************************************/ if ( strcmp(command_name, "checktime") == 0 ) { /* char *sdate; if ( (sdate = malloc( 80 * sizeof(char) ) )== NULL)return NULL; sdate = current_time(sdate); return_value = json_option_string("status",sdate); printf("%s\n",return_value); free(sdate); */ //long pystep = process_read_step(1); //process_position(pystep); //process_expression(3,1,3,1); //process_pass_through_check(); //process_syncclock(); process_expression(3,1,3,0); process_read_home_switch(1); } if ( strcmp(command_name, "settime") == 0 ) { if ( argc < 4 ) { print_comusage (stderr, 1); } char *date = argv[2]; char *time = argv[3]; int *buf = (int*)malloc(6*sizeof(int)); parse(buf,date,time); int i,m_buf[6]; for(i=0;i<=5;i++) { m_buf[i]=*(buf+i); } feedback = set_time(&m_buf); return_value = json_option("status:",feedback); printf("%s\n",return_value); login("Set local time"); login(return_value); sleep(5); } if ( strcmp(command_name, "voltage") == 0 ) { double voltage; voltage = voltage_read(); return_value = json_float_option("status",voltage); printf("%s\n",return_value); } if ( strcmp(command_name, "temp") == 0 ) { double temp; temp = temp_read(); return_value = json_float_option("status",temp); printf("%s\n",return_value); } if(strcmp(command_name, "enable_power") == 0) { enable(0); initbus(1); return_value = json_option("status:",1); } if(strcmp(command_name, "disable_power") == 0) { enable(0); initbus(0); return_value = json_option("status:",1); } if ( strcmp(command_name, "backup") == 0 ) { feedback = system("cp /home/sampler/lr.sl3 /home/sampler/lr_default.sl3"); if(feedback == -1) { return_value = json_float_option("status",-1); } else return_value = json_float_option("status",1); printf("%s\n",return_value); } if ( strcmp(command_name, "restore") == 0 ) { feedback = system("cp /home/sampler/lr_default.sl3 /home/sampler/lr.sl3"); if(feedback == -1) { return_value = json_float_option("status",-1); } else return_value = json_float_option("status",1); printf("%s\n",return_value); } if ( strcmp(command_name, "debug") == 0 ) { long return_steps; char *debug_result; enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; uint16_t *debug_position_registers = (uint16_t*)malloc(2*sizeof(uint16_t)); debug_result = (char*)malloc(50*sizeof(char)); return_steps = checksteps(ctx,debug_position_registers); sprintf(debug_result,"%x,%x,%x\n",debug_position_registers[0],debug_position_registers[1],return_steps); json_option_string("status",debug_result); printf("%s\n",debug_result); initbus(0); } if ( strcmp(command_name, "power_check") == 0 ) { int power_status = check_power(); printf("Power is %d\n",power_status); } if ( strcmp(command_name, "sdl") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl != NULL) { double vol = sdltest(sdl); return_value = json_float_option("status",vol); printf("%s\n",return_value); setsdl(30000,vol); login("Read SDL"); login(return_value); } else setsdl(30000,-100000); modbus_close(sdl); modbus_free(sdl); } if ( strcmp(command_name, "sdl_reset") == 0 ) { resetsdl(); } if ( strcmp(command_name, "sdl_get") == 0 ) { int num_records; SLEN * sdl_records; sdl_records = (SLEN*)malloc(100*sizeof(SLEN)); sdl_records = getsdl(&num_records, sdl_records); return_value = json_sdl_option(num_records,sdl_records); printf("%s\n",return_value); free(sdl_records); } if ( strcmp(command_name, "sdl_uploadtime") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_setuploadtime(sdl,12,5,21,12,50,0); } if ( strcmp(command_name, "sdl_settime") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_rtc_time(sdl,12,5,25,7,58,0); } if ( strcmp(command_name, "sdl_readsize") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_readbuffsize(sdl); } if ( strcmp(command_name, "sdl_readsensor") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_read_sensor(sdl,1,1); } if ( strcmp(command_name, "sdl_upload") == 0 ) { //sdl_read_log_data(16); int number; modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else { profile_save_data(sdl); } modbus_close(sdl); } if ( strcmp(command_name, "sdl_sample") == 0 ) { int number; modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else { sdl_read_sensor(sdl,1,1); sleep(60); sample_save_data(sdl); //sdl_start_profile(sdl,2); } modbus_close(sdl); } if ( strcmp(command_name, "shutdown") == 0 ) { feedback = system("/sbin/shutdown now"); } if ( strcmp(command_name, "maxstep") == 0 ) { enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = set_max_step(ctx,rd_position_registers); return_value = json_option("status",feedback); initbus(0); } if(strcmp(command_name, "slave") == 0) { slave(); } if(strcmp(command_name, "motor_status") == 0) { if (check_power()== 1) { sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = checkmotorstatus(ctx,tab_rp_registers); if(feedback == -1) { printf("0\n"); return 0; } else { printf("%d\n",feedback); return feedback; } } else { printf("0\n"); return 0; } } close: /* Free the memory */ free(config); free(tab_rp_registers); free(rd_position_registers); //modbus_mapping_free(mb_mapping); /* Close the connection */ if (modbus == 1) { modbus_close(ctx); } if (motor_stop == 1) { printf("stop setting\n"); setconfig(9,last_position); } return return_value; }
static void setup_all_test_file_truncate(void) { setup_all_test_file(); write_domain_policy("allow_truncate /tmp/testfile\\$", 0); set_profile(3, "file::truncate"); }
static BOOL load_gecko(void) { nsresult nsres; nsIObserver *pStartNotif; nsIComponentRegistrar *registrar = NULL; nsAString path; nsIFile *gre_dir; PRUnichar gre_path[MAX_PATH]; static BOOL tried_load = FALSE; TRACE("()\n"); if(tried_load) return pCompMgr != NULL; tried_load = TRUE; if(!load_wine_gecko(gre_path) && !load_mozctl(gre_path) && !load_mozilla(gre_path)) { install_wine_gecko(); if(!load_wine_gecko(gre_path)) { MESSAGE("Could not load Mozilla. HTML rendering will be disabled.\n"); return FALSE; } } NS_StringContainerInit(&path); NS_StringSetData(&path, gre_path, PR_UINT32_MAX); nsres = NS_NewLocalFile(&path, FALSE, &gre_dir); NS_StringContainerFinish(&path); if(NS_FAILED(nsres)) { ERR("NS_NewLocalFile failed: %08lx\n", nsres); FreeLibrary(hXPCOM); return FALSE; } nsres = NS_InitXPCOM2(&pServMgr, gre_dir, NULL); if(NS_FAILED(nsres)) { ERR("NS_InitXPCOM2 failed: %08lx\n", nsres); FreeLibrary(hXPCOM); return FALSE; } nsres = nsIServiceManager_QueryInterface(pServMgr, &IID_nsIComponentManager, (void**)&pCompMgr); if(NS_FAILED(nsres)) ERR("Could not get nsIComponentManager: %08lx\n", nsres); nsres = NS_GetComponentRegistrar(®istrar); if(NS_SUCCEEDED(nsres)) { nsres = nsIComponentRegistrar_AutoRegister(registrar, NULL); if(NS_FAILED(nsres)) ERR("AutoRegister(NULL) failed: %08lx\n", nsres); nsres = nsIComponentRegistrar_AutoRegister(registrar, gre_dir); if(NS_FAILED(nsres)) ERR("AutoRegister(gre_dir) failed: %08lx\n", nsres); init_nsio(pCompMgr, registrar); }else { ERR("NS_GetComponentRegistrar failed: %08lx\n", nsres); } nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_APPSTARTUPNOTIFIER_CONTRACTID, NULL, &IID_nsIObserver, (void**)&pStartNotif); if(NS_SUCCEEDED(nsres)) { nsres = nsIObserver_Observe(pStartNotif, NULL, APPSTARTUP_TOPIC, NULL); if(NS_FAILED(nsres)) ERR("Observe failed: %08lx\n", nsres); nsIObserver_Release(pStartNotif); }else { ERR("could not get appstartup-notifier: %08lx\n", nsres); } set_profile(); nsres = nsIComponentManager_CreateInstanceByContractID(pCompMgr, NS_MEMORY_CONTRACTID, NULL, &IID_nsIMemory, (void**)&nsmem); if(NS_FAILED(nsres)) ERR("Could not get nsIMemory: %08lx\n", nsres); if(registrar) { register_nsservice(registrar, pServMgr); nsIComponentRegistrar_Release(registrar); } return TRUE; }
static void cleanup_test_file_truncate(void) { cleanup_test_file(); write_domain_policy("allow_truncate /tmp/testfile\\$", 1); set_profile(0, "file::truncate"); }
int main(int argc, char **argv) { cap_rights_t rights; int dec_ind; /* current indentation for declarations */ int di_stack[20]; /* a stack of structure indentation levels */ int force_nl; /* when true, code must be broken */ int hd_type = 0; /* used to store type of stmt for if (...), * for (...), etc */ int i; /* local loop counter */ int scase; /* set to true when we see a case, so we will * know what to do with the following colon */ int sp_sw; /* when true, we are in the expression of * if(...), while(...), etc. */ int squest; /* when this is positive, we have seen a ? * without the matching : in a <c>?<s>:<s> * construct */ const char *t_ptr; /* used for copying tokens */ int tabs_to_var; /* true if using tabs to indent to var name */ int type_code; /* the type of token, returned by lexi */ int last_else = 0; /* true iff last keyword was an else */ const char *profile_name = NULL; const char *envval = NULL; struct parser_state transient_state; /* a copy for lookup */ /*-----------------------------------------------*\ | INITIALIZATION | \*-----------------------------------------------*/ found_err = 0; ps.p_stack[0] = stmt; /* this is the parser's stack */ ps.last_nl = true; /* this is true if the last thing scanned was * a newline */ ps.last_token = semicolon; combuf = (char *) malloc(bufsize); if (combuf == NULL) err(1, NULL); labbuf = (char *) malloc(bufsize); if (labbuf == NULL) err(1, NULL); codebuf = (char *) malloc(bufsize); if (codebuf == NULL) err(1, NULL); tokenbuf = (char *) malloc(bufsize); if (tokenbuf == NULL) err(1, NULL); alloc_typenames(); l_com = combuf + bufsize - 5; l_lab = labbuf + bufsize - 5; l_code = codebuf + bufsize - 5; l_token = tokenbuf + bufsize - 5; combuf[0] = codebuf[0] = labbuf[0] = ' '; /* set up code, label, and * comment buffers */ combuf[1] = codebuf[1] = labbuf[1] = '\0'; ps.else_if = 1; /* Default else-if special processing to on */ s_lab = e_lab = labbuf + 1; s_code = e_code = codebuf + 1; s_com = e_com = combuf + 1; s_token = e_token = tokenbuf + 1; in_buffer = (char *) malloc(10); if (in_buffer == NULL) err(1, NULL); in_buffer_limit = in_buffer + 8; buf_ptr = buf_end = in_buffer; line_no = 1; had_eof = ps.in_decl = ps.decl_on_line = break_comma = false; sp_sw = force_nl = false; ps.in_or_st = false; ps.bl_line = true; dec_ind = 0; di_stack[ps.dec_nest = 0] = 0; ps.want_blank = ps.in_stmt = ps.ind_stmt = false; scase = ps.pcase = false; squest = 0; sc_end = NULL; bp_save = NULL; be_save = NULL; output = NULL; tabs_to_var = 0; envval = getenv("SIMPLE_BACKUP_SUFFIX"); if (envval) simple_backup_suffix = envval; /*--------------------------------------------------*\ | COMMAND LINE SCAN | \*--------------------------------------------------*/ #ifdef undef max_col = 78; /* -l78 */ lineup_to_parens = 1; /* -lp */ lineup_to_parens_always = 0; /* -nlpl */ ps.ljust_decl = 0; /* -ndj */ ps.com_ind = 33; /* -c33 */ star_comment_cont = 1; /* -sc */ ps.ind_size = 8; /* -i8 */ verbose = 0; ps.decl_indent = 16; /* -di16 */ ps.local_decl_indent = -1; /* if this is not set to some nonnegative value * by an arg, we will set this equal to * ps.decl_ind */ ps.indent_parameters = 1; /* -ip */ ps.decl_com_ind = 0; /* if this is not set to some positive value * by an arg, we will set this equal to * ps.com_ind */ btype_2 = 1; /* -br */ cuddle_else = 1; /* -ce */ ps.unindent_displace = 0; /* -d0 */ ps.case_indent = 0; /* -cli0 */ format_block_comments = 1; /* -fcb */ format_col1_comments = 1; /* -fc1 */ procnames_start_line = 1; /* -psl */ proc_calls_space = 0; /* -npcs */ comment_delimiter_on_blankline = 1; /* -cdb */ ps.leave_comma = 1; /* -nbc */ #endif for (i = 1; i < argc; ++i) if (strcmp(argv[i], "-npro") == 0) break; else if (argv[i][0] == '-' && argv[i][1] == 'P' && argv[i][2] != '\0') profile_name = argv[i]; /* non-empty -P (set profile) */ set_defaults(); if (i >= argc) set_profile(profile_name); for (i = 1; i < argc; ++i) { /* * look thru args (if any) for changes to defaults */ if (argv[i][0] != '-') {/* no flag on parameter */ if (input == NULL) { /* we must have the input file */ in_name = argv[i]; /* remember name of input file */ input = fopen(in_name, "r"); if (input == NULL) /* check for open error */ err(1, "%s", in_name); continue; } else if (output == NULL) { /* we have the output file */ out_name = argv[i]; /* remember name of output file */ if (strcmp(in_name, out_name) == 0) { /* attempt to overwrite * the file */ errx(1, "input and output files must be different"); } output = fopen(out_name, "w"); if (output == NULL) /* check for create error */ err(1, "%s", out_name); continue; } errx(1, "unknown parameter: %s", argv[i]); } else set_option(argv[i]); } /* end of for */ if (input == NULL) input = stdin; if (output == NULL) { if (input == stdin) output = stdout; else { out_name = in_name; bakcopy(); } } /* Restrict input/output descriptors and enter Capsicum sandbox. */ cap_rights_init(&rights, CAP_FSTAT, CAP_WRITE); if (cap_rights_limit(fileno(output), &rights) < 0 && errno != ENOSYS) err(EXIT_FAILURE, "unable to limit rights for %s", out_name); cap_rights_init(&rights, CAP_FSTAT, CAP_READ); if (cap_rights_limit(fileno(input), &rights) < 0 && errno != ENOSYS) err(EXIT_FAILURE, "unable to limit rights for %s", in_name); if (cap_enter() < 0 && errno != ENOSYS) err(EXIT_FAILURE, "unable to enter capability mode"); if (ps.com_ind <= 1) ps.com_ind = 2; /* dont put normal comments before column 2 */ if (block_comment_max_col <= 0) block_comment_max_col = max_col; if (ps.local_decl_indent < 0) /* if not specified by user, set this */ ps.local_decl_indent = ps.decl_indent; if (ps.decl_com_ind <= 0) /* if not specified by user, set this */ ps.decl_com_ind = ps.ljust_decl ? (ps.com_ind <= 10 ? 2 : ps.com_ind - 8) : ps.com_ind; if (continuation_indent == 0) continuation_indent = ps.ind_size; fill_buffer(); /* get first batch of stuff into input buffer */ parse(semicolon); { char *p = buf_ptr; int col = 1; while (1) { if (*p == ' ') col++; else if (*p == '\t') col = tabsize * (1 + (col - 1) / tabsize) + 1; else break; p++; } if (col > ps.ind_size) ps.ind_level = ps.i_l_follow = col / ps.ind_size; } /* * START OF MAIN LOOP */ while (1) { /* this is the main loop. it will go until we * reach eof */ int comment_buffered = false; type_code = lexi(&ps); /* lexi reads one token. The actual * characters read are stored in "token". lexi * returns a code indicating the type of token */ /* * The following code moves newlines and comments following an if (), * while (), else, etc. up to the start of the following stmt to * a buffer. This allows proper handling of both kinds of brace * placement (-br, -bl) and cuddling "else" (-ce). */ while (ps.search_brace) { switch (type_code) { case newline: if (sc_end == NULL) { save_com = sc_buf; save_com[0] = save_com[1] = ' '; sc_end = &save_com[2]; } *sc_end++ = '\n'; /* * We may have inherited a force_nl == true from the previous * token (like a semicolon). But once we know that a newline * has been scanned in this loop, force_nl should be false. * * However, the force_nl == true must be preserved if newline * is never scanned in this loop, so this assignment cannot be * done earlier. */ force_nl = false; case form_feed: break; case comment: if (sc_end == NULL) { /* * Copy everything from the start of the line, because * pr_comment() will use that to calculate original * indentation of a boxed comment. */ memcpy(sc_buf, in_buffer, buf_ptr - in_buffer - 4); save_com = sc_buf + (buf_ptr - in_buffer - 4); save_com[0] = save_com[1] = ' '; sc_end = &save_com[2]; } comment_buffered = true; *sc_end++ = '/'; /* copy in start of comment */ *sc_end++ = '*'; for (;;) { /* loop until we get to the end of the comment */ *sc_end = *buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); if (*sc_end++ == '*' && *buf_ptr == '/') break; /* we are at end of comment */ if (sc_end >= &save_com[sc_size]) { /* check for temp buffer * overflow */ diag2(1, "Internal buffer overflow - Move big comment from right after if, while, or whatever"); fflush(output); exit(1); } } *sc_end++ = '/'; /* add ending slash */ if (++buf_ptr >= buf_end) /* get past / in buffer */ fill_buffer(); break; case lbrace: /* * Put KNF-style lbraces before the buffered up tokens and * jump out of this loop in order to avoid copying the token * again under the default case of the switch below. */ if (sc_end != NULL && btype_2) { save_com[0] = '{'; /* * Originally the lbrace may have been alone on its own * line, but it will be moved into "the else's line", so * if there was a newline resulting from the "{" before, * it must be scanned now and ignored. */ while (isspace((unsigned char)*buf_ptr)) { if (++buf_ptr >= buf_end) fill_buffer(); if (*buf_ptr == '\n') break; } goto sw_buffer; } /* FALLTHROUGH */ default: /* it is the start of a normal statement */ { int remove_newlines; remove_newlines = /* "} else" */ (type_code == sp_nparen && *token == 'e' && e_code != s_code && e_code[-1] == '}') /* "else if" */ || (type_code == sp_paren && *token == 'i' && last_else && ps.else_if); if (remove_newlines) force_nl = false; if (sc_end == NULL) { /* ignore buffering if * comment wasn't saved up */ ps.search_brace = false; goto check_type; } while (sc_end > save_com && isblank((unsigned char)sc_end[-1])) { sc_end--; } if (swallow_optional_blanklines || (!comment_buffered && remove_newlines)) { force_nl = !remove_newlines; while (sc_end > save_com && sc_end[-1] == '\n') { sc_end--; } } if (force_nl) { /* if we should insert a nl here, put * it into the buffer */ force_nl = false; --line_no; /* this will be re-increased when the * newline is read from the buffer */ *sc_end++ = '\n'; *sc_end++ = ' '; if (verbose) /* print error msg if the line was * not already broken */ diag2(0, "Line broken"); } for (t_ptr = token; *t_ptr; ++t_ptr) *sc_end++ = *t_ptr; sw_buffer: ps.search_brace = false; /* stop looking for start of * stmt */ bp_save = buf_ptr; /* save current input buffer */ be_save = buf_end; buf_ptr = save_com; /* fix so that subsequent calls to * lexi will take tokens out of * save_com */ *sc_end++ = ' ';/* add trailing blank, just in case */ buf_end = sc_end; sc_end = NULL; break; } } /* end of switch */ /* * We must make this check, just in case there was an unexpected * EOF. */ if (type_code != 0) { /* * The only intended purpose of calling lexi() below is to * categorize the next token in order to decide whether to * continue buffering forthcoming tokens. Once the buffering * is over, lexi() will be called again elsewhere on all of * the tokens - this time for normal processing. * * Calling it for this purpose is a bug, because lexi() also * changes the parser state and discards leading whitespace, * which is needed mostly for comment-related considerations. * * Work around the former problem by giving lexi() a copy of * the current parser state and discard it if the call turned * out to be just a look ahead. * * Work around the latter problem by copying all whitespace * characters into the buffer so that the later lexi() call * will read them. */ if (sc_end != NULL) { while (*buf_ptr == ' ' || *buf_ptr == '\t') { *sc_end++ = *buf_ptr++; if (sc_end >= &save_com[sc_size]) { errx(1, "input too long"); } } if (buf_ptr >= buf_end) { fill_buffer(); } } transient_state = ps; type_code = lexi(&transient_state); /* read another token */ if (type_code != newline && type_code != form_feed && type_code != comment && !transient_state.search_brace) { ps = transient_state; } } } /* end of while (search_brace) */ last_else = 0; check_type: if (type_code == 0) { /* we got eof */ if (s_lab != e_lab || s_code != e_code || s_com != e_com) /* must dump end of line */ dump_line(); if (ps.tos > 1) /* check for balanced braces */ diag2(1, "Stuff missing from end of file"); if (verbose) { printf("There were %d output lines and %d comments\n", ps.out_lines, ps.out_coms); printf("(Lines with comments)/(Lines with code): %6.3f\n", (1.0 * ps.com_lines) / code_lines); } fflush(output); exit(found_err); } if ( (type_code != comment) && (type_code != newline) && (type_code != preesc) && (type_code != form_feed)) { if (force_nl && (type_code != semicolon) && (type_code != lbrace || !btype_2)) { /* we should force a broken line here */ if (verbose) diag2(0, "Line broken"); dump_line(); ps.want_blank = false; /* dont insert blank at line start */ force_nl = false; } ps.in_stmt = true; /* turn on flag which causes an extra level of * indentation. this is turned off by a ; or * '}' */ if (s_com != e_com) { /* the turkey has embedded a comment * in a line. fix it */ int len = e_com - s_com; CHECK_SIZE_CODE(len + 3); *e_code++ = ' '; memcpy(e_code, s_com, len); e_code += len; *e_code++ = ' '; *e_code = '\0'; /* null terminate code sect */ ps.want_blank = false; e_com = s_com; } } else if (type_code != comment) /* preserve force_nl thru a comment */ force_nl = false; /* cancel forced newline after newline, form * feed, etc */ /*-----------------------------------------------------*\ | do switch on type of token scanned | \*-----------------------------------------------------*/ CHECK_SIZE_CODE(3); /* maximum number of increments of e_code * before the next CHECK_SIZE_CODE or * dump_line() is 2. After that there's the * final increment for the null character. */ switch (type_code) { /* now, decide what to do with the token */ case form_feed: /* found a form feed in line */ ps.use_ff = true; /* a form feed is treated much like a newline */ dump_line(); ps.want_blank = false; break; case newline: if (ps.last_token != comma || ps.p_l_follow > 0 || !ps.leave_comma || ps.block_init || !break_comma || s_com != e_com) { dump_line(); ps.want_blank = false; } ++line_no; /* keep track of input line number */ break; case lparen: /* got a '(' or '[' */ /* count parens to make Healy happy */ if (++ps.p_l_follow == nitems(ps.paren_indents)) { diag3(0, "Reached internal limit of %d unclosed parens", nitems(ps.paren_indents)); ps.p_l_follow--; } if (*token == '[') /* not a function pointer declaration or a function call */; else if (ps.in_decl && !ps.block_init && !ps.dumped_decl_indent && ps.procname[0] == '\0' && ps.paren_level == 0) { /* function pointer declarations */ indent_declaration(dec_ind, tabs_to_var); ps.dumped_decl_indent = true; } else if (ps.want_blank && ((ps.last_token != ident && ps.last_token != funcname) || proc_calls_space || /* offsetof (1) is never allowed a space; sizeof (2) gets * one iff -bs; all other keywords (>2) always get a space * before lparen */ ps.keyword + Bill_Shannon > 2)) *e_code++ = ' '; ps.want_blank = false; *e_code++ = token[0]; ps.paren_indents[ps.p_l_follow - 1] = count_spaces_until(1, s_code, e_code) - 1; if (sp_sw && ps.p_l_follow == 1 && extra_expression_indent && ps.paren_indents[0] < 2 * ps.ind_size) ps.paren_indents[0] = 2 * ps.ind_size; if (ps.in_or_st && *token == '(' && ps.tos <= 2) { /* * this is a kluge to make sure that declarations will be * aligned right if proc decl has an explicit type on it, i.e. * "int a(x) {..." */ parse(semicolon); /* I said this was a kluge... */ ps.in_or_st = false; /* turn off flag for structure decl or * initialization */ } /* parenthesized type following sizeof or offsetof is not a cast */ if (ps.keyword == 1 || ps.keyword == 2) ps.not_cast_mask |= 1 << ps.p_l_follow; break; case rparen: /* got a ')' or ']' */ if (ps.cast_mask & (1 << ps.p_l_follow) & ~ps.not_cast_mask) { ps.last_u_d = true; ps.cast_mask &= (1 << ps.p_l_follow) - 1; ps.want_blank = space_after_cast; } else ps.want_blank = true; ps.not_cast_mask &= (1 << ps.p_l_follow) - 1; if (--ps.p_l_follow < 0) { ps.p_l_follow = 0; diag3(0, "Extra %c", *token); } if (e_code == s_code) /* if the paren starts the line */ ps.paren_level = ps.p_l_follow; /* then indent it */ *e_code++ = token[0]; if (sp_sw && (ps.p_l_follow == 0)) { /* check for end of if * (...), or some such */ sp_sw = false; force_nl = true;/* must force newline after if */ ps.last_u_d = true; /* inform lexi that a following * operator is unary */ ps.in_stmt = false; /* dont use stmt continuation * indentation */ parse(hd_type); /* let parser worry about if, or whatever */ } ps.search_brace = btype_2; /* this should insure that constructs * such as main(){...} and int[]{...} * have their braces put in the right * place */ break; case unary_op: /* this could be any unary operation */ if (!ps.dumped_decl_indent && ps.in_decl && !ps.block_init && ps.procname[0] == '\0' && ps.paren_level == 0) { /* pointer declarations */ /* * if this is a unary op in a declaration, we should indent * this token */ for (i = 0; token[i]; ++i) /* find length of token */; indent_declaration(dec_ind - i, tabs_to_var); ps.dumped_decl_indent = true; } else if (ps.want_blank) *e_code++ = ' '; { int len = e_token - s_token; CHECK_SIZE_CODE(len); memcpy(e_code, token, len); e_code += len; } ps.want_blank = false; break; case binary_op: /* any binary operation */ { int len = e_token - s_token; CHECK_SIZE_CODE(len + 1); if (ps.want_blank) *e_code++ = ' '; memcpy(e_code, token, len); e_code += len; } ps.want_blank = true; break; case postop: /* got a trailing ++ or -- */ *e_code++ = token[0]; *e_code++ = token[1]; ps.want_blank = true; break; case question: /* got a ? */ squest++; /* this will be used when a later colon * appears so we can distinguish the * <c>?<n>:<n> construct */ if (ps.want_blank) *e_code++ = ' '; *e_code++ = '?'; ps.want_blank = true; break; case casestmt: /* got word 'case' or 'default' */ scase = true; /* so we can process the later colon properly */ goto copy_id; case colon: /* got a ':' */ if (squest > 0) { /* it is part of the <c>?<n>: <n> construct */ --squest; if (ps.want_blank) *e_code++ = ' '; *e_code++ = ':'; ps.want_blank = true; break; } if (ps.in_or_st) { *e_code++ = ':'; ps.want_blank = false; break; } ps.in_stmt = false; /* seeing a label does not imply we are in a * stmt */ /* * turn everything so far into a label */ { int len = e_code - s_code; CHECK_SIZE_LAB(len + 3); memcpy(e_lab, s_code, len); e_lab += len; *e_lab++ = ':'; *e_lab = '\0'; e_code = s_code; } force_nl = ps.pcase = scase; /* ps.pcase will be used by * dump_line to decide how to * indent the label. force_nl * will force a case n: to be * on a line by itself */ scase = false; ps.want_blank = false; break; case semicolon: /* got a ';' */ if (ps.dec_nest == 0) ps.in_or_st = false;/* we are not in an initialization or * structure declaration */ scase = false; /* these will only need resetting in an error */ squest = 0; if (ps.last_token == rparen) ps.in_parameter_declaration = 0; ps.cast_mask = 0; ps.not_cast_mask = 0; ps.block_init = 0; ps.block_init_level = 0; ps.just_saw_decl--; if (ps.in_decl && s_code == e_code && !ps.block_init && !ps.dumped_decl_indent && ps.paren_level == 0) { /* indent stray semicolons in declarations */ indent_declaration(dec_ind - 1, tabs_to_var); ps.dumped_decl_indent = true; } ps.in_decl = (ps.dec_nest > 0); /* if we were in a first level * structure declaration, we * arent any more */ if ((!sp_sw || hd_type != forstmt) && ps.p_l_follow > 0) { /* * This should be true iff there were unbalanced parens in the * stmt. It is a bit complicated, because the semicolon might * be in a for stmt */ diag2(1, "Unbalanced parens"); ps.p_l_follow = 0; if (sp_sw) { /* this is a check for an if, while, etc. with * unbalanced parens */ sp_sw = false; parse(hd_type); /* dont lose the if, or whatever */ } } *e_code++ = ';'; ps.want_blank = true; ps.in_stmt = (ps.p_l_follow > 0); /* we are no longer in the * middle of a stmt */ if (!sp_sw) { /* if not if for (;;) */ parse(semicolon); /* let parser know about end of stmt */ force_nl = true;/* force newline after an end of stmt */ } break; case lbrace: /* got a '{' */ ps.in_stmt = false; /* dont indent the {} */ if (!ps.block_init) force_nl = true;/* force other stuff on same line as '{' onto * new line */ else if (ps.block_init_level <= 0) ps.block_init_level = 1; else ps.block_init_level++; if (s_code != e_code && !ps.block_init) { if (!btype_2) { dump_line(); ps.want_blank = false; } else if (ps.in_parameter_declaration && !ps.in_or_st) { ps.i_l_follow = 0; if (function_brace_split) { /* dump the line prior to the * brace ... */ dump_line(); ps.want_blank = false; } else /* add a space between the decl and brace */ ps.want_blank = true; } } if (ps.in_parameter_declaration) prefix_blankline_requested = 0; if (ps.p_l_follow > 0) { /* check for preceding unbalanced * parens */ diag2(1, "Unbalanced parens"); ps.p_l_follow = 0; if (sp_sw) { /* check for unclosed if, for, etc. */ sp_sw = false; parse(hd_type); ps.ind_level = ps.i_l_follow; } } if (s_code == e_code) ps.ind_stmt = false; /* dont put extra indentation on line * with '{' */ if (ps.in_decl && ps.in_or_st) { /* this is either a structure * declaration or an init */ di_stack[ps.dec_nest] = dec_ind; if (++ps.dec_nest == nitems(di_stack)) { diag3(0, "Reached internal limit of %d struct levels", nitems(di_stack)); ps.dec_nest--; } /* ? dec_ind = 0; */ } else { ps.decl_on_line = false; /* we can't be in the middle of * a declaration, so don't do * special indentation of * comments */ if (blanklines_after_declarations_at_proctop && ps.in_parameter_declaration) postfix_blankline_requested = 1; ps.in_parameter_declaration = 0; ps.in_decl = false; } dec_ind = 0; parse(lbrace); /* let parser know about this */ if (ps.want_blank) /* put a blank before '{' if '{' is not at * start of line */ *e_code++ = ' '; ps.want_blank = false; *e_code++ = '{'; ps.just_saw_decl = 0; break; case rbrace: /* got a '}' */ if (ps.p_stack[ps.tos] == decl && !ps.block_init) /* semicolons can be * omitted in * declarations */ parse(semicolon); if (ps.p_l_follow) {/* check for unclosed if, for, else. */ diag2(1, "Unbalanced parens"); ps.p_l_follow = 0; sp_sw = false; } ps.just_saw_decl = 0; ps.block_init_level--; if (s_code != e_code && !ps.block_init) { /* '}' must be first on * line */ if (verbose) diag2(0, "Line broken"); dump_line(); } *e_code++ = '}'; ps.want_blank = true; ps.in_stmt = ps.ind_stmt = false; if (ps.dec_nest > 0) { /* we are in multi-level structure * declaration */ dec_ind = di_stack[--ps.dec_nest]; if (ps.dec_nest == 0 && !ps.in_parameter_declaration) ps.just_saw_decl = 2; ps.in_decl = true; } prefix_blankline_requested = 0; parse(rbrace); /* let parser know about this */ ps.search_brace = cuddle_else && ps.p_stack[ps.tos] == ifhead && ps.il[ps.tos] >= ps.ind_level; if (ps.tos <= 1 && blanklines_after_procs && ps.dec_nest <= 0) postfix_blankline_requested = 1; break; case swstmt: /* got keyword "switch" */ sp_sw = true; hd_type = swstmt; /* keep this for when we have seen the * expression */ goto copy_id; /* go move the token into buffer */ case sp_paren: /* token is if, while, for */ sp_sw = true; /* the interesting stuff is done after the * expression is scanned */ hd_type = (*token == 'i' ? ifstmt : (*token == 'w' ? whilestmt : forstmt)); /* * remember the type of header for later use by parser */ goto copy_id; /* copy the token into line */ case sp_nparen: /* got else, do */ ps.in_stmt = false; if (*token == 'e') { if (e_code != s_code && (!cuddle_else || e_code[-1] != '}')) { if (verbose) diag2(0, "Line broken"); dump_line();/* make sure this starts a line */ ps.want_blank = false; } force_nl = true;/* also, following stuff must go onto new line */ last_else = 1; parse(elselit); } else { if (e_code != s_code) { /* make sure this starts a line */ if (verbose) diag2(0, "Line broken"); dump_line(); ps.want_blank = false; } force_nl = true;/* also, following stuff must go onto new line */ last_else = 0; parse(dolit); } goto copy_id; /* move the token into line */ case type_def: case storage: prefix_blankline_requested = 0; goto copy_id; case structure: if (ps.p_l_follow > 0) goto copy_id; case decl: /* we have a declaration type (int, etc.) */ parse(decl); /* let parser worry about indentation */ if (ps.last_token == rparen && ps.tos <= 1) { if (s_code != e_code) { dump_line(); ps.want_blank = 0; } } if (ps.in_parameter_declaration && ps.indent_parameters && ps.dec_nest == 0) { ps.ind_level = ps.i_l_follow = 1; ps.ind_stmt = 0; } ps.in_or_st = true; /* this might be a structure or initialization * declaration */ ps.in_decl = ps.decl_on_line = ps.last_token != type_def; if ( /* !ps.in_or_st && */ ps.dec_nest <= 0) ps.just_saw_decl = 2; prefix_blankline_requested = 0; for (i = 0; token[i++];); /* get length of token */ if (ps.ind_level == 0 || ps.dec_nest > 0) { /* global variable or struct member in local variable */ dec_ind = ps.decl_indent > 0 ? ps.decl_indent : i; tabs_to_var = (use_tabs ? ps.decl_indent > 0 : 0); } else { /* local variable */ dec_ind = ps.local_decl_indent > 0 ? ps.local_decl_indent : i; tabs_to_var = (use_tabs ? ps.local_decl_indent > 0 : 0); } goto copy_id; case funcname: case ident: /* got an identifier or constant */ if (ps.in_decl) { if (type_code == funcname) { ps.in_decl = false; if (procnames_start_line && s_code != e_code) { *e_code = '\0'; dump_line(); } else if (ps.want_blank) { *e_code++ = ' '; } ps.want_blank = false; } else if (!ps.block_init && !ps.dumped_decl_indent && ps.paren_level == 0) { /* if we are in a declaration, we * must indent identifier */ indent_declaration(dec_ind, tabs_to_var); ps.dumped_decl_indent = true; ps.want_blank = false; } } else if (sp_sw && ps.p_l_follow == 0) { sp_sw = false; force_nl = true; ps.last_u_d = true; ps.in_stmt = false; parse(hd_type); } copy_id: { int len = e_token - s_token; CHECK_SIZE_CODE(len + 1); if (ps.want_blank) *e_code++ = ' '; memcpy(e_code, s_token, len); e_code += len; } if (type_code != funcname) ps.want_blank = true; break; case strpfx: { int len = e_token - s_token; CHECK_SIZE_CODE(len + 1); if (ps.want_blank) *e_code++ = ' '; memcpy(e_code, token, len); e_code += len; } ps.want_blank = false; break; case period: /* treat a period kind of like a binary * operation */ *e_code++ = '.'; /* move the period into line */ ps.want_blank = false; /* dont put a blank after a period */ break; case comma: ps.want_blank = (s_code != e_code); /* only put blank after comma * if comma does not start the * line */ if (ps.in_decl && ps.procname[0] == '\0' && !ps.block_init && !ps.dumped_decl_indent && ps.paren_level == 0) { /* indent leading commas and not the actual identifiers */ indent_declaration(dec_ind - 1, tabs_to_var); ps.dumped_decl_indent = true; } *e_code++ = ','; if (ps.p_l_follow == 0) { if (ps.block_init_level <= 0) ps.block_init = 0; if (break_comma && (!ps.leave_comma || count_spaces_until(compute_code_target(), s_code, e_code) > max_col - tabsize)) force_nl = true; } break; case preesc: /* got the character '#' */ if ((s_com != e_com) || (s_lab != e_lab) || (s_code != e_code)) dump_line(); CHECK_SIZE_LAB(1); *e_lab++ = '#'; /* move whole line to 'label' buffer */ { int in_comment = 0; int com_start = 0; char quote = 0; int com_end = 0; while (*buf_ptr == ' ' || *buf_ptr == '\t') { buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); } while (*buf_ptr != '\n' || (in_comment && !had_eof)) { CHECK_SIZE_LAB(2); *e_lab = *buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); switch (*e_lab++) { case BACKSLASH: if (!in_comment) { *e_lab++ = *buf_ptr++; if (buf_ptr >= buf_end) fill_buffer(); } break; case '/': if (*buf_ptr == '*' && !in_comment && !quote) { in_comment = 1; *e_lab++ = *buf_ptr++; com_start = e_lab - s_lab - 2; } break; case '"': if (quote == '"') quote = 0; break; case '\'': if (quote == '\'') quote = 0; break; case '*': if (*buf_ptr == '/' && in_comment) { in_comment = 0; *e_lab++ = *buf_ptr++; com_end = e_lab - s_lab; } break; } } while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t')) e_lab--; if (e_lab - s_lab == com_end && bp_save == NULL) { /* comment on preprocessor line */ if (sc_end == NULL) { /* if this is the first comment, * we must set up the buffer */ save_com = sc_buf; sc_end = &save_com[0]; } else { *sc_end++ = '\n'; /* add newline between * comments */ *sc_end++ = ' '; --line_no; } if (sc_end - save_com + com_end - com_start > sc_size) errx(1, "input too long"); memmove(sc_end, s_lab + com_start, com_end - com_start); sc_end += com_end - com_start; e_lab = s_lab + com_start; while (e_lab > s_lab && (e_lab[-1] == ' ' || e_lab[-1] == '\t')) e_lab--; bp_save = buf_ptr; /* save current input buffer */ be_save = buf_end; buf_ptr = save_com; /* fix so that subsequent calls to * lexi will take tokens out of * save_com */ *sc_end++ = ' '; /* add trailing blank, just in case */ buf_end = sc_end; sc_end = NULL; } CHECK_SIZE_LAB(1); *e_lab = '\0'; /* null terminate line */ ps.pcase = false; } if (strncmp(s_lab, "#if", 3) == 0) { /* also ifdef, ifndef */ if ((size_t)ifdef_level < nitems(state_stack)) { match_state[ifdef_level].tos = -1; state_stack[ifdef_level++] = ps; } else diag2(1, "#if stack overflow"); } else if (strncmp(s_lab, "#el", 3) == 0) { /* else, elif */ if (ifdef_level <= 0) diag2(1, s_lab[3] == 'i' ? "Unmatched #elif" : "Unmatched #else"); else { match_state[ifdef_level - 1] = ps; ps = state_stack[ifdef_level - 1]; } } else if (strncmp(s_lab, "#endif", 6) == 0) { if (ifdef_level <= 0) diag2(1, "Unmatched #endif"); else ifdef_level--; } else { struct directives { int size; const char *string; } recognized[] = { {7, "include"}, {6, "define"}, {5, "undef"}, {4, "line"}, {5, "error"}, {6, "pragma"} }; int d = nitems(recognized); while (--d >= 0) if (strncmp(s_lab + 1, recognized[d].string, recognized[d].size) == 0) break; if (d < 0) { diag2(1, "Unrecognized cpp directive"); break; } } if (blanklines_around_conditional_compilation) { postfix_blankline_requested++; n_real_blanklines = 0; } else { postfix_blankline_requested = 0; prefix_blankline_requested = 0; } break; /* subsequent processing of the newline * character will cause the line to be printed */ case comment: /* we have gotten a / followed by * this is a biggie */ pr_comment(); break; } /* end of big switch stmt */ *e_code = '\0'; /* make sure code section is null terminated */ if (type_code != comment && type_code != newline && type_code != preesc) ps.last_token = type_code; } /* end of main while (1) loop */ }
int main(int argc, char *argv[]) { char c = 0; tomoyo_test_init(); /* Test mount(). */ { set_profile(3, "file::mount"); show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 1); if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else if (errno == ENODEV) printf("OK: No such device.\n"); else printf("BUG: %s\n", strerror(errno)); set_profile(1, "file::mount"); show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 0); if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF && errno == ENOMEM) printf("OK: Out of memory.\n"); else if (errno == ENODEV) printf("OK: No such device.\n"); else printf("BUG: %s\n", strerror(errno)); set_profile(3, "file::mount"); show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 0); if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF && errno == ENOMEM) printf("OK: Out of memory.\n"); else if (errno == ENODEV) printf("OK: No such device.\n"); else printf("BUG: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_mount dev\\011name / " "fs\\011name 0\n"); show_prompt("mount('dev\\011name', '/', 'fs\\011name') ", 1); if (mount("dev\tname", "/", "fs\tname", 0, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else if (errno == ENODEV) printf("OK: No such device.\n"); else printf("BUG: %s\n", strerror(errno)); set_profile(1, "file::mount"); show_prompt("mount(NULL, '/', 'tmpfs') ", 0); if (mount(NULL, "/", "tmpfs", 0, NULL)) printf("BUG: %s\n", strerror(errno)); else printf("OK: Success\n"); set_profile(3, "file::mount"); show_prompt("mount(NULL, '/', 'tmpfs') ", 0); if (mount(NULL, "/", "tmpfs", 0, NULL)) printf("BUG: %s\n", strerror(errno)); else printf("OK: Success\n"); show_prompt("mount('anydev', '/', 'tmpfs') ", 0); if (mount("anydev", "/", "tmpfs", 0, NULL)) printf("BUG: %s\n", strerror(errno)); else printf("OK: Success\n"); fprintf(domain_fp, "delete allow_mount <NULL> / tmpfs 0\n"); fprintf(domain_fp, "allow_mount anydev / tmpfs 0\n"); show_prompt("mount(NULL, '/', 'tmpfs') ", 0); if (mount(NULL, "/", "tmpfs", 0, NULL)) printf("BUG: %s\n", strerror(errno)); else printf("OK: Success\n"); fprintf(domain_fp, "delete allow_mount anydev / tmpfs 0\n"); set_profile(2, "file::mount"); show_prompt("mount(NULL, NULL, 'tmpfs') ", 1); if (mount(NULL, NULL, "tmpfs", 0, NULL)) printf("OK: %s\n", strerror(errno)); else printf("BUG: Did not fail.\n"); show_prompt("mount(NULL, NULL, NULL) ", 1); if (mount(NULL, NULL, NULL, 0, NULL)) printf("OK: %s\n", strerror(errno)); else printf("BUG: Did not fail.\n"); show_prompt("mount('/', NULL, NULL) ", 1); if (mount("/", NULL, NULL, 0, NULL)) printf("OK: %s\n", strerror(errno)); else printf("BUG: Did not fail.\n"); show_prompt("mount('/', NULL, 'tmpfs') ", 1); if (mount("/", NULL, "tmpfs", 0, NULL)) printf("OK: %s\n", strerror(errno)); else printf("BUG: Did not fail.\n"); show_prompt("mount('/', '/', 'nonexistentfs') ", 1); if (mount("/", "/", "nonexistentfs", 0, NULL)) printf("OK: %s\n", strerror(errno)); else printf("BUG: Did not fail.\n"); set_profile(0, "file::mount"); } mkdir("/tmp/mount/", 0755); mkdir("/tmp/mount_bind/", 0755); mkdir("/tmp/mount_move/", 0755); /* Test mount(). */ { static char buf[4096]; char *dev_ram_path = canonicalize_file_name("/dev/ram0"); if (!dev_ram_path) dev_ram_path = canonicalize_file_name("/dev/ram"); if (!dev_ram_path) { dev_ram_path = "/dev/ram0"; mknod(dev_ram_path, S_IFBLK, MKDEV(1, 0)); } memset(buf, 0, sizeof(buf)); { struct stat sbuf; FILE *fp = NULL; snprintf(buf, sizeof(buf) - 1, "zcat - > %s", dev_ram_path); if (lstat(dev_ram_path, &sbuf) == 0 && S_ISBLK(sbuf.st_mode) && MAJOR(sbuf.st_rdev) == 1) fp = popen(buf, "w"); if (fp) { if (fwrite(compressed_ext2_image_sample, 1, sizeof(compressed_ext2_image_sample), fp) != sizeof(compressed_ext2_image_sample)) err(1, "fwrite"); pclose(fp); } else fprintf(stderr, "Can't write to %s .\n", dev_ram_path); } set_profile(3, "file::mount"); /* Test standard case */ show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for " "'/tmp/mount/'", 1); if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); /* Test device_name with pattern */ snprintf(buf, sizeof(buf) - 1, "mount('%s', '/tmp/mount/', " "'ext2') for '%s\\*'", dev_ram_path, dev_ram_path); show_prompt(buf, 1); if (mount(dev_ram_path, "/tmp/mount/", "ext2", MS_RDONLY, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); /* Test dir_name with pattern */ show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for " "'/tmp/\\?\\?\\?\\?\\?/'", 1); if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); /* Test standard case */ fprintf(domain_fp, "allow_mount none /tmp/mount/ tmpfs 0\n"); show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for " "'/tmp/mount/'", 0); if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_mount none /tmp/mount/ tmpfs 0\n"); /* Test device_name with pattern */ fprintf(domain_fp, "allow_mount %s\\* /tmp/mount/ ext2 1\n", dev_ram_path); snprintf(buf, sizeof(buf) - 1, "mount('%s', '/tmp/mount/', " "'ext2') for '%s\\*'", dev_ram_path, dev_ram_path); show_prompt(buf, 0); if (mount(dev_ram_path, "/tmp/mount/", "ext2", MS_RDONLY, NULL) == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_mount %s\\* " "/tmp/mount/ ext2 1\n", dev_ram_path); /* Test dir_name with pattern */ fprintf(domain_fp, "allow_mount none /tmp/\\?\\?\\?\\?\\?/ tmpfs 0\n"); show_prompt("mount('none', '/tmp/mount/', 'tmpfs') for " "'/tmp/\\?\\?\\?\\?\\?/'", 0); if (mount("none", "/tmp/mount/", "tmpfs", 0, NULL) == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_mount none " "/tmp/\\?\\?\\?\\?\\?/ tmpfs 0\n"); set_profile(0, "file::mount"); while (umount("/tmp/mount/") == 0) c++; /* Dummy. */ } /* Test mount(). */ { mount2("none", "/tmp/mount/", "tmpfs"); set_profile(3, "file::mount"); /* Test remount case */ show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 1); if (mount("none", "/tmp/mount/", "tmpfs", MS_REMOUNT, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 1); if (mount(NULL, "/tmp/mount/", NULL, MS_REMOUNT, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); fprintf(domain_fp, "allow_mount something /tmp/mount/ " "--remount 0\n"); show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 0); if (mount(NULL, "/tmp/mount/", NULL, MS_REMOUNT, NULL)) printf("BUG: %s\n", strerror(errno)); else printf("OK: Success.\n"); fprintf(domain_fp, "delete allow_mount something /tmp/mount/ " "--remount 0\n"); /* Test bind case */ show_prompt("mount('/tmp/mount/', '/tmp/mount_bind/', " "MS_BIND)", 1); if (mount("/tmp/mount/", "/tmp/mount_bind/", NULL, MS_BIND, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); /* Test move case */ show_prompt("mount('/tmp/mount/', '/tmp/mount_move/', " "MS_MOVE)", 1); if (mount("/tmp/mount/", "/tmp/mount_move/", NULL, MS_MOVE, NULL) == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); /* Test remount case */ fprintf(domain_fp, "allow_mount any /tmp/mount/ --remount 0\n"); show_prompt("mount('/tmp/mount/', MS_REMOUNT)", 0); if (mount("none", "/tmp/mount/", "tmpfs", MS_REMOUNT, NULL) == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_mount any /tmp/mount/ " "--remount 0\n"); /* Test bind case */ fprintf(domain_fp, "allow_mount /tmp/mount/ /tmp/mount_bind/ --bind 0\n"); show_prompt("mount('/tmp/mount/', '/tmp/mount_bind', MS_BIND)", 0); if (mount("/tmp/mount/", "/tmp/mount_bind/", NULL, MS_BIND, NULL) == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); set_profile(0, "file::mount"); umount("/tmp/mount_bind/"); fprintf(domain_fp, "delete allow_mount /tmp/mount/ " "/tmp/mount_bind/ --bind 0\n"); /* Test move case */ set_profile(3, "file::mount"); fprintf(domain_fp, "allow_unmount /tmp/mount/\n"); fprintf(domain_fp, "allow_mount /tmp/mount/ /tmp/mount_move/ " "--move 0\n"); show_prompt("mount('/tmp/mount/', '/tmp/mount_move/', " "MS_MOVE)", 0); if (mount("/tmp/mount/", "/tmp/mount_move/", NULL, MS_MOVE, NULL) == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); set_profile(0, "file::mount"); umount("/tmp/mount_move/"); fprintf(domain_fp, "delete allow_unmount /tmp/mount/\n"); fprintf(domain_fp, "delete allow_mount /tmp/mount/ " "/tmp/mount_move/ --move 0\n"); while (umount("/tmp/mount/") == 0) c++; /* Dummy. */ } /* Test umount(). */ { /* Test standard case */ fprintf(domain_fp, "allow_unmount /tmp/mount/\n"); set_profile(0, "file::umount"); mount2("none", "/tmp/mount/", "tmpfs"); set_profile(3, "file::umount"); show_prompt("umount('/tmp/mount/') for '/tmp/mount/'", 0); if (umount("/tmp/mount/") == 0) printf("OK\n"); else printf("BUG: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_unmount /tmp/mount/\n"); set_profile(0, "file::umount"); mount2("none", "/tmp/mount/", "tmpfs"); set_profile(3, "file::umount"); show_prompt("umount('/tmp/mount/') for '/tmp/mount/'", 1); if (umount("/tmp/mount/") == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("FAILED: %s\n", strerror(errno)); /* Test pattern */ fprintf(domain_fp, "allow_unmount /tmp/\\?\\?\\?\\?\\?/\n"); set_profile(0, "file::umount"); mount2("none", "/tmp/mount/", "tmpfs"); set_profile(3, "file::umount"); show_prompt("umount('/tmp/mount/') for " "'/tmp/\\?\\?\\?\\?\\?/'", 1); if (umount("/tmp/mount/") == 0) printf("OK\n"); else printf("BUG: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_unmount /tmp/\\?\\?\\?\\?\\?/\n"); set_profile(0, "file::umount"); while (umount("/tmp/mount/") == 0) c++; /* Dummy. */ } /* Test chroot(). */ { set_profile(3, "file::chroot"); /* Test standard case */ fprintf(domain_fp, "allow_chroot /tmp/mount/\n"); show_prompt("chroot('/tmp/mount/') for '/tmp/mount/'", 0); fflush(stdout); if (fork() == 0) { if (chroot("/tmp/mount/") == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fflush(stdout); _exit(0); } wait(NULL); fprintf(domain_fp, "delete allow_chroot /tmp/mount/\n"); show_prompt("chroot('/tmp/mount/') for '/tmp/mount/'", 1); fflush(stdout); if (fork() == 0) { if (chroot("/tmp/mount/") == EOF && errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); fflush(stdout); _exit(0); } wait(NULL); /* Test pattern */ fprintf(domain_fp, "allow_chroot /tmp/\\?\\?\\?\\?\\?/\n"); show_prompt("chroot('/tmp/mount/') for " "'/tmp/\\?\\?\\?\\?\\?/'", 0); fflush(stdout); if (fork() == 0) { if (chroot("/tmp/mount/") == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fflush(stdout); _exit(0); } wait(NULL); fprintf(domain_fp, "delete allow_chroot /tmp/\\?\\?\\?\\?\\?/\n"); set_profile(0, "file::chroot"); } /* Test pivot_root(). */ { int error; static char stack[8192]; set_profile(3, "file::pivot_root"); fprintf(domain_fp, "allow_pivot_root %s %s\n", pivot_root_dir, proc_policy_dir); snprintf(stack, 8191, "pivot_root('%s', '%s')", pivot_root_dir, proc_policy_dir); show_prompt(stack, 0); { const pid_t pid = ltp_clone_quick(CLONE_NEWNS, child, NULL); while (waitpid(pid, &error, __WALL) == EOF && errno == EINTR) c++; /* Dummy. */ } errno = WIFEXITED(error) ? WEXITSTATUS(error) : -1; if (errno == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); fprintf(domain_fp, "delete allow_pivot_root %s %s\n", pivot_root_dir, proc_policy_dir); snprintf(stack, 8191, "pivot_root('%s', '%s')", pivot_root_dir, proc_policy_dir); show_prompt(stack, 1); { const pid_t pid = ltp_clone_quick(CLONE_NEWNS, child, NULL); while (waitpid(pid, &error, __WALL) == EOF && errno == EINTR) c++; /* Dummy. */ } errno = WIFEXITED(error) ? WEXITSTATUS(error) : -1; if (errno == EPERM) printf("OK: Permission denied.\n"); else printf("BUG: %s\n", strerror(errno)); set_profile(2, "file::pivot_root"); snprintf(stack, 8191, "pivot_root('%s', '%s')", pivot_root_dir, proc_policy_dir); show_prompt(stack, 0); { const pid_t pid = ltp_clone_quick(CLONE_NEWNS, child, NULL); while (waitpid(pid, &error, __WALL) == EOF && errno == EINTR) c++; /* Dummy. */ } errno = WIFEXITED(error) ? WEXITSTATUS(error) : -1; if (errno == 0) printf("OK\n"); else printf("FAILED: %s\n", strerror(errno)); set_profile(0, "file::pivot_root"); } rmdir("/tmp/mount_move/"); rmdir("/tmp/mount_bind/"); rmdir("/tmp/mount/"); clear_status(); return 0; }