Esempio n. 1
0
/**
 * This function figures out what interface is used, and reads the
 * two different configuration files, the global and the user one.
 */
void settings_read_interface(void)
{
  char *interface, *global_filename, *user_filename;
  char *homedir;
  void *value;

  /* Get the name of the interface. */
  settings_get("interface", &value);
  interface = (char *)value;

  /* Global configuration file, /etc/zen/<interface>.conf */
  global_filename = (char *)malloc(strlen(GLOBAL_CONFIGDIR) +
				   strlen(interface) + 42);
  if(global_filename == NULL)
    return;
  sprintf(global_filename, "%s/%s.conf", GLOBAL_CONFIGDIR, interface);
  read_configuration(global_filename, 0);
  free(global_filename);

  /* User configuration file, ~/.zen/<interface>.conf */
  homedir = find_homedir();
  user_filename = (char *)malloc(strlen(homedir) + 
				 strlen(interface) + 42);
  if(user_filename == NULL)
    return;
  sprintf(user_filename, "%s/.zen/%s.conf", homedir, interface);
  read_configuration(user_filename, 0);
  free(user_filename);
}
Esempio n. 2
0
int cmain ()
{
    programme_identification = cons (sym_server_seteh, make_integer (1));

    initialise_kyu_script_commands ();
    initialise_kyu_types ();
    multiplex_add_kyu_stdio (on_event, (void *)0);
    graph_initialise();

    global_environment = kyu_sx_default_environment ();
    global_environment =
        lx_environment_bind (global_environment, sym_action_wrap,
                             lx_foreign_mu (sym_action_wrap, action_wrap));
    global_environment =
        lx_environment_bind (global_environment, sym_action_dispatch,
                             lx_foreign_mu (sym_action_dispatch,
                                            action_dispatch));
    my_modules    = lx_make_environment (sx_end_of_list);
    mod_functions = lx_make_environment (sx_end_of_list);
    mod_metadata  = lx_make_environment (sx_end_of_list);

    read_configuration ();

    while (multiplex() == mx_ok);

    return 0;
}
// Constructor
preferences_dialog::preferences_dialog( wxWindow* parent )
{
    wxXmlResource::Get()->LoadDialog( this, parent, "preferences_dialog" );

#if ( ! setupUSE_SHOWCASE_PREVIEW_PANE )
    // If not using the preview, then hide and disable the images checkbox
    // TODO: is enable(false) needed, when already using a show(false)?
    XRCCTRL( *this, "preferences_dialog_showcase_images_checkbox", wxCheckBox )->Enable( FALSE );
    XRCCTRL( *this, "preferences_dialog_showcase_images_checkbox", wxCheckBox )->Show( FALSE );
#endif

    // Attach time controls to their XRC "unknown" placeholders.
    m_autoupdate_lower_time_control = new time_control( this, ID_PREFERENCES_DIALOG_LOWER_TIME_CONTROL  );
    wxXmlResource::Get()->AttachUnknownControl( "preferences_dialog_autoupdate_lower_time_control",
            m_autoupdate_lower_time_control );

    m_autoupdate_upper_time_control = new time_control( this, ID_PREFERENCES_DIALOG_UPPER_TIME_CONTROL  );
    wxXmlResource::Get()->AttachUnknownControl( "preferences_dialog_autoupdate_upper_time_control",
            m_autoupdate_upper_time_control );

    wxLogDebug( "Attached custom time_controls" );

    // Read the configuration file to set up the values for the controls.
    read_configuration();

    // Set the size, position of the frame using our common function for this dialog
    // [utils_controls.cpp]
    utils_controls::read_dialog_position_and_size( this, "preferences_dialog" );
}
/************************************************************
read_cal()		Read all EEPROM stored variables & constants.

Read from EEPROM, and stores into the RAM
*************************************************************/
byte* read_cal()
{
	byte* addr;
	addr = read_configuration();		// myinstance, confirmed status, config bytes
	addr = read_stops_eeprom			(addr);
	addr = read_currentThresholds_eeprom(addr);
	addr = read_latest_position_eeprom	(addr);
	return addr;
}
Esempio n. 5
0
/*-------------------------------------------------------------------------------------------------------*/
int main(int argcount, char** argvektor) {

	/* Read parameters from given file, default is "config.txt", check that input string fits char *infile.
	 * This way several different simulations with different starting parameters are possible. */
	char infile[1024];
	unsigned int length = 1024;

	double* init_positions;

	if(argcount == 4) {
		strncpy(infile, argvektor[1], length);
		sim_number = atoi(argvektor[2]);
		init_positions = read_configuration(argvektor[3]);

		// return with a failure if the specified array could not be read
		if (init_positions == NULL) 
			return EXIT_FAILURE;

	} else if (argcount == 3) {
		strncpy(infile, argvektor[1], length);
		sim_number = atoi(argvektor[2]);
		init_positions = NULL;
	} else if (argcount == 2) {
		strncpy(infile, argvektor[1], length);
		sim_number = 0;
		init_positions = NULL;
	} else {
		strncpy(infile,"Config_Files/default", length);		// default
		sim_number = 0;
		init_positions = NULL;
	}

	// pass arguments to file reader
	int success_check = read_struct(infile);

	// check whether file could be properly read
	if(success_check != EXIT_SUCCESS) {
		return EXIT_FAILURE;
	}

	// create a new struct for the simulation
	struct sim_struct *sim = make_sim_struct();

	// Initiate all variables, here a memory problem is most likely the issue at hand
	success_check = init(sim, init_positions);
	if(success_check != EXIT_SUCCESS) {
		return EXIT_FAILURE;
	}

	// run simulation
	simulation();

	return EXIT_SUCCESS;
}
Esempio n. 6
0
static void init() {
  // read configuration 
  read_configuration();
    
  // register configurable messages
  app_message_register_inbox_received(in_received_handler);
  app_message_register_inbox_dropped(in_dropped_handler);
  app_message_open(64, 64);
  
  // Create main Window element
  s_main_window = window_create();
  window_set_background_color(s_main_window, GColorBlack);

  // Set handlers to manage the elements inside the Window
  window_set_window_handlers(s_main_window, (WindowHandlers) {
    .load = main_window_load,
    .unload = main_window_unload
  });
Esempio n. 7
0
/**
    Provides to parse a configuration file
*/
static void check_configuration ()
{
    int fsize;
    gchar *file;
    xmlDocPtr doc;

    file = read_configuration (&fsize);
    doc = xmlReadMemory (file, fsize, NULL, NULL, XML_PARSE_NOBLANKS);

    if (doc == NULL) {
        g_warning ("Unable to read configuration");
    }
    else {
        build_hierarchy_tree_from_xml (doc);
        xmlFreeDoc (doc);
    }

    g_free (file);
}
Esempio n. 8
0
GA::GA(TString configfile)
{
  read_configuration(configfile);
  print_configuration();

  init_random();

  // output file
  output.open(m_name+".log");

  // chains
  m_signal_chain = new TChain(m_signal_treename);
  for (auto signal_file : m_signal_files)
    m_signal_chain->Add(signal_file);

  m_background_chain = new TChain(m_background_treename);
  for (auto bkg_file : m_background_files)
    m_background_chain->Add(bkg_file);

  // init some variables
  m_stall_generation = 0;

  // histograms
  Int_t bins[m_nvars];
  Double_t xmin[m_nvars];
  Double_t xmax[m_nvars];

  for (unsigned int i=0; i<m_nvars; i++) {
    bins[i] = (m_variables[i].max - m_variables[i].min)/m_variables[i].step;
    xmin[i] = m_variables[i].min;
    xmax[i] = m_variables[i].max;
  }

  hist_s = new THnSparseD("hist_s", "Signal", m_nvars, bins, xmin, xmax);
  hist_b = new THnSparseD("hist_b", "Background", m_nvars, bins, xmin, xmax);
  hist_z = new THnSparseD("hist_z", "Significance", m_nvars, bins, xmin, xmax);

}
Esempio n. 9
0
void TestMode(const char * f, int color) {
	ChessBoard board;
	string Line;
	file.open("DEBUG.TXT");
	string board_status;
	cout.setf (ios::unitbuf); //disable buffering
	board.changeColor(color);
	ifstream in(f);
	read_configuration(board,in);
	bestMove move = board.negaMax(1,color,-20000,200000,0,board.board);
	cout << move.move << " " << move.score << endl;
	//board.movePiece("b4c3",board.board);
	//board.genMove();
	//board.history.push_back("d2d4");
	cout << board.printBoard() << endl;
	//unordered_map<int, vector<int> > map = board.formLocationDictionary(board.board);
	//vector<string> moves = board.addAllMoves(color,board.board, map);
	/*for (auto it = moves.begin(); it != moves.end(); it++) {
		cout << *it << endl;
	}*/
	//board.movePiece("a7b8q",board.board);
	//cout << board.printBoard();
}
Esempio n. 10
0
void WindowManager::init_internals(void)
{
	ELOG("Starting window manager");
	wm_conf = new WindowManagerConfig;

	app_starting = false;

	// defaults, in case world goes down
	wm_conf->title_active_color = fl_rgb(0,0,128);
	wm_conf->title_active_color_text = fl_rgb(255,255,255);
	wm_conf->title_normal_color = fl_rgb(192,192,192);
	wm_conf->title_normal_color_text = fl_rgb(0,0,128);
	wm_conf->title_label_align = FL_ALIGN_LEFT;
	wm_conf->title_height = 20;
	wm_conf->title_box_type = 0;
	wm_conf->frame_do_opaque = false;
	wm_conf->frame_animate = true;
	wm_conf->frame_animate_speed = 15;

	fl_open_display();
	XSetErrorHandler(xerror_handler);
	wm_area.set(0, 0, Fl::w(), Fl::h());

	read_configuration();
	read_xset_configuration();

	//register_protocols();
#ifdef _DEBUG
	InitAtoms(fl_display, atom_map);
	register_events();
#else
	InitAtoms(fl_display);
#endif

	//cur = XCreateFontCursor(fl_display, XC_left_ptr);
	//XDefineCursor(fl_display, RootWindow(fl_display, fl_screen), cur);
	// load cursor
	cur = new CursorHandler;
	cur->load(X_CURSORS);
	cur->set_root_cursor();

	sound_system = new SoundSystem();
	sound_system->init();

	sound_system->add(SOUND_MINIMIZE, "sounds/minimize.ogg");
	sound_system->add(SOUND_MAXIMIZE, "sounds/maximize.ogg");
	sound_system->add(SOUND_CLOSE,    "sounds/close.ogg");
	sound_system->add(SOUND_RESTORE,  "sounds/restore.ogg");
	sound_system->add(SOUND_SHADE,    "sounds/shade.ogg");

	// the world is starting here
	show();
	register_protocols();

	hint_stuff = new Hints;
	hint_stuff->icccm_set_iconsizes(this);

	init_clients();
	Fl::add_handler(wm_event_handler);
	XSync(fl_display, 0);

	is_running = true;
}
Esempio n. 11
0
/**
 * @param argc: Number of command line arguments supplied.
 * @param argv: Char* array containing the command line arguments supplied.
 * @return: To the system, normally 0.
 * @brief: The first function once enotes is called.
 */
int
main(int argc, char *argv[])
{
	int             note_count;

	/* IPC Check */
	ecore_ipc_init();
	dml("IPC Initiated Successfully", 1);

	/* loading will increment this if there are notes if not we may need to
	 * create a blank one */
	note_count = 0;

	if ((ecore_config_init("enotes")) == ECORE_CONFIG_ERR_FAIL) {
		ecore_ipc_shutdown();
		return (-1);
	}
	ecore_app_args_set(argc, (const char **) argv);

	ecore_config_app_describe("E-Notes - Sticky Notes for Enlightenment\n\
Copyright (c) Thomas Fletcher\n\
Usage: enotes [options]");

	/* Read the Usage and Configurations */
	main_config = mainconfig_new();
	if (read_configuration(main_config) != ECORE_CONFIG_PARSE_CONTINUE) {
		ecore_config_shutdown();
		ecore_ipc_shutdown();
		ecore_shutdown();
		mainconfig_free(main_config);
		return (-1);
	}

	dml("Successfully Read Configurations and Usage", 1);

	process_note_storage_locations();

	if (find_server() != 0) {
		if (remotecmd != NULL)
			send_to_server(remotecmd);
		else
			send_to_server("DEFNOTE");
	} else {
		dml("Server wasn't found.. Creating one", 1);
		/* Setup Server */
		setup_server();

		/* Initialise the E-Libs */
		ecore_init();
		ecore_x_init(NULL);
		ecore_app_args_set(argc, (const char **) argv);
		if (!ecore_evas_init()) {
			mainconfig_free(main_config);
			return -1;
		}
		ewl_init(&argc, argv);
		edje_init();

		dml("Efl Successfully Initiated", 1);

		autoload();
		/* create autosave timer */
		update_autosave();

		if (remotecmd != NULL)
			handle_ipc_message(remotecmd);

		/* Begin the Control Centre */
		if (main_config->controlcentre == 1) {
			setup_cc();
			dml("Control Centre Setup", 1);
		} else {
			dml("No Control Centre - Displaying Notice", 1);
			if (get_note_count() == 0)
				new_note();
		}

		if (main_config->welcome == 1) {
			open_welcome();
		}

		/* Begin the main loop */
		dml("Starting Main Loop", 1);
		ecore_main_loop_begin();

		dml("Main Loop Ended", 1);

		/* Save Controlcentre Settings */
		set_cc_pos();

		autosave();
		if (autosave_timer)
			ecore_timer_del(autosave_timer);

		/* Save and Free the Configuration */
		ecore_config_save();
		dml("Configuration Saved", 1);
		mainconfig_free(main_config);
		dml("Configuration Structure Free'd", 1);

		/* Shutdown the E-Libs */
		edje_shutdown();
		ecore_evas_shutdown();
		ecore_x_shutdown();
		ecore_shutdown();
		dml("Efl Shutdown", 1);
	}

	/* End IPC */
	ecore_ipc_shutdown();
	dml("IPC Shutdown", 1);

	dml("Leaving.", 1);
	return (0);
}
Esempio n. 12
0
int main( int argc, char *argv[] )
{
	int	i;
#ifdef _REENTRANT
        int     ret;
#endif
	fclose(stderr);

	Alarm_set_types( NONE ); 

	Alarmp( SPLOG_PRINT, SYSTEM, "/===========================================================================\\\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| The Spread Toolkit.                                                       |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| Copyright (c) 1993-2014 Spread Concepts LLC                               |\n"); 
	Alarmp( SPLOG_PRINT, SYSTEM, "| All rights reserved.                                                      |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| The Spread package is licensed under the Spread Open-Source License.      |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| You may only use this software in compliance with the License.            |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| A copy of the license can be found at http://www.spread.org/license       |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "| This product uses software developed by Spread Concepts LLC for use       |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "| in the Spread toolkit. For more information about Spread,                 |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "| see http://www.spread.org                                                 |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF     |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| ANY KIND, either express or implied.                                      |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| Creators:                                                                 |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|    Yair Amir             [email protected]                              |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|    Michal Miskin-Amir    [email protected]                        |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|    Jonathan Stanton      [email protected]                      |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    John Schultz          [email protected]                      |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| Contributors:                                                             |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    Amy Babay            [email protected] - accelerated ring protocol.     |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    Ryan Caudy           [email protected] - contribution to process groups.|\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    Claudiu Danilov      [email protected] - scalable, wide-area support.    |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    Cristina Nita-Rotaru [email protected] - GC security.                |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    Theo Schlossnagle    [email protected] - Perl, autoconf, old skiplist   |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|    Dan Schoenblum   [email protected] - Java Interface Developer.       |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| Special thanks to the following for discussions and ideas:                |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|    Ken Birman, Danny Dolev, Jacob Green, Mike Goodrich, Ben Laurie,       |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|    David Shaw, Gene Tsudik, Robbert VanRenesse.                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "| Partial funding provided by the Defense Advanced Research Project Agency  |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "| (DARPA) and the National Security Agency (NSA) 2000-2004. The Spread      |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "| toolkit is not necessarily endorsed by DARPA or the NSA.                  |\n");
        Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| For a full list of contributors, see Readme.txt in the distribution.      |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| WWW:     www.spread.org     www.spreadconcepts.com                        |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| Contact: [email protected]                                          |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "|                                                                           |\n");
	Alarmp( SPLOG_PRINT, SYSTEM, "| Version %d.%02d.%02d Built %-17s                                   |\n", 
		(int)SP_MAJOR_VERSION, (int)SP_MINOR_VERSION, (int)SP_PATCH_VERSION, Spread_build_date );
	Alarmp( SPLOG_PRINT, SYSTEM, "\\===========================================================================/\n");

#ifdef ARCH_PC_WIN95
        ret = WSAStartup( MAKEWORD(2,0), &WSAData );
        if( ret != 0 )
            Alarm( EXIT, "sptmonitor: main: winsock initialization error %d\n", ret );
#endif	/* ARCH_PC_WIN95 */

	Usage( argc, argv );
        
        Alarm_set_interactive();
        read_configuration();

        initialize_locks();

	for( i=0; i < Conf_num_procs( &Cn ); i++ )
		Partition[i] = 0;

	for( i=0; i < Conf_num_procs( &Cn ); i++ )
		Status_vector[i] = 0;

	Pack_scat.elements[0].len = sizeof( packet_header );
	Pack_scat.elements[0].buf = (char *)&Pack;

	Pack.proc_id = My.id;
	Pack.seq = My_port;
	Pack.memb_id.proc_id = 15051963;

	Report_scat.num_elements = 2;
	Report_scat.elements[0].buf = (char *)&Report_pack;
	Report_scat.elements[0].len = sizeof(packet_header);
	Report_scat.elements[1].buf = (char *)&GlobalStatus;
	Report_scat.elements[1].len = sizeof(status);

        SendChan = DL_init_channel( SEND_CHANNEL , My_port, 0, 0 );

        Report_socket = DL_init_channel( RECV_CHANNEL, My_port, 0, 0 );

	E_init(); /* both reentrent and non-reentrant code uses events */

#ifndef	_REENTRANT
	E_attach_fd( 0, READ_FD, User_command, 0, NULL, LOW_PRIORITY );

        E_attach_fd( Report_socket, READ_FD, Report_message, 0, NULL, HIGH_PRIORITY );
#endif	/* _REENTRANT */

        
	Print_menu();

#ifdef	_REENTRANT

#ifndef	        ARCH_PC_WIN95
	ret = pthread_create( &Read_thread, NULL, Read_thread_routine, 0 );
	ret = pthread_create( &Status_thread, NULL, Status_send_thread_routine, 0 );
	ret = pthread_create( &Partition_thread, NULL, Partition_send_thread_routine, 0 );
#else		/* ARCH_PC_WIN95 */
	Read_thread = CreateThread( NULL, 0, Read_thread_routine, NULL, 0, &ret );
	Status_thread = CreateThread( NULL, 0, Status_send_thread_routine, NULL, 0, &ret );
	Partition_thread = CreateThread( NULL, 0, Partition_send_thread_routine, NULL, 0, &ret );
#endif		/* ARCH_PC_WIN95 */

	for(;;)
	{
		User_command();
	}

#else	/*! _REENTRANT */

	E_handle_events();

#endif	/* _REENTRANT */

	return 0;
}
Esempio n. 13
0
/* Send message to all daemons to reload their configuration files to change the set of daemons */
static  void    Reload_Conf()
{
       	int32	proc_id;
	proc	p;
	int	proc_index;
	int	i,j;

	Pack.type    = RELOAD_TYPE;
	Pack.type    = Set_endian( Pack.type );
        Pack.conf_hash = MONITOR_HASH;
	Pack.data_len = 0;

	Pack_scat.num_elements    = 1;

        Alarm( PRINT, "Old configuration hash is: %u\n", Cn.hash_code);

	Alarm( PRINT  , "Monitor: send conf reload command\n");
	for( i=0; i < Cn.num_segments ; i++ )
	{
	    for( j=0; j < Cn.segments[i].num_procs; j++ )
	    {
		proc_id = Cn.segments[i].procs[j]->id;
		proc_index = Conf_proc_by_id( proc_id, &p );
		DL_send( SendChan, p.id, p.port, &Pack_scat );
	    }
	}
        /* Now reload monitor's configuration 
         * and clear all Partition, Status, FC arrays as they are now inaccurate
         */

        read_configuration();

        for( i=0; i < Conf_num_procs( &Cn ); i++ )
	{
            Partition[i] = 0;
            Work_partition[i] = 0;
            Fc_buf[i][0] = 0;
            Fc_buf[i][1] = 0;
            Work_fc_buf[i][0] = 0;
            Work_fc_buf[i][1] = 0;
            Status_vector[i] = 0;
	}
        Mutex_lock( &Partition_mutex );
        Partition_active = 0;
        Mutex_unlock( &Partition_mutex );
        
#ifndef _REENTRANT
        E_dequeue( Send_partition, 0, NULL );
#endif

        Mutex_lock( &Status_mutex );
        Status_active = 0;
        Mutex_unlock( &Status_mutex );

#ifndef _REENTRANT
	E_dequeue( Send_status_query, 0, NULL );
#endif

        Alarm( PRINT, "New configuration hash is: %u\n", Cn.hash_code);
        Alarm( PRINT, "All Status, Partition, FC, etc commands are reset by configuration reload!\n");

}
Esempio n. 14
0
File: main.c Progetto: asdr/PCA
int main ( int argc, char** argv ) {
  FILE* pipe;
  SHAREDBUFFER* shared_buffer;
  CONFIG* config;
  char main_process_lifetime[15];
  int producer_count = 0;
  char producer_lifetime[15];
  int consumer_count = 0;
  int child_exit_status = 0;
  int child_exit_pid;
  int child_pid;
  int i = 0;
  int logfd;
  char message[150];
  char dir[255];
  int available_process_count = 10000;

  strncpy(dir, argv[0], last_index_of(argv[0], '/'));
  chdir(dir);

  logfd = log_open_file( NULL );
  if ( !logfd )
    {
      printf("Unable to open log file.\n");
      return EXIT_FAILURE;
    }

  log_event( "--------------------------------" );
  log_event( "Main process started." );

  // first of all load configuration file
  config = load_config_file();

  if ( !config )
    {
      log_event( "Unable to access configuration." );
      return EXIT_FAILURE;
    }

  // read values from configuration
  producer_count = atoi(read_configuration(config, "producer_count", "5"));
  consumer_count = atoi(read_configuration(config, "consumer_count", "2"));
  strcpy(producer_lifetime, read_configuration(config, "producer_lifetime", "10"));
  strcpy(main_process_lifetime, read_configuration(config, "main_process_lifetime", "40"));

  destroy_config( config );

  log_event( "Fetching available process count of system." );
  pipe = popen(PROCESS_COUNT_SCRIPT, "r");
  if ( pipe )
    {
      fgets(message, 100, pipe);
      pclose(pipe);
      available_process_count = atoi(message);
    }

  if ( producer_count + consumer_count + 1 > available_process_count )
    {
      log_event( "Requested total process count is more than available process count of system." );
      goto SAFE_EXIT;
    }

  //initialize shared buffer
  shared_buffer = create_shared_buffer();

  if ( !shared_buffer )
    {
      log_event( "Unable to initialize shared buffer." );
      destroy_config( config );
      return EXIT_FAILURE;
    }

  // create and start producer processes
  // producer processes run for a specified lifetime ( in seconds )
  // which is read from configuration
  for ( i=0; i<producer_count; ++i)
    {
      child_pid = vfork();
      if ( child_pid == 0 ) // producer process
        {
          execl("producer", "producer", producer_lifetime, NULL);
          exit(0);
        }
    }

  // start consumer processes
  // consumer processes run until a SIGKILL signal
  // there is no specific entry in the requirements that
  // when a consumer process should end.
  for ( i=0; i<consumer_count; ++i)
    {
      child_pid = vfork();
      if ( child_pid == 0 ) // consumer process
        {
          execl("consumer", "consumer", NULL);
          exit(0);
        }
    }

  // start controller process
  // controller process checks elapsed time
  // once in every 5 seconds
  // if total execution time is above a specified time (in seconds)
  // signals all child processes except itself, to force exit
  child_pid = vfork();
  if ( child_pid == 0 ) //controller process
    {
      execl("controller", "controller", main_process_lifetime, NULL);
      exit(0);
    }

  // in order to catch all child processes exits
  // we need a common wait for all them
  // here exitting processes is cought with pid and exit status
  // wait childs to exit
  while( (child_exit_pid = wait(&child_exit_status)) > 0 )
    {
      sprintf( message, "Process [PID:%d] exitid with status: %d", child_exit_pid, child_exit_status );
      log_event( message );
    }

 SAFE_EXIT:
  log_event( "Main process is being closed." );

  // relase allocated data structures to OS
  destroy_shared_buffer( shared_buffer );

  log_close_file(  );

  return EXIT_SUCCESS;
}
// Constructor. Parent is the wizard page
proxy_wizardpage::proxy_wizardpage( wxWizard *parent,
                                    wxBitmap bitmap )
       : wxWizardPageSimple( parent )
{
    wxLogDebug( wxT( "Entering proxy_wizardpage constructor") );
    
    // To set a custom bitmap in a derived wxWizardPageSimple, you just have to 
    // set the wxWizardPageSimple m_bitmap member in the derived constructor.
    // ( see wx examples ). .
    m_bitmap = bitmap;
    
    wxFlexGridSizer *root_flexgridsizer = new wxFlexGridSizer( 1, 0, 0 );
    root_flexgridsizer->AddGrowableCol( 0 );
    root_flexgridsizer->AddGrowableRow( 1 );

    wxStaticBox *enable_staticbox = new wxStaticBox( this, -1, _("Enable proxy") );
    wxStaticBoxSizer *enable_staticboxsizer = new wxStaticBoxSizer( enable_staticbox, wxVERTICAL );

    // This control needs an ID number, so that update events only get processed if
    // it is this checkbox that calls it, instead of all of them calling the update handler.
    m_use_proxy_checkbox = new wxCheckBox( this, ID_USE_PROXY_CHECKBOX, _("This computer uses a proxy to access the Internet"), wxDefaultPosition, wxDefaultSize, 0 );
    enable_staticboxsizer->Add( m_use_proxy_checkbox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxStaticText *unsure_statictext = new wxStaticText( this, -1, _( "(If you are not sure whether or not you have a proxy, then just click 'Next')" ) );
    enable_staticboxsizer->Add( unsure_statictext, 0, wxALIGN_CENTRE|wxALL, 5 );

    root_flexgridsizer->Add( enable_staticboxsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL, 5 );

    wxStaticBox *settings_staticbox = new wxStaticBox( this, -1, _( "Proxy settings" ) );
    wxStaticBoxSizer *settings_staticboxsizer = new wxStaticBoxSizer( settings_staticbox, wxVERTICAL );

    wxFlexGridSizer *settings_flexgridsizer = new wxFlexGridSizer( 2, 0, 0 );

    wxStaticText *proxy_server_statictext = new wxStaticText( this, -1, _( "Proxy server:" ) );
    settings_flexgridsizer->Add( proxy_server_statictext, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    m_proxy_server_textctrl = new wxTextCtrl( this, -1, wxT( ""), wxDefaultPosition, wxSize(290,-1), 0 );
    settings_flexgridsizer->Add( m_proxy_server_textctrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxStaticText *proxy_port_statictext = new wxStaticText( this, -1, _( "Port:" ) );
    settings_flexgridsizer->Add( proxy_port_statictext, 0, wxALIGN_RIGHT|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    m_proxy_port_textctrl = new wxTextCtrl( this, -1, wxT( ""), wxDefaultPosition, wxSize(50,-1), 0 );
    settings_flexgridsizer->Add( m_proxy_port_textctrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxStaticText *proxy_login_statictext = new wxStaticText( this, -1, _( "Proxy login:"******""), wxDefaultPosition, wxSize(150,-1), wxTE_PASSWORD );
    settings_flexgridsizer->Add( m_proxy_login_textctrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxStaticText *proxy_password_statictext = new wxStaticText( this, -1, _( "Proxy password:"******""), wxDefaultPosition, wxSize(150,-1), wxTE_PASSWORD );
    settings_flexgridsizer->Add( m_proxy_password_textctrl, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    settings_staticboxsizer->Add( settings_flexgridsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL, 0 );

    m_proxy_password_prompt_checkbox = new wxCheckBox( this, ID_PROXY_PASSWORD_PROMPT_CHECKBOX, _( "Prompt for proxy password each time (more secure)" ) );
    settings_staticboxsizer->Add( m_proxy_password_prompt_checkbox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    root_flexgridsizer->Add( settings_staticboxsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxTOP, 5 );

    // Now that everything is added into the flexgrid sizer, send some commands to
    // tell it calculate all the control sizes nicely to fill up the available space.
    SetAutoLayout( TRUE );
    SetSizer( root_flexgridsizer );
    root_flexgridsizer->Fit( this );
    root_flexgridsizer->SetSizeHints( this );         
 
    // Set up the initial values
    read_configuration();
 }
Esempio n. 16
0
void in_received_handler(DictionaryIterator *received, void *context)
{
  APP_LOG(APP_LOG_LEVEL_DEBUG, "in_received_handler");
  
  Tuple *hh_in_bold_tuple = dict_find(received, MESSAGE_KEY_HH_IN_BOLD);
  if (hh_in_bold_tuple)
  {
    app_log(APP_LOG_LEVEL_DEBUG,
            __FILE__,
            __LINE__,
            "hh_in_bold=%s",
            hh_in_bold_tuple->value->cstring);

    if (strcmp(hh_in_bold_tuple->value->cstring, "0") == 0)
    {
      persist_write_bool(MESSAGE_KEY_HH_IN_BOLD, false);
    }
    else
    {
      persist_write_bool(MESSAGE_KEY_HH_IN_BOLD, true);
    }
  }

  Tuple *mm_in_bold_tuple = dict_find(received, MESSAGE_KEY_MM_IN_BOLD);
  if (mm_in_bold_tuple)
  {
    app_log(APP_LOG_LEVEL_DEBUG,
            __FILE__,
            __LINE__,
            "mm_in_bold=%s",
            mm_in_bold_tuple->value->cstring);

    if (strcmp(mm_in_bold_tuple->value->cstring, "1") == 0)
    {
      persist_write_bool(MESSAGE_KEY_MM_IN_BOLD, true);
    }
    else
    {
      persist_write_bool(MESSAGE_KEY_MM_IN_BOLD, false);
    }
  }
  
  Tuple *locale_tuple = dict_find(received, MESSAGE_KEY_LOCALE);
  if (locale_tuple)
  {
    app_log(APP_LOG_LEVEL_DEBUG,
            __FILE__,
            __LINE__,
            "locale=%s",
            locale_tuple->value->cstring);

    if (strcmp(locale_tuple->value->cstring, "default") == 0)
    {
      if (persist_exists(MESSAGE_KEY_LOCALE)) 
      {
        persist_delete(MESSAGE_KEY_LOCALE);
      }
    }
    else if (strcmp(locale_tuple->value->cstring, "fr") == 0)
    {
      persist_write_int(MESSAGE_KEY_LOCALE, locale_fr);
    }
    else if (strcmp(locale_tuple->value->cstring, "de") == 0)
    {
      persist_write_int(MESSAGE_KEY_LOCALE, locale_de);
    }
    else if (strcmp(locale_tuple->value->cstring, "es") == 0)
    {
      persist_write_int(MESSAGE_KEY_LOCALE, locale_es);
    }
    else if (strcmp(locale_tuple->value->cstring, "it") == 0)
    {
      persist_write_int(MESSAGE_KEY_LOCALE, locale_it);
    }
    else
    {
      persist_write_int(MESSAGE_KEY_LOCALE, locale_en);
    }
  }
  
  Tuple *hh_strip_zero_tuple = dict_find(received, MESSAGE_KEY_HH_STRIP_ZERO);
  if (hh_strip_zero_tuple)
  {
    app_log(APP_LOG_LEVEL_DEBUG,
            __FILE__,
            __LINE__,
            "hh_strip_zero=%s",
            hh_strip_zero_tuple->value->cstring);

    if (strcmp(hh_strip_zero_tuple->value->cstring, "0") == 0)
    {
      persist_write_bool(MESSAGE_KEY_HH_STRIP_ZERO, false);
    }
    else
    {
      persist_write_bool(MESSAGE_KEY_HH_STRIP_ZERO, true);
    }
  }
  
  Tuple *time_sep_tuple = dict_find(received, MESSAGE_KEY_TIME_SEP);
  if (time_sep_tuple)
  {
    app_log(APP_LOG_LEVEL_DEBUG,
            __FILE__,
            __LINE__,
            "time_sep=%s",
            time_sep_tuple->value->cstring);

    if (strcmp(time_sep_tuple->value->cstring, "square") == 0)
    {
      persist_write_int(MESSAGE_KEY_TIME_SEP, time_sep_square);
    }
    else if (strcmp(time_sep_tuple->value->cstring, "round") == 0)
    {
      persist_write_int(MESSAGE_KEY_TIME_SEP, time_sep_round);
    }
    else if (strcmp(time_sep_tuple->value->cstring, "squareb") == 0)
    {
      persist_write_int(MESSAGE_KEY_TIME_SEP, time_sep_square_bold);
    }
    else if (strcmp(time_sep_tuple->value->cstring, "roundb") == 0)
    {
      persist_write_int(MESSAGE_KEY_TIME_SEP, time_sep_round_bold);
    }
    else
    {
      persist_write_int(MESSAGE_KEY_TIME_SEP, time_sep_none);
    }
  }
  
  Tuple *repeat_vib_tuple = dict_find(received, MESSAGE_KEY_REPEAT_VIB);
  if (repeat_vib_tuple)
  {
    app_log(APP_LOG_LEVEL_DEBUG,
            __FILE__,
            __LINE__,
            "repeat_vib=%s",
            repeat_vib_tuple->value->cstring);

    if (strcmp(repeat_vib_tuple->value->cstring, "1") == 0)
    {
      persist_write_bool(MESSAGE_KEY_REPEAT_VIB, true);
    }
    else
    {
      persist_write_bool(MESSAGE_KEY_REPEAT_VIB, false);
    }
  }  

  read_configuration();
  update_display();
}
Esempio n. 17
0
/*
 * main application method
 */
int main(int argc, char** argv)
{
	// catch process signals
	ibrcommon::SignalHandler sighandler(term);
	sighandler.handle(SIGINT);
	sighandler.handle(SIGTERM);

	// read the configuration
	read_configuration(argc, argv);

	//initialize sighandler after possible exit call
	sighandler.initialize();

	if (_conf_workdir.length() > 0)
	{
		ibrcommon::File blob_path(_conf_workdir);

		if (blob_path.exists())
		{
			ibrcommon::BLOB::changeProvider(new ibrcommon::FileBLOBProvider(blob_path), true);
		}
	}

	// backoff for reconnect
	unsigned int backoff = 2;

	// loop, if no stop if requested
	while (_running)
	{
		try {
			// Create a stream to the server using TCP.
			ibrcommon::vaddress addr("localhost", 4550);
			ibrcommon::socketstream conn(new ibrcommon::tcpsocket(addr));

			// set the connection globally
			_conn = &conn;

			// Initiate a client for synchronous receiving
			dtn::api::Client client(_conf_name, conn);

			// Connect to the server. Actually, this function initiate the
			// stream protocol by starting the thread and sending the contact header.
			client.connect();

			// reset backoff if connected
			backoff = 2;

			// check the connection
			while (_running)
			{
				// receive the bundle
				dtn::data::Bundle b = client.getBundle();
				if(!_conf_quiet)
					std::cout << "received bundle: " << b.toString() << std::endl;

				// get the reference to the blob
				ibrcommon::BLOB::Reference ref = b.find<dtn::data::PayloadBlock>().getBLOB();

				// write files into BLOB while it is locked
				{
					ibrcommon::BLOB::iostream stream = ref.iostream();
					io::TarUtils::read(_conf_inbox, *stream);
				}
			}

			// close the client connection
			client.close();

			// close the connection
			conn.close();

			// set the global connection to NULL
			_conn = NULL;
		} catch (const ibrcommon::socket_exception&) {
			// set the global connection to NULL
			_conn = NULL;

			if (_running)
			{
				std::cout << "Connection to bundle daemon failed. Retry in " << backoff << " seconds." << std::endl;
				ibrcommon::Thread::sleep(backoff * 1000);

				// if backoff < 10 minutes
				if (backoff < 600)
				{
					// set a new backoff
					backoff = backoff * 2;
				}
			}
		} catch (const ibrcommon::IOException&) {
			// set the global connection to NULL
			_conn = NULL;

			if (_running)
			{
				std::cout << "Connection to bundle daemon failed. Retry in " << backoff << " seconds." << std::endl;
				ibrcommon::Thread::sleep(backoff * 1000);

				// if backoff < 10 minutes
				if (backoff < 600)
				{
					// set a new backoff
					backoff = backoff * 2;
				}
			}
		} catch (const std::exception&) {
			// set the global connection to NULL
			_conn = NULL;
		}
	}

	return (EXIT_SUCCESS);
}
Esempio n. 18
0
int
main(int argc, const char *argv[])
{
#ifndef WIN32
	struct sigaction act;
#endif
#ifdef ENABLE_LOCALE
#ifndef ENABLE_NLS
	G_GNUC_UNUSED
#endif
	const char *charset = NULL;
#endif
	GIOChannel *keyboard_channel;
#ifdef ENABLE_LIRC
	int lirc_socket;
	GIOChannel *lirc_channel = NULL;
#endif
	GIOChannel *sigwinch_channel = NULL;

#ifdef ENABLE_LOCALE
	/* time and date formatting */
	setlocale(LC_TIME,"");
	/* care about sorting order etc */
	setlocale(LC_COLLATE,"");
	/* charset */
	setlocale(LC_CTYPE,"");
	/* initialize charset conversions */
	charset = charset_init();

	/* initialize i18n support */
#endif

#ifdef ENABLE_NLS
	setlocale(LC_MESSAGES, "");
	bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
#ifdef ENABLE_LOCALE
	bind_textdomain_codeset(GETTEXT_PACKAGE, charset);
#endif
	textdomain(GETTEXT_PACKAGE);
#endif

	/* initialize options */
	options_init();

	/* parse command line options - 1 pass get configuration files */
	options_parse(argc, argv);

#ifndef NCMPC_MINI
	/* read configuration */
	read_configuration();

	/* check key bindings */
	check_key_bindings(NULL, NULL, 0);
#endif

	/* parse command line options - 2 pass */
	options_parse(argc, argv);

#ifndef WIN32
	/* setup signal behavior - SIGINT */
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	act.sa_handler = catch_sigint;
	if (sigaction(SIGINT, &act, NULL) < 0) {
		perror("signal");
		exit(EXIT_FAILURE);
	}

	/* setup signal behavior - SIGTERM */

	act.sa_handler = catch_sigint;
	if (sigaction(SIGTERM, &act, NULL) < 0) {
		perror("sigaction()");
		exit(EXIT_FAILURE);
	}

	/* setup signal behavior - SIGCONT */

	act.sa_handler = catch_sigcont;
	if (sigaction(SIGCONT, &act, NULL) < 0) {
		perror("sigaction(SIGCONT)");
		exit(EXIT_FAILURE);
	}

	/* setup signal behaviour - SIGHUP*/

	act.sa_handler = catch_sigint;
	if (sigaction(SIGHUP, &act, NULL) < 0) {
		perror("sigaction(SIGHUP)");
		exit(EXIT_FAILURE);
	}

	/* setup SIGWINCH */

	act.sa_flags = SA_RESTART;
	act.sa_handler = catch_sigwinch;
	if (sigaction(SIGWINCH, &act, NULL) < 0) {
		perror("sigaction(SIGWINCH)");
		exit(EXIT_FAILURE);
	}

	/* ignore SIGPIPE */

	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, NULL) < 0) {
		perror("sigaction(SIGPIPE)");
		exit(EXIT_FAILURE);
	}
#endif

	ncu_init();

#ifdef ENABLE_LYRICS_SCREEN
	lyrics_init();
#endif

	/* create mpdclient instance */
	mpd = mpdclient_new();

	/* initialize curses */
	screen_init(mpd);

	/* the main loop */
	main_loop = g_main_loop_new(NULL, FALSE);

	/* watch out for keyboard input */
	keyboard_channel = g_io_channel_unix_new(STDIN_FILENO);
	g_io_add_watch(keyboard_channel, G_IO_IN, keyboard_event, NULL);

#ifdef ENABLE_LIRC
	/* watch out for lirc input */
	lirc_socket = ncmpc_lirc_open();
	if (lirc_socket >= 0) {
		lirc_channel = g_io_channel_unix_new(lirc_socket);
		g_io_add_watch(lirc_channel, G_IO_IN, lirc_event, NULL);
	}
#endif

#ifndef WIN32
	if (!pipe(sigwinch_pipes) &&
		!fcntl(sigwinch_pipes[1], F_SETFL, O_NONBLOCK)) {
		sigwinch_channel = g_io_channel_unix_new(sigwinch_pipes[0]);
		g_io_add_watch(sigwinch_channel, G_IO_IN, sigwinch_event, NULL);
	}
	else {
		perror("sigwinch pipe creation failed");
		exit(EXIT_FAILURE);
	}
#endif

	/* attempt to connect */
	reconnect_source_id = g_timeout_add(1, timer_reconnect, NULL);

	auto_update_timer();

#ifndef NCMPC_MINI
	check_key_bindings_source_id = g_timeout_add(10000, timer_check_key_bindings, NULL);
#endif

	screen_paint(mpd);

	g_main_loop_run(main_loop);

	/* cleanup */

	cancel_seek_timer();

	disable_update_timer();

	if (reconnect_source_id != 0)
		g_source_remove(reconnect_source_id);

#ifndef NCMPC_MINI
	if (check_key_bindings_source_id != 0)
		g_source_remove(check_key_bindings_source_id);
#endif

	g_main_loop_unref(main_loop);
	g_io_channel_unref(keyboard_channel);
	g_io_channel_unref(sigwinch_channel);
	close(sigwinch_pipes[0]);
	close(sigwinch_pipes[1]);

#ifdef ENABLE_LIRC
	if (lirc_socket >= 0)
		g_io_channel_unref(lirc_channel);
	ncmpc_lirc_close();
#endif

	exit_and_cleanup();

#ifdef ENABLE_LYRICS_SCREEN
	lyrics_deinit();
#endif

	ncu_deinit();
	options_deinit();

	return 0;
}
Esempio n. 19
0
int main(int argc, char * argv[])
{
	server_configuration config;
	bzero(&config, sizeof(config));

	if(!network_subsystem_init())
	{
		fprintf(stderr, "Network subsystem init failed.\n");
		return error_network_subsystem;
	}

	if(!read_configuration(argc, argv, &config))
	{
		fprintf(stderr, PROG_NAME ": configuration error! Exit.\n");
		return error_config;
	}

	if(config.discover)
		interfaces_discover(0);

	if(config.print_header_offsets)
	{
		print_dhcp_header_offsets();
		return 0;
	}

	if(!log_init(config.log_file_name,
			(config.debug_mode ? LOG_DEBUG_FLAG : 0) |
			(config.log_stdout ? LOG_STDOUT_FLAG : 0),
			config.uid)
		)
	{
		fprintf(stderr, "Can't open log file.\n");
		return error_log;
	}

	log_wr(ILOG, "Program " PROG_NAME " " PROG_VERS " " PROG_DESC " started.");

	struct sigaction sig_handler_s;
	sig_handler_s.sa_handler = sig_handler;
	sigemptyset(&sig_handler_s.sa_mask);
	sig_handler_s.sa_flags = 0;

	if(config.daemon)
		daemonize();

	/* Init DHCP cache */
	if(config.cache_ttl && !dhcp_cache_init(config.cache_ttl))
	{
		log_wr(CLOG, "Can't init DHCP cache. Exit.");
		return error_abnormal;
	}

	/* STARTING DATABASE CLIENTS */

	/* Create array of childen threads */
	request_handler_thread_t **handler_threads =
		(request_handler_thread_t **) malloc(sizeof(request_handler_thread_t *) * config.db_clients_count);

	CHECK_VALUE(handler_threads, "Can't allocate memory for array of children threads for connecting to DB.",
		error_memory);

	/* Create DHCP messages queue */
	config.dhcp_queue = dhcp_queue_create("DHCP requests", YES, DEFAULT_QUEUE_MAX_SIZE);
	CHECK_VALUE(config.dhcp_queue, "Can't create DHCP queue.", error_queue_init);

	/* Running DB clients */
	CHECK_VALUE(run_requests_handlers(handler_threads, &config), "", error_run_db_clients);

	/* STARTING DHCP PROCESSES  */
	dhcp_proc_thread_t **dhcp_threads =
		(dhcp_proc_thread_t**) malloc(sizeof(dhcp_proc_thread_t *) * config.if_count);

	CHECK_VALUE(dhcp_threads, "Can't allocate memory for array of children threads for "
			"processing DHCP clients.", error_run_dhcp_procs);

	CHECK_VALUE(run_dhcp_threads(dhcp_threads, &config, handler_threads), "", error_run_dhcp_procs);

	/* Set signal handlers */
    if( sigaction(SIGINT, &sig_handler_s, NULL) ||
        sigaction(SIGTERM, &sig_handler_s, NULL) ||
        sigaction(SIGUSR1, &sig_handler_s, NULL))
    {
		log_wr(CLOG, "Can't set signal handlers: '%s'", strerror(errno));
        return error_abnormal;
    }

#ifndef _WIN32
	if(config.uid)
	{
		log_wr(DLOG, "Set effective and real user ID to %u.", config.uid);
		if(setreuid(config.uid, config.uid))
		{
			log_wr(CLOG, "Can't execute setreuid(%u): '%s'", config.uid, strerror(errno));
			return 0;
		}
	}
	else
		log_wr(WLOG, "Running with uid 0 - it is not safe!!! Use configuration directive 'User' for set uid.");
#endif

	int i;
	for(i = 0; i < config.if_count; ++i)
		pthread_join(dhcp_threads[i]->thread_id, 0);

	log_wr(ILOG, "All DHCP threads finished");

	for(i = 0; i < config.db_clients_count; ++i)
		pthread_join(handler_threads[i]->thread_id, 0);

	log_wr(ILOG, "All DB threads finished.");

	/* Cleaning up */
	/* TODO 30 Need gracefull cleanup database connections and free all allocated memory */
	log_wr(ILOG, "Program exited.");
	log_close();

	return EXIT_SUCCESS;
}
Esempio n. 20
0
int main(int argc, char *argv[])
{
	char *configuration = NULL;
	char *infile = NULL;
	char *outfile = NULL;
	char *verbose = NULL;
	int version_opt = 0;
	char *logdir = NULL;
	char *logfile = NULL;
	char *home = NULL;
	int help_opt = 0;

	int c;
	
	static struct option long_options[] = {
		{"configuration",	required_argument, 0, 'c'},
		{"silent", no_argument, 0, 1},
		{"verbose", no_argument, 0, 'v'},
		{"version", no_argument, 0, 'V'},
		{"logdir", required_argument, 0, 'l'},
		{"logfile", required_argument, 0, 'L'},
		{"home", required_argument, 0, 2},
		{"infile", required_argument, 0, 'i'},
		{"outfile", required_argument, 0, 'o'},
		{"help", no_argument, 0, 'h'},
		{0, 0, 0, 0}
	};

#ifdef XCP	
	int is_bash_exist = system("command -v bash");

	if ( is_bash_exist != 0 )
	{
		fprintf(stderr, "Cannot find bash. Please ensure that bash is "
				"installed and available in the PATH\n");
		exit(2);
	}
#endif

	strcpy(progname, argv[0]);
	init_var_hash();

	while(1) {
		int option_index = 0;

		c = getopt_long(argc, argv, "i:o:c:vVl:L:h", long_options, &option_index);

		if (c == -1)
			break;
		switch(c)
		{
			case 1:
				verbose = "n";
				break;
			case 2:
				if (home)
					free (home);
				home = strdup(optarg);
				break;
			case 'i':
				if (infile)
					free(infile);
				infile = strdup(optarg);
				break;
			case 'o':
				if (outfile)
					free(outfile);
				outfile = strdup(optarg);
				break;
			case 'v':
				verbose = "y";
				break;
			case 'V':
				version_opt = 1;
				break;
			case 'l':
				if (logdir)
					free(logdir);
				logdir = strdup(optarg);
				break;
			case 'L':
				if (logfile)
					free(logfile);
				logfile = strdup(optarg);
				break;
			case 'c':
				if (configuration)
					free(configuration);
				configuration = strdup(optarg);
				break;
			case 'h':
				help_opt = 1;
				break;
			default:
				fprintf(stderr, "Invalid optin value, received code 0%o\n", c);
				exit(1);
		}
	}
	if (version_opt || help_opt)
	{
		if (version_opt)
			print_version();
		if (help_opt)
			print_help();
		exit(0);
	}
	setup_my_env();		/* Read $HOME/.pgxc_ctl */
	build_pgxc_ctl_home(home);
	if (infile)
		reset_var_val(VAR_configFile, infile);
	if (logdir)
		reset_var_val(VAR_logDir, logdir);
	if (logfile)
		reset_var_val(VAR_logFile, logfile);
	startLog(sval(VAR_logDir), sval(VAR_logFile));
	prepare_pgxc_ctl_bash(pgxc_ctl_bash_path);
	build_configuration_path(configuration);
	read_configuration();
	check_configuration();
	/*
	 * Setop output
	 */
	if (outfile)
	{
		elog(INFO, "Output file: %s\n", outfile);
		if ((outF = fopen(outfile, "w")))
			dup2(fileno(outF),2);
		else
			elog(ERROR, "ERROR: Cannot open output file %s, %s\n", outfile, strerror(errno));
	}
	else
		outF = stdout;
	/* 
	 * Startup Message
	 */
	elog(NOTICE, "   ******** PGXC_CTL START ***************\n\n");
	elog(NOTICE, "Current directory: %s\n", pgxc_ctl_home);
	/*
	 * Setup input
	 */
	if (infile)
	{
		elog(INFO, "Input file: %s\n", infile);
		inF =  fopen(infile, "r");
		if(inF == NULL)
		{
			elog(ERROR, "ERROR: Cannot open input file %s, %s\n", infile, strerror(errno));
			exit(1);
		}
	}
	else
		inF = stdin;
	/*
	 * If we have remaing arguments, they will be treated as a command to do.  Do this
	 * first, then handle the input from input file specified by -i option.
	 * If it is not found, then exit.
	 */
#if 0
	print_vars();
#endif
	if (optind < argc)
	{
		char orgBuf[MAXLINE + 1];
		char wkBuf[MAXLINE + 1];
		orgBuf[0] = 0;
		while (optind < argc)
		{
			strncat(orgBuf, argv[optind++], MAXLINE);
			strncat(orgBuf, " ", MAXLINE);
		}
		strncpy(wkBuf, orgBuf, MAXLINE);
		do_singleLine(orgBuf, wkBuf);
		if (infile)
			do_command(inF, outF);
	}
	else
		do_command(inF, outF);
	exit(0);
}
Esempio n. 21
0
static void
handle_option(int c, const char *arg)
{
	switch (c) {
	case '?': /* --help */
		display_help();
		exit(EXIT_SUCCESS);
	case 'V': /* --version */
		puts(PACKAGE " version: " VERSION "\n"
		     "build options:"
#ifdef NCMPC_MINI
		     " mini"
#endif
#ifndef NDEBUG
		     " debug"
#endif
#ifdef ENABLE_MULTIBYTE
		     " multibyte"
#endif
#ifdef HAVE_CURSES_ENHANCED
		     " wide"
#endif
#ifdef ENABLE_LOCALE
		     " locale"
#endif
#ifdef ENABLE_NLS
		     " nls"
#endif
#ifdef ENABLE_COLORS
		     " colors"
#else
		     " no-colors"
#endif
#ifdef ENABLE_LIRC
		     " lirc"
#endif
#ifdef HAVE_GETMOUSE
		     " getmouse"
#endif
#ifdef ENABLE_ARTIST_SCREEN
		     " artist-screen"
#endif
#ifdef ENABLE_HELP_SCREEN
		     " help-screen"
#endif
#ifdef ENABLE_SEARCH_SCREEN
		     " search-screen"
#endif
#ifdef ENABLE_SONG_SCREEN
		     " song-screen"
#endif
#ifdef ENABLE_KEYDEF_SCREEN
		     " key-screen"
#endif
#ifdef ENABLE_LYRICS_SCREEN
		     " lyrics-screen"
#endif
#ifdef ENABLE_OUTPUTS_SCREEN
		     " outputs-screen"
#endif

		     "\n");
#ifndef NCMPC_MINI
		{
			char *user_conf = build_user_conf_filename();
			char *system_conf = build_system_conf_filename();

			printf("configuration files:\n %s\n %s\n\n",
			       user_conf, system_conf);

			g_free(user_conf);
			g_free(system_conf);
		}
		if (strcmp("translator-credits", _("translator-credits")) != 0)
			/* To translators: these credits are shown
			   when ncmpc is started with "--version" */
			printf("\n%s\n", _("translator-credits"));
#endif
		exit(EXIT_SUCCESS);
	case 'c': /* --colors */
#ifdef ENABLE_COLORS
		options.enable_colors = true;
#endif
		break;
	case 'C': /* --no-colors */
#ifdef ENABLE_COLORS
		options.enable_colors = false;
#endif
		break;
	case 'm': /* --mouse */
#ifdef HAVE_GETMOUSE
		options.enable_mouse = true;
#endif
		break;
	case 'M': /* --no-mouse */
#ifdef HAVE_GETMOUSE
		options.enable_mouse = false;
#endif
		break;
	case 'e': /* --exit */
		/* deprecated */
		break;
	case 'p': /* --port */
		options.port = atoi(arg);
		break;
	case 'h': /* --host */
		g_free(options.host);
		options.host = g_strdup(arg);
		break;
	case 'P': /* --password */
		g_free(options.password);
		options.password = locale_to_utf8(arg);
		break;
	case 'f': /* --config */
		g_free(options.config_file);
		options.config_file = g_strdup(arg);
		break;
	case 'k': /* --key-file */
		g_free(options.key_file);
		options.key_file = g_strdup(arg);
		break;
#if !defined(NDEBUG) && !defined(NCMPC_MINI)
	case 'K': /* --dump-keys */
		read_configuration();
		write_key_bindings(stdout, KEYDEF_WRITE_ALL | KEYDEF_COMMENT_ALL);
		exit(EXIT_SUCCESS);
		break;
#endif
	default:
		fprintf(stderr,"Unknown Option %c = %s\n", c, arg);
		break;
	}
}
limits_wizardpage::limits_wizardpage( wxWizard *parent, const wxString& channel_section,
                                      wxBitmap bitmap )
       : wxWizardPageSimple( parent )
{
    wxLogDebug( "Entering limits_wizardpage constructor" );
 
    // To set a custom bitmap in a derived wxWizardPageSimple, you just have to 
    // set the wxWizardPageSimple m_bitmap member in the derived constructor.
    // ( see wx examples ). .
    m_bitmap = bitmap;  

    wxFlexGridSizer *root_flexgridsizer = new wxFlexGridSizer( 1, 0, 0 );
    root_flexgridsizer->AddGrowableCol( 0 );
    root_flexgridsizer->AddGrowableRow( 4 );

    // Add a Insruction message and add to boxsizer
    wxStaticText *maxdepth_instructions_statictext = new wxStaticText( this, -1,
        _( "Enter the depth of pages that you want to retrieve (1=retrieve starting page only):" ) );
    root_flexgridsizer->Add( maxdepth_instructions_statictext, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );

    // Add the maxdepth controls
    wxStaticBox *maxdepth_staticbox = new wxStaticBox( this, -1, _( "Maximum depth" ) );
    wxStaticBoxSizer *maxdepth_staticboxsizer = new wxStaticBoxSizer( maxdepth_staticbox, wxHORIZONTAL );

    wxStaticText *maxdepth1_statictext = new wxStaticText( this, -1, 
        _( "Retreive linked pages to a depth of" ) );
    maxdepth_staticboxsizer->Add( maxdepth1_statictext, 0, wxALIGN_CENTRE|wxALL, 5 );

    m_maxdepth_spinctrl = new wxSpinCtrl( this, -1, "2", wxDefaultPosition, wxSize(70,-1), 0, 1, 100000, 2 );
    maxdepth_staticboxsizer->Add( m_maxdepth_spinctrl, 0, wxALIGN_CENTRE|wxALL, 5 );

    wxStaticText *maxdepth2_statictext = new wxStaticText( this, -1, 
        _( "from the starting page" ) );
    maxdepth_staticboxsizer->Add( maxdepth2_statictext, 0, wxALIGN_CENTRE|wxALL, 5 );

    root_flexgridsizer->Add( maxdepth_staticboxsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 0 );

    // Add a spacer
    root_flexgridsizer->Add( 20, 10, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT, 0 );

    // Add the stayonhost/stayondomain controls
    wxStaticText *stayonhost_stayondomain_instructions = new wxStaticText( this, -1,
        _( "Enter whether you want to exclude linked pages that are not on the server:" ) );
    root_flexgridsizer->Add( stayonhost_stayondomain_instructions, 0, 
                             wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM, 5 );

    wxStaticBox *stayonhost_stayondomain_staticbox = new wxStaticBox( this, -1, 
        _( "'Stay on host' / 'Stay on domain' filters" ) );
    wxStaticBoxSizer *stayonhost_stayondomain_staticboxsizer = new wxStaticBoxSizer( stayonhost_stayondomain_staticbox, wxVERTICAL );

    m_stayonhost_stayondomain_checkbox = new wxCheckBox( this, ID_LIMITS_WIZARDPAGE_STAYONHOST_STAYONDOMAIN_CHECKBOX,
        _( "Ignore links to a server that is different from starting page's server" ) );
    stayonhost_stayondomain_staticboxsizer->Add( m_stayonhost_stayondomain_checkbox, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxBoxSizer *stayonhost_boxsizer = new wxBoxSizer( wxHORIZONTAL );

    stayonhost_boxsizer->Add( 10, 10, 0, wxALIGN_CENTRE|wxALL, 5 );

    m_stayonhost_radiobutton = new wxRadioButton( this, -1,
        _( "Limit to the exact server only" ),
        wxDefaultPosition, wxDefaultSize, wxRB_GROUP );
    stayonhost_boxsizer->Add( m_stayonhost_radiobutton, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT|wxBOTTOM, 5 );

    stayonhost_stayondomain_staticboxsizer->Add( stayonhost_boxsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL, 5 );

    wxBoxSizer *stayondomain_boxsizer = new wxBoxSizer( wxHORIZONTAL );

    stayondomain_boxsizer->Add( 10, 10, 0, wxALIGN_CENTRE|wxALL, 5 );

    m_stayondomain_radiobutton = new wxRadioButton( this, -1,
        _( "Only restrict to domain (eg allow www.plkr.org and www2.plkr.org)" ) );
    stayondomain_boxsizer->Add( m_stayondomain_radiobutton, 0, wxALIGN_CENTRE|wxLEFT|wxRIGHT, 5 );

    stayonhost_stayondomain_staticboxsizer->Add( stayondomain_boxsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL, 5 );

    // Add the stayonhost/stayondomain controls to root boxizer
    root_flexgridsizer->Add( stayonhost_stayondomain_staticboxsizer, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 0 );
  
    // Set the default values
    read_configuration( channel_section );
  
    // Now that everything is added into the boxsizer, send some commands to 
    // tell it calculate all the control sizes nicely to fill up the available space.
    SetAutoLayout( TRUE );
    SetSizer( root_flexgridsizer );
    root_flexgridsizer->Fit( this );
    root_flexgridsizer->SetSizeHints( this );                
 }
int main( int argc, char *argv[] ) {

  char sectype_code = '_';
  MarFS_SecType marfs_sectype;
  char compType_code = '_';
  MarFS_CompType marfs_comptype;
  char comptype_code = '_';
  MarFS_CorrectType marfs_correcttype;
  char code;
  int ret_val;
  MarFS_Namespace_Ptr namespacePtr;
  MarFS_Repo_Ptr repoPtr;


  INIT_LOG();
  fprintf( stdout, "\n" );

  if (read_configuration()) {
    fprintf( stderr, "ERROR: Reading MarFS configuration failed.\n" );
    return 1;
  }
  fprintf( stdout, "CORRECT: The members of the MarFS config structure are:\n" );
  fprintf( stdout, "\tconfig name            : %s\n", marfs_config->name );
  fprintf( stdout, "\tconfig version         : %d.%d\n", marfs_config->version_major, marfs_config->version_minor );
  fprintf( stdout, "\tconfig mnt-top          : %s\n", marfs_config->mnt_top );
  // fprintf( stdout, "\tconfig namespace count : %lu\n", marfs_config->namespace_count );
  fprintf( stdout, "\n" );

  ret_val = free_configuration();
  if ( ! ret_val ) {
     fprintf( stdout, "CORRECT: free_configuration returned %d\n", ret_val );
     if ( marfs_config == NULL ) {
        fprintf( stdout, "CORRECT: We freed the MarFS configuration and it is now NULL.\n" );
     } else {
        fprintf( stderr, "ERROR: free_configuration did not set the MarFS configuration to NULL.\n" );
     }
  } else {
    fprintf( stderr, "ERROR: free_configuration returned %d\n", ret_val );
  }
  fprintf( stdout, "\n" );


  fprintf( stdout, "Re-reading the configuration to continue testing...\n" );
  read_configuration(); 
  if ( marfs_config == NULL ) {
    fprintf( stderr, "ERROR: Reading MarFS configuration failed.\n" );
    return 1;
  }
  fprintf( stdout, "\n" );


  if ( lookup_sectype( "none", &marfs_sectype )) {
    fprintf( stderr, "ERROR: Invalid sectype value of \"%s\".\n", "none" );
  } else {
    fprintf( stdout, "CORRECT: SecType value of \"%s\" translates to %d.\n", "none", marfs_sectype );
  }

  if ( encode_sectype( SECTYPE_NONE, &code )) {
    fprintf( stderr, "ERROR: Invalid enumeration value of %d.\n", SECTYPE_NONE );
  } else {
    fprintf( stdout, "CORRECT: Encode value of %d is \"%c\".\n", SECTYPE_NONE, code );
  }

  if ( decode_sectype( '_', &marfs_sectype )) {
    fprintf( stderr, "ERROR: Invalid code of \"%c\".\n", '_' );
  } else {
    fprintf( stdout, "CORRECT: Decode code of \"%c\" is %d.\n", '_',marfs_sectype ); 
  }

  fprintf( stdout, "\n" );

  if ( lookup_comptype( "none", &marfs_comptype )) {
    fprintf( stderr, "ERROR: Invalid comptype value of \"%s\".\n", "none" );
  } else {
    fprintf( stdout, "CORRECT: CompType value of \"%s\" translates to %d.\n", "none", marfs_comptype );
  }

  if ( encode_comptype( COMPTYPE_NONE, &code )) {
    fprintf( stderr, "ERROR: Invalid enumeration value of %d.\n", COMPTYPE_NONE );
  } else {
    fprintf( stdout, "CORRECT: Encode value of %d is \"%c\".\n", COMPTYPE_NONE, code );
  }

  if ( decode_comptype( '_', &marfs_comptype )) {
    fprintf( stderr, "ERROR: Invalid code of \"%c\".\n", '_' );
  } else {
    fprintf( stdout, "CORRECT: Decode code of \"%c\" is %d.\n", '_',marfs_comptype ); 
  }

  fprintf( stdout, "\n" );

  if ( lookup_correcttype( "none", &marfs_correcttype )) {
    fprintf( stderr, "ERROR: Invalid correcttype value of \"%s\".\n", "none" );
  } else {
    fprintf( stdout, "CORRECT: CorrectType value of \"%s\" translates to %d.\n", "none", marfs_correcttype );
  }

  if ( encode_correcttype( CORRECTTYPE_NONE, &code )) {
    fprintf( stderr, "ERROR: Invalid enumeration value of %d.\n", CORRECTTYPE_NONE );
  } else {
    fprintf( stdout, "CORRECT: Encode value of %d is \"%c\".\n", CORRECTTYPE_NONE, code );
  }

  if ( decode_correcttype( '_', &marfs_correcttype )) {
    fprintf( stderr, "ERROR: Invalid code of \"%c\".\n", '_' );
  } else {
    fprintf( stdout, "CORRECT: Decode code of \"%c\" is %d.\n", '_',marfs_correcttype ); 
  }
  fprintf( stdout, "\n" );


  namespacePtr = find_namespace_by_name( "BoGuS" );
  if ( namespacePtr == NULL ) {
    fprintf( stdout, "CORRECT: Namespace \"BoGuS\" does not exist.\n" );
  } else {
    fprintf( stderr, "ERROR: Namespace \"BoGuS\" does not exist and was found.\n" );
  }
  fprintf( stdout, "\n" );

  namespacePtr = find_namespace_by_name( "s3" );
  if ( namespacePtr != NULL ) {
    fprintf( stdout, "CORRECT: Namespace \"s3\" does exist and has mnt_path \"%s\".\n", namespacePtr->mnt_path );
  } else {
    fprintf( stderr, "ERROR: Namespace \"s3\" does exist and was not found.\n" );
  }
  fprintf( stdout, "\n" );


  namespacePtr = find_namespace_by_mnt_path( "/BoGuS" );
  if ( namespacePtr == NULL ) {
    fprintf( stdout, "CORRECT: Mntpath \"/BoGuS\" does not exist.\n" );
  } else {
    fprintf( stderr, "ERROR: Mntpath \"/BoGuS\" does not exist and was found.\n" );
  }
  fprintf( stdout, "\n" );


  namespacePtr = find_namespace_by_mnt_path( "/s3" );
  if ( namespacePtr != NULL ) {
    fprintf( stdout, "CORRECT: Mntpath \"/s3\" does exist and has name \"%s\".\n", namespacePtr->name );
  } else {
    fprintf( stderr, "ERROR: Mntpath \"/s3\" does exist and was not found.\n" );
  }

  repoPtr = find_repo_by_range( namespacePtr, 38 );
  if ( repoPtr != NULL ) {
    fprintf( stdout, "CORRECT: Namespace \"%s\" has a repo \"%s\" for files of size 38.\n",
			namespacePtr->name,
			repoPtr->name );
  } else {
    fprintf( stderr, "ERROR: Namespace \"%s\" should have a repo for files of size 38.\n",
			namespacePtr->name );
  }
  fprintf( stdout, "\n" );

  namespacePtr = find_namespace_by_mnt_path( "/" );
  if ( namespacePtr != NULL ) {
    fprintf( stdout, "CORRECT: Mntpath \"/\" does exist and has name \"%s\".\n", namespacePtr->name );
  } else {
    fprintf( stderr, "ERROR: Mntpath \"/\" does exist and was not found.\n" );
  }
  fprintf( stdout, "\n" );



/*
 * Since the file_size argument is size_t, that is unsigned and negative numbers
 * are not allowed.
 *
  fprintf( stdout, "\n" );

  repoPtr = find_repo_by_range( namespacePtr, -2 );
  if ( repoPtr == NULL ) {
    fprintf( stdout, "CORRECT: Namespace \"%s\" should not have a repo for files of size -2.\n",
			namespacePtr->name );
  } else {
    fprintf( stderr, "ERROR: Namespace \"%s\" incorrectly has a repo \"%s\" for files of size -2.\n",
			namespacePtr->name,
                        repoPtr->repo_name );
  }
 */

  fprintf( stdout, "\n" );

  repoPtr = find_repo_by_range( NULL, 38 );
  if ( repoPtr == NULL ) {
    fprintf( stdout, "CORRECT: A NULL namespace should not have a repo for files of size 38.\n" );
  } else {
    fprintf( stderr, "ERROR: A NULL namespace incorrectly has a repo \"%s\" for files of size 38.\n",
			repoPtr->name );
  }

  fprintf( stdout, "\n" );

  repoPtr = find_repo_by_name( "BoGuS" );
  if ( repoPtr == NULL ) {
    fprintf( stdout, "CORRECT: Repo name \"BoGuS\" does not exist.\n" );
  } else {
    fprintf( stderr, "ERROR: Repo name \"BoGuS\" does not exist and was found.\n" );
  }

  fprintf( stdout, "\n" );

  repoPtr = find_repo_by_name( "emcS3_00" );
  if ( repoPtr != NULL ) {
    fprintf( stdout, "CORRECT: Repo name \"emcS3_00\" does exist and has host \"%s\".\n", repoPtr->host );
  } else {
    fprintf( stderr, "ERROR: Repo name \"emcS3_00\" does exist and was not found.\n" );
  }
  fprintf( stdout, "\n" );

  // --- show contents of all repos
  RepoIterator rit = repo_iterator();
  while (( repoPtr = repo_next( &rit )) != NULL ) {
     debug_repo(repoPtr);
     fprintf(stdout, "\n");
  }
  fprintf(stdout, "\n");

  // --- show contents of all namespaces
  NSIterator nit = namespace_iterator();
  while (( namespacePtr = namespace_next( &nit )) != NULL ) {
     debug_namespace(namespacePtr);
     fprintf(stdout, "\n");
  }
  fprintf( stdout, "\n" );


  return 0;
}
Esempio n. 24
0
void WindowManager::init_internals(int argc, char* argv[])
{
	DBG("starting window manager");

	fl_open_display();
	XSetErrorHandler(xerror_handler);
	XShapeQueryExtension(fl_display, &XShapeEventBase, &XShapeErrorBase);

	wm_area.set(0, 0/*22*/, Fl::w(), Fl::h()/*-22*/);

	// TODO: make this part of class
	program_name = fl_file_filename(argv[0]);

	int i;
	if(Fl::args(argc, argv, i, arg) < argc)
		Fl::error("options are:\n"
			" -d[isplay] host:#.#\tX display & screen to use\n"
			" -v[isual] #\t\tvisual to use\n"
			" -g[eometry] WxH+X+Y\tlimits windows to this area\n"
			" -x\t\t\tmenu says Exit instead of logout\n"
			" -bg color\t\tFrame color\n"
			" -fg color\t\tLabel color\n"
			" -bg2 color\t\tText field color\n"
			" -cfg color\t\tCursor color\n"
			" -cbg color\t\tCursor outline color" );

	// Init started
	is_init = false;

	Fl::add_handler(wm_event_handler);
	
	// intern atoms
	init_atoms();
	read_configuration();
	read_xset_configuration();
	
	// Set XID now
	show();

	set_default_cursor();
	ICCCM::set_iconsizes(this);
	MWM::set_motif_info(this);
	register_protocols(fl_xid(this));
	Grab_Hotkeys(this);

	XSync(fl_display, 0);

	init_desktops(this);

	//Init done
	is_init = true;

	// find all the windows and create a Frame for each:
	Frame *f=0;
	unsigned int n;
	Window w1, w2, *wins;
	XWindowAttributes attr;
	XQueryTree(fl_display, fl_xid(this), &w1, &w2, &wins, &n);
	for (i = 0; i < (int)n; ++i)
	{
		XGetWindowAttributes(fl_display, wins[i], &attr);
		if(attr.override_redirect) continue;
		if(!attr.map_state)
		{
			if(getIntProperty(wins[i], _XA_WM_STATE, _XA_WM_STATE, 0) != IconicState)
				continue;
		}
		f = new Frame(wins[i], &attr);
	}
	XFree((void *)wins);

	// Activate last one
	for(uint n=0; n<map_order.size(); n++)
	{
		Frame *f = map_order[n];
		if(f->desktop()==Desktop::current())
		{
			f->activate();
			f->raise();
			break;
		}
	}

	update_workarea(true);
	is_running = true;
}
Esempio n. 25
0
/*
 * main application method
 */
int main( int argc, char** argv )
{
	// catch process signals
	ibrcommon::SignalHandler sighandler(sighandler_func);
	sighandler.handle(SIGINT);
	sighandler.handle(SIGTERM);
#ifndef __WIN32__
	sighandler.handle(SIGUSR1);
#endif

	// configration object
	config_t conf;

	// read the configuration
	read_configuration(argc, argv, conf);

	init_logger(conf);

	// initialize sighandler after possible exit call
	sighandler.initialize();

	// init working directory
	if (conf.workdir.length() > 0)
	{
		ibrcommon::File blob_path(conf.workdir);

		if (blob_path.exists())
		{
			ibrcommon::BLOB::changeProvider(new ibrcommon::FileBLOBProvider(blob_path), true);
		}
	}

	// backoff for reconnect
	unsigned int backoff = 2;

	ibrcommon::File outbox_file(conf.outbox);

	// create new file lists
	fileset new_files, prev_files, deleted_files, files_to_send;
	filelist observed_files;
	hashlist sent_hashes;

	// observed root file
	io::ObservedFile root(ibrcommon::File("/"));

#ifdef HAVE_LIBTFFS
	io::FatImageReader *imagereader = NULL;
#endif

	if (outbox_file.exists() && !outbox_file.isDirectory())
	{
#ifdef HAVE_LIBTFFS
		conf.fat = true;
		imagereader = new io::FatImageReader(conf.outbox);
		const io::FATFile fat_root(*imagereader, conf.path);
		root = io::ObservedFile(fat_root);
#else
		IBRCOMMON_LOGGER_TAG(TAG,error) << "ERROR: image-file provided, but this tool has been compiled without libtffs support!" << IBRCOMMON_LOGGER_ENDL;
		return -1;
#endif
	}
	else
	{
		if (!outbox_file.exists()) {
			ibrcommon::File::createDirectory(outbox_file);
		}
		root = io::ObservedFile(outbox_file);
	}

	IBRCOMMON_LOGGER_TAG(TAG,info) << "-- dtnoutbox --" << IBRCOMMON_LOGGER_ENDL;

	// loop, if no stop if requested
	while (_running)
	{
		try
		{
			// Create a stream to the server using TCP.
			ibrcommon::vaddress addr("localhost", 4550);
			ibrcommon::socketstream conn(new ibrcommon::tcpsocket(addr));

			// Initiate a client for synchronous receiving
			dtn::api::Client client(conf.name, conn, dtn::api::Client::MODE_SENDONLY);

			// Connect to the server. Actually, this function initiate the
			// stream protocol by starting the thread and sending the contact header.
			client.connect();

			// reset backoff if connected
			backoff = 2;

			// check the connection
			while (_running)
			{
				// get all files
				fileset current_files;
				root.findFiles(current_files);

				// determine deleted files
				fileset deleted_files;
				std::set_difference(prev_files.begin(), prev_files.end(), current_files.begin(), current_files.end(), std::inserter(deleted_files, deleted_files.begin()));

				// remove deleted files from observation
				for (fileset::const_iterator iter = deleted_files.begin(); iter != deleted_files.end(); ++iter)
				{
					const io::ObservedFile &deletedFile = (*iter);

					// remove references in the sent_hashes
					for (hashlist::iterator hash_it = sent_hashes.begin(); hash_it != sent_hashes.end(); /* blank */) {
						if ((*hash_it).getPath() == deletedFile.getFile().getPath()) {
							sent_hashes.erase(hash_it++);
						} else {
							++hash_it;
						}
					}

					// remove from observed files
					observed_files.remove(deletedFile);

					// output
					IBRCOMMON_LOGGER_TAG(TAG,info) << "file removed: " << deletedFile.getFile().getBasename() << IBRCOMMON_LOGGER_ENDL;
				}

				// determine new files
				fileset new_files;
				std::set_difference(current_files.begin(), current_files.end(), prev_files.begin(), prev_files.end(), std::inserter(new_files, new_files.begin()));

				// add new files to observation
				for (fileset::const_iterator iter = new_files.begin(); iter != new_files.end(); ++iter)
				{
					const io::ObservedFile &of = (*iter);

					int reg_ret = regexec(&conf.regex, of.getFile().getBasename().c_str(), 0, NULL, 0);
					if (!reg_ret && !conf.invert)
						continue;
					if (reg_ret && conf.invert)
						continue;

					// print error message, if regex error occurs
					if (reg_ret && reg_ret != REG_NOMATCH)
					{
							char msgbuf[100];
							regerror(reg_ret,&conf.regex,msgbuf,sizeof(msgbuf));
							IBRCOMMON_LOGGER_TAG(TAG,info) << "ERROR: regex match failed : " << std::string(msgbuf) << IBRCOMMON_LOGGER_ENDL;
					}

					// add new file to the observed set
					observed_files.push_back(of);

					// log output
					IBRCOMMON_LOGGER_TAG(TAG, info) << "file found: " << of.getFile().getBasename() << IBRCOMMON_LOGGER_ENDL;
				}

				// store current files for the next round
				prev_files.clear();
				prev_files.insert(current_files.begin(), current_files.end());

				IBRCOMMON_LOGGER_TAG(TAG, notice)
						<< "file statistics: "
						<< observed_files.size() << " observed, "
						<< deleted_files.size() << " deleted, "
						<< new_files.size() << " new"
						<< IBRCOMMON_LOGGER_ENDL;

				// find files to send, create std::list
				files_to_send.clear();


				IBRCOMMON_LOGGER_TAG(TAG, notice) << "updating observed files:" << IBRCOMMON_LOGGER_ENDL;
				for (filelist::iterator iter = observed_files.begin(); iter != observed_files.end(); ++iter)
				{
					io::ObservedFile &of = (*iter);

					// tick and update all files
					of.update();

					if (of.getStableCounter() > conf.rounds)
					{
						if (sent_hashes.find(of.getHash()) == sent_hashes.end())
						{
							sent_hashes.insert(of.getHash());
							files_to_send.insert(*iter);
						}
					}

					IBRCOMMON_LOGGER_TAG(TAG, notice)
						<< "\t"
						<< of.getFile().getBasename() << ": "
						<< of.getStableCounter()
						<< IBRCOMMON_LOGGER_ENDL;
				}

				if (!files_to_send.empty())
				{
					std::stringstream ss;
					for (fileset::const_iterator it = files_to_send.begin(); it != files_to_send.end(); ++it) {
						ss << (*it).getFile().getBasename() << " ";
					}
					IBRCOMMON_LOGGER_TAG("dtnoutbox",info) << "files sent: " << ss.str() << IBRCOMMON_LOGGER_ENDL;

					try {
						// create a blob
						ibrcommon::BLOB::Reference blob = ibrcommon::BLOB::create();

						// write files into BLOB while it is locked
						{
							ibrcommon::BLOB::iostream stream = blob.iostream();
							io::TarUtils::write(*stream, root, files_to_send);
						}

						// create a new bundle
						dtn::data::EID destination = EID(conf.destination);

						// create a new bundle
						dtn::data::Bundle b;

						// set destination
						b.destination = destination;

						// add payload block using the blob
						b.push_back(blob);

						// set destination address to non-singleton, if configured
						if (conf.bundle_group)
							b.set(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON, false);

						// send the bundle
						client << b;
						client.flush();
					} catch (const ibrcommon::IOException &e) {
						IBRCOMMON_LOGGER_TAG(TAG,error) << "send failed: " << e.what() << IBRCOMMON_LOGGER_ENDL;
					}
				}

				// wait defined seconds
				ibrcommon::MutexLock l(_wait_cond);
				IBRCOMMON_LOGGER_TAG(TAG, notice) << conf.interval <<" ms wait" << IBRCOMMON_LOGGER_ENDL;
				while (!_wait_abort && _running) {
					_wait_cond.wait(conf.interval);
				}
				_wait_abort = false;
			}

			// clean up regex
			regfree(&conf.regex);

			// close the client connection
			client.close();

			// close the connection
			conn.close();

		}
		catch (const ibrcommon::socket_exception&)
		{
			if (_running)
			{
				IBRCOMMON_LOGGER_TAG(TAG,error) << "Connection to bundle daemon failed. Retry in " << backoff << " seconds." << IBRCOMMON_LOGGER_ENDL;
				ibrcommon::Thread::sleep(backoff * 1000);

				// if backoff < 10 minutes
				if (backoff < 600)
				{
					// set a new backoff
					backoff = backoff * 2;
				}
			}
		}
		catch (const ibrcommon::IOException&)
		{
			if (_running)
			{
				IBRCOMMON_LOGGER_TAG(TAG,error) << "Connection to bundle daemon failed. Retry in " << backoff << " seconds." << IBRCOMMON_LOGGER_ENDL;
				ibrcommon::Thread::sleep(backoff * 1000);

				// if backoff < 10 minutes
				if (backoff < 600)
				{
					// set a new backoff
					backoff = backoff * 2;
				}
			}
		}
		catch (const std::exception&) { };
	}

	// clear observed files
	observed_files.clear();

#ifdef HAVE_LIBTFFS
	// clean-up
	if (imagereader != NULL) delete imagereader;
#endif

	return (EXIT_SUCCESS);
}
Esempio n. 26
0
static void mail_tick(char *sysname)
{

  DIR *dirp;
  FILE *fp;
  char line[1024];
  char spooldir[80];
  char tmp1[1024];
  char tmp2[1024];
  char tmp3[1024];
  int clients;
  int cnt;
  struct dirent *dp;
  struct mailjob mj, *jp, *tail;
  struct mailsys *sp;
  struct stat statbuf;

  struct filelist {
    struct filelist *next;
    char name[16];
  } *filelist, *p, *q;

  if (!*UUCP_DIR) return;

  start_timer(&Mail_timer);
  read_configuration();

  for (clients = 0, sp = Systems; sp; sp = sp->next)
    if (sp->state >= MS_TRYING) clients++;
  for (sp = Systems; sp && clients < Maxclients; sp = sp->next) {
    if (sysname && !strcmp(sp->sysname, sysname)) sp->nexttime = 0;
    if (sp->state >= MS_TRYING || sp->nexttime > secclock()) continue;
    sprintf(spooldir, "%s/%s", UUCP_DIR, sp->sysname);
    if (!(dirp = opendir(spooldir))) continue;
    filelist = 0;
    cnt = 0;
    for (dp = readdir(dirp); dp; dp = readdir(dirp)) {
      if (*dp->d_name != 'C') continue;
      p = (struct filelist *) malloc(sizeof(struct filelist));
      strcpy(p->name, dp->d_name);
      if (!filelist || strcmp(p->name, filelist->name) < 0) {
	p->next = filelist;
	filelist = p;
      } else {
	for (q = filelist; q->next && strcmp(p->name, q->next->name) > 0; q = q->next) ;
	p->next = q->next;
	q->next = p;
      }
      if (++cnt > MAXJOBS) {
	for (q = 0, p = filelist; p->next; q = p, p = p->next) ;
	q->next = 0;
	free(p);
	cnt--;
      }
    }
    closedir(dirp);
    tail = 0;
    for (; (p = filelist); filelist = p->next, free(p)) {
      memset(&mj, 0, sizeof(mj));
      sprintf(mj.cfile, "%s/%s", spooldir, p->name);
      if (!(fp = fopen(mj.cfile, "r"))) continue;
      while (fgets(line, sizeof(line), fp)) {
	if (*line == 'E' && sscanf(line, "%*s %*s %*s %*s %*s %s %*s %*s %*s %s %s", tmp1, tmp2, tmp3) == 3 && *tmp1 == 'D' && !strcmp(tmp2, "rmail")) {
	  sprintf(mj.dfile, "%s/%s", spooldir, tmp1);
	  sprintf(mj.to, "%s!%s", sp->sysname, tmp3);
	  strtrim(mj.to);
	}
	if (*line == 'S' && sscanf(line, "%*s %*s %s %*s %*s %s", tmp1, tmp2) == 2 && *tmp1 == 'D')
	  sprintf(mj.dfile, "%s/%s", spooldir, tmp2);
	if (*line == 'S' && sscanf(line, "%*s %*s %s %*s %*s %s", tmp1, tmp2) == 2 && *tmp1 == 'X')
	  sprintf(mj.xfile, "%s/%s", spooldir, tmp2);
      }
      fclose(fp);
      if (!*mj.dfile) continue;
      if (*mj.xfile) {
	if (!(fp = fopen(mj.xfile, "r"))) continue;
	while (fgets(line, sizeof(line), fp))
	  if (!strncmp(line, "C rmail ", 8)) {
	    sprintf(mj.to, "%s!%s", sp->sysname, line + 8);
	    strtrim(mj.to);
	    break;
	  }
	fclose(fp);
      }
      if (!*mj.to) continue;
      if (!(fp = fopen(mj.dfile, "r"))) continue;
      if (fscanf(fp, "%*s %s", tmp1) == 1) {
	if (!strcmp(tmp1, "MAILER-DAEMON") || !strcmp(tmp1, "!"))
	  strcpy(tmp1, Hostname);
	sprintf(mj.from, "%s!%s", Hostname, tmp1);
	strtrim(mj.from);
	while (fgets(line, sizeof(line), fp))
	  if (!strncmp(line, "Subject: ", 9)) {
	    strcpy(mj.subject, line + 9);
	    strtrim(mj.subject);
	    break;
	  }
      }
      fclose(fp);
      if (!*mj.from) continue;
      if (stat(mj.cfile, &statbuf)) continue;
      if (statbuf.st_mtime + RETURNTIME < secclock()) {
	sprintf(mj.return_reason, "520 %s... Cannot connect for %ld days\n", sp->sysname, RETURNTIME / (60L*60*24));
	mail_return(&mj);
      } else {
	jp = (struct mailjob *) malloc(sizeof(struct mailjob));
	*jp = mj;
	if (!sp->jobs)
	  sp->jobs = jp;
	else
	  tail->next = jp;
	tail = jp;
      }
    }
    if (sp->jobs) {
      sp->state = MS_TRYING;
      clients++;
      (*sp->mailer->func)(sp);
    }
  }
}
Esempio n. 27
0
int dosmtp(int argc, char *argv[], void *p)
{
  read_configuration();
  return subcmd(Mail_cmds, argc, argv, p);
}
Esempio n. 28
0
int main(void) {
  /* Early system initialisation */
  early_board_init();
  system_init_early();
  leds_init();

  set_busy_led(1);
  set_dirty_led(0);

  /* Due to an erratum in the LPC17xx chips anything that may change */
  /* peripheral clock scalers must come before system_init_late()    */
  uart_init();
#ifndef SPI_LATE_INIT
  spi_init(SPI_SPEED_SLOW);
#endif
  timer_init();
  i2c_init();

  /* Second part of system initialisation, switches to full speed on ARM */
  system_init_late();
  enable_interrupts();

  /* Prompt software name and version string */
  uart_puts_P(PSTR("\r\nNODISKEMU " VERSION "\r\n"));

  /* Internal-only initialisation, called here because it's faster */
  buffers_init();
  buttons_init();

  /* Anything that does something which needs the system clock */
  /* should be placed after system_init_late() */
  rtc_init();    // accesses I2C
  disk_init();   // accesses card
  read_configuration(); // restores configuration, may change device address

  filesystem_init(0);
  // FIXME: change_init();

#ifdef CONFIG_REMOTE_DISPLAY
  /* at this point all buffers should be free, */
  /* so just use the data area of the first to build the string */
  uint8_t *strbuf = buffers[0].data;
  ustrcpy_P(strbuf, versionstr);
  ustrcpy_P(strbuf+ustrlen(strbuf), longverstr);
  if (display_init(ustrlen(strbuf), strbuf)) {
    display_address(device_address);
    display_current_part(0);
  }
#endif

  set_busy_led(0);

#if defined(HAVE_SD)
  /* card switch diagnostic aid - hold down PREV button to use */
  if (menu_system_enabled && get_key_press(KEY_PREV))
    board_diagnose();
#endif

  if (menu_system_enabled)
    lcd_splashscreen();

  bus_interface_init();
  bus_init();
  read_configuration();
  late_board_init();

  for (;;) {
    if (menu_system_enabled)
      lcd_refresh();
    else {
      lcd_clear();
      lcd_printf("#%d", device_address);
    }
    /* Unit number may depend on hardware and stored settings */
    /* so present it here at last */
    printf("#%02d\r\n", device_address);
    bus_mainloop();
    bus_interface_init();
    bus_init();    // needs delay, inits device address with HW settings
  }
}
Esempio n. 29
0
int main(void) {
  /* Early system initialisation */
  board_init();
  system_init_early();
  leds_init();

  set_busy_led(1);
  set_dirty_led(0);

  /* Due to an erratum in the LPC17xx chips anything that may change */
  /* peripheral clock scalers must come before system_init_late()    */
  uart_init();
#ifndef SPI_LATE_INIT
  spi_init(SPI_SPEED_SLOW);
#endif
  timer_init();
  bus_interface_init();
  i2c_init();

  /* Second part of system initialisation, switches to full speed on ARM */
  system_init_late();
  enable_interrupts();

  /* Internal-only initialisation, called here because it's faster */
  buffers_init();
  buttons_init();

  /* Anything that does something which needs the system clock */
  /* should be placed after system_init_late() */
  bus_init();    // needs delay
  rtc_init();    // accesses I2C
  disk_init();   // accesses card
  read_configuration();

  fatops_init(0);
  change_init();

  uart_puts_P(PSTR("\r\nsd2iec " VERSION " #"));
  uart_puthex(device_address);
  uart_putcrlf();

#ifdef CONFIG_REMOTE_DISPLAY
  /* at this point all buffers should be free, */
  /* so just use the data area of the first to build the string */
  uint8_t *strbuf = buffers[0].data;
  ustrcpy_P(strbuf, versionstr);
  ustrcpy_P(strbuf+ustrlen(strbuf), longverstr);
  if (display_init(ustrlen(strbuf), strbuf)) {
    display_address(device_address);
    display_current_part(0);
  }
#endif

  set_busy_led(0);

#if defined(HAVE_SD) && BUTTON_PREV != 0
  /* card switch diagnostic aid - hold down PREV button to use */
  if (!(buttons_read() & BUTTON_PREV)) {
    while (buttons_read() & BUTTON_NEXT) {
      set_dirty_led(sdcard_detect());
# ifndef SINGLE_LED
      set_busy_led(sdcard_wp());
# endif
    }
    reset_key(0xff);
  }
#endif

  bus_mainloop();

  while (1);
}
Esempio n. 30
0
int main(int argc, char **argv)
{
	int rc = 1;
	int opt, longind;
	char *config_file = "/etc/freight-agent/config";
	char *mode = NULL;
	char *rpm = NULL;
	struct db_api *api;
	char *list = "all";
	char *name = NULL;
	int verbose = 0;	
	/*
 	 * Parse command line options
 	 */

#ifdef HAVE_GETOPT_LONG
	while ((opt = getopt_long(argc, argv, "hc:m:r:l:vn:", lopts, &longind)) != -1) {
#else
	while ((opt = getopt(argc, argv, "hc:m:r:l:vn:") != -1) {
#endif
		switch(opt) {

		case '?':
			/* FALLTHROUGH */
		case 'h':
			usage(argv);
			goto out;
			/* NOTREACHED */
			break;
		case 'c':
			config_file = optarg;
			break;
		case 'm':
			mode = optarg;
			break;
		case 'n':
			name = optarg;
			break;
		case 'r':
			rpm = optarg;
			break;
		case 'l':
			list = optarg;
			break;
		case 'v':
			verbose = 1;
			break;
		}
	}


	if (strcmp(list, "all") &&
	    strcmp(list, "local") &&
	    strcmp(list, "running")) {
		LOG(ERROR, "list option must be all,running or local\n");
		goto out;
	}

	/*
 	 * Read in the configuration file
 	 */
	rc = read_configuration(config_file, &config);
	if (rc)
		goto out_release;

	config.cmdline.verbose = verbose;

	/*
 	 * Sanity checks
 	 */
	if (!mode) {
		LOG(ERROR, "You must specify a mode\n");
		goto out_release;
	}

	if (streq(mode, "node"))
		config.cmdline.mode = OP_MODE_NODE;
	else if (streq(mode, "init"))
		config.cmdline.mode = OP_MODE_INIT; 
	else if (streq(mode, "clean"))
		config.cmdline.mode = OP_MODE_CLEAN;
	else if (streq(mode, "install"))
		config.cmdline.mode = OP_MODE_INSTALL;
	else if (streq(mode, "uninstall"))
		config.cmdline.mode = OP_MODE_UNINSTALL;
	else if (streq(mode, "list"))
		config.cmdline.mode = OP_MODE_LIST;
	else if (streq(mode, "exec"))
		config.cmdline.mode = OP_MODE_EXEC;
	else {
		LOG(ERROR, "Invalid mode spcified\n");
		goto out_release;
	}

	if (!config.node.container_root) {
		LOG(ERROR, "Mode requires a container_root specification\n");
		goto out_release;
	}

	api = get_db_api(&config);
	if (!api) {
		LOG(ERROR, "No DB configuration selected\n");
		goto out_release;
	}

	if (db_init(api, &config)) {
		LOG(ERROR, "Unable to initalize DB subsystem\n");
		goto out_release;
	}

	if (db_connect(api, &config))
		goto out_cleanup_db;
	

	/*
 	 * Enter the appropriate function loop based on mode
 	 * Note, for all modes other than node mode (in which we 
 	 * monitor the database for mutiple tennant requests, all the modes
 	 * here are for the local user only, meaning everything goes to the 
 	 * 'local' tennant
 	 */
	switch (config.cmdline.mode) {

	case OP_MODE_INIT:
		rc = init_container_root(api, &config);
		if (rc) {
			LOG(ERROR, "Init of container root failed: %s\n",
				strerror(rc));
			goto out_disconnect;
		}
		break;
	case OP_MODE_CLEAN:
		LOG(INFO, "Removing container root %s\n",
			  config.node.container_root);
		clean_container_root(api, &config);
		break;
	case OP_MODE_INSTALL:
		if (!rpm) {
			LOG(ERROR, "Must specify a container name or rpm with "
				   "-r option in install mode\n");
			goto out_disconnect;
		}
		rc = local_install_container(rpm, &config);
		if (rc) {
			LOG(ERROR, "Failed to install container: %s\n",
				strerror(rc));
			goto out_disconnect;
		}
		break;
	case OP_MODE_UNINSTALL:
		if (!rpm) {
			LOG(ERROR, "Must specify the container name with -r\n");
			goto out_disconnect;
		}
		rc = local_uninstall_container(rpm, &config);
		if (rc) {
			LOG(ERROR, "Uninstall of container %s failed: %s\n",
				rpm, strerror(rc));
			goto out_disconnect;
		}
		break;
	case OP_MODE_LIST:
		local_list_containers(list, &config);
		break;
	case OP_MODE_EXEC:
		if (!rpm) {
			LOG(ERROR, "Must specify the container name with -r\n");
			goto out_disconnect;
		}
		if (!name) {
			LOG(ERROR, "Must specify a container instance name with -n\n");
			goto out_disconnect;
		}
		rc = local_exec_container(rpm, name, &config);
		if (rc) {
			LOG(ERROR, "Exec of container %s failed: %s\n",
				rpm, strerror(rc));
			goto out_disconnect;
		}
	case OP_MODE_NODE:
		rc = enter_mode_loop(api, &config);
		if (rc) {
			LOG(ERROR, "Mode operation terminated abnormally: %s\n",
				strerror(rc));
			goto out_disconnect;
		}
		break;
	}

	rc = 0;

out_disconnect:
	db_disconnect(api, &config);
out_cleanup_db:
	db_cleanup(api, &config);
out_release:
	release_configuration(&config);
out:
	return rc;
}