Beispiel #1
7
inline void include_(char *line, char *var_head, FILE *out)	//SSI made total brutal, no checks of file path, and include must be along in string of file!
{
    char *var_head2;
    struct parsestr strct;

do{
    if ((var_head2 = parsestr2(&strct, var_head,"par=\"/[/*/]\"/ "))!=NULL){	//<!--#include par="size:web_name:name:pattern" -->
	/*collect parameters in a array*/
	char *a, *ptr;
	int i = 0, str_size, val_size;
	struct cfg_parse1 *cfg_pointer;
	*cfg_p = (struct cfg_parse1 *)malloc(sizeof(struct cfg_parse1));

	cfg_pointer = *cfg_p;
	if(cfg_pointer == NULL) continue;
	ptr = var_head2;

	    while(i < 3){
		a = w_strtok(&ptr, ':');
	        if(a)
		    switch(i){
		    case 0:	val_size = atoi(a);
				if(!val_size || val_size > 300) return;	//size is in impassable range - so skip it all (whole parameter string will be skipped!)
				a = ptr;
				str_size = strlen(a)+1;
				ptr = (char*)malloc(str_size + 2*val_size);//str = "[part of var_head2][value][new_value]"
				if(ptr == NULL){
					i = 5; continue;
				}
				strcpy(ptr, a);
				cfg_pointer->type = CFG_PAR;
				cfg_pointer->str = ptr;
				cfg_pointer->size = val_size;
				cfg_pointer->changed = 0;
				cfg_pointer->saved = 0;
				cfg_pointer->value = ptr + str_size;
//				*(cfg_pointer->value) = '\0';
				cfg_pointer->new_value = ptr + str_size + val_size;
//				*(cfg_pointer->new_value) = '\0';
				memset(cfg_pointer->value, 0, 2*val_size);//fill with zeros
				cfg_pointer->name = NULL;
				cfg_pointer->pattern = NULL;
				cfg_pointer->web_name = NULL;
				cfg_pointer->next = NULL;
				break;
	    	    case 1:	cfg_pointer->web_name = a; break;
		    case 2:	cfg_pointer->name = a; cfg_pointer->pattern = ptr; break;
		    }
		else {
		    printf("par=\"\" not full, broken by %d\n", i+1);
		    break;
		}
	    i++;
	    }
	if(i != 5){
printf("Collected parameter: %s:%s:%lld:%s\n", cfg_pointer->web_name, cfg_pointer->name, cfg_pointer->size, cfg_pointer->pattern);
	    cfg_p = &(cfg_pointer->next);
	}else{
	    printf("ERROR allocate memory\n");
	    if(cfg_p && *cfg_p){
		free(*cfg_p);
		*cfg_p = NULL;	//main criteria to abort moving in array.
	    }
	}

    } else if ((var_head2 = parsestr2(&strct, var_head,"readcfg/ "))!=NULL){	//<!--#include readcfg -->
	/*start to fill parameters from config to collected array*/
	ReadConfiguration();
    } else if ((var_head2 = parsestr2(&strct, var_head,"area=\"/[/*/]\"/ "))!=NULL){	//<!--#include area="size:web_name" -->
	/*collect parameters in a array*/
	char *a, *ptr;
	int i = 0, str_size;
	long long val_size;
	struct cfg_parse1 *cfg_pointer;
	*cfg_p = (struct cfg_parse1 *)malloc(sizeof(struct cfg_parse1));

	cfg_pointer = *cfg_p;
	if(cfg_pointer == NULL) continue;
	ptr = var_head2;

	    while(i < 2){
		a = w_strtok(&ptr, ':');
	        if(a)
		    switch(i){
		    case 0:	val_size = atoll(a);
				if(val_size > 32 *1024) return;	//size is in impassable range - so skip it all (whole parameter string will be skipped!)
				a = ptr;
				str_size = strlen(a)+1;
				ptr = (char*)malloc(str_size + val_size);//str = "[part of var_head2][value]"
				if(ptr == NULL){
					i = 5; continue;
				}
				strcpy(ptr, a);
				cfg_pointer->type = (val_size != 0) ? CFG_AREA : CFG_TMP;
				cfg_pointer->str = ptr;
				cfg_pointer->size = val_size;
				cfg_pointer->changed = 0;
				cfg_pointer->saved = 0;
				if(val_size != 0){//AREA="size:name"
				cfg_pointer->value = ptr + str_size;
				cfg_pointer->new_value = ptr + str_size;
				memset(cfg_pointer->value, 0, val_size);//fill memory with 0
				}else{//AREA="0:temp_name"
				cfg_pointer->value = NULL;
				cfg_pointer->new_value = NULL;
				}
				cfg_pointer->name = NULL; //ptr + str_size - 1;
				cfg_pointer->pattern = NULL; //ptr + str_size - 1;
				cfg_pointer->web_name = NULL;
				cfg_pointer->next = NULL;
				break;
		    case 1:	cfg_pointer->web_name = a; break;
		    }
		else {
		    printf("area=\"\" not full, broken by %d\n", i+1);
		    break;
		}
	    i++;
	    }
	if(i != 5){
printf("Collected parameter: [%s:%lld]\n", cfg_pointer->web_name, cfg_pointer->size);
	    cfg_p = &(cfg_pointer->next);
	}else{
	    printf("ERROR allocate memory\n");
	    if(cfg_p && *cfg_p){
		free(*cfg_p);
		*cfg_p = NULL;	//main criteria to abort moving in array.
	    }
	}

    } else
    
//printf("include file: %s\n", var_head);
    if ((var_head2 = parsestr2(&strct, var_head,"file=\"/[/*/N\\N/]\"/ "))!=NULL){	//<!--#include file="..\".." -->

//printf("include file: %s\n", var_head2);
	copy_file_include(var_head2, out);
    } else
    if ((var_head2 = parsestr2(&strct, var_head,"exec=\"/[/*/]\"/ "))!=NULL){	//<!--#include exec="..." -->

        my_system(out, var_head2);
    } else if ((var_head2 = parsestr2(&strct, var_head,"shell=\"\"/[/*/]\"\"/ "))!=NULL){	//<!--#include shell=""..."" -->

        my_shell(out, var_head2);
    } else if ((var_head2 = parsestr2(&strct, var_head,"cgi=\"/[/*/]\"/ "))!=NULL){	//<!--#include cgi="..." -->

	if(DoCGI(out, var_head2))  fprintf(out, "Not Found: %s\n", var_head2);// what about arg??
	else  free_par_tmp();//clear all "temp"-parameters

    } else if((var_head2 = parsestr2(&strct, var_head, "tbl_select=\"/[/*/]\"/ "))!=NULL){

	show_tbl(var_head2, out);
    } else if((var_head2 = parsestr2(&strct, var_head, "tbl_check=\"/[/*/]\"/ "))!=NULL){

	show_tbl_chck(var_head2, out);
    } else if((var_head2 = parsestr2(&strct, var_head, "chtbl_stat=\"/[/*/]\"/ "))!=NULL){

	change_tbl_stat(var_head2);
    } else if((var_head2 = parsestr2(&strct, var_head, "InIt/ "))!=NULL){		//<!--#include InIt -->

	ReadConfiguration();
    } else if((var_head2 = parsestr2(&strct, var_head, "write_par=\"/[/*/N\\N/]\"/ "))!=NULL){	//<!--#include write_par="par:value" -->

		// write_par  par:value		this is used in copy_CGI.c - the same code!
		char *tmp, *tmp2;
		long long size;
			    tmp2 = w_strtok(&var_head2, ':');
			    if(tmp2 && *tmp2 && *var_head2){
			    	tmp = get_var(&size, tmp2);
				if(tmp && size){
				    strncpy_(tmp, var_head2, size-1);
//				    tmp[size-1] = '\0';
				}
//				if(tmp2 != var_head2) *(var_head2-1) = ':';
			    }
    }//need some end hier (else)

}while(var_head2 && (var_head = strct.end));	//end of parsing string

}
Beispiel #2
0
bool
glexec_starter_prepare(const char* starter_path,
                       const char* proxy_file,
                       const ArgList& orig_args,
                       const Env* orig_env,
                       const int orig_std_fds[3],
                       ArgList& glexec_args,
                       Env& glexec_env,
                       int glexec_std_fds[3])
{
    // if GLEXEC_STARTER is set, use glexec to invoke the
    // starter (or fail if we can't). this involves:
    //   - verifying that we have a delegated proxy from
    //     the user stored, since we need to hand it to
    //     glexec so it can look up the UID/GID
    //   - invoking 'glexec_starter_setup.sh' via glexec to
    //     setup the starter's "private directory" for a copy
    //     of the job's proxy to go into, as well as the StarterLog
    //     and execute dir
    //   - adding the contents of the GLEXEC and config param
    //     and the path to 'condor_glexec_wrapper' to the front
    //     of the command line
    //   - setting up glexec's environment (setting the
    //     mode, handing off the proxy, etc.)
    //   - creating a UNIX-domain socket to use to communicate
    //     with our wrapper script, and munging the std_fds
    //     array

    // verify that we have a stored proxy
    if( proxy_file == NULL ) {
        dprintf( D_ALWAYS,
                 "cannot use glexec to spawn starter: no proxy "
                 "(is GLEXEC_STARTER set in the shadow?)\n" );
        return false;
    }

    // using the file name of the proxy that was stashed ealier, construct
    // the name of the starter's "private directory". the naming scheme is
    // (where XXXXXX is randomly generated via condor_mkstemp):
    //   - $(GLEXEC_USER_DIR)/startd-tmp-proxy-XXXXXX
    //       - startd's copy of the job's proxy
    //   - $(GLEXEC_USER_DIR)/starter-tmp-dir-XXXXXX
    //       - starter's private dir
    //
    MyString glexec_private_dir;
    char* dir_part = condor_dirname(proxy_file);
    ASSERT(dir_part != NULL);
    glexec_private_dir = dir_part;
    free(dir_part);
    glexec_private_dir += "/starter-tmp-dir-";
    const char* random_part = proxy_file;
    random_part += strlen(random_part) - 6;
    glexec_private_dir += random_part;
    dprintf(D_ALWAYS,
            "GLEXEC: starter private dir is '%s'\n",
            glexec_private_dir.Value());

    // get the glexec command line prefix from config
    char* glexec_argstr = param( "GLEXEC" );
    if ( ! glexec_argstr ) {
        dprintf( D_ALWAYS,
                 "cannot use glexec to spawn starter: "
                 "GLEXEC not given in config\n" );
        return false;
    }

    // cons up a command line for my_system. we'll run the
    // script $(LIBEXEC)/glexec_starter_setup.sh, which
    // will create the starter's "private directory" (and
    // its log and execute subdirectories). the value of
    // glexec_private_dir will be passed as an argument to
    // the script

    // parse the glexec args for invoking glexec_starter_setup.sh.
    // do not free them yet, except on an error, as we use them
    // again below.
    MyString setup_err;
    ArgList  glexec_setup_args;
    glexec_setup_args.SetArgV1SyntaxToCurrentPlatform();
    if( ! glexec_setup_args.AppendArgsV1RawOrV2Quoted( glexec_argstr,
            &setup_err ) ) {
        dprintf( D_ALWAYS,
                 "GLEXEC: failed to parse GLEXEC from config: %s\n",
                 setup_err.Value() );
        free( glexec_argstr );
        return 0;
    }

    // set up the rest of the arguments for the glexec setup script
    char* tmp = param("LIBEXEC");
    if (tmp == NULL) {
        dprintf( D_ALWAYS,
                 "GLEXEC: LIBEXEC not defined; can't find setup script\n" );
        free( glexec_argstr );
        return 0;
    }
    MyString libexec = tmp;
    free(tmp);
    MyString setup_script = libexec;
    setup_script += "/glexec_starter_setup.sh";
    glexec_setup_args.AppendArg(setup_script.Value());
    glexec_setup_args.AppendArg(glexec_private_dir.Value());

    // debug info.  this display format totally screws up the quoting, but
    // my_system gets it right.
    MyString disp_args;
    glexec_setup_args.GetArgsStringForDisplay(&disp_args, 0);
    dprintf (D_ALWAYS, "GLEXEC: about to glexec: ** %s **\n",
             disp_args.Value());

    // the only thing actually needed by glexec at this point is the cert, so
    // that it knows who to map to.  the pipe outputs the username that glexec
    // ended up using, on a single text line by itself.
    SetEnv( "GLEXEC_CLIENT_CERT", proxy_file );

    // create the starter's private dir
    int ret = my_system(glexec_setup_args);

    // clean up
    UnsetEnv( "GLEXEC_CLIENT_CERT");

    if ( ret != 0 ) {
        dprintf(D_ALWAYS,
                "GLEXEC: error creating private dir: my_system returned %d\n",
                ret);
        free( glexec_argstr );
        return 0;
    }

    // now prepare the starter command line, starting with glexec and its
    // options (if any), then condor_glexec_wrapper.
    MyString err;
    if( ! glexec_args.AppendArgsV1RawOrV2Quoted( glexec_argstr,
            &err ) ) {
        dprintf( D_ALWAYS,
                 "failed to parse GLEXEC from config: %s\n",
                 err.Value() );
        free( glexec_argstr );
        return 0;
    }
    free( glexec_argstr );
    MyString wrapper_path = libexec;
    wrapper_path += "/condor_glexec_wrapper";
    glexec_args.AppendArg(wrapper_path.Value());

    // complete the command line by adding in the original
    // arguments. we also make sure that the full path to the
    // starter is given
    int starter_path_pos = glexec_args.Count();
    glexec_args.AppendArgsFromArgList( orig_args );
    glexec_args.RemoveArg( starter_path_pos );
    glexec_args.InsertArg( starter_path, starter_path_pos );

    // set up the environment stuff
    if( orig_env ) {
        // first merge in the original
        glexec_env.MergeFrom( *orig_env );
    }

    // GLEXEC_MODE - get account from lcmaps
    glexec_env.SetEnv( "GLEXEC_MODE", "lcmaps_get_account" );

    // GLEXEC_CLIENT_CERT - cert to use for the mapping
    glexec_env.SetEnv( "GLEXEC_CLIENT_CERT", proxy_file );

#if defined(HAVE_EXT_GLOBUS) && !defined(SKIP_AUTHENTICATION)
    // GLEXEC_SOURCE_PROXY -  proxy to provide to the child
    //                        (file is owned by us)
    glexec_env.SetEnv( "GLEXEC_SOURCE_PROXY", proxy_file );
    dprintf (D_ALWAYS,
             "GLEXEC: setting GLEXEC_SOURCE_PROXY to %s\n",
             proxy_file);

    // GLEXEC_TARGET_PROXY - child-owned file to copy its proxy to.
    // this needs to be in a directory owned by that user, and not world
    // writable.  glexec enforces this.  hence, all the whoami/mkdir mojo
    // above.
    MyString child_proxy_file = glexec_private_dir;
    child_proxy_file += "/glexec_starter_proxy";
    dprintf (D_ALWAYS, "GLEXEC: setting GLEXEC_TARGET_PROXY to %s\n",
             child_proxy_file.Value());
    glexec_env.SetEnv( "GLEXEC_TARGET_PROXY", child_proxy_file.Value() );

    // _CONDOR_GSI_DAEMON_PROXY - starter's proxy
    MyString var_name;
    var_name.sprintf("_CONDOR_%s", STR_GSI_DAEMON_PROXY);
    glexec_env.SetEnv( var_name.Value(), child_proxy_file.Value() );
    var_name.sprintf("_condor_%s", STR_GSI_DAEMON_PROXY);
    glexec_env.SetEnv( var_name.Value(), child_proxy_file.Value() );
#endif

    // the EXECUTE dir should be owned by the mapped user.  we created this
    // earlier, and now we override it in the condor_config via the
    // environment.
    MyString execute_dir = glexec_private_dir;
    execute_dir += "/execute";
    glexec_env.SetEnv ( "_CONDOR_EXECUTE", execute_dir.Value());
    glexec_env.SetEnv ( "_condor_EXECUTE", execute_dir.Value());

    // the LOG dir should be owned by the mapped user.  we created this
    // earlier, and now we override it in the condor_config via the
    // environment.
    MyString log_dir = glexec_private_dir;
    log_dir += "/log";
    glexec_env.SetEnv ( "_CONDOR_LOG", log_dir.Value());
    glexec_env.SetEnv ( "_condor_LOG", log_dir.Value());
    glexec_env.SetEnv ( "_CONDOR_LOCK", log_dir.Value());
    glexec_env.SetEnv ( "_condor_LOCK", log_dir.Value());

    // PROCD_ADDRESS: the Starter that we are about to create will
    // not have access to our ProcD. we'll explicitly set PROCD_ADDRESS
    // to be in its LOG directory. the Starter will see that its
    // PROCD_ADDRESS knob is different from what it inherits in
    // CONDOR_PROCD_ADDRESS, and know it needs to create its own ProcD
    //
    MyString procd_address = log_dir;
    procd_address += "/procd_pipe";
    glexec_env.SetEnv( "_CONDOR_PROCD_ADDRESS", procd_address.Value() );
    glexec_env.SetEnv( "_condor_PROCD_ADDRESS", procd_address.Value() );

    // CONDOR_GLEXEC_STARTER_CLEANUP_FLAG: this serves as a flag in the
    // Starter's environment that it will check for in order to determine
    // whether to do GLEXEC_STARTER-specific cleanup
    //
    glexec_env.SetEnv( "CONDOR_GLEXEC_STARTER_CLEANUP_FLAG",
                       "CONDOR_GLEXEC_STARTER_CLEANUP_FLAG" );

    // now set up a socket pair for communication with
    // condor_glexec_wrapper
    //
    if (socketpair(PF_UNIX, SOCK_STREAM, 0, s_saved_sock_fds) == -1)
    {
        dprintf(D_ALWAYS,
                "GLEXEC: socketpair error: %s\n",
                strerror(errno));
        return false;
    }
    glexec_std_fds[0] = s_saved_sock_fds[1];
    if (orig_std_fds == NULL) {
        s_saved_starter_stdin = -1;
        glexec_std_fds[1] = glexec_std_fds[2] = -1;
    }
    else {
        s_saved_starter_stdin = orig_std_fds[0];
        glexec_std_fds[1] = orig_std_fds[1];
        glexec_std_fds[2] = orig_std_fds[2];
    }

    // save the environment we're handing back to the caller for use in
    // glexec_starter_handle_env()
    //
    s_saved_env.Clear();
    s_saved_env.MergeFrom(glexec_env);

    return true;
}
Beispiel #3
0
static void
do_execute (const char *shell, const char *command, int flags)
{
#ifdef HAVE_SUBSHELL_SUPPORT
    char *new_dir = NULL;
#endif				/* HAVE_SUBSHELL_SUPPORT */

#ifdef USE_VFS
    char *old_vfs_dir = 0;

    if (!vfs_current_is_local ())
	old_vfs_dir = g_strdup (vfs_get_current_dir ());
#endif				/* USE_VFS */

    save_cwds_stat ();
    pre_exec ();
    if (console_flag)
	handle_console (CONSOLE_RESTORE);

    if (!use_subshell && command && !(flags & EXECUTE_INTERNAL)) {
	printf ("%s%s\n", prompt, command);
    }
#ifdef HAVE_SUBSHELL_SUPPORT
    if (use_subshell && !(flags & EXECUTE_INTERNAL)) {
	do_update_prompt ();

	/* We don't care if it died, higher level takes care of this */
#ifdef USE_VFS
	invoke_subshell (command, VISIBLY, old_vfs_dir ? 0 : &new_dir);
#else
	invoke_subshell (command, VISIBLY, &new_dir);
#endif				/* !USE_VFS */
    } else
#endif				/* HAVE_SUBSHELL_SUPPORT */
	my_system (flags, shell, command);

    if (!(flags & EXECUTE_INTERNAL)) {
	if ((pause_after_run == pause_always
	     || (pause_after_run == pause_on_dumb_terminals && !xterm_flag
		 && !console_flag)) && !quit
#ifdef HAVE_SUBSHELL_SUPPORT
	    && subshell_state != RUNNING_COMMAND
#endif				/* HAVE_SUBSHELL_SUPPORT */
	    ) {
	    printf (_("Press any key to continue..."));
	    fflush (stdout);
	    mc_raw_mode ();
	    get_key_code (0);
	    printf ("\r\n");
	    fflush (stdout);
	}
	if (console_flag) {
	    if (output_lines && keybar_visible) {
		putchar ('\n');
		fflush (stdout);
	    }
	}
    }

    if (console_flag)
	handle_console (CONSOLE_SAVE);
    edition_post_exec ();

#ifdef HAVE_SUBSHELL_SUPPORT
    if (new_dir)
	do_possible_cd (new_dir);

#endif				/* HAVE_SUBSHELL_SUPPORT */

#ifdef USE_VFS
    if (old_vfs_dir) {
	mc_chdir (old_vfs_dir);
	g_free (old_vfs_dir);
    }
#endif				/* USE_VFS */

    update_panels (UP_OPTIMIZE, UP_KEEPSEL);
    update_xterm_title_path ();

    do_refresh ();
    use_dash (TRUE);
}
Beispiel #4
0
void
toggle_panels (void)
{
#ifdef HAVE_SUBSHELL_SUPPORT
    char *new_dir = NULL;
    char **new_dir_p;
#endif				/* HAVE_SUBSHELL_SUPPORT */

    channels_down ();
    disable_mouse ();
    if (clear_before_exec)
	clr_scr ();
    if (alternate_plus_minus)
	numeric_keypad_mode ();
#ifndef HAVE_SLANG
    /* With slang we don't want any of this, since there
     * is no mc_raw_mode supported
     */
    reset_shell_mode ();
    noecho ();
#endif				/* !HAVE_SLANG */
    keypad (stdscr, FALSE);
    endwin ();
    do_exit_ca_mode ();
    mc_raw_mode ();
    if (console_flag)
	handle_console (CONSOLE_RESTORE);

#ifdef HAVE_SUBSHELL_SUPPORT
    if (use_subshell) {
	new_dir_p = vfs_current_is_local ()? &new_dir : NULL;
	if (invoke_subshell (NULL, VISIBLY, new_dir_p))
	    quiet_quit_cmd ();	/* User did `exit' or `logout': quit MC quietly */
    } else
#endif				/* HAVE_SUBSHELL_SUPPORT */
    {
	if (output_starts_shell) {
	    fprintf (stderr,
		     _("Type `exit' to return to the Midnight Commander"));
	    fprintf (stderr, "\n\r\n\r");

	    my_system (EXECUTE_INTERNAL, shell, NULL);
	} else
	    get_key_code (0);
    }
    if (console_flag)
	handle_console (CONSOLE_SAVE);

    do_enter_ca_mode ();

    reset_prog_mode ();
    keypad (stdscr, TRUE);

    /* Prevent screen flash when user did 'exit' or 'logout' within
       subshell */
    if (quit)
	return;

    enable_mouse ();
    channels_up ();
    if (alternate_plus_minus)
	application_keypad_mode ();

#ifdef HAVE_SUBSHELL_SUPPORT
    if (use_subshell) {
	load_prompt (0, 0);
	if (new_dir)
	    do_possible_cd (new_dir);
	if (console_flag && output_lines)
	    show_console_contents (output_start_y,
				   LINES - keybar_visible - output_lines -
				   1, LINES - keybar_visible - 1);
    }
#endif				/* HAVE_SUBSHELL_SUPPORT */

    update_panels (UP_OPTIMIZE, UP_KEEPSEL);
    update_xterm_title_path ();
    do_refresh ();
}
Beispiel #5
0
int
nem_execute_event_handler(nfc_device* nfc_device, nfc_target* tag, const nem_event_t event) {
    int onerr;
    const char *onerrorstr;
    const nfcconf_list *actionlist;
    nfcconf_block **blocklist, *myblock;

    const char* action;

    switch (event) {
    case EVENT_TAG_INSERTED:
        action = "tag_insert";
        if ( _tag_uid != NULL ) {
            free(_tag_uid);
        }
        tag_get_uid(nfc_device, tag, &_tag_uid);
        break;
    case EVENT_TAG_REMOVED:
        action = "tag_remove";
        break;
    default:
	return -1;
	break;
    }

    blocklist = nfcconf_find_blocks ( _nem_execute_config_context, _nem_execute_config_block, "event", action );
    if ( !blocklist ) {
        DBG ( "%s", "Event block list not found" );
        return -1;
    }
    myblock = blocklist[0];
    free ( blocklist );
    if ( !myblock ) {
        DBG ( "Event item not found: '%s'", action );
        return -1;
    }
    onerrorstr = nfcconf_get_str ( myblock, "on_error", "ignore" );
    if ( !strcmp ( onerrorstr, "ignore" ) ) onerr = ONERROR_IGNORE;
    else if ( !strcmp ( onerrorstr, "return" ) ) onerr = ONERROR_RETURN;
    else if ( !strcmp ( onerrorstr, "quit" ) ) onerr = ONERROR_QUIT;
    else {
        onerr = ONERROR_IGNORE;
        DBG ( "Invalid onerror value: '%s'. Assumed 'ignore'", onerrorstr );
    }

    /* search actions */
    actionlist = nfcconf_find_list ( myblock, "action" );
    if ( !actionlist ) {
        DBG ( "No action list for event '%s'", action );
        return 0;
    }
    // DBG ( "Onerror is set to: '%s'", onerrorstr );

    if ( _tag_uid == NULL ) {
        ERR( "%s", "Unable to read tag UID... This should not happend !" );
        switch ( onerr ) {
        case ONERROR_IGNORE:
            break;
        case ONERROR_RETURN:
            return 0;
        case ONERROR_QUIT:
            exit ( EXIT_FAILURE );
        default:
            DBG ( "%s", "Invalid onerror value" );
            return -1;
        }
    } else {
        while ( actionlist ) {
            int res;
            char *action_cmd_src = actionlist->data;
            char *action_cmd_dest = malloc((strlen(action_cmd_src) + strlen(_tag_uid))*sizeof(char));
            strsubst(action_cmd_dest, action_cmd_src, "$TAG_UID", _tag_uid);

            DBG ( "Executing action: '%s'", action_cmd_dest );
            /*
            there are some security issues on using system() in
            setuid/setgid programs. so we will use an alternate function
            	*/
            /* res=system(action_cmd); */
            res = my_system ( action_cmd_dest );
            actionlist = actionlist->next;
            /* evaluate return and take care on "onerror" value */
            DBG ( "Action '%s' returns %d", action_cmd_dest, res );
            if ( !res ) continue;
            switch ( onerr ) {
            case ONERROR_IGNORE:
                continue;
            case ONERROR_RETURN:
                return 0;
            case ONERROR_QUIT:
                exit ( EXIT_FAILURE );
            default:
                DBG ( "%s", "Invalid onerror value" );
                return -1;
            }
        }
    }
    return 0;
}
Beispiel #6
0
int main(int argc, char **argv) {
    XEvent event;
    XpmColorSymbol colors[2] = { {"Back0", NULL, 0}, {"Back1", NULL, 0} };
    int ncolor = 0;
    struct sigaction sa;

    sa.sa_handler = SIG_IGN;
    sa.sa_flags = SA_NOCLDWAIT;

    sigemptyset(&sa.sa_mask);
    sigaction(SIGCHLD, &sa, NULL);

    /* Parse CommandLine */
    parse_arguments(argc, argv);

    /* Initialize Application */

    dockapp_open_window(display_name, PACKAGE, SIZE, SIZE, argc, argv);
    dockapp_set_eventmask(ButtonPressMask);

    if(light_color) {
        colors[0].pixel = dockapp_getcolor(light_color);
        colors[1].pixel =
            dockapp_blendedcolor(light_color, -24, -24, -24, 1.0);
        ncolor = 2;
    }

    /* change raw xpm data to pixmap */
    if(dockapp_iswindowed)
        backlight_on_xpm[1] = backlight_off_xpm[1] = WINDOWED_BG;

    if(!dockapp_xpm2pixmap(backlight_on_xpm, &backdrop_on, &mask, colors, ncolor)) {
        fprintf(stderr, "Error initializing backlit background image.\n");
        exit(1);
    }
    if(!dockapp_xpm2pixmap(backlight_off_xpm, &backdrop_off, NULL, NULL, 0)) {
        fprintf(stderr, "Error initializing background image.\n");
        exit(1);
    }
    if(!dockapp_xpm2pixmap(parts_xpm, &parts, NULL, colors, ncolor)) {
        fprintf(stderr, "Error initializing parts image.\n");
        exit(1);
    }

    /* shape window */
    if(!dockapp_iswindowed)
        dockapp_setshape(mask, 0, 0);
    if(mask)
        XFreePixmap(display, mask);

    /* pixmap : draw area */
    pixmap = dockapp_XCreatePixmap(SIZE, SIZE);

    /* Initialize pixmap */
    if(backlight == LIGHTON)
        dockapp_copyarea(backdrop_on, pixmap, 0, 0, SIZE, SIZE, 0, 0);
    else
        dockapp_copyarea(backdrop_off, pixmap, 0, 0, SIZE, SIZE, 0, 0);

    dockapp_set_background(pixmap);
    dockapp_show();

    /* initialize ibam */
    i.update();
    if(i.valid())
        i.update_statistics();
    else
        i.ignore_statistics();
    i.save();

    update();

    /* Main loop */
    while(1) {
        if(dockapp_nextevent_or_timeout(&event, update_interval * 1000)) {
            /* Next Event */
            switch(event.type) {
            case ButtonPress:
                switch(event.xbutton.button) {
                case 1:
                    switch_light();
                    break;
                case 2:
                    if(event.xbutton.state == ControlMask)
                        my_system((char *)(suspend_cmd ? suspend_cmd : SUSPEND_CMD));	/* Suspend */
                    else
                        my_system((char *)(standby_cmd ? standby_cmd : STANDBY_CMD));	/* Standby */
                    break;
                case 3:
                    switch_authorized = !switch_authorized;
                    break;
                default:
                    break;
                }
                break;
            default:
                break;
            }
        } else {
            /* Time Out */
            update();
        }
    }

    return 0;
}
Beispiel #7
0
std::pair<std::size_t,std::size_t> node_server::save(integer loc_id, std::string fname) const {
	static hpx::lcos::local::mutex mtx;


	std::size_t total_cnt = 0;
	std::size_t bytes_written = 0;
	std::list<hpx::future<std::pair<std::size_t,std::size_t>>> futs;
	integer nloc = hpx::find_all_localities().size();
	if( my_location.level() == 0 && loc_id == 0 ) {
		if( file_exists( fname )) {
			std::string command = "rm ";
			command += fname;
			if(system( command.c_str())){}
		}
		for( integer i = 0; i != nloc; ++i) {
			auto this_name = fname + std::string(".") + std::to_string(integer(hpx::get_locality_id()));
			if( file_exists( this_name)) {
				std::string command = "rm ";
				command += this_name;
				if(system( command.c_str())){}
			}
		}
	}

	std::list<hpx::future<std::pair<std::size_t,std::size_t> >> sfuts;

	if( is_refined ) {
		for( auto i = children.begin(); i != children.end(); ++i) {
			sfuts.push_back( i->save(loc_id, fname));
		}
	}

	{
		boost::lock_guard<hpx::lcos::local::mutex> file_lock(mtx);
		FILE* fp = fopen( (fname + std::string(".") + std::to_string(integer(hpx::get_locality_id()))).c_str(), "ab");
		total_cnt++;
		bytes_written += my_location.save(fp);
		bytes_written += save_me(fp);
		fclose(fp);
	}

	if( is_refined ) {
		for( auto i = sfuts.begin(); i != sfuts.end(); ++i) {
			auto tmp = i->get();
			total_cnt += tmp.first;
			bytes_written += tmp.second;
		}
	}

	if( loc_id == 0  && my_location.level() == 0) {
		FILE* fp = fopen("size.tmp2", "wb");
		bytes_written += 2 * fwrite( &total_cnt, sizeof(integer), 1, fp) * sizeof(integer);
		std::size_t tmp = bytes_written + 2 * sizeof(std::size_t) + sizeof(real);
		bytes_written += 2 * fwrite( &tmp, sizeof(std::size_t), 1, fp)*sizeof(std::size_t);
		fclose( fp);
		my_system( "cp size.tmp2 size.tmp1\n");
		fp = fopen("size.tmp1", "ab");
		real omega = grid::get_omega();
		bytes_written += fwrite( &omega, sizeof(real), 1, fp) * sizeof(real);
		fclose( fp);
		std::string command = "rm -r -f " + fname + "\n";
		my_system (command);
		command = "cat size.tmp1 ";
		for( integer i = 0; i != nloc; ++i ) {
				command += fname + "." + std::to_string(integer(i)) + " ";
		}
		command += "size.tmp2 > " + fname + "\n";
		my_system( command);
		command = "rm -f -r " + fname + ".*\n";
		my_system( command);
		my_system( "rm -r -f size.tmp?\n");
		printf( "Saved %i sub-grids with %lli bytes written\n", int(total_cnt), (long long)(bytes_written));

	}
	return std::make_pair(total_cnt, bytes_written);

}
Beispiel #8
0
/** Submit the DAGMan submit file unless the -no_submit option was given.
	@param shallowOpts: the condor_submit_dag shallow options
	@return 0 if successful, 1 if failed
*/
int
submitDag( SubmitDagShallowOptions &shallowOpts )
{
	printf("-----------------------------------------------------------------------\n");
	printf("File for submitting this DAG to Condor           : %s\n", 
			shallowOpts.strSubFile.Value());
	printf("Log of DAGMan debugging messages                 : %s\n",
		   	shallowOpts.strDebugLog.Value());
	printf("Log of Condor library output                     : %s\n", 
			shallowOpts.strLibOut.Value());
	printf("Log of Condor library error messages             : %s\n", 
			shallowOpts.strLibErr.Value());
	printf("Log of the life of condor_dagman itself          : %s\n",
		   	shallowOpts.strSchedLog.Value());
	printf("\n");

	if (shallowOpts.bSubmit)
	{
		ArgList args;
		args.AppendArg( "condor_submit" );
		if( shallowOpts.strRemoteSchedd != "" ) {
			args.AppendArg( "-r" );
			args.AppendArg( shallowOpts.strRemoteSchedd );
		}
		args.AppendArg( shallowOpts.strSubFile );

			// It is important to set the destination Schedd before
			// calling condor_submit, otherwise it may submit to the
			// wrong Schedd.
			//
			// my_system() has a variant that takes an Env.
			// Unfortunately, it results in an execve and no path
			// searching, which makes the relative path to
			// "condor_submit" above not work. Instead, we'll set the
			// env before execvp is called. It may be more correct to
			// fix my_system to inject the Env after the fork() and
			// before the execvp().
		if ( shallowOpts.strScheddDaemonAdFile != "" ) {
			SetEnv("_CONDOR_SCHEDD_DAEMON_AD_FILE",
				   shallowOpts.strScheddDaemonAdFile.Value());
		}
		if ( shallowOpts.strScheddAddressFile != "" ) {
			SetEnv("_CONDOR_SCHEDD_ADDRESS_FILE",
				   shallowOpts.strScheddAddressFile.Value());
		}

		int retval = my_system( args );
		if( retval != 0 ) {
			fprintf( stderr, "ERROR: condor_submit failed; aborting.\n" );
			return 1;
		}
	}
	else
	{
		printf("-no_submit given, not submitting DAG to Condor.  "
					"You can do this with:\n");
		printf("\"condor_submit %s\"\n", shallowOpts.strSubFile.Value());
	}
	printf("-----------------------------------------------------------------------\n");

	return 0;
}
void CKernelOptions::unloadModule(int i)
{
	my_system(2, "rmmod", modules[i].moduleList.back().first.c_str());
}
Beispiel #10
0
Datei: sfs.c Projekt: dborca/mc
static int
sfs_vfmake (struct vfs_class *me, const char *name, char *cache)
{
    char *inpath, *op;
    int w;
    char pad[10240];
    char *s, *t = pad;
    int was_percent = 0;
    char *pname;	/* name of parent archive */
    char *pqname;	/* name of parent archive, quoted */

    pname = g_strdup (name);
    vfs_split (pname, &inpath, &op);
    if ((w = (*me->which) (me, op)) == -1)
	vfs_die ("This cannot happen... Hopefully.\n");

    if (!(sfs_flags[w] & F_1) && strcmp (pname, "/")) {
	g_free (pname);
	return -1;
    }

    /*    if ((sfs_flags[w] & F_2) || (!inpath) || (!*inpath)); else return -1; */
    if (!(sfs_flags[w] & F_NOLOCALCOPY)) {
	s = mc_getlocalcopy (pname);
	if (!s) {
	    g_free (pname);
	    return -1;
	}
	pqname = name_quote (s, 0);
	g_free (s);
    } else {
	pqname = name_quote (pname, 0);
    }
    g_free (pname);

#define COPY_CHAR \
    if ((size_t) (t-pad) > sizeof(pad)) { \
	g_free (pqname); \
	return -1; \
    } \
    else \
	*t++ = *s;

#define COPY_STRING(a) \
    if ((t-pad)+strlen(a)>sizeof(pad)) { \
	g_free (pqname); \
	return -1; \
    } else { \
	strcpy (t, a); \
	t+= strlen(a); \
    }

    for (s = sfs_command[w]; *s; s++) {
	if (was_percent) {

	    const char *ptr = NULL;
	    was_percent = 0;

	    switch (*s) {
	    case '1':
		ptr = pqname;
		break;
	    case '2':
		ptr = op + strlen (sfs_prefix[w]);
		break;
	    case '3':
		ptr = cache;
		break;
	    case '%':
		COPY_CHAR;
		continue;
	    }
	    COPY_STRING (ptr);
	} else {
	    if (*s == '%')
		was_percent = 1;
	    else
		COPY_CHAR;
	}
    }

    g_free (pqname);
    open_error_pipe ();
    if (my_system (EXECUTE_AS_SHELL, "/bin/sh", pad)) {
	close_error_pipe (1, NULL);
	return -1;
    }

    close_error_pipe (0, NULL);
    return 0;			/* OK */
}
Beispiel #11
0
//------------------------------------------------------------------------
int CPictureViewerGui::exec(CMenuTarget* parent, const std::string & /*actionKey*/)
{
	selected = 0;
	width = w_max (710, 30);
	height = h_max (570, 0);
	sheight      = g_Font[SNeutrinoSettings::FONT_TYPE_INFOBAR_SMALL]->getHeight();
	buttonHeight = std::max(25, sheight);
	frameBuffer->getIconSize(NEUTRINO_ICON_MP3, &ticonwidth, &ticonheight);
	theight      = std::max(ticonheight, g_Font[SNeutrinoSettings::FONT_TYPE_MENU_TITLE]->getHeight());
	fheight      = g_Font[SNeutrinoSettings::FONT_TYPE_MENU]->getHeight();
	listmaxshow = (height-theight-2*buttonHeight)/(fheight);
	height = theight+2*buttonHeight+listmaxshow*fheight;	// recalc height

	x = getScreenStartX (width);
	y = getScreenStartY (height);

	m_viewer->SetScaling((CPictureViewer::ScalingMode)g_settings.picviewer_scaling);
	m_viewer->SetVisible(g_settings.screen_StartX, g_settings.screen_EndX, g_settings.screen_StartY, g_settings.screen_EndY);

	if(g_settings.video_Format == CControldClient::VIDEOFORMAT_16_9)
		m_viewer->SetAspectRatio(16.0/9);
	else if(g_settings.video_Format == CControldClient::VIDEOFORMAT_AUTO)
	{
		g_Controld->setVideoFormat(CControldClient::VIDEOFORMAT_4_3);
		m_viewer->SetAspectRatio(4.0/3);
	}
	else
		m_viewer->SetAspectRatio(4.0/3);

	if(parent)
	{
		parent->hide();
	}

	puts("[pictureviewer.cpp] executing " PICTUREVIEWER_START_SCRIPT ".");
	if (my_system(PICTUREVIEWER_START_SCRIPT) != 0)
		perror(PICTUREVIEWER_START_SCRIPT " failed");

	// tell neutrino we're in pic_mode
	CNeutrinoApp::getInstance()->handleMsg( NeutrinoMessages::CHANGEMODE , NeutrinoMessages::mode_pic );
	// remember last mode
	CZapitClient::responseGetLastChannel firstchannel;
	g_Zapit->getLastChannel(firstchannel.channelNumber, firstchannel.mode);
	if ((firstchannel.mode == 'r') ?
	    (CNeutrinoApp::getInstance()->zapto_radio_on_init_done) :
	    (CNeutrinoApp::getInstance()->zapto_tv_on_init_done))
		m_LastMode=(CNeutrinoApp::getInstance()->getLastMode() | NeutrinoMessages::norezap);
	else
		m_LastMode=(CNeutrinoApp::getInstance()->getLastMode());

	g_Sectionsd->setPauseScanning(true); 

	show();

	// free picviewer mem
	m_viewer->Cleanup();

	puts("[pictureviewer.cpp] executing " PICTUREVIEWER_END_SCRIPT ".");
	if (my_system(PICTUREVIEWER_END_SCRIPT) != 0)
		perror(PICTUREVIEWER_END_SCRIPT " failed");

	// Start Sectionsd
	g_Sectionsd->setPauseScanning(false);
	
	// Restore last mode
	CNeutrinoApp::getInstance()->handleMsg( NeutrinoMessages::CHANGEMODE , m_LastMode );
	g_RCInput->postMsg( NeutrinoMessages::SHOW_INFOBAR, 0 );

	// always exit all	
	return menu_return::RETURN_EXIT_ALL;
}
bool CExtUpdate::applySettings()
{
	if(!hintBox)
		hintBox = new CHintBox(LOCALE_MESSAGEBOX_INFO, g_Locale->getText(LOCALE_FLASHUPDATE_UPDATE_WITH_SETTINGS_PROCESSED));
	hintBox->paint();
	mtdRamError = "";
	std::string osrelease = "";
	mtdramDriver = ""; // driver path
	char buf1[256] = "";
	char buf2[256] = "";

	CMTDInfo * mtdInfo = CMTDInfo::getInstance();
	std::string mtdFilename = mtdInfo->findMTDsystem(); // /dev/mtdX
	if (mtdFilename.empty())
		return ErrorReset(0, "error system mtd not found");

#ifdef BOXMODEL_APOLLO
	uint64_t mtdSize = 65536*1024; // FIXME hack, mtd size more than free RAM
#else
	uint64_t mtdSize = mtdInfo->getMTDSize(mtdFilename);
#endif
	uint64_t mtdEraseSize = mtdInfo->getMTDEraseSize(mtdFilename);
	mtdNumber = mtdInfo->findMTDNumber(mtdFilename);

	// get osrelease
	struct utsname uts_info;
	if( uname(&uts_info) == 0 ) {
		osrelease = uts_info.release;
		size_t pos = osrelease.find_first_of(" "); 
		if (pos != std::string::npos) 
			osrelease = osrelease.substr(0, pos); 
	}
	else
		return ErrorReset(0, "error no kernel info");

	// check if mtdram driver is already loaded
	if (!isMtdramLoad()) {
		// check if exist mtdram driver
		snprintf(buf1, sizeof(buf1), "/lib/modules/%s/mtdram.ko", osrelease.c_str());
		mtdramDriver = buf1;
		if ( !file_exists(mtdramDriver.c_str()) )
			return ErrorReset(0, "no mtdram driver available");
		// load mtdram driver
		snprintf(buf1, sizeof(buf1), "total_size=%llu", mtdSize/1024);
		snprintf(buf2, sizeof(buf2), "erase_size=%llu", mtdEraseSize/1024);
		my_system(4, "insmod", mtdramDriver.c_str(), buf1, buf2);
		// check if mtdram driver is now loaded
		if (!isMtdramLoad())
			return ErrorReset(0, "error load mtdram driver");
	}
	else {
		DBG_MSG("mtdram driver is already loaded");
	}

	// find mtdram device
	std::string mtdRamFilename = "", mtdBlockFileName = "";
	uint64_t mtdRamSize = 0, mtdRamEraseSize = 0;
	int mtdRamNr = 0;
	f1 = fopen("/proc/mtd", "r");
	if(!f1)
		return ErrorReset(RESET_UNLOAD, "cannot read /proc/mtd");
	fgets(buf1, sizeof(buf1), f1);
	while(!feof(f1)) {
		if(fgets(buf1, sizeof(buf1), f1)!=NULL) {
			char dummy[50] = "";
			uint32_t tmp1, tmp2;
			sscanf(buf1, "mtd%1d: %8x %8x \"%48s\"\n", &mtdRamNr, &tmp1, &tmp2, dummy);
			mtdRamSize = (uint64_t)tmp1;
			mtdRamEraseSize = (uint64_t)tmp2;
			if (strstr(buf1, "mtdram test device") != NULL) {
				sprintf(buf1, "/dev/mtd%d", mtdRamNr);
				mtdRamFilename = buf1;
				sprintf(buf1, "/dev/mtdblock%d", mtdRamNr);
				mtdBlockFileName = buf1;
				break;
			}
		}
	}
	fclose(f1);

	if (mtdRamFilename.empty())
		return ErrorReset(RESET_UNLOAD, "no mtdram test device found");
	else {
		// check mtdRamSize / mtdRamEraseSize
		if ((mtdRamSize != mtdSize) || (mtdRamEraseSize != mtdEraseSize)) {
			snprintf(buf2, sizeof(buf2), "error MTDSize(%08llx/%08llx) or MTDEraseSize(%08llx/%08llx)\n", mtdSize, mtdRamSize, mtdEraseSize, mtdRamEraseSize);
			return ErrorReset(RESET_UNLOAD, buf2);
		}
	}

	int MTDBufSize = 0xFFFF;
	MTDBuf         = new char[MTDBufSize];
	// copy image to mtdblock
	if (MTDBuf == NULL)
		return ErrorReset(RESET_UNLOAD, "memory allocation error");
	fd1 = open(imgFilename.c_str(), O_RDONLY);
	if (fd1 < 0)
		return ErrorReset(RESET_UNLOAD | DELETE_MTDBUF, "cannot read image file: " + imgFilename);
	uint64_t filesize = (uint64_t)lseek(fd1, 0, SEEK_END);
	lseek(fd1, 0, SEEK_SET);
	if(filesize == 0)
		return ErrorReset(RESET_UNLOAD | CLOSE_FD1 | DELETE_MTDBUF, "image filesize is 0");
	if(filesize > mtdSize)
		return ErrorReset(RESET_UNLOAD | CLOSE_FD1 | DELETE_MTDBUF, "image filesize too large");
	fd2 = -1;
	int tmpCount = 0;
	while (fd2 < 0) {
		fd2 = open(mtdBlockFileName.c_str(), O_WRONLY);
		tmpCount++;
		if (tmpCount > 3)
			break;
		sleep(1);
	}
	if (fd2 < 0)
		return ErrorReset(RESET_UNLOAD | CLOSE_FD1 | DELETE_MTDBUF, "cannot open mtdBlock");
	uint64_t fsize = filesize;
	uint32_t block;
	while(fsize > 0) {
		block = (uint32_t)fsize;
		if(block > (uint32_t)MTDBufSize)
			block = MTDBufSize;
		read(fd1, MTDBuf, block);
		write(fd2, MTDBuf, block);
		fsize -= block;
	}
	close(fd1);
	close(fd2);

	FileHelpers->createDir(mountPkt.c_str(), 0755);
	int res = mount(mtdBlockFileName.c_str(), mountPkt.c_str(), "jffs2", 0, NULL);
	if (res)
		return ErrorReset(RESET_UNLOAD | DELETE_MTDBUF, "mount error");

	if (get_fs_usage(mountPkt.c_str(), total, used, &bsize))
		free1 = (total * bsize) / 1024 - (used * bsize) / 1024;

	if (!readBackupList(mountPkt)) {
		if (MTDBuf != NULL)
			delete[] MTDBuf;
		MTDBuf = NULL;
		if (flashErrorFlag)
			return false;
		return ErrorReset(0, "error readBackupList");
	}

	res = umount(mountPkt.c_str());
	if (res)
		return ErrorReset(RESET_UNLOAD | DELETE_MTDBUF, "unmount error");

	unlink(imgFilename.c_str());

	// copy mtdblock to image
	if (MTDBuf == NULL)
		return ErrorReset(RESET_UNLOAD, "memory allocation error");
	fd1 = open(mtdBlockFileName.c_str(), O_RDONLY);
	if (fd1 < 0)
		return ErrorReset(RESET_UNLOAD | DELETE_MTDBUF, "cannot read mtdBlock");
	fsize = mtdRamSize;
	fd2 = open(imgFilename.c_str(), O_WRONLY | O_CREAT);
	if (fd2 < 0)
		return ErrorReset(RESET_UNLOAD | CLOSE_FD1 | DELETE_MTDBUF, "cannot open image file: ", imgFilename);
	while(fsize > 0) {
		block = (uint32_t)fsize;
		if(block > (uint32_t)MTDBufSize)
			block = MTDBufSize;
		read(fd1, MTDBuf, block);
		write(fd2, MTDBuf, block);
		fsize -= block;
	}
	lseek(fd2, 0, SEEK_SET);
	uint64_t fsizeDst = (uint64_t)lseek(fd2, 0, SEEK_END);
	close(fd1);
	close(fd2);
	// check image file size
	if (mtdRamSize != fsizeDst) {
		unlink(imgFilename.c_str());
		return ErrorReset(DELETE_MTDBUF, "error file size: ", imgFilename);
	}

	// unload mtdramDriver only
	ErrorReset(RESET_UNLOAD);

	if(hintBox)
		hintBox->hide();

	if (MTDBuf != NULL)
		delete[] MTDBuf;
	MTDBuf = NULL;
	sync();
	return true;
}
Beispiel #13
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    char buf[400];

    global_app = &a;
    //enable the watchdog
    global_wdg->start(QThread::HighPriority);
    //global_wdg->watchdog_timer.start(45*1000);

    //drawPrimitive();
    // QWSServer::setCursorVisible(false);
    //no valid
    //a.setOverrideCursor(Qt::BlankCursor);

    //system("/bin/rm /var/log/eth0-setting.log");
    //system("/bin/rm /etc/rebootTime");
    //register segment default
    signal(SIGSEGV,func);

    //my_system("ps");

    arg_main = argv[0];
    //camThread camera;
    //camera.start(QThread::LowPriority);

    setting_timezone();
    
    dealLog(0, 0, 0, 0);
    
    sprintf(buf, "\n**************Cartvu:VERSION:%4.2f**********************\n", CARTVU_NOW_VERSION);
    qDebug() << buf;
    recordLog(1, 1, buf);

    sprintf(buf, "df >>%s", filename);
    my_system(buf);


    recordLog(1, 1, (char*)"reboot time here!!!");

    sprintf(buf, "%s size is %ld", argv[0], read_self_size(argv[0]));
    printf("%s\n", buf);
    recordLog(1, 1, buf);


    global_buffer = (unsigned char *)malloc(CAMERA_WIDTH * CAMERA_HEIGHT * CAM_LINELEN);   // allocate memory for camera
    if (!global_buffer) {
        perror("shmat shm_buffer fail");
        recordLog(1, 1, (char*)"malloc camera buffer fail!!");
        //exit(1);
    }

    global_camera = new camThread(global_buffer);              // instance of a camera class
    //global_camera->start(QThread::LowPriority);
    qDebug() << "camera start";
    qDebug() << global_camera;


    //global_sensor->start();




    global_rsys = new read_sys(config_sys);
    //download config.sys file  read local server ip
    //读取当前的config.sys的信息
    global_rsys->sys_decode(CFG_SYS, config_sys);
    //读取eth0-setting中的mac及lane number
    global_rsys->read_eth0(ETH0SETTING); //read mac  and lane number
    //程序启动后的随机延时,延时后进去登陆下载等步骤

    //显示登陆窗口
    //cartvu *w = new cartvu(global_camera);
    global_log = new login(global_camera);
    //系统开机的随机延时
    global_rsys->get_file_delay();//need local server ip
    //解码    将user密码与接收到的加密的密码比较
    global_rsys->decode_passwd("car1998", CONFIG_ADMIN);


    // QTranslator translator;
    // translator.load("zh_CN",".");
    // a.installTranslator(&translator);


#if 1
    //global_log->show();
    ;
#else
    w->showFullScreen();
#endif
    return a.exec();
}
Beispiel #14
0
void
toggle_panels (void)
{
#ifdef ENABLE_SUBSHELL
    vfs_path_t *new_dir_vpath = NULL;
#endif /* ENABLE_SUBSHELL */

    SIG_ATOMIC_VOLATILE_T was_sigwinch = 0;

    channels_down ();
    disable_mouse ();
    disable_bracketed_paste ();
    if (clear_before_exec)
        clr_scr ();
    if (mc_global.tty.alternate_plus_minus)
        numeric_keypad_mode ();
#ifndef HAVE_SLANG
    /* With slang we don't want any of this, since there
     * is no raw_mode supported
     */
    tty_reset_shell_mode ();
#endif /* !HAVE_SLANG */
    tty_noecho ();
    tty_keypad (FALSE);
    tty_reset_screen ();
    do_exit_ca_mode ();
    tty_raw_mode ();
    if (mc_global.tty.console_flag != '\0')
        handle_console (CONSOLE_RESTORE);

#ifdef ENABLE_SUBSHELL
    if (mc_global.tty.use_subshell)
    {
        vfs_path_t **new_dir_p;

        new_dir_p = vfs_current_is_local ()? &new_dir_vpath : NULL;
        invoke_subshell (NULL, VISIBLY, new_dir_p);
    }
    else
#endif /* ENABLE_SUBSHELL */
    {
        if (output_starts_shell)
        {
            fprintf (stderr, _("Type 'exit' to return to the Midnight Commander"));
            fprintf (stderr, "\n\r\n\r");

            my_system (EXECUTE_INTERNAL, mc_global.tty.shell, NULL);
        }
        else
            get_key_code (0);
    }

    if (mc_global.tty.console_flag != '\0')
        handle_console (CONSOLE_SAVE);

    do_enter_ca_mode ();

    tty_reset_prog_mode ();
    tty_keypad (TRUE);

    /* Prevent screen flash when user did 'exit' or 'logout' within
       subshell */
    if ((quit & SUBSHELL_EXIT) != 0)
    {
        /* User did 'exit' or 'logout': quit MC */
        if (quiet_quit_cmd ())
            return;

        quit = 0;
#ifdef ENABLE_SUBSHELL
        /* restart subshell */
        if (mc_global.tty.use_subshell)
            init_subshell ();
#endif /* ENABLE_SUBSHELL */
    }

    enable_mouse ();
    enable_bracketed_paste ();
    channels_up ();
    if (mc_global.tty.alternate_plus_minus)
        application_keypad_mode ();

    /* HACK:
     * Save sigwinch flag that will be reset in mc_refresh() called via update_panels().
     * There is some problem with screen redraw in ncurses-based mc in this situation.
     */
    was_sigwinch = mc_global.tty.winch_flag;
    mc_global.tty.winch_flag = 0;

#ifdef ENABLE_SUBSHELL
    if (mc_global.tty.use_subshell)
    {
        do_load_prompt ();
        if (new_dir_vpath != NULL)
            do_possible_cd (new_dir_vpath);
        if (mc_global.tty.console_flag != '\0' && output_lines)
            show_console_contents (output_start_y,
                                   LINES - mc_global.keybar_visible - output_lines -
                                   1, LINES - mc_global.keybar_visible - 1);
    }

    vfs_path_free (new_dir_vpath);
#endif /* ENABLE_SUBSHELL */

    if (mc_global.mc_run_mode == MC_RUN_FULL)
    {
        update_panels (UP_OPTIMIZE, UP_KEEPSEL);
        update_xterm_title_path ();
    }

    if (was_sigwinch != 0 || mc_global.tty.winch_flag != 0)
        dialog_change_screen_size ();
    else
        repaint_screen ();
}
Beispiel #15
0
int CHDDFmtExec::exec(CMenuTarget* /*parent*/, const std::string& key)
{
	char cmd[100];
	char cmd2[100];
	CHintBox * hintbox;
	int res;
	FILE * f;
	char src[128], dst[128];
	CProgressWindow * progress;

	snprintf(src, sizeof(src), "/dev/%s1", key.c_str());
	snprintf(dst, sizeof(dst), "/media/%s1", key.c_str());

	printf("CHDDFmtExec: key %s\n", key.c_str());

	res = ShowMsg ( LOCALE_HDD_FORMAT, g_Locale->getText(LOCALE_HDD_FORMAT_WARN), CMessageBox::mbrNo, CMessageBox::mbYes | CMessageBox::mbNo );
	if(res != CMessageBox::mbrYes)
		return 0;

	bool srun = my_system(3, "killall", "-9", "smbd");

	//res = check_and_umount(dst);
	res = check_and_umount(src, dst);
	printf("CHDDFmtExec: umount res %d\n", res);

	if(res) {
		hintbox = new CHintBox(LOCALE_HDD_FORMAT, g_Locale->getText(LOCALE_HDD_UMOUNT_WARN));
		hintbox->paint();
		sleep(2);
		delete hintbox;
		goto _return;
	}

	f = fopen("/proc/sys/kernel/hotplug", "w");
	if(f) {
		fprintf(f, "none\n");
		fclose(f);
	}

	progress = new CProgressWindow();
	progress->setTitle(LOCALE_HDD_FORMAT);
	progress->exec(NULL,"");
	progress->showStatusMessageUTF("Executing fdisk");
	progress->showGlobalStatus(0);

	if (access("/sbin/sfdisk", X_OK) == 0) {
		snprintf(cmd, sizeof(cmd), "/sbin/sfdisk -f -uM /dev/%s", key.c_str());
		strcpy(cmd2, "0,\n;\n;\n;\ny\n");
	} else {
		snprintf(cmd, sizeof(cmd), "/sbin/fdisk /dev/%s", key.c_str());
		strcpy(cmd2, "o\nn\np\n1\n\n\nw\n");
	}

	printf("CHDDFmtExec: executing %s\n", cmd);
	f=popen(cmd, "w");
	if (!f) {
		hintbox = new CHintBox(LOCALE_HDD_FORMAT, g_Locale->getText(LOCALE_HDD_FORMAT_FAILED));
		hintbox->paint();
		sleep(2);
		delete hintbox;
		goto _remount;
	}

	fprintf(f, "%s", cmd2);
	pclose(f);
	//sleep(1);

	switch(g_settings.hdd_fs) {
		case 0:
			snprintf(cmd, sizeof(cmd), "/sbin/mkfs.ext3 -T largefile -m0 %s", src);
			break;
		case 1:
			snprintf(cmd, sizeof(cmd), "/sbin/mkreiserfs -f -f %s", src);
			break;
		default:
			return 0;
	}

	printf("CHDDFmtExec: executing %s\n", cmd);

	f=popen(cmd, "r");
	if (!f) {
		hintbox = new CHintBox(LOCALE_HDD_FORMAT, g_Locale->getText(LOCALE_HDD_FORMAT_FAILED));
		hintbox->paint();
		sleep(2);
		delete hintbox;
		goto _remount;
	}

	char buf[256];
	setbuf(f, NULL);
	int n, t, in, pos, stage;
	pos = 0;
	stage = 0;
	while (true)
	{
		in = fgetc(f);
		if (in == EOF)
			break;

		buf[pos] = (char)in;
		pos++;
		buf[pos] = 0;
		if (in == '\b' || in == '\n')
			pos = 0; /* start a new line */
		//printf("%s", buf);
		switch (stage) {
			case 0:
				if (strcmp(buf, "Writing inode tables:") == 0) {
					stage++;
					progress->showGlobalStatus(20);
					progress->showStatusMessageUTF(buf);
				}
				break;
			case 1:
				if (in == '\b' && sscanf(buf, "%d/%d\b", &n, &t) == 2) {
					int percent = 100 * n / t;
					progress->showLocalStatus(percent);
					progress->showGlobalStatus(20 + percent / 5);
				}
				if (strstr(buf, "done")) {
					stage++;
					pos = 0;
				}
				break;
			case 2:
				if (strstr(buf, "blocks):") && sscanf(buf, "Creating journal (%d blocks):", &n) == 1) {
					progress->showLocalStatus(0);
					progress->showGlobalStatus(60);
					progress->showStatusMessageUTF(buf);
					pos = 0;
				}
				if (strstr(buf, "done")) {
					stage++;
					pos = 0;
				}
				break;
			case 3:
				if (strcmp(buf, "Writing superblocks and filesystem accounting information:") == 0) {
					progress->showGlobalStatus(80);
					progress->showStatusMessageUTF(buf);
					pos = 0;
				}
				break;
			default:
				// printf("unknown stage! %d \n\t", stage);
				break;
		}
	}
	progress->showLocalStatus(100);
	pclose(f);
	progress->showGlobalStatus(100);
	sleep(2);

	printf("CHDDFmtExec: executing %s %s\n","/sbin/tune2fs -r 0 -c 0 -i 0", src);
	my_system(8, "/sbin/tune2fs", "-r", "0", "-c", "0", "-i", "0", src);

_remount:
	progress->hide();
	delete progress;

        switch(g_settings.hdd_fs) {
                case 0:
			safe_mkdir(dst);
			res = mount(src, dst, "ext3", 0, NULL);
                        break;
                case 1:
			safe_mkdir(dst);
			res = mount(src, dst, "reiserfs", 0, NULL);
                        break;
		default:
                        break;
        }
	f = fopen("/proc/sys/kernel/hotplug", "w");
	if(f) {
#ifdef ASSUME_MDEV
		fprintf(f, "/sbin/mdev\n");
#else
		fprintf(f, "/sbin/hotplug\n");
#endif
		fclose(f);
	}

	if(!res) {
		snprintf(cmd, sizeof(cmd), "%s/movies", dst);
		safe_mkdir(cmd);
		snprintf(cmd, sizeof(cmd), "%s/pictures", dst);
		safe_mkdir(cmd);
		snprintf(cmd, sizeof(cmd), "%s/epg", dst);
		safe_mkdir(cmd);
		snprintf(cmd, sizeof(cmd), "%s/music", dst);
		safe_mkdir(cmd);
		snprintf(cmd, sizeof(cmd), "%s/logos", dst);
		safe_mkdir(cmd);
		snprintf(cmd, sizeof(cmd), "%s/plugins", dst);
		safe_mkdir(cmd);
		sync();
	}
_return:
	if (!srun) my_system(1, "smbd");
	return menu_return::RETURN_REPAINT;
}
Beispiel #16
0
void do_cc(void) {
    if (i_files) {
	PAIRLIST pl;
	/* The i_files variable was only filled in if we are stoping after -S or -c */
	assert(stop_at==STOP_AT_S || stop_at==STOP_AT_O);
	for (pl=i_files; pl; pl=pl->rest) {
	    MY_ARGV ma = make_my_argv();
	    push_stringified_args(ma, get_cc());
	    pusharg(ma, pl->a);
	    pusharg(ma, "-o");
	    pusharg(ma, pl->b);
	    pushargs(ma, cc_early_args);
	    if (stop_at==STOP_AT_S) pusharg(ma, "-S");
	    else if (stop_at==STOP_AT_O) pusharg(ma, "-c");
	    else abort(); /* This cannot happen.  See the assert() above. */
	    push_stringified_args(ma, CILKC_PTHREAD_CFLAGS);
	    if (save_temps) pusharg(ma, "-save-temps");
	    VERBOSE(2, pusharg(ma, "-v"));
	    VERBOSE(1, print_my_argv(stderr, ma, 0));
	    if (my_system(ma, 0)!=0) barf("failed running the final %s to produce %s", get_cc(), pl->b);
	    free_my_argv(ma);
	}
    }
    if (n_gcc_files>0) {
	MY_ARGV ma = make_my_argv();
	push_stringified_args(ma, get_cc());
	switch (stop_at) {
	case STOP_AT_M:     barf("I called final cc when I was supposed to do -M");
	case STOP_AT_CILKI:
	case STOP_AT_CILKC: barf("I called final cc when I was supposed to stop earlier");
	case STOP_AT_I: pusharg(ma, "-E"); break;
	case STOP_AT_S: pusharg(ma, "-S"); break;
	case STOP_AT_O: pusharg(ma, "-c"); break;
	case STOP_AT_END: break;
	}
	pushargs(ma, cc_args);
	if (stop_at==STOP_AT_END) {
	    pusharg(ma, "-L" LIBS_DIR);
	    pusharg(ma, "-L" LIBS2_DIR);
	    if (cilk_debug) {
	      if (cilk_profile) { pusharg(ma, "-lcilkrt0gp"); pusharg(ma, "-lcilk.g.p"); }
		else              { pusharg(ma, "-lcilkrt0g");  pusharg(ma, "-lcilk.g"); }
	    } else {
		if (cilk_profile) { pusharg(ma, "-lcilkrt0p");  pusharg(ma, "-lcilk.p"); }
		else              { pusharg(ma, "-lcilkrt0");   pusharg(ma, "-lcilk"); }
	    }
#           ifdef WITH_GNU_LD
	       pusharg(ma, "-Wl,-rpath," LIBS_DIR);
#           endif
	}
	push_stringified_args(ma, CILKC_PTHREAD_CFLAGS);
	push_stringified_args(ma, CILKC_PTHREAD_LIBS);
	if (output_name) {
	    pusharg(ma, "-o");
	    pusharg(ma, output_name);
	}
	VERBOSE(2, pusharg(ma, "-v"));
	VERBOSE(1, print_my_argv(stderr, ma, 0));
	if (my_system(ma, 0)!=0) barf("failed running the final %s", get_cc());
	free_my_argv(ma);
    }
}
Beispiel #17
0
int CHDDChkExec::exec(CMenuTarget* /*parent*/, const std::string& key)
{
	char cmd[100];
	CHintBox * hintbox;
	int res;
	char src[128], dst[128];
	FILE * f;
	CProgressWindow * progress;
	int oldpass = 0, pass, step, total;
	int percent = 0, opercent = 0;

	snprintf(src, sizeof(src), "/dev/%s1", key.c_str());
	snprintf(dst, sizeof(dst), "/media/%s1", key.c_str());

printf("CHDDChkExec: key %s\n", key.c_str());

	bool srun = my_system(3, "killall", "-9", "smbd");

	//res = check_and_umount(dst);
	res = check_and_umount(src, dst);
	printf("CHDDChkExec: umount res %d\n", res);
	if(res) {
		hintbox = new CHintBox(LOCALE_HDD_CHECK, g_Locale->getText(LOCALE_HDD_UMOUNT_WARN));
		hintbox->paint();
		sleep(2);
		delete hintbox;
		return menu_return::RETURN_REPAINT;
	}

	switch(g_settings.hdd_fs) {
		case 0:
			snprintf(cmd, sizeof(cmd), "/sbin/fsck.ext3 -C 1 -f -y %s", src);
			break;
		case 1:
			snprintf(cmd, sizeof(cmd), "/sbin/reiserfsck --fix-fixable %s", src);
			break;
		default:
			return 0;
	}

	printf("CHDDChkExec: Executing %s\n", cmd);
	f=popen(cmd, "r");
	if(!f) {
		hintbox = new CHintBox(LOCALE_HDD_CHECK, g_Locale->getText(LOCALE_HDD_CHECK_FAILED));
		hintbox->paint();
		sleep(2);
		delete hintbox;
		goto ret1;
	}

	progress = new CProgressWindow();
	progress->setTitle(LOCALE_HDD_CHECK);
	progress->exec(NULL,"");

	char buf[256];
	while(fgets(buf, 255, f) != NULL)
	{
		if(isdigit(buf[0])) {
			sscanf(buf, "%d %d %d\n", &pass, &step, &total);
			if(total == 0)
				total = 1;
			if(oldpass != pass) {
				oldpass = pass;
				progress->showGlobalStatus(pass > 0 ? (pass-1)*20: 0);
			}
			percent = (step * 100) / total;
			if(opercent != percent) {
				opercent = percent;
//printf("CHDDChkExec: pass %d : %d\n", pass, percent);
				progress->showLocalStatus(percent);
			}
		}
		else if(!strncmp(buf, "Pass", 4)) {
			char *t = strrchr(buf, '\n');
			if (t)
				*t = 0;
			progress->showStatusMessageUTF(buf);
		}
	}
//printf("CHDDChkExec: %s\n", buf);
	pclose(f);
	progress->showGlobalStatus(100);
	progress->showStatusMessageUTF(buf);
	sleep(2);
	progress->hide();
	delete progress;

ret1:
        switch(g_settings.hdd_fs) {
                case 0:
			safe_mkdir(dst);
			res = mount(src, dst, "ext3", 0, NULL);
                        break;
                case 1:
			safe_mkdir(dst);
			res = mount(src, dst, "reiserfs", 0, NULL);
                        break;
		default:
                        break;
        }
	printf("CHDDChkExec: mount res %d\n", res);

	if (!srun) my_system(1, "smbd");
	return menu_return::RETURN_REPAINT;
}
Beispiel #18
0
/* handles a client connection */
void handle_connection(int sock){
        u_int32_t calculated_crc32;
	command *temp_command;
	packet receive_packet;
	packet send_packet;
	int bytes_to_send;
	int bytes_to_recv;
	char buffer[MAX_INPUT_BUFFER];
	char raw_command[MAX_INPUT_BUFFER];
	char processed_command[MAX_INPUT_BUFFER];
	int result=STATE_OK;
	int early_timeout=FALSE;
	int rc;
	int x;
#ifdef DEBUG
	FILE *errfp;
#endif
#ifdef HAVE_SSL
	SSL *ssl=NULL;
#endif


	/* log info to syslog facility */
	if(debug==TRUE)
		syslog(LOG_DEBUG,"Handling the connection...");

#ifdef OLDSTUFF
	/* socket should be non-blocking */
	fcntl(sock,F_SETFL,O_NONBLOCK);
#endif

#ifdef HAVE_SSL
	/* do SSL handshake */
	if(result==STATE_OK && use_ssl==TRUE){
		if((ssl=SSL_new(ctx))!=NULL){
			SSL_set_fd(ssl,sock);
			if((rc=SSL_accept(ssl))!=1){
				syslog(LOG_ERR,"Error: Could not complete SSL handshake. %d\n",SSL_get_error(ssl,rc));
#ifdef DEBUG
				errfp=fopen("/tmp/err.log","w");
				ERR_print_errors_fp(errfp);
				fclose(errfp);
#endif
				return;
			        }
		        }
		else{
			syslog(LOG_ERR,"Error: Could not create SSL connection structure.\n");
#ifdef DEBUG
			errfp=fopen("/tmp/err.log","w");
			ERR_print_errors_fp(errfp);
			fclose(errfp);
#endif
			return;
		        }
	        }
#endif

	bytes_to_recv=sizeof(receive_packet);
	if(use_ssl==FALSE)
		rc=recvall(sock,(char *)&receive_packet,&bytes_to_recv,socket_timeout);
#ifdef HAVE_SSL
	else
		rc=SSL_read(ssl,&receive_packet,bytes_to_recv);
#endif

	/* recv() error or client disconnect */
	if(rc<=0){

		/* log error to syslog facility */
		syslog(LOG_ERR,"Could not read request from client, bailing out...");

#ifdef HAVE_SSL
		SSL_shutdown(ssl);
		SSL_free(ssl);
		syslog(LOG_INFO,"INFO: SSL Socket Shutdown.\n");
#endif

		return;
                }

	/* we couldn't read the correct amount of data, so bail out */
	else if(bytes_to_recv!=sizeof(receive_packet)){

		/* log error to syslog facility */
		syslog(LOG_ERR,"Data packet from client was too short, bailing out...");

#ifdef HAVE_SSL
		SSL_shutdown(ssl);
		SSL_free(ssl);
#endif

		return;
	        }

#ifdef DEBUG
	fp=fopen("/tmp/packet","w");
	if(fp){
		fwrite(&receive_packet,1,sizeof(receive_packet),fp);
		fclose(fp);
	        }
#endif

	/* make sure the request is valid */
	if(validate_request(&receive_packet)==ERROR){

		/* log an error */
		syslog(LOG_ERR,"Client request was invalid, bailing out...");

		/* free memory */
		free(command_name);
		command_name=NULL;
		for(x=0;x<MAX_COMMAND_ARGUMENTS;x++){
			free(macro_argv[x]);
			macro_argv[x]=NULL;
	                }

#ifdef HAVE_SSL
		SSL_shutdown(ssl);
		SSL_free(ssl);
#endif

		return;
	        }

	/* log info to syslog facility */
	if(debug==TRUE)
		syslog(LOG_DEBUG,"Host is asking for command '%s' to be run...",receive_packet.buffer);

	/* if this is the version check command, just spew it out */
	if(!strcmp(command_name,NRPE_HELLO_COMMAND)){

		snprintf(buffer,sizeof(buffer),"NRPE v%s",PROGRAM_VERSION);
		buffer[sizeof(buffer)-1]='\x0';

		/* log info to syslog facility */
		if(debug==TRUE)
			syslog(LOG_DEBUG,"Response: %s",buffer);

		result=STATE_OK;
	        }

	/* find the command we're supposed to run */
	else{
		temp_command=find_command(command_name);
		if(temp_command==NULL){

			snprintf(buffer,sizeof(buffer),"NRPE: Command '%s' not defined",command_name);
			buffer[sizeof(buffer)-1]='\x0';

			/* log error to syslog facility */
			if(debug==TRUE)
				syslog(LOG_DEBUG,"%s",buffer);

			result=STATE_CRITICAL;
	                }

		else{

			/* process command line */
			strncpy(raw_command,temp_command->command_line,sizeof(raw_command)-1);
			raw_command[sizeof(raw_command)-1]='\x0';
			process_macros(raw_command,processed_command,sizeof(processed_command));

			/* log info to syslog facility */
			if(debug==TRUE)
				syslog(LOG_DEBUG,"Running command: %s",processed_command);

			/* run the command */
			strcpy(buffer,"");
			result=my_system(processed_command,command_timeout,&early_timeout,buffer,sizeof(buffer));

			/* log debug info */
			if(debug==TRUE)
				syslog(LOG_DEBUG,"Command completed with return code %d and output: %s",result,buffer);

			/* see if the command timed out */
			if(early_timeout==TRUE)
				snprintf(buffer,sizeof(buffer)-1,"NRPE: Command timed out after %d seconds\n",command_timeout);
			else if(!strcmp(buffer,""))
				snprintf(buffer,sizeof(buffer)-1,"NRPE: Unable to read output\n");

			buffer[sizeof(buffer)-1]='\x0';

			/* check return code bounds */
			if((result<0) || (result>3)){

				/* log error to syslog facility */
				syslog(LOG_ERR,"Bad return code for [%s]: %d", buffer,result);

				result=STATE_UNKNOWN;
			        }
		        }
	        }

	/* free memory */
	free(command_name);
	command_name=NULL;
	for(x=0;x<MAX_COMMAND_ARGUMENTS;x++){
		free(macro_argv[x]);
		macro_argv[x]=NULL;
	        }

	/* strip newline character from end of output buffer */
	if(buffer[strlen(buffer)-1]=='\n')
		buffer[strlen(buffer)-1]='\x0';

	/* clear the response packet buffer */
	bzero(&send_packet,sizeof(send_packet));

	/* fill the packet with semi-random data */
	randomize_buffer((char *)&send_packet,sizeof(send_packet));

	/* initialize response packet data */
	send_packet.packet_version=(int16_t)htons(NRPE_PACKET_VERSION_2);
	send_packet.packet_type=(int16_t)htons(RESPONSE_PACKET);
	send_packet.result_code=(int16_t)htons(result);
	strncpy(&send_packet.buffer[0],buffer,MAX_PACKETBUFFER_LENGTH);
	send_packet.buffer[MAX_PACKETBUFFER_LENGTH-1]='\x0';
	
	/* calculate the crc 32 value of the packet */
	send_packet.crc32_value=(u_int32_t)0L;
	calculated_crc32=calculate_crc32((char *)&send_packet,sizeof(send_packet));
	send_packet.crc32_value=(u_int32_t)htonl(calculated_crc32);


	/***** ENCRYPT RESPONSE *****/


	/* send the response back to the client */
	bytes_to_send=sizeof(send_packet);
	if(use_ssl==FALSE)
		sendall(sock,(char *)&send_packet,&bytes_to_send);
#ifdef HAVE_SSL
	else
		SSL_write(ssl,&send_packet,bytes_to_send);
#endif

#ifdef HAVE_SSL
	SSL_shutdown(ssl);
	SSL_free(ssl);
#endif

	/* log info to syslog facility */
	if(debug==TRUE)
		syslog(LOG_DEBUG,"Return Code: %d, Output: %s",result,buffer);

	return;
        }
Beispiel #19
0
int main(int argc, char *argv[]){
	my_system();
	return 0;
}