Пример #1
0
static status_t
vmi_init_private(
    vmi_instance_t *vmi,
    uint32_t flags,
    unsigned long id,
    char *name,
    vmi_config_t *config)
{
    uint32_t access_mode = flags & 0x0000FFFF;
    uint32_t init_mode = flags & 0x00FF0000;
    uint32_t config_mode = flags & 0xFF000000;
    status_t status = VMI_FAILURE;

    /* allocate memory for instance structure */
    *vmi = (vmi_instance_t) safe_malloc(sizeof(struct vmi_instance));
    memset(*vmi, 0, sizeof(struct vmi_instance));

    /* initialize instance struct to default values */
    dbprint("LibVMI Version 0.9_alpha\n");  //TODO change this with each release

    /* save the flags and init mode */
    (*vmi)->flags = flags;
    (*vmi)->init_mode = init_mode;
    (*vmi)->config = config;
    (*vmi)->config_mode = config_mode;

    /* setup the caches */
    pid_cache_init(*vmi);
    sym_cache_init(*vmi);
    rva_cache_init(*vmi);
    v2p_cache_init(*vmi);

    /* connecting to xen, kvm, file, etc */
    if (VMI_FAILURE == set_driver_type(*vmi, access_mode, id, name)) {
        goto error_exit;
    }

    /* resolve the id and name */
    if (VMI_FAILURE == set_id_and_name(*vmi, access_mode, id, name)) {
        goto error_exit;
    }

    /* driver-specific initilization */
    if (VMI_FAILURE == driver_init(*vmi)) {
        goto error_exit;
    }
    dbprint("--completed driver init.\n");

    /* we check VMI_INIT_COMPLETE first as
       VMI_INIT_PARTIAL is not exclusive */
    if (init_mode & VMI_INIT_COMPLETE) {

        /* init_complete requires configuration */
        if(VMI_CONFIG_NONE & (*vmi)->config_mode) {
            /* falling back to VMI_CONFIG_GLOBAL_FILE_ENTRY is unsafe here
                as the config pointer is probably NULL */
            goto error_exit;
        }
        /* read and parse the config file */
        else if ( (VMI_CONFIG_STRING & (*vmi)->config_mode || VMI_CONFIG_GLOBAL_FILE_ENTRY & (*vmi)->config_mode)
                 && VMI_FAILURE == read_config_file(*vmi)) {
            goto error_exit;
        }
        /* read and parse the ghashtable */
        else if (VMI_CONFIG_GHASHTABLE & (*vmi)->config_mode
                 && VMI_FAILURE == read_config_ghashtable(*vmi)) {
            dbprint("--failed to parse ghashtable\n");
            goto error_exit;
        }

        /* setup the correct page offset size for the target OS */
        if (VMI_FAILURE == init_page_offset(*vmi)) {
            goto error_exit;
        }

        /* get the memory size */
        if (driver_get_memsize(*vmi, &(*vmi)->size) == VMI_FAILURE) {
            errprint("Failed to get memory size.\n");
            goto error_exit;
        }
        dbprint("**set size = %"PRIu64" [0x%"PRIx64"]\n", (*vmi)->size,
                (*vmi)->size);

        /* determine the page sizes and layout for target OS */

        // Find the memory layout. If this fails, then proceed with the
        // OS-specific heuristic techniques.
        (*vmi)->pae = (*vmi)->pse = (*vmi)->lme = (*vmi)->cr3 = 0;
        (*vmi)->page_mode = VMI_PM_UNKNOWN;

        status = get_memory_layout(*vmi,
                                        &((*vmi)->page_mode),
                                        &((*vmi)->cr3),
                                        &((*vmi)->pae),
                                        &((*vmi)->pse),
                                        &((*vmi)->lme));

        if (VMI_FAILURE == status) {
            dbprint
                ("**Failed to get memory layout for VM. Trying heuristic method.\n");
            // fall-through
        }   // if

        // Heuristic method
        if (!(*vmi)->cr3) {
            (*vmi)->cr3 = find_cr3((*vmi));
            dbprint("**set cr3 = 0x%.16"PRIx64"\n", (*vmi)->cr3);
        }   // if

        /* setup OS specific stuff */
        if (VMI_OS_LINUX == (*vmi)->os_type) {
            status = linux_init(*vmi);
        }
        else if (VMI_OS_WINDOWS == (*vmi)->os_type) {
            status = windows_init(*vmi);
        }

        /* Enable event handlers only if we're in a consistent state */
        if((status == VMI_SUCCESS) && (init_mode & VMI_INIT_EVENTS)){
            events_init(*vmi);
        }

        return status;
    } else if (init_mode & VMI_INIT_PARTIAL) {
        init_page_offset(*vmi);
        driver_get_memsize(*vmi, &(*vmi)->size);

        /* Enable event handlers */
        if(init_mode & VMI_INIT_EVENTS){
            events_init(*vmi);
        }

        return VMI_SUCCESS;
    }

error_exit:
    return status;
}
Пример #2
0
int main( int argc, char **argv ) 
{
    /* Print copyright notice */

    fprintf( stderr, 
         "Tux Rider World Challenge -- http://www.barlow-server.com\n"
         "a fork from:\n"
         "Tux Racer " VERSION " -- a Sunspire Studios Production "
	     "(http://www.sunspirestudios.com)\n"
	     "(c) 1999-2000 Jasmin F. Patry "
	     "<*****@*****.**>\n"
	     "\"Tux Racer\" is a trademark of Jasmin F. Patry\n"
	     "Tux Rider World Challenge comes with ABSOLUTELY NO WARRANTY. "
	     "This is free software,\nand you are welcome to redistribute "
	     "it under certain conditions.\n"
	     "See http://www.gnu.org/copyleft/gpl.html for details.\n\n" );

    /* Init the game clock */
    g_game.secs_since_start = 0;

    /* Seed the random number generator */
    srand( time(NULL) );


    /*
     * Set up the game configuration
     */

    /* Don't support multiplayer, yet... */
    g_game.num_players = 2;

    /* Create a Tcl interpreter */
    g_game.tcl_interp = Tcl_CreateInterp();

    if ( g_game.tcl_interp == NULL ) {
	handle_error( 1, "cannot create Tcl interpreter" ); 
    }

    /* Setup the configuration variables and read the ~/.tuxracer/options file */
    init_game_configuration();
    read_config_file();

    /* Set up the debugging modes */
    init_debug();

    /* Setup diagnostic log if requested */
    if ( getparam_write_diagnostic_log() ) {
	setup_diagnostic_log();
    }

    /*
     * Setup Tcl stdout and stderr channels to point to C stdout and stderr 
     * streams
     */
    setup_tcl_std_channels();


    /* 
     * Initialize rendering context, create window
     */
    winsys_init( &argc, argv, WINDOW_TITLE, WINDOW_TITLE );


    /* Ingore key-repeat messages */
    winsys_enable_key_repeat(0);


    /* Set up a function to clean up when program exits */
    winsys_atexit( cleanup );

    /* 
     * Initial OpenGL settings 
     */
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    init_opengl_extensions();

    /* Print OpenGL debugging information if requested */
    if ( debug_mode_is_active( DEBUG_GL_INFO ) ) {
	print_debug( DEBUG_GL_INFO, 
		     "OpenGL information:" );
	print_gl_info();
    }


    /* 
     * Load the game data and initialize game state
     */
    register_game_config_callbacks( g_game.tcl_interp );
    register_course_load_tcl_callbacks( g_game.tcl_interp );
    register_key_frame_callbacks( g_game.tcl_interp );
    register_fog_callbacks( g_game.tcl_interp );
    register_course_light_callbacks( g_game.tcl_interp );
    register_particle_callbacks( g_game.tcl_interp );
    register_texture_callbacks( g_game.tcl_interp );
    register_font_callbacks( g_game.tcl_interp );
    register_sound_tcl_callbacks( g_game.tcl_interp );
    register_sound_data_tcl_callbacks( g_game.tcl_interp );
    register_course_manager_callbacks( g_game.tcl_interp );


    init_saved_games();
    load_tux();
    init_textures();
    init_fonts();
    init_audio_data();
    init_audio();
    init_ui_manager();
    init_course_manager();
    init_joystick();

    /* Read the tuxracer_init.tcl file */
    read_game_init_script();

    /* Need to set up an initial view position for select_course 
       (quadtree simplification)
    */
    
    //Player 0 = classic mode player ; Player 1 = Speed Only Mode Player
    
    g_game.player[0].view.pos = make_point( 0., 0., 0. );
    g_game.player[1].view.pos = make_point( 0., 0., 0. );
    

    /* Placeholder name until we give players way to enter name */
    g_game.player[0].name = "noname";
    g_game.player[1].name = "nonameSpeedOnly";
   

    init_preview();

    splash_screen_register();
    intro_register();
    racing_register();
    game_over_register();
    paused_register();
    reset_register();
    game_type_select_register();
    racing_mode_select_register();
    event_select_register();
    race_select_register();
    credits_register();
    loading_register();

    g_game.mode = NO_MODE;
    set_game_mode( SPLASH );

    g_game.difficulty = DIFFICULTY_LEVEL_NORMAL;

    init_keyboard();
    

    winsys_show_cursor( False );

    /* We use this to "prime" the GLUT loop */
    winsys_set_idle_func( main_loop );

    
    /* 
     * ...and off we go!
     */
    winsys_process_events();

    return 0;
} 
	int
check_password (char *pPasswd, char **ppErrStr, Entry *pEntry)
{

	char *szErrStr = (char *) ber_memalloc(MEM_INIT_SZ);
	int  mem_len = MEM_INIT_SZ;

	int nLen;
	int nLower = 0;
	int nUpper = 0;
	int nDigit = 0;
	int nPunct = 0;
	int min_lower = 0;
	int min_upper = 0;
	int min_digit = 0;
	int min_punct = 0;
  int max_consecutive_per_class = 0;
	int nQuality = 0;
	int i;

	/* Set a sensible default to keep original behaviour. */
	int min_quality = DEFAULT_QUALITY;
	int use_cracklib = DEFAULT_CRACKLIB;

	nLen = strlen (pPasswd);

  if (read_config_file() == -1) {
    syslog(LOG_ERR, "Warning: Could not read values from config file %s. Using defaults.", CONFIG_FILE);
#if defined(LDEBUG)
    printf("Error: Could not read values from config file %s\n", CONFIG_FILE);
#endif
  }

#if defined(LDEBUG) || defined(DEBUG) 
  print_config_entries();
#endif

	min_quality = get_config_entry_int("min_points");
	use_cracklib = get_config_entry_int("use_cracklib");
	min_upper = get_config_entry_int("min_upper");
	min_lower = get_config_entry_int("min_lower");
	min_digit = get_config_entry_int("min_digit");
	min_punct = get_config_entry_int("min_punct");
  max_consecutive_per_class = get_config_entry_int("max_consecutive_per_class");

  /* Check Max Consecutive Per Class first since this has the most likelihood
   * of being wrong.
   */

  if ( max_consecutive_per_class != 0 ) {
    char prev_type = '\0';
    char this_type = ' ';
    i = 0;
    int consec_chars = 0;
    for ( i = 0; i < nLen; i++ ) {
      if ( islower(pPasswd[i]) ) {
        this_type = 'l';
      }
      else if ( isupper(pPasswd[i]) ) {
        this_type = 'u';
      }
      else if ( isdigit(pPasswd[i]) ) {
        this_type = 'd';
      }
      else if ( ispunct(pPasswd[i]) ) {
        this_type = 'p';
      }
      else {
        this_type = ' ';
      }
      if (this_type == prev_type) {
        ++consec_chars;
      } else if (i > 0) {
        consec_chars = 0;
      }
      prev_type = this_type;
      if ( consec_chars >= max_consecutive_per_class ) {
        mem_len = realloc_error_message(&szErrStr, mem_len,
          strlen(CONSEC_FAIL_SZ) +
          strlen(pEntry->e_name.bv_val));
        sprintf (szErrStr, CONSEC_FAIL_SZ, pEntry->e_name.bv_val);
        goto fail;
      }
    }
  }

	/** The password must have at least min_quality strength points with one
	 * point for the first occurrance of a lower, upper, digit and
	 * punctuation character
	 */

	for ( i = 0; i < nLen; i++ ) {

		//if ( nQuality >= min_quality ) break;

		if ( islower (pPasswd[i]) ) {
			min_lower--;
			if ( !nLower && (min_lower < 1)) {
				nLower = 1; nQuality++;
#if defined(DEBUG)
				syslog(LOG_NOTICE, "check_password: Found lower character - quality raise %d", nQuality);
#endif
#if defined(LDEBUG)
  printf("check_password: Found lower character - quality raise %d\n", nQuality);
#endif
			}
			continue;
		}

		if ( isupper (pPasswd[i]) ) {
			min_upper--;
			if ( !nUpper && (min_upper < 1)) {
				nUpper = 1; nQuality++;
#if defined(DEBUG)
				syslog(LOG_NOTICE, "check_password: Found upper character - quality raise %d", nQuality);
#endif
#if defined(LDEBUG)
  printf("check_password: Found upper character - quality raise %d\n", nQuality);
#endif
			}
			continue;
		}

		if ( isdigit (pPasswd[i]) ) {
			min_digit--;
			if ( !nDigit && (min_digit < 1)) {
				nDigit = 1; nQuality++;
#if defined(DEBUG)
				syslog(LOG_NOTICE, "check_password: Found digit character - quality raise %d", nQuality);
#endif
#if defined(LDEBUG)
  printf("check_password: Found digit character - quality raise %d\n", nQuality);
#endif
			}
			continue;
		}

		if ( ispunct (pPasswd[i]) ) {
			min_punct--;
			if ( !nPunct && (min_punct < 1)) {
				nPunct = 1; nQuality++;
#if defined(DEBUG)
				syslog(LOG_NOTICE, "check_password: Found punctuation character - quality raise %d", nQuality);
#endif
#if defined(LDEBUG)
  printf("check_password: Found punctuation character - quality raise %d\n", nQuality);
#endif
			}
			continue;
		}
	}

  /*
   * If you have a required field, then it should be required in the strength
   * checks. 
   */

  if ( 
        (min_lower > 0 ) || 
        (min_upper > 0 ) ||
        (min_digit > 0 ) ||
        (min_punct > 0 ) ||
        (nQuality < min_quality) 
    ) {
		mem_len = realloc_error_message(&szErrStr, mem_len,
				strlen(PASSWORD_QUALITY_SZ) +
				strlen(pEntry->e_name.bv_val) + 2);
		sprintf (szErrStr, PASSWORD_QUALITY_SZ, pEntry->e_name.bv_val,
				nQuality, min_quality);
		goto fail;
	}

#ifdef HAVE_CRACKLIB

	/** Check password with cracklib */

	if ( use_cracklib > 0 ) {
		int   j = 0;
		FILE* fp;
		char  filename[FILENAME_MAXLEN];
		char  const* ext[] = { "hwm", "pwd", "pwi" };
		int   nErr = 0;

		/**
		 * Silently fail when cracklib wordlist is not found
		 */

		for ( j = 0; j < 3; j++ ) {

			snprintf (filename, FILENAME_MAXLEN - 1, "%s.%s", \
					CRACKLIB_DICTPATH, ext[j]);

			if (( fp = fopen ( filename, "r")) == NULL ) {

				nErr = 1;
				break;

			} else {

				fclose (fp);

			}
		}

		char *r;
		if ( nErr  == 0) {

			r = (char *) FascistCheck (pPasswd, CRACKLIB_DICTPATH);
			if ( r != NULL ) {
				mem_len = realloc_error_message(&szErrStr, mem_len,
						strlen(BAD_PASSWORD_SZ) +
						strlen(pEntry->e_name.bv_val) +
						strlen(r));
				sprintf (szErrStr, BAD_PASSWORD_SZ, pEntry->e_name.bv_val, r);
				goto fail;
			}
		}
	}

	else {
#if defined(DEBUG)
		syslog(LOG_NOTICE, "check_password: Cracklib verification disabled by configuration");
#endif
#if defined(LDEBUG)
		printf("check_password: Cracklib verification disabled by configuration");
#endif
	}

#endif

#if defined(LDEBUG) || defined(DEBUG) 
  print_config_entries();
#endif
  dealloc_config_entries();
	*ppErrStr = strdup ("");
	ber_memfree(szErrStr);
	return (LDAP_SUCCESS);

fail:
  dealloc_config_entries();
	*ppErrStr = strdup (szErrStr);
	ber_memfree(szErrStr);
	return (EXIT_FAILURE);

}
Пример #4
0
int main(int argc, char**argv)
{
	GMainLoop *loop;
	DBusError error;
	int godaemon = 1;

/*
 * Signal the kernel that we're not timing critical
 */
#ifdef PR_SET_TIMERSLACK
	prctl(PR_SET_TIMERSLACK,1000*1000*1000, 0, 0, 0);
#endif

	read_config_file("/etc/kerneloops.conf");

	if (argc > 1 && strstr(argv[1], "--nodaemon"))
		godaemon = 0;
	if (argc > 1 && strstr(argv[1], "--debug")) {
		printf("Starting kerneloops in debug mode\n");
		godaemon = 0;
		testmode = 1;
		opted_in = 2;
	}

	if (!opted_in && !testmode) {
		fprintf(stderr, " [Inactive by user preference]");
		return EXIT_SUCCESS;
	}

	/*
	 * the curl docs say that we "should" call curl_global_init early,
	 * even though it'll be called later on via curl_easy_init().
	 * We ignore this advice, since 99.99% of the time this program
	 * will not use http at all, but the curl code does consume
	 * memory.
	 */

/*
	curl_global_init(CURL_GLOBAL_ALL);
*/

	if (godaemon && daemon(0, 0)) {
		printf("kerneloops failed to daemonize.. exiting \n");
		return EXIT_FAILURE;
	}
	sched_yield();

	loop = g_main_loop_new(NULL, FALSE);
	dbus_error_init(&error);
	bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
	if (bus) {
		dbus_connection_setup_with_g_main(bus, NULL);
		dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.ping'", &error);
		dbus_bus_add_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);
		dbus_connection_add_filter(bus, got_message, NULL, NULL);
	}

	/* we scan dmesg before /var/log/messages; dmesg is a more accurate source normally */
	scan_dmesg(NULL);
	/* during boot... don't go too fast and slow the system down */
	if (!testmode)
		sleep(10);
	scan_filename(log_file, 1);

	if (argc > 2 && strstr(argv[1], "--file"))
		scan_filename(argv[2], 1);

	if (testmode && argc > 2) {
		int q;
		for (q = 2; q < argc; q++) {
			printf("Scanning %s\n", argv[q]);
			scan_filename(argv[q], 0);
		}
	}

	if (testmode) {
		g_main_loop_unref(loop);
		dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.ping'", &error);
		dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);
		free(submit_url);
		return EXIT_SUCCESS;
	}

	/* now, start polling for oopses to occur */

	g_timeout_add_seconds(10, scan_dmesg, NULL);

	g_main_loop_run(loop);
	dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.ping'", &error);
	dbus_bus_remove_match(bus, "type='signal',interface='org.kerneloops.submit.permission'", &error);

	g_main_loop_unref(loop);
	free(submit_url);

	return EXIT_SUCCESS;
}
Пример #5
0
void main(int argc, char **argv)
{
   bool	 running = TRUE;

   /*---------------------------------------------------*/
   /* parse command line arguments and initialize stuff */
   /*---------------------------------------------------*/

   parse_args( argc, argv );
   log_file.init_log(TRUE,TRUE,2,NULL);
   read_config_file();

   init_socket();

   command.list_commands();
   command.prompt();
   do
   {
      command.get_input();
      switch( command.input[0] )
      {

         case 'd':
         	server_list.ListServers();
         	break;

         case 'b':
         	banned_list.ListServers();
         	break;

         case 'r':
			   read_config_file();
         	break;

         case 'g':
         	query_game();
//            wait_for_response( GAMESVR_REPLY );
            break;

      	case 'q':
         case 'Q':
         	running = FALSE;
            break;

         case 'l':
         	enable_log = !enable_log;
            log_file.set_log(enable_log);
            cout << "Log file is " << (enable_log?"on.":"off.") << endl;
         	break;

         case 'e':
         	enable_echo = !enable_echo;
            log_file.set_echo(enable_echo);
            cout << "Log echo is " << (enable_echo?"on.":"off.") << endl;
         	break;

         case '?':
         case 'h':
         	command.list_commands();
            break;

         default:
         case 'x':
         	server_list.DeleteList();
         	break;
      }
      if( GetTickCount() > next_reload_time )
      {
      	read_config_file();
         next_reload_time = GetTickCount() + reload_interval;
      }
      command.prompt();
   }
   while( running );
}
Пример #6
0
cChannelMap::cChannelMap (string conffile)
{
    chanmap.clear ();
    read_config_file(conffile);
}
Пример #7
0
/*
 * Main program for the ssh client.
 */
int
main(int ac, char **av)
{
	int i, r, opt, exit_status, use_syslog;
	char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg;
	char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
	struct stat st;
	struct passwd *pw;
	int dummy, timeout_ms;
	extern int optind, optreset;
	extern char *optarg;

	struct servent *sp;
	Forward fwd;

	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
	sanitise_stdfd();

	__progname = ssh_get_progname(av[0]);

#ifndef HAVE_SETPROCTITLE
	/* Prepare for later setproctitle emulation */
	/* Save argv so it isn't clobbered by setproctitle() emulation */
	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
	for (i = 0; i < ac; i++)
		saved_av[i] = xstrdup(av[i]);
	saved_av[i] = NULL;
	compat_init_setproctitle(ac, av);
	av = saved_av;
#endif

	/*
	 * Discard other fds that are hanging around. These can cause problem
	 * with backgrounded ssh processes started by ControlPersist.
	 */
	closefrom(STDERR_FILENO + 1);

	/*
	 * Save the original real uid.  It will be needed later (uid-swapping
	 * may clobber the real uid).
	 */
	original_real_uid = getuid();
	original_effective_uid = geteuid();

	/*
	 * Use uid-swapping to give up root privileges for the duration of
	 * option processing.  We will re-instantiate the rights when we are
	 * ready to create the privileged port, and will permanently drop
	 * them when the port has been created (actually, when the connection
	 * has been made, as we may need to create the port several times).
	 */
	PRIV_END;

#ifdef HAVE_SETRLIMIT
	/* If we are installed setuid root be careful to not drop core. */
	if (original_real_uid != original_effective_uid) {
		struct rlimit rlim;
		rlim.rlim_cur = rlim.rlim_max = 0;
		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
			fatal("setrlimit failed: %.100s", strerror(errno));
	}
#endif
	/* Get user data. */
	pw = getpwuid(original_real_uid);
	if (!pw) {
		logit("You don't exist, go away!");
		exit(255);
	}
	/* Take a copy of the returned structure. */
	pw = pwcopy(pw);

	/*
	 * Set our umask to something reasonable, as some files are created
	 * with the default umask.  This will make them world-readable but
	 * writable only by the owner, which is ok for all files for which we
	 * don't set the modes explicitly.
	 */
	umask(022);

	/*
	 * Initialize option structure to indicate that no values have been
	 * set.
	 */
	initialize_options(&options);

	/* Parse command-line arguments. */
	host = NULL;
	use_syslog = 0;
	argv0 = av[0];

 again:
	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
	    "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
		switch (opt) {
		case '1':
			options.protocol = SSH_PROTO_1;
			break;
		case '2':
			options.protocol = SSH_PROTO_2;
			break;
		case '4':
			options.address_family = AF_INET;
			break;
		case '6':
			options.address_family = AF_INET6;
			break;
		case 'n':
			stdin_null_flag = 1;
			break;
		case 'f':
			fork_after_authentication_flag = 1;
			stdin_null_flag = 1;
			break;
		case 'x':
			options.forward_x11 = 0;
			break;
		case 'X':
			options.forward_x11 = 1;
			break;
		case 'y':
			use_syslog = 1;
			break;
		case 'Y':
			options.forward_x11 = 1;
			options.forward_x11_trusted = 1;
			break;
		case 'g':
			options.gateway_ports = 1;
			break;
		case 'O':
			if (stdio_forward_host != NULL)
				fatal("Cannot specify multiplexing "
				    "command with -W");
			else if (muxclient_command != 0)
				fatal("Multiplexing command already specified");
			if (strcmp(optarg, "check") == 0)
				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
			else if (strcmp(optarg, "forward") == 0)
				muxclient_command = SSHMUX_COMMAND_FORWARD;
			else if (strcmp(optarg, "exit") == 0)
				muxclient_command = SSHMUX_COMMAND_TERMINATE;
			else if (strcmp(optarg, "stop") == 0)
				muxclient_command = SSHMUX_COMMAND_STOP;
			else if (strcmp(optarg, "cancel") == 0)
				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
			else
				fatal("Invalid multiplex command.");
			break;
		case 'P':	/* deprecated */
			options.use_privileged_port = 0;
			break;
		case 'a':
			options.forward_agent = 0;
			break;
		case 'A':
			options.forward_agent = 1;
			break;
		case 'k':
			options.gss_deleg_creds = 0;
			break;
		case 'K':
			options.gss_authentication = 1;
			options.gss_deleg_creds = 1;
			break;
		case 'i':
			if (stat(optarg, &st) < 0) {
				fprintf(stderr, "Warning: Identity file %s "
				    "not accessible: %s.\n", optarg,
				    strerror(errno));
				break;
			}
			if (options.num_identity_files >=
			    SSH_MAX_IDENTITY_FILES)
				fatal("Too many identity files specified "
				    "(max %d)", SSH_MAX_IDENTITY_FILES);
			options.identity_files[options.num_identity_files++] =
			    xstrdup(optarg);
			break;
		case 'I':
#ifdef ENABLE_PKCS11
			options.pkcs11_provider = xstrdup(optarg);
#else
			fprintf(stderr, "no support for PKCS#11.\n");
#endif
			break;
		case 't':
			if (options.request_tty == REQUEST_TTY_YES)
				options.request_tty = REQUEST_TTY_FORCE;
			else
				options.request_tty = REQUEST_TTY_YES;
			break;
		case 'v':
			if (debug_flag == 0) {
				debug_flag = 1;
				options.log_level = SYSLOG_LEVEL_DEBUG1;
			} else {
				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
					options.log_level++;
				break;
			}
			/* FALLTHROUGH */
		case 'V':
			fprintf(stderr, "%s, %s\n",
			    SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
			if (opt == 'V')
				exit(0);
			break;
		case 'w':
			if (options.tun_open == -1)
				options.tun_open = SSH_TUNMODE_DEFAULT;
			options.tun_local = a2tun(optarg, &options.tun_remote);
			if (options.tun_local == SSH_TUNID_ERR) {
				fprintf(stderr,
				    "Bad tun device '%s'\n", optarg);
				exit(255);
			}
			break;
		case 'W':
			if (stdio_forward_host != NULL)
				fatal("stdio forward already specified");
			if (muxclient_command != 0)
				fatal("Cannot specify stdio forward with -O");
			if (parse_forward(&fwd, optarg, 1, 0)) {
				stdio_forward_host = fwd.listen_host;
				stdio_forward_port = fwd.listen_port;
				xfree(fwd.connect_host);
			} else {
				fprintf(stderr,
				    "Bad stdio forwarding specification '%s'\n",
				    optarg);
				exit(255);
			}
			options.request_tty = REQUEST_TTY_NO;
			no_shell_flag = 1;
			options.clear_forwardings = 1;
			options.exit_on_forward_failure = 1;
			break;
		case 'q':
			options.log_level = SYSLOG_LEVEL_QUIET;
			break;
		case 'e':
			if (optarg[0] == '^' && optarg[2] == 0 &&
			    (u_char) optarg[1] >= 64 &&
			    (u_char) optarg[1] < 128)
				options.escape_char = (u_char) optarg[1] & 31;
			else if (strlen(optarg) == 1)
				options.escape_char = (u_char) optarg[0];
			else if (strcmp(optarg, "none") == 0)
				options.escape_char = SSH_ESCAPECHAR_NONE;
			else {
				fprintf(stderr, "Bad escape character '%s'.\n",
				    optarg);
				exit(255);
			}
			break;
		case 'c':
			if (ciphers_valid(optarg)) {
				/* SSH2 only */
				options.ciphers = xstrdup(optarg);
				options.cipher = SSH_CIPHER_INVALID;
			} else {
				/* SSH1 only */
				options.cipher = cipher_number(optarg);
				if (options.cipher == -1) {
					fprintf(stderr,
					    "Unknown cipher type '%s'\n",
					    optarg);
					exit(255);
				}
				if (options.cipher == SSH_CIPHER_3DES)
					options.ciphers = "3des-cbc";
				else if (options.cipher == SSH_CIPHER_BLOWFISH)
					options.ciphers = "blowfish-cbc";
				else
					options.ciphers = (char *)-1;
			}
			break;
		case 'm':
			if (mac_valid(optarg))
				options.macs = xstrdup(optarg);
			else {
				fprintf(stderr, "Unknown mac type '%s'\n",
				    optarg);
				exit(255);
			}
			break;
		case 'M':
			if (options.control_master == SSHCTL_MASTER_YES)
				options.control_master = SSHCTL_MASTER_ASK;
			else
				options.control_master = SSHCTL_MASTER_YES;
			break;
		case 'p':
			options.port = a2port(optarg);
			if (options.port <= 0) {
				fprintf(stderr, "Bad port '%s'\n", optarg);
				exit(255);
			}
			break;
		case 'l':
			options.user = optarg;
			break;

		case 'L':
			if (parse_forward(&fwd, optarg, 0, 0))
				add_local_forward(&options, &fwd);
			else {
				fprintf(stderr,
				    "Bad local forwarding specification '%s'\n",
				    optarg);
				exit(255);
			}
			break;

		case 'R':
			if (parse_forward(&fwd, optarg, 0, 1)) {
				add_remote_forward(&options, &fwd);
			} else {
				fprintf(stderr,
				    "Bad remote forwarding specification "
				    "'%s'\n", optarg);
				exit(255);
			}
			break;

		case 'D':
			if (parse_forward(&fwd, optarg, 1, 0)) {
				add_local_forward(&options, &fwd);
			} else {
				fprintf(stderr,
				    "Bad dynamic forwarding specification "
				    "'%s'\n", optarg);
				exit(255);
			}
			break;

		case 'C':
			options.compression = 1;
			break;
		case 'N':
			no_shell_flag = 1;
			options.request_tty = REQUEST_TTY_NO;
			break;
		case 'T':
			options.request_tty = REQUEST_TTY_NO;
			break;
		case 'o':
			dummy = 1;
			line = xstrdup(optarg);
			if (process_config_line(&options, host ? host : "",
			    line, "command-line", 0, &dummy) != 0)
				exit(255);
			xfree(line);
			break;
		case 's':
			subsystem_flag = 1;
			break;
		case 'S':
			if (options.control_path != NULL)
				free(options.control_path);
			options.control_path = xstrdup(optarg);
			break;
		case 'b':
			options.bind_address = optarg;
			break;
		case 'F':
			config = optarg;
			break;
		default:
			usage();
		}
	}

	ac -= optind;
	av += optind;

	if (ac > 0 && !host) {
		if (strrchr(*av, '@')) {
			p = xstrdup(*av);
			cp = strrchr(p, '@');
			if (cp == NULL || cp == p)
				usage();
			options.user = p;
			*cp = '\0';
			host = ++cp;
		} else
			host = *av;
		if (ac > 1) {
			optind = optreset = 1;
			goto again;
		}
		ac--, av++;
	}

	/* Check that we got a host name. */
	if (!host)
		usage();

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	/* Initialize the command to execute on remote host. */
	buffer_init(&command);

	if (options.request_tty == REQUEST_TTY_YES ||
	    options.request_tty == REQUEST_TTY_FORCE)
		tty_flag = 1;

	/*
	 * Save the command to execute on the remote host in a buffer. There
	 * is no limit on the length of the command, except by the maximum
	 * packet size.  Also sets the tty flag if there is no command.
	 */
	if (!ac) {
		/* No command specified - execute shell on a tty. */
		tty_flag = options.request_tty != REQUEST_TTY_NO;
		if (subsystem_flag) {
			fprintf(stderr,
			    "You must specify a subsystem to invoke.\n");
			usage();
		}
	} else {
		/* A command has been specified.  Store it into the buffer. */
		for (i = 0; i < ac; i++) {
			if (i)
				buffer_append(&command, " ", 1);
			buffer_append(&command, av[i], strlen(av[i]));
		}
	}

	/* Cannot fork to background if no command. */
	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
	    !no_shell_flag)
		fatal("Cannot fork into background without a command "
		    "to execute.");

	/* Allocate a tty by default if no command specified. */
	if (buffer_len(&command) == 0)
		tty_flag = options.request_tty != REQUEST_TTY_NO;

	/* Force no tty */
	if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
		tty_flag = 0;
	/* Do not allocate a tty if stdin is not a tty. */
	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
	    options.request_tty != REQUEST_TTY_FORCE) {
		if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
			logit("Pseudo-terminal will not be allocated because "
			    "stdin is not a terminal.");
		tty_flag = 0;
	}

	/*
	 * Initialize "log" output.  Since we are the client all output
	 * actually goes to stderr.
	 */
	log_init(argv0,
	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
	    SYSLOG_FACILITY_USER, !use_syslog);

	/*
	 * Read per-user configuration file.  Ignore the system wide config
	 * file if the user specifies a config file on the command line.
	 */
	if (config != NULL) {
		if (!read_config_file(config, host, &options, 0))
			fatal("Can't open user config file %.100s: "
			    "%.100s", config, strerror(errno));
	} else {
		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
		    _PATH_SSH_USER_CONFFILE);
		if (r > 0 && (size_t)r < sizeof(buf))
			(void)read_config_file(buf, host, &options, 1);

		/* Read systemwide configuration file after user config. */
		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
		    &options, 0);
	}

	/* Fill configuration defaults. */
	fill_default_options(&options);

	channel_set_af(options.address_family);

	/* reinit */
	log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);

	seed_rng();

	if (options.user == NULL)
		options.user = xstrdup(pw->pw_name);

	/* Get default port if port has not been set. */
	if (options.port == 0) {
		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
		options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
	}

	/* preserve host name given on command line for %n expansion */
	host_arg = host;
	if (options.hostname != NULL) {
		host = percent_expand(options.hostname,
		    "h", host, (char *)NULL);
	}

	if (gethostname(thishost, sizeof(thishost)) == -1)
		fatal("gethostname: %s", strerror(errno));
	strlcpy(shorthost, thishost, sizeof(shorthost));
	shorthost[strcspn(thishost, ".")] = '\0';
	snprintf(portstr, sizeof(portstr), "%d", options.port);

	if (options.local_command != NULL) {
		debug3("expanding LocalCommand: %s", options.local_command);
		cp = options.local_command;
		options.local_command = percent_expand(cp, "d", pw->pw_dir,
		    "h", host, "l", thishost, "n", host_arg, "r", options.user,
		    "p", portstr, "u", pw->pw_name, "L", shorthost,
		    (char *)NULL);
		debug3("expanded LocalCommand: %s", options.local_command);
		xfree(cp);
	}

	/* force lowercase for hostkey matching */
	if (options.host_key_alias != NULL) {
		for (p = options.host_key_alias; *p; p++)
			if (isupper(*p))
				*p = (char)tolower(*p);
	}

	if (options.proxy_command != NULL &&
	    strcmp(options.proxy_command, "none") == 0) {
		xfree(options.proxy_command);
		options.proxy_command = NULL;
	}
	if (options.control_path != NULL &&
	    strcmp(options.control_path, "none") == 0) {
		xfree(options.control_path);
		options.control_path = NULL;
	}

	if (options.control_path != NULL) {
		cp = tilde_expand_filename(options.control_path,
		    original_real_uid);
		xfree(options.control_path);
		options.control_path = percent_expand(cp, "h", host,
		    "l", thishost, "n", host_arg, "r", options.user,
		    "p", portstr, "u", pw->pw_name, "L", shorthost,
		    (char *)NULL);
		xfree(cp);
	}
	if (muxclient_command != 0 && options.control_path == NULL)
		fatal("No ControlPath specified for \"-O\" command");
	if (options.control_path != NULL)
		muxclient(options.control_path);

	timeout_ms = options.connection_timeout * 1000;

	/* Open a connection to the remote host. */
	if (ssh_connect(host, &hostaddr, options.port,
	    options.address_family, options.connection_attempts, &timeout_ms,
	    options.tcp_keep_alive, 
#ifdef HAVE_CYGWIN
	    options.use_privileged_port,
#else
	    original_effective_uid == 0 && options.use_privileged_port,
#endif
	    options.proxy_command) != 0)
		exit(255);

	if (timeout_ms > 0)
		debug3("timeout: %d ms remain after connect", timeout_ms);

	/*
	 * If we successfully made the connection, load the host private key
	 * in case we will need it later for combined rsa-rhosts
	 * authentication. This must be done before releasing extra
	 * privileges, because the file is only readable by root.
	 * If we cannot access the private keys, load the public keys
	 * instead and try to execute the ssh-keysign helper instead.
	 */
	sensitive_data.nkeys = 0;
	sensitive_data.keys = NULL;
	sensitive_data.external_keysign = 0;
	if (options.rhosts_rsa_authentication ||
	    options.hostbased_authentication) {
		sensitive_data.nkeys = 7;
		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
		    sizeof(Key));
		for (i = 0; i < sensitive_data.nkeys; i++)
			sensitive_data.keys[i] = NULL;

		PRIV_START;
		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
		    _PATH_HOST_KEY_FILE, "", NULL, NULL);
		sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
#ifdef OPENSSL_HAS_ECC
		sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
#endif
		sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
		sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
#ifdef OPENSSL_HAS_ECC
		sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
#endif
		sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
		PRIV_END;

		if (options.hostbased_authentication == 1 &&
		    sensitive_data.keys[0] == NULL &&
		    sensitive_data.keys[4] == NULL &&
		    sensitive_data.keys[5] == NULL &&
		    sensitive_data.keys[6] == NULL) {
			sensitive_data.keys[1] = key_load_cert(
			    _PATH_HOST_DSA_KEY_FILE);
#ifdef OPENSSL_HAS_ECC
			sensitive_data.keys[2] = key_load_cert(
			    _PATH_HOST_ECDSA_KEY_FILE);
#endif
			sensitive_data.keys[3] = key_load_cert(
			    _PATH_HOST_RSA_KEY_FILE);
			sensitive_data.keys[4] = key_load_public(
			    _PATH_HOST_DSA_KEY_FILE, NULL);
#ifdef OPENSSL_HAS_ECC
			sensitive_data.keys[5] = key_load_public(
			    _PATH_HOST_ECDSA_KEY_FILE, NULL);
#endif
			sensitive_data.keys[6] = key_load_public(
			    _PATH_HOST_RSA_KEY_FILE, NULL);
			sensitive_data.external_keysign = 1;
		}
	}
	/*
	 * Get rid of any extra privileges that we may have.  We will no
	 * longer need them.  Also, extra privileges could make it very hard
	 * to read identity files and other non-world-readable files from the
	 * user's home directory if it happens to be on a NFS volume where
	 * root is mapped to nobody.
	 */
	if (original_effective_uid == 0) {
		PRIV_START;
		permanently_set_uid(pw);
	}

	/*
	 * Now that we are back to our own permissions, create ~/.ssh
	 * directory if it doesn't already exist.
	 */
	if (config == NULL) {
		r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
		    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
		if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
#ifdef WITH_SELINUX
			ssh_selinux_setfscreatecon(buf);
#endif
			if (mkdir(buf, 0700) < 0)
				error("Could not create directory '%.200s'.",
				    buf);
#ifdef WITH_SELINUX
			ssh_selinux_setfscreatecon(NULL);
#endif
		}
	}
	/* load options.identity_files */
	load_public_identity_files();

	/* Expand ~ in known host file names. */
	tilde_expand_paths(options.system_hostfiles,
	    options.num_system_hostfiles);
	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);

	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
	signal(SIGCHLD, main_sigchld_handler);

	/* Log into the remote system.  Never returns if the login fails. */
	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
	    options.port, pw, timeout_ms);

	if (packet_connection_is_on_socket()) {
		verbose("Authenticated to %s ([%s]:%d).", host,
		    get_remote_ipaddr(), get_remote_port());
	} else {
		verbose("Authenticated to %s (via proxy).", host);
	}

	/* We no longer need the private host keys.  Clear them now. */
	if (sensitive_data.nkeys != 0) {
		for (i = 0; i < sensitive_data.nkeys; i++) {
			if (sensitive_data.keys[i] != NULL) {
				/* Destroys contents safely */
				debug3("clear hostkey %d", i);
				key_free(sensitive_data.keys[i]);
				sensitive_data.keys[i] = NULL;
			}
		}
		xfree(sensitive_data.keys);
	}
	for (i = 0; i < options.num_identity_files; i++) {
		if (options.identity_files[i]) {
			xfree(options.identity_files[i]);
			options.identity_files[i] = NULL;
		}
		if (options.identity_keys[i]) {
			key_free(options.identity_keys[i]);
			options.identity_keys[i] = NULL;
		}
	}

	exit_status = compat20 ? ssh_session2() : ssh_session();
	packet_close();

	if (options.control_path != NULL && muxserver_sock != -1)
		unlink(options.control_path);

	/* Kill ProxyCommand if it is running. */
	ssh_kill_proxy_command();

	return exit_status;
}
Пример #8
0
// not used
int Timidity_Init(int rate, int format, int channels, int samples)
{
	if (read_config_file(CONFIG_FILE)<0) {
		return(-1);
	}

	/* Set play mode parameters */
	play_mode->rate = rate;
	play_mode->encoding = 0;
	if ( (format&0xFF) == 16 ) {
		play_mode->encoding |= PE_16BIT;
	}
	if ( (format&0x8000) ) {
		play_mode->encoding |= PE_SIGNED;
	}
	if ( channels == 1 ) {
		play_mode->encoding |= PE_MONO;
	} 
	switch (format) {
		case AUDIO_S8:
			s32tobuf = s32tos8;
			break;
		case AUDIO_U8:
			s32tobuf = s32tou8;
			break;
		case AUDIO_S16LSB:
			s32tobuf = s32tos16l;
			break;
		case AUDIO_S16MSB:
			s32tobuf = s32tos16b;
			break;
		case AUDIO_U16LSB:
			s32tobuf = s32tou16l;
			break;
		case AUDIO_U16MSB:
			s32tobuf = s32tou16b;
			break;
		default:
			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Unsupported audio format");
			return(-1);
	}
	AUDIO_BUFFER_SIZE = samples;

	/* Allocate memory for mixing (WARNING:  Memory leak!) */
	resample_buffer = safe_Malloc<sample_t>(AUDIO_BUFFER_SIZE);
	common_buffer = safe_Malloc<sint32>(AUDIO_BUFFER_SIZE*2);

	init_tables();

	if (ctl->open(0, 0)) {
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Couldn't open %s\n", ctl->id_name);
		return(-1);
	}

	if (!control_ratio) {
		control_ratio = play_mode->rate / CONTROLS_PER_SECOND;
		if(control_ratio<1)
			control_ratio=1;
		else if (control_ratio > MAX_CONTROL_RATIO)
			control_ratio=MAX_CONTROL_RATIO;
	}
	if (*def_instr_name)
		set_default_instrument(def_instr_name);
	return(0);
}
Пример #9
0
int Timidity_Init_Simple(int rate, int samples, sint32 encoding)
{
	std::string configfile;
	/* see if the pentagram config file specifies an alternate timidity.cfg */
#ifndef PENTAGRAM_IN_EXULT
	SettingManager* settings = SettingManager::get_instance();
	if (!settings->get("timiditycfg", configfile))
		configfile = CONFIG_FILE;
#else
	config->value("config/audio/midi/timiditycfg", configfile, CONFIG_FILE);
#endif

	if (read_config_file(configfile.c_str())<0) {
		return(-1);
	}

	/* Check to see if the encoding is 'valid' */

	// Only 16 bit can be byte swapped
	if ((encoding & PE_BYTESWAP) && !(encoding & PE_16BIT))
		return(-1);

	// u-Law can only be mono or stereo 
	if ((encoding & PE_ULAW) && (encoding & ~(PE_ULAW|PE_MONO)))
		return(-1);

	/* Set play mode parameters */
	play_mode->rate = rate;
	play_mode->encoding = encoding;
	switch (play_mode->encoding) {
		case 0:
		case PE_MONO:
			s32tobuf = s32tou8;
			break;

		case PE_SIGNED:
		case PE_SIGNED|PE_MONO:
			s32tobuf = s32tos8;
			break;

		case PE_ULAW:
		case PE_ULAW|PE_MONO:
			s32tobuf = s32toulaw;
			break;

		case PE_16BIT:
		case PE_16BIT|PE_MONO:
			s32tobuf = s32tou16;
			break;

		case PE_16BIT|PE_SIGNED:
		case PE_16BIT|PE_SIGNED|PE_MONO:
			s32tobuf = s32tos16;
			break;

		case PE_BYTESWAP|PE_16BIT:
		case PE_BYTESWAP|PE_16BIT|PE_MONO:
			s32tobuf = s32tou16x;
			break;

		case PE_BYTESWAP|PE_16BIT|PE_SIGNED:
		case PE_BYTESWAP|PE_16BIT|PE_SIGNED|PE_MONO:
			s32tobuf = s32tos16x;
			break;

		default:
			ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Unsupported audio format");
			return(-1);
	}

	AUDIO_BUFFER_SIZE = samples;

	/* Allocate memory for mixing (WARNING:  Memory leak!) */
	resample_buffer = safe_Malloc<sample_t>(AUDIO_BUFFER_SIZE);
	common_buffer = safe_Malloc<sint32>(AUDIO_BUFFER_SIZE*2);

	init_tables();

	if (ctl->open(0, 0)) {
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Couldn't open %s\n", ctl->id_name);
		return(-1);
	}

	if (!control_ratio) {
		control_ratio = play_mode->rate / CONTROLS_PER_SECOND;
		if(control_ratio<1)
			control_ratio=1;
		else if (control_ratio > MAX_CONTROL_RATIO)
			control_ratio=MAX_CONTROL_RATIO;
	}
	if (*def_instr_name)
		set_default_instrument(def_instr_name);
	return(0);
}
Пример #10
0
int process_arg(int option, const char *name, const char *val, priority_t precedence, arg_pass_t pass)
{
    int count = 0;

    (void) precedence;		/* suppress compiler warning */
    (void) pass;		/* suppress compiler warning */

    switch (option) {
    case '?':
	fprintf(stderr, "Unknown option '%s'.\n", name);
	break;

    case 'd':
	flag = M_DUMP;
	count += 1;
	ds_file = val;
	break;

    case O_CONFIG_FILE:
	read_config_file(val, false, false, PR_COMMAND, longopts_bogoutil);
	/*@fallthrough@*/
	/* fall through to suppress reading config files */

    case 'C':
	suppress_config_file = true;
	break;

    case 'k':
	db_cachesize=(uint) atoi(val);
	break;

    case 'l':
	flag = M_LOAD;
	count += 1;
	ds_file = val;
	break;

    case 'm':
	flag = M_MAINTAIN;
	count += 1;
	ds_file = val;
	break;

    case 'p':
	prob = true;
	/*@fallthrough@*/

    case 'w':
	flag = M_WORD;
	count += 1;
	ds_file = val;
	break;

    case O_DB_PRINT_LEAFPAGE_COUNT:
	flag = M_LEAFPAGES;
	count += 1;
	ds_file = val;
	break;

    case O_DB_PRINT_PAGESIZE:
	flag = M_PAGESIZE;
	count += 1;
	ds_file = val;
	break;

    case 'r':
	onlyprint = true;
    case 'R':
	flag = M_ROBX;
	count += 1;
	ds_file = val;
	break;

    case 'u':
	upgrade_wordlist_version = true;
	flag = M_MAINTAIN;
	count += 1;
	ds_file = val;
	break;

    case 'v':
	verbose++;
	break;

    case ':':
	fprintf(stderr, "Option %s requires an argument.\n", name);
	exit(EX_ERROR);

    case 'h':
	help(stdout);
	exit(EX_OK);

    case 'H':
	flag = M_HIST;
	count += 1;
	ds_file = val;
	break;

    case 'V':
	print_version();
	exit(EX_OK);

    case 'x':
	set_debug_mask(val);
	break;

    case 'X':
	set_bogotest(val);
	break;

    case 'a':
	maintain = true;
	thresh_date = string_to_date(val);
	break;

    case 'c':
	maintain = true;
	thresh_count = (uint) atoi(val);
	break;

    case 's':
    {
	unsigned long mi, ma;

	maintain = true;
	    
	if (2 == sscanf(val, "%lu,%lu", &mi, &ma)) {
	    size_min = mi;
	    size_max = ma;
	} else {
	    fprintf(stderr, "syntax error in argument \"%s\" of -s\n.",
		    val);
	    exit(EX_ERROR);
	}
    }
    break;

    case 'n':
	maintain = true;
	replace_nonascii_characters ^= true;
	break;

    case 'y':		/* date as YYYYMMDD */
    {
	YYYYMMDD date = string_to_date(val);
	maintain = true;
	if (date != 0 && date < 19990000) {
	    fprintf(stderr, "Date format for '-y' option is YYYYMMDD\n");
	    exit(EX_ERROR);
	}
	set_date( date );
	break;
    }

    case 'I':
	fpin = fopen(val, "r");
	if (fpin == NULL) {
	    fprintf(stderr, "Can't read file '%s'\n", val);
	    exit(EX_ERROR);
	}
	break;

    case 'O':
	fpo = fopen(val, "wt");
	if (fpo == NULL) {
	    fprintf(stderr, "Can't write file '%s'\n", val);
	    exit(EX_ERROR);
	}
	break;

    case 'D':
	dbgout = stdout;
	break;

    case O_DB_VERIFY:
	flag = M_VERIFY;
	count += 1;
	ds_file = val;
	break;

    case O_UNICODE:
	encoding = str_to_bool(val) ? E_UNICODE : E_RAW;
	break;

    case O_MAX_TOKEN_LEN:
	max_token_len = atoi(val);
	break;

    case O_MIN_TOKEN_LEN:
	min_token_len = atoi(val);
	break;

    case O_MAX_MULTI_TOKEN_LEN:
	max_multi_token_len=atoi(val);
	break;

    case O_MULTI_TOKEN_COUNT:
	multi_token_count=atoi(val);
	break;

    default:
	if (!dsm_options_bogoutil(option, &flag, &count, &ds_file, name, val)) {
	    fprintf(stderr, "Invalid option '%s'\n", name);
	    exit(EX_ERROR);
	}
    }

    return count;
}
Пример #11
0
/* Main */
int
main(int argc, char *argv[])
{
	int					 n, detach, sock;
	socklen_t				 size;
	struct sigaction			 sa;
	struct sockaddr_hci			 addr;
	struct ng_btsocket_hci_raw_filter	 filter;
	char					 buffer[HCSECD_BUFFER_SIZE];
	ng_hci_event_pkt_t			*event = NULL;

	detach = 1;

	while ((n = getopt(argc, argv, "df:h")) != -1) {
		switch (n) {
		case 'd':
			detach = 0;
			break;

		case 'f':
			config_file = optarg;
			break;

		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	if (config_file == NULL)
		usage();
		/* NOT REACHED */

	if (getuid() != 0)
		errx(1, "** ERROR: You should run %s as privileged user!",
			HCSECD_IDENT);

	/* Set signal handlers */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sigint;
	sa.sa_flags = SA_NOCLDWAIT;
	if (sigaction(SIGINT, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGINT)");
	if (sigaction(SIGTERM, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGINT)");

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sighup;
	if (sigaction(SIGHUP, &sa, NULL) < 0)
		err(1, "Could not sigaction(SIGHUP)");

	/* Open socket and set filter */
	sock = socket(PF_BLUETOOTH, SOCK_RAW, BLUETOOTH_PROTO_HCI);
	if (sock < 0)
		err(1, "Could not create HCI socket");

	memset(&filter, 0, sizeof(filter));
	bit_set(filter.event_mask, NG_HCI_EVENT_PIN_CODE_REQ - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_LINK_KEY_REQ - 1);
	bit_set(filter.event_mask, NG_HCI_EVENT_LINK_KEY_NOTIFICATION - 1);

	if (setsockopt(sock, SOL_HCI_RAW, SO_HCI_RAW_FILTER,
			(void * const) &filter, sizeof(filter)) < 0)
		err(1, "Could not set HCI socket filter");

	if (detach && daemon(0, 0) < 0)
		err(1, "Could not daemon()ize");

	openlog(HCSECD_IDENT, LOG_NDELAY|LOG_PERROR|LOG_PID, LOG_DAEMON);

	read_config_file();
	read_keys_file();

	if (detach) {
		FILE	*pid = NULL;

		if ((pid = fopen(HCSECD_PIDFILE, "w")) == NULL) {
			syslog(LOG_ERR, "Could not create PID file %s. %s (%d)",
					HCSECD_PIDFILE, strerror(errno), errno);
			exit(1);
		}

		fprintf(pid, "%d", getpid());
		fclose(pid);
	}

	event = (ng_hci_event_pkt_t *) buffer;
	while (!done) {
		size = sizeof(addr);
		n = recvfrom(sock, buffer, sizeof(buffer), 0,
				(struct sockaddr *) &addr, &size);
		if (n < 0) {
			if (errno == EINTR)
				continue;

			syslog(LOG_ERR, "Could not receive from HCI socket. " \
					"%s (%d)", strerror(errno), errno);
			exit(1);
		}

		if (event->type != NG_HCI_EVENT_PKT) {
			syslog(LOG_ERR, "Received unexpected HCI packet, " \
					"type=%#x", event->type);
			continue;
		}

		switch (event->event) {
		case NG_HCI_EVENT_PIN_CODE_REQ:
			process_pin_code_request_event(sock, &addr,
							(bdaddr_p)(event + 1));
			break;

		case NG_HCI_EVENT_LINK_KEY_REQ:
			process_link_key_request_event(sock, &addr,
							(bdaddr_p)(event + 1));
			break;

		case NG_HCI_EVENT_LINK_KEY_NOTIFICATION:
			process_link_key_notification_event(sock, &addr,
				(ng_hci_link_key_notification_ep *)(event + 1));
			break;

		default:
			syslog(LOG_ERR, "Received unexpected HCI event, " \
					"event=%#x", event->event);
			break;
		}
	}

	if (detach)
		if (remove(HCSECD_PIDFILE) < 0)
			syslog(LOG_ERR, "Could not remove PID file %s. %s (%d)",
					HCSECD_PIDFILE, strerror(errno), errno);

	dump_keys_file();
	clean_config();
	closelog();
	close(sock);

	return (0);
}
Пример #12
0
int main(int argc, char **argv){
	int result=OK;
	int x;
	char buffer[MAX_INPUT_BUFFER];
#ifdef HAVE_SSL
	DH *dh;
#endif

	result=process_arguments(argc,argv);

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE){

		printf("\n");
		printf("NRPE - Nagios Remote Plugin Executor\n");
		printf("Copyright (c) 1999-2003 Ethan Galstad ([email protected])\n");
		printf("Version: %s\n",PROGRAM_VERSION);
		printf("Last Modified: %s\n",MODIFICATION_DATE);
		printf("License: GPL with exemptions (-l for more info)\n");
#ifdef HAVE_SSL
		printf("SSL/TLS Available: Anonymous DH Mode, OpenSSL 0.9.6 or higher required\n");
#endif
		printf("\n");
#ifdef ENABLE_COMMAND_ARGUMENTS
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - COMMAND ARGUMENTS ARE SUPPORTED! **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
	        }

	if(show_license==TRUE)
		display_license();

	else if(result!=OK || show_help==TRUE){

		printf("Usage: nrpe -c <config_file> <mode>\n");
		printf("\n");
		printf("Options:\n");
		printf(" <config_file> = Name of config file to use\n");
		printf(" <mode>        = One of the following two operating modes:\n");  
		printf("   -i          =    Run as a service under inetd or xinetd\n");
		printf("   -d          =    Run as a standalone daemon\n");
		printf("\n");
		printf("Notes:\n");
		printf("This program is designed to process requests from the check_nrpe\n");
		printf("plugin on the host(s) running Nagios.  It can run as a service\n");
		printf("under inetd or xinetd (read the docs for info on this), or as a\n");
		printf("standalone daemon. Once a request is received from an authorized\n");
		printf("host, NRPE will execute the command/plugin (as defined in the\n");
		printf("config file) and return the plugin output and return code to the\n");
		printf("check_nrpe plugin.\n");
		printf("\n");
		}

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE)
		exit(STATE_UNKNOWN);


	/* open a connection to the syslog facility */
        openlog("nrpe",LOG_PID,LOG_DAEMON); 

	/* read the config file */
	result=read_config_file(config_file);	

	/* exit if there are errors... */
	if(result==ERROR){
		syslog(LOG_ERR,"Config file '%s' contained errors, bailing out...",config_file);
		return STATE_CRITICAL;
		}

	/* initialize macros */
	for(x=0;x<MAX_COMMAND_ARGUMENTS;x++)
		macro_argv[x]=NULL;

        /* generate the CRC 32 table */
        generate_crc32_table();

#ifdef HAVE_SSL
	/* initialize SSL */
	if(use_ssl==TRUE){
		SSL_library_init();
		SSLeay_add_ssl_algorithms();
		meth=SSLv23_server_method();
		SSL_load_error_strings();
		if((ctx=SSL_CTX_new(meth))==NULL){
			syslog(LOG_ERR,"Error: could not create SSL context.\n");
			exit(STATE_CRITICAL);
		        }
		/*SSL_CTX_set_cipher_list(ctx,"ALL");*/
		SSL_CTX_set_cipher_list(ctx,"ADH");
		dh=get_dh512();
		SSL_CTX_set_tmp_dh(ctx,dh);
		DH_free(dh);
		if(debug==TRUE)
			syslog(LOG_INFO,"INFO: SSL/TLS initialized. All network traffic will be encrypted.");
	        }
	else{
		if(debug==TRUE)
			syslog(LOG_INFO,"INFO: SSL/TLS NOT initialized. Network encryption DISABLED.");
	        }
#endif

	/* wait for connections */
	wait_for_connections();

#ifdef HAVE_SSL
	if(use_ssl==TRUE)
		SSL_CTX_free(ctx);
#endif

	/* We are now running in daemon mode, or the connection handed over by inetd has
	   been completed, so the parent process exits */
        return STATE_OK;
	}
Пример #13
0
/* process all config files in a specific config directory (with directory recursion) */
int read_config_dir(char *dirname){
	char config_file[MAX_FILENAME_LENGTH];
	DIR *dirp;
	struct dirent *dirfile;
	int result=OK;
	int x;

	/* open the directory for reading */
	dirp=opendir(dirname);
        if(dirp==NULL){
		syslog(LOG_ERR,"Could not open config directory '%s' for reading.\n",dirname);
		return ERROR;
	        }

	/* process all files in the directory... */
	while((dirfile=readdir(dirp))!=NULL){

		/* process this if it's a config file... */
		x=strlen(dirfile->d_name);
		if(x>4 && !strcmp(dirfile->d_name+(x-4),".cfg")){

#ifdef _DIRENT_HAVE_D_TYPE
			/* only process normal files */
			if(dirfile->d_type!=DT_REG)
				continue;
#endif

			/* create the full path to the config file */
			snprintf(config_file,sizeof(config_file)-1,"%s/%s",dirname,dirfile->d_name);
			config_file[sizeof(config_file)-1]='\x0';

			/* process the config file */
			result=read_config_file(config_file);

			/* break out if we encountered an error */
			if(result==ERROR)
				break;
		        }

#ifdef _DIRENT_HAVE_D_TYPE
		/* recurse into subdirectories... */
		if(dirfile->d_type==DT_DIR){

			/* ignore current, parent and hidden directory entries */
			if(dirfile->d_name[0]=='.')
				continue;

			/* create the full path to the config directory */
			snprintf(config_file,sizeof(config_file)-1,"%s/%s",dirname,dirfile->d_name);
			config_file[sizeof(config_file)-1]='\x0';

			/* process the config directory */
			result=read_config_dir(config_file);

			/* break out if we encountered an error */
			if(result==ERROR)
				break;
		        }
#endif
		}

	closedir(dirp);

	return result;
        }
Пример #14
0
/* read in the configuration file */
int read_config_file(char *filename){
	FILE *fp;
	char config_file[MAX_FILENAME_LENGTH];
	char input_buffer[MAX_INPUT_BUFFER];
	char *temp_buffer;
	char *varname;
	char *varvalue;
	int line;


	/* open the config file for reading */
	fp=fopen(filename,"r");

	/* exit if we couldn't open the config file */
	if(fp==NULL){
		syslog(LOG_ERR,"Unable to open config file '%s' for reading\n",filename);
		return ERROR;
	        }

	line=0;
	while(fgets(input_buffer,MAX_INPUT_BUFFER-1,fp)){

		line++;

		/* skip comments and blank lines */
		if(input_buffer[0]=='#')
			continue;
		if(input_buffer[0]=='\x0')
			continue;
		if(input_buffer[0]=='\n')
			continue;

		/* get the variable name */
		varname=strtok(input_buffer,"=");
		if(varname==NULL){
			syslog(LOG_ERR,"No variable name specified in config file '%s' - Line %d\n",filename,line);
			return ERROR;
		        }

		/* get the variable value */
		varvalue=strtok(NULL,"\n");
		if(varvalue==NULL){
			syslog(LOG_ERR,"No variable value specified in config file '%s' - Line %d\n",filename,line);
			return ERROR;
		        }

		/* allow users to specify directories to recurse into for config files */
		else if(!strcmp(varname,"include_dir")){

			strncpy(config_file,varvalue,sizeof(config_file)-1);
			config_file[sizeof(config_file)-1]='\x0';

			/* strip trailing / if necessary */
			if(config_file[strlen(config_file)-1]=='/')
				config_file[strlen(config_file)-1]='\x0';

			/* process the config directory... */
			if(read_config_dir(config_file)==ERROR)
				break;
		        }

		/* allow users to specify individual config files to include */
		else if(!strcmp(varname,"include") || !strcmp(varname,"include_file")){

			/* process the config file... */
			if(read_config_file(varvalue)==ERROR)
				break;
		        }

		else if(!strcmp(varname,"server_port")){
			server_port=atoi(varvalue);
			if(server_port<1024){
				syslog(LOG_ERR,"Invalid port number specified in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
		        }

		else if(!strcmp(varname,"server_address")){
                        strncpy(server_address,varvalue,sizeof(server_address) - 1);
                        server_address[sizeof(server_address)-1]='\0';
                        }

		else if(!strcmp(varname,"allowed_hosts")){
			if(strlen(input_buffer)>sizeof(allowed_hosts)){
				syslog(LOG_ERR,"Allowed hosts list too long in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
			strncpy(allowed_hosts,varvalue,sizeof(allowed_hosts));
			allowed_hosts[sizeof(allowed_hosts)-1]='\x0';
		        }

		else if(strstr(input_buffer,"command[")){
			temp_buffer=strtok(varname,"[");
			temp_buffer=strtok(NULL,"]");
			if(temp_buffer==NULL){
				syslog(LOG_ERR,"Invalid command specified in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
			add_command(temp_buffer,varvalue);
		        }

		else if(strstr(input_buffer,"debug")){
			debug=atoi(varvalue);
			if(debug>0)
				debug=TRUE;
			else 
				debug=FALSE;
		        }

                else if(!strcmp(varname,"nrpe_user"))
			nrpe_user=strdup(varvalue);

                else if(!strcmp(varname,"nrpe_group"))
			nrpe_group=strdup(varvalue);
		
		else if(!strcmp(varname,"dont_blame_nrpe"))
			allow_arguments=(atoi(varvalue)==1)?TRUE:FALSE;

 		else if(!strcmp(varname,"command_timeout")){
			command_timeout=atoi(varvalue);
			if(command_timeout<1){
				syslog(LOG_ERR,"Invalid command_timeout specified in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
		        }

		else{
			syslog(LOG_ERR,"Unknown option specified in config file '%s' - Line %d\n",filename,line);

			return ERROR;
		        }

	        }


	/* close the config file */
	fclose(fp);

	return OK;
	}
Пример #15
0
int main(int argc, char **argv)
{
	/* command line options */
	int c;

	/* function-local options */
	int foreground = FALSE;
	char *pid_file = NULL;

	/* config file */
	char *configFile = NULL;

	/* config file parsing temp strings */
	char tmp[MAX_CONFIG_STRING_SIZE], *tmpstr;

	/* open a connection to the syslog daemon */
	openlog("pptpd", LOG_PID, PPTP_FACILITY);
	syslog(LOG_ERR, "MGR: Config file not found!");

	/* process command line options */
	while (1) {
		int option_index = 0;
#ifdef BCRELAY
		char *optstring = "b:c:de:fhil:o:p:s:t:T:vwC:Dk";
#else
		char *optstring = "c:de:fhil:o:p:s:t:T:vwC:Dk";
#endif

		static struct option long_options[] =
		{
#ifdef BCRELAY
			{"bcrelay", 1, 0, 0},
#endif
			{"conf", 1, 0, 'c'},
			{"debug", 0, 0, 'd'},
			{"ppp", 1, 0, 'e'},
			{"fg", 0, 0, 'f'},
			{"help", 0, 0, 'h'},
			{"noipparam", 0, 0, 'i'},
			{"listen", 1, 0, 'l'},
			{"option", 1, 0, 'o'},
			{"pidfile", 1, 0, 'p'},
			{"speed", 1, 0, 's'},
			{"stimeout", 1, 0, 't'},
			{"ptimeout", 1, 0, 'T'},
			{"version", 0, 0, 'v'},
			{"logwtmp", 0, 0, 'w'},
			{"connections", 1, 0, 'C'},
			{"delegate", 0, 0, 'D'},
			{"keep", 0, 0, 'k'},
			{0, 0, 0, 0}
		};

		c = getopt_long(argc, argv, optstring, long_options, &option_index);
		if (c == -1)
			break;
		/* convert long options to short form */
		if (c == 0)
#ifdef BCRELAY
			c = "bcdefhilopstvwCDk"[option_index];
#else
			c = "cdefhilopstvwCDk"[option_index];
#endif
		switch (c) {
#ifdef BCRELAY
		case 'b': /* --bcrelay */
			if (bcrelay) free(bcrelay);
			bcrelay = strdup(optarg);
			break;
#endif

		case 'l': /* --listen */
			tmpstr = lookup(optarg);
			if (!tmpstr) {
				syslog(LOG_ERR, "MGR: Invalid listening address: %s!", optarg);
				return 1;
			}
			if (bindaddr) free(bindaddr);
			bindaddr = strdup(tmpstr);
			break;

		case 'h': /* --help */
			showusage(argv[0]);
			return 0;

		case 'i': /* --noipparam */
			pptp_noipparam = TRUE;
			break;

		case 'e': /* --ppp */
			if (ppp_binary) free(ppp_binary);
			ppp_binary = strdup(optarg);
			break;

		case 'd': /* --debug */
			pptp_debug = TRUE;
			break;

		case 'f': /* --fg */
			foreground = TRUE;
			break;

		case 'v': /* --version */
			showversion();
			return 0;

		case 'w': /* --logwtmp */
		        pptp_logwtmp = TRUE;
			break;

		case 'C': /* --connections */
		        pptp_connections = atoi(optarg);
			break;

		case 'D': /* --delegate */
		        pptp_delegate = TRUE;
			break;

		case 'o': /* --option */
			if (pppdoptstr) free(pppdoptstr);
			pppdoptstr = strdup(optarg);
			break;

		case 'p': /* --pidfile */
			if (pid_file) free(pid_file);
			pid_file = strdup(optarg);
			break;

		case 's': /* --speed */
			if (speedstr) free(speedstr);
			speedstr = strdup(optarg);
			break;

		case 't': /* --stimeout */
			pptp_stimeout = atoi(optarg);
			break;

		case 'T': /* --stimeout */
			pptp_ptimeout = atoi(optarg);
			break;
		case 'k': /* --keep */
			keep_connections = 1;
			break;

		case 'c': /* --conf */
			{
				FILE *f;
				if (!(f = fopen(optarg, "r"))) {
					syslog(LOG_ERR, "MGR: Config file not found!");
					return 1;
				}
				fclose(f);
				if(configFile) free(configFile);
				configFile = strdup(optarg);
				break;
			}

		default:
			showusage(argv[0]);
			return 1;
		}
	}

	/* Now that we have all the command line args.. lets open the
	 * conf file and add anything else (remembering not to override
	 * anything since the command line has more privilages :-)
	 */

	if (!configFile)
		configFile = strdup(PPTPD_CONFIG_FILE_DEFAULT);

	if (read_config_file(configFile, CONNECTIONS_KEYWORD, tmp) > 0) {
		pptp_connections = atoi(tmp);
		if (pptp_connections <= 0)
			pptp_connections = CONNECTIONS_DEFAULT;
	}

	slot_init(pptp_connections);

	if (!pptp_debug && read_config_file(configFile, DEBUG_KEYWORD, tmp) > 0)
		pptp_debug = TRUE;

#ifdef BCRELAY
	if (!bcrelay && read_config_file(configFile, BCRELAY_KEYWORD, tmp) > 0) 
		bcrelay = strdup(tmp);
#endif

	if (!pptp_stimeout && read_config_file(configFile, STIMEOUT_KEYWORD, tmp) > 0) {
		pptp_stimeout = atoi(tmp);
		if (pptp_stimeout <= 0)
			pptp_stimeout = STIMEOUT_DEFAULT;
	}

	if (!pptp_ptimeout && read_config_file(configFile, PTIMEOUT_KEYWORD, tmp) > 0) {
		pptp_ptimeout = atoi(tmp);
		if (pptp_ptimeout <= 0)
			pptp_ptimeout = PTIMEOUT_DEFAULT;
	}

	if (!pptp_noipparam && read_config_file(configFile, NOIPPARAM_KEYWORD, tmp) > 0) {
		pptp_noipparam = TRUE;
	}

	if (!bindaddr && read_config_file(configFile, LISTEN_KEYWORD, tmp) > 0) {
		tmpstr = lookup(tmp);
		if(!tmpstr) {
			syslog(LOG_ERR, "MGR: Invalid listening address: %s!", tmp);
			return 1;
		}
		bindaddr = strdup(tmpstr);
	}

	if (!speedstr && read_config_file(configFile, SPEED_KEYWORD, tmp) > 0)
		speedstr = strdup(tmp);

	if (!pppdoptstr && read_config_file(configFile, PPPD_OPTION_KEYWORD, tmp) > 0) {
		pppdoptstr = strdup(tmp);
	}

	if (!ppp_binary && read_config_file(configFile, PPP_BINARY_KEYWORD, tmp) > 0) {
		ppp_binary = strdup(tmp);
	}

	if (!pptp_logwtmp && read_config_file(configFile, LOGWTMP_KEYWORD, tmp) > 0) {
		pptp_logwtmp = TRUE;
	}

	if (!pptp_delegate && read_config_file(configFile, DELEGATE_KEYWORD, tmp) > 0) {
		pptp_delegate = TRUE;
	}

	if (read_config_file(configFile, KEEP_KEYWORD, tmp) > 0) {
		keep_connections = TRUE;
	}

	if (!pid_file)
		pid_file = strdup((read_config_file(configFile, PIDFILE_KEYWORD,
					tmp) > 0) ? tmp : PIDFILE_DEFAULT);

	if (!pptp_delegate) {
		/* NOTE: remote then local, reason can be seen at the end of processIPStr */

		/* grab the remoteip string from the config file */
		if (read_config_file(configFile, REMOTEIP_KEYWORD, tmp) <= 0) {
			/* use "smart" defaults */
			strlcpy(tmp, DEFAULT_REMOTE_IP_LIST, sizeof(tmp));
		}
		processIPStr(REMOTE, tmp);
	
		/* grab the localip string from the config file */
		if (read_config_file(configFile, LOCALIP_KEYWORD, tmp) <= 0) {
			/* use "smart" defaults */
			strlcpy(tmp, DEFAULT_LOCAL_IP_LIST, sizeof(tmp));
		}
		processIPStr(LOCAL, tmp);
	}

	free(configFile);

	/* if not yet set, adopt default PPP binary path */
	if (!ppp_binary) ppp_binary = strdup(PPP_BINARY);
	/* check that the PPP binary is executable */
	if (access(ppp_binary, X_OK) < 0) {
		syslog(LOG_ERR, "MGR: PPP binary %s not executable",
		       ppp_binary);
		return 1;
	}
	/* check that the PPP options file is readable */
	if (pppdoptstr && access(pppdoptstr, R_OK) < 0) {
		syslog(LOG_ERR, "MGR: PPP options file %s not readable",
		       pppdoptstr);
		return 1;
	}
#ifdef BCRELAY
	/* check that the bcrelay binary is executable */
	if (bcrelay && access(BCRELAY_BIN, X_OK) < 0) {
		syslog(LOG_ERR, "MGR: bcrelay binary %s not executable", 
		       BCRELAY_BIN);
		return 1;
	}
#endif

	syslog(LOG_INFO, "accel-pptpd-%s compiled for pppd-%s\n",VERSION, "2.4.2");

	if (!foreground) {
#if HAVE_DAEMON
		closelog();
		freopen("/dev/null", "r", stdin);
		daemon(0, 0);
		/* returns to child only */
		/* pid will have changed */
		openlog("pptpd", LOG_PID, PPTP_FACILITY);
#else	/* !HAVE_DAEMON */
		my_daemon(argc, argv);
		/* returns to child if !HAVE_FORK
		 * never returns if HAVE_FORK (re-execs with -f)
		 */
#endif
	}

#ifdef BCRELAY
      if (bcrelay) {
             syslog(LOG_DEBUG, "CTRL: BCrelay incoming interface is %s", bcrelay);
             /* Launch BCrelay  */
#ifndef HAVE_FORK
             switch(bcrelayfork = vfork()){
#else
             switch(bcrelayfork = fork()){
#endif
             case -1:        /* fork() error */
                   syslog(LOG_ERR, "CTRL: Error forking to exec bcrelay");
                   _exit(1);

             case 0:         /* child */
                   syslog(LOG_DEBUG, "CTRL (BCrelay Launcher): Launching BCrelay with pid %i", bcrelayfork);
                   launch_bcrelay();
                   syslog(LOG_ERR, "CTRL (BCrelay Launcher): Failed to launch BCrelay.");
                   _exit(1);
             }
       } /* End bcrelay */
#endif

#ifdef CONFIG_NETtel
	/* turn the NETtel VPN LED on */
	ledman_cmd(LEDMAN_CMD_ON, LEDMAN_VPN);
#endif
	/* after we have our final pid... */
	log_pid(pid_file);

	/* manage connections until SIGTERM */
	pptp_manager(argc, argv);
	
#ifdef BCRELAY
	if (bcrelayfork > 0) {
		syslog(LOG_DEBUG, "CTRL: Closing child BCrelay with pid %i", bcrelayfork);
		kill(bcrelayfork, SIGTERM);
	}
#endif

	slot_free();
	return 0;
}

static void log_pid(char *pid_file) {
        FILE    *f;
        pid_t   pid;

        pid = getpid();
        if ((f = fopen(pid_file, "w")) == NULL) {
                syslog(LOG_ERR, "PPTPD: failed to open(%s), errno=%d\n",
                        pid_file, errno);
                return;
        }
        fprintf(f, "%d\n", pid);
        fclose(f);
}
Пример #16
0
static int read_config_file(const char *name)
{
	FILE *fp;
	char tmp[1024], *w[MAXWORDS], *cp;
	ToneBank *bank=0;
	int i, j, k, line=0, words;
	static int rcf_count=0;

	if (rcf_count>50)
	{
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
		          "Probable source loop in configuration files");
		return (-1);
	}

	if (!(fp=open_file(name, 1, OF_VERBOSE)))
		return -1;

	while (fgets(tmp, sizeof(tmp), fp))
	{
		line++;
		w[words=0]=strtok(tmp, " \t\r\n\240");
		if (!w[0] || (*w[0]=='#')) continue;
		while (w[words] && (words < MAXWORDS))
			w[++words]=strtok(0," \t\r\n\240");
		if (!strcmp(w[0], "dir"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
				          "%s: line %d: No directory given\n", name, line);
				return -2;
			}
			for (i=1; i<words; i++)
				add_to_pathlist(w[i]);
		}
		else if (!strcmp(w[0], "source"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
				          "%s: line %d: No file name given\n", name, line);
				return -2;
			}
			for (i=1; i<words; i++)
			{
				rcf_count++;
				read_config_file(w[i]);
				rcf_count--;
			}
		}
		else if (!strcmp(w[0], "default"))
		{
			if (words != 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
				          "%s: line %d: Must specify exactly one patch name\n",
				          name, line);
				return -2;
			}
			strncpy(def_instr_name, w[1], 255);
			def_instr_name[255]='\0';
		}
		else if (!strcmp(w[0], "drumset"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
				          "%s: line %d: No drum set number given\n", 
				          name, line);
				return -2;
			}
			i=atoi(w[1]);
			if (i<0 || i>127)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
				          "%s: line %d: Drum set must be between 0 and 127\n",
				          name, line);
				return -2;
			}
			if (!drumset[i])
			{
				drumset[i]=safe_Malloc<ToneBank>();
				memset(drumset[i], 0, sizeof(ToneBank));
			}
			bank=drumset[i];
		}
		else if (!strcmp(w[0], "bank"))
		{
			if (words < 2)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
				          "%s: line %d: No bank number given\n", 
				          name, line);
				return -2;
			}
			i=atoi(w[1]);
			if (i<0 || i>127)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
				          "%s: line %d: Tone bank must be between 0 and 127\n",
				          name, line);
				return -2;
			}
			if (!tonebank[i])
			{
				tonebank[i]=safe_Malloc<ToneBank>();
				memset(tonebank[i], 0, sizeof(ToneBank));
			}
			bank=tonebank[i];
		}
		else {
			if ((words < 2) || (*w[0] < '0' || *w[0] > '9'))
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
				          "%s: line %d: syntax error\n", name, line);
				return -2;
			}
			i=atoi(w[0]);
			if (i<0 || i>127)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
				          "%s: line %d: Program must be between 0 and 127\n",
				          name, line);
				return -2;
			}
			if (!bank)
			{
				ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
				          "%s: line %d: Must specify tone bank or drum set "
				          "before assignment\n",
				          name, line);
				return -2;
			}
			if (bank->tone[i].name)
				free(bank->tone[i].name);
			strcpy((bank->tone[i].name=safe_Malloc<char>(strlen(w[1])+1)),w[1]);
			bank->tone[i].note=bank->tone[i].amp=bank->tone[i].pan=
				bank->tone[i].strip_loop=bank->tone[i].strip_envelope=
				bank->tone[i].strip_tail=-1;

			for (j=2; j<words; j++)
			{
				if (!(cp=strchr(w[j], '=')))
				{
					ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: line %d: bad patch option %s\n",
					          name, line, w[j]);
					return -2;
				}
				*cp++=0;
				if (!strcmp(w[j], "amp"))
				{
					k=atoi(cp);
					if ((k<0 || k>MAX_AMPLIFICATION) || (*cp < '0' || *cp > '9'))
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
						          "%s: line %d: amplification must be between "
						          "0 and %d\n", name, line, MAX_AMPLIFICATION);
						return -2;
					}
					bank->tone[i].amp=k;
				}
				else if (!strcmp(w[j], "note"))
				{
					k=atoi(cp);
					if ((k<0 || k>127) || (*cp < '0' || *cp > '9'))
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
						          "%s: line %d: note must be between 0 and 127\n",
						          name, line);
						return -2;
					}
					bank->tone[i].note=k;
				}
				else if (!strcmp(w[j], "pan"))
				{
					if (!strcmp(cp, "center"))
						k=64;
					else if (!strcmp(cp, "left"))
						k=0;
					else if (!strcmp(cp, "right"))
						k=127;
					else
						k=((atoi(cp)+100) * 100) / 157;
					if ((k<0 || k>127) ||
					    (k==0 && *cp!='-' && (*cp < '0' || *cp > '9')))
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL, 
						          "%s: line %d: panning must be left, right, "
						          "center, or between -100 and 100\n",
						          name, line);
						return -2;
					}
					bank->tone[i].pan=k;
				}
				else if (!strcmp(w[j], "keep"))
				{
					if (!strcmp(cp, "env"))
						bank->tone[i].strip_envelope=0;
					else if (!strcmp(cp, "loop"))
						bank->tone[i].strip_loop=0;
					else
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
						          "%s: line %d: keep must be env or loop\n", name, line);
						return -2;
					}
				}
				else if (!strcmp(w[j], "strip"))
				{
					if (!strcmp(cp, "env"))
						bank->tone[i].strip_envelope=1;
					else if (!strcmp(cp, "loop"))
						bank->tone[i].strip_loop=1;
					else if (!strcmp(cp, "tail"))
						bank->tone[i].strip_tail=1;
					else
					{
						ctl->cmsg(CMSG_ERROR, VERB_NORMAL,
						          "%s: line %d: strip must be env, loop, or tail\n",
						          name, line);
						return -2;
					}
				}
				else
				{
					ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "%s: line %d: bad patch option %s\n",
					          name, line, w[j]);
					return -2;
				}
			}
		}
	}
	if (ferror(fp))
	{
		ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "Can't read from %s\n", name);
		close_file(fp);
		return -2;
	}
	close_file(fp);
	return 0;
}
Пример #17
0
int
main(int argc, char *argv[])
{
  double **sound, **image;
  int i;

  char path[MUT_MAX_PATH_LEN], name[MUT_MAX_NAME_LEN], ext[MUT_MAX_NAME_LEN];

  //=============================
  // parse command line arguments
  //=============================

  if (! mut_parse_cmd_line(argc, argv, arglist, NULL))
  {
    fprintf(stderr, "ASPERES %s\n", version);
    fprintf(stderr, "%s:\n%s.\n", err_1, mut_errmsg(mut_last_error()));
    return 1;
  }

  //==================================
  // check for help or version request
  //==================================
  
  if (help_req)
  {
    print_help();
    return 1;
  }

  if (vers_req)
  {
    print_version();
    return 1;
  }

  //===============
  // set up logging
  //===============

  mut_set_logname(logname);
  mut_setlog(1);
  unlink(logname);
  mut_get_date(date);
  message("ASPERES version %s (%s)", version, date);

  //=================
  // read config file
  //=================

  if (read_config_file(config_file) < 0)
  {
    message("%s %s", err_4, config_file);
    return 1;
  }

  //===============================
  // process command line arguments
  //===============================

  //======= program operation mode =======

  if (prog_mode_s[0] == 0)
  {
    message("%s", err_2);
    return 1;
  }

  if (strcmp(prog_mode_s, "anal") == 0)
    prog_mode = MODE_ANAL;
  else if (strcmp(prog_mode_s, "sine") == 0)
    prog_mode = MODE_SINE_SYNTH;
  else if (strcmp(prog_mode_s, "noise") == 0)
    prog_mode = MODE_NOISE_SYNTH;
  else
  {
    message("%s (%s)", err_3, prog_mode_s);
    return 1;
  }

  //======= file names =======

  if (input_file[0] == 0)
  {
    message("%s", err_5);
    return 1;
  }
      
  if (! mut_fname_split(input_file, path, name, ext))
  {
     message("%s", err_16);
     return 1;
  }

  if (prog_mode == MODE_ANAL)
  {
     if (strcmp(ext, ".wav") != 0)
     {
       message("%s", err_17);
       return 1;
     }
  }
  else
  {
     if (strcmp(ext, ".bmp") != 0)
     {
       message("%s", err_18);
       return 1;
     }
  }
  
  if (output_file[0] == 0) 
  {
    strcpy(output_file, path);
    strcat(output_file, name);
    strcat(output_file, "~");
    
    if (prog_mode == MODE_ANAL)
      strcat(output_file, ".bmp");
    else
      strcat(output_file, ".wav");
  }
 
  //======= WAV sample rate =======

  if (wav_rate_s[0] != 0)
  {
    if (! mut_stoi(wav_rate_s, MUT_BASE_DEC, &wav_rate))
    {
      message("%s '%s'", err_7, wav_rate_s);
      return 1;
    }
  }

  i = 0;
  while (std_wav_rates[i] != -1)
  {
    if (std_wav_rates[i] == wav_rate)
      break;
    else
      i++;
  }
    
  if (std_wav_rates[i] == -1)
  {
    message("'%s' %s", wav_rate_s, err_8);
    return 1;
  }

  //======= frequency limits =======

  if (low_freq_s[0] != 0)
  {
    if (! mut_stof(low_freq_s, &low_freq))
    {
      message("%s '%s'", err_7, low_freq_s);
      return 1;
    }
  }
      
  if (low_freq < MIN_LOW_FREQ || low_freq > MAX_LOW_FREQ)
  {
    message("%s", err_9);
    return 1;
  }

  if (high_freq_s[0] != 0)
  {
    if (! mut_stof(high_freq_s, &high_freq))
    {
      message("%s '%s'", err_7, high_freq_s);
      return 1;
    }
  }

  if (high_freq < MIN_HIGH_FREQ || high_freq > MAX_HIGH_FREQ)
  {
    message("%s", err_10);
    return 1;
  }
      
  //======= resolutions =======

  if (band_per_oct_s[0] != 0)
  {
    if (! mut_stof(band_per_oct_s, &band_per_oct))
    {
      message("%s '%s'", err_7, band_per_oct_s);
      return 1;
    }
  }
      
  if (band_per_oct < MIN_BPO || band_per_oct > MAX_BPO)
  {
    message("%s", err_11);
    return 1;
  }

  if (pix_per_sec_s[0] != 0)
  {
    if (! mut_stof(pix_per_sec_s, &pix_per_sec))
    {
      message("%s '%s'", err_7, pix_per_sec_s);
      return 1;
    }
  }

  if (pix_per_sec < MIN_PPS || pix_per_sec > MAX_PPS)
  {
    message("%s", err_12);
    return 1;
  }
      
  //======= brightness control =======

  if (gamma_corr_s[0] != 0)
  {
    if (! mut_stof(gamma_corr_s, &gamma_corr))
    {
      message("%s '%s'", err_7, gamma_corr_s);
      return 1;
    }
  }

  if (gamma_corr < MIN_GAMMA || gamma_corr > MAX_GAMMA)
  {
    message("%s", err_13);
    return 1;
  }

  //======= image dimensions =======

  if (img_width_s[0] != 0)
  {
    if (! mut_stoi(img_width_s, MUT_BASE_DEC, &img_width))
    {
      message("%s '%s'", err_7, img_width_s);
      return 1;
    }
  }

  if (img_height_s[0] != 0)
  {
    if (! mut_stoi(img_height_s, MUT_BASE_DEC, &img_height))
    {
      message("%s '%s'", err_7, img_height_s);
      return 1;
    }
  }

  //======= miscellaneous parameters =======

  if (use_linear)
    logbase = 1;
  else
    logbase = 2;

  //====================
  // open & create files
  //====================

  infile = fopen(input_file, "rb");
  if (infile == NULL)
  {
    message("%s", err_14);
    return 1;
  }

  outfile = fopen(output_file, "wb");
  if (outfile == NULL)
  {
    fclose(infile);
    message("%s", err_15);
    return 1;
  }

  //===================================
  // perform the requested operation(s)
  //===================================

  srand(time(NULL));

  if (prog_mode == MODE_ANAL)
  {
    message("Sound '%s' to spectrogram '%s'", input_file, output_file);
    sound = wav_in(infile, &channels, &samplecount, &wav_rate);
    setup
    (
      &img_height, samplecount, &wav_rate, &low_freq, &high_freq,
      &pix_per_sec, &band_per_oct, img_width, 0
    );

    start_time = gettime();
    image = anal
            (
              sound[0], samplecount, wav_rate,
              &img_width, img_height, band_per_oct, pix_per_sec, low_freq
            );

    if (gamma_corr != 1.0)
      brightness_control(image, img_height, img_width, 1.0 / gamma_corr);

    bmp_out(outfile, image, img_height, img_width);
  }

  if (prog_mode == MODE_SINE_SYNTH || prog_mode == MODE_NOISE_SYNTH)
  {
    message("Image '%s' to sound '%s'", input_file, output_file);
    sound = calloc(1, sizeof(double *));
    image = bmp_in(infile, &img_height, &img_width);

    setup
    (
      &img_height, samplecount, &wav_rate, &low_freq, &high_freq,
      &pix_per_sec, &band_per_oct, img_width, 1
    );

    if (gamma_corr != 1.0)
      brightness_control(image, img_height, img_width, gamma_corr);

    start_time = gettime();

    if (prog_mode == MODE_SINE_SYNTH)
      sound[0] = synt_sine
                 (
                   image, img_width, img_height, &samplecount, wav_rate,
                   low_freq, pix_per_sec, band_per_oct
                 );
    else
      sound[0] = synt_noise
                 (
                   image, img_width, img_height, &samplecount, wav_rate,
                   low_freq, pix_per_sec, band_per_oct
                 );

    wav_out(outfile, sound, 1, samplecount, wav_rate, WAV_FORMAT);
  }

  end_time = gettime();
  message("Processing time: %.3f s", (double) (end_time - start_time) / 1000.0);

  return 0;
}
/** read the command-line options
 *
 * \return length of modified argv
 *
 * \todo possibly maintain a list of dirs to search??
 */
int
setup_options(int argc, char *argv[])
{
	char *str = NULL;
	int pos, i;

	/* first set up defaults */
	for (i = 0; i < (int) ARRAY_LENGTH(env_vars); ++i)
	{
		if ((str = getenv(env_vars[i].name)))
			*env_vars[i].dest = xstrdup(str);
		else if (strcmp(env_vars[i].name, ENVIRON_SAVEDIR) == 0
			&& (str = get_homedir()))
		{
			size_t len = strlen(str) + strlen(PACKAGE_TARNAME) + 3;

			*env_vars[i].dest = xmalloc(len);
			sprintf(*env_vars[i].dest, "%s/.%s", str, PACKAGE_TARNAME);
			free(str);
		}
		else
			*env_vars[i].dest = xstrdup(env_vars[i].def_val);
	}

	/* set up default values */
	options.want_audio = 1;
	options.want_intro = 1;
	options.want_cheats = 0;
	options.want_fullscreen = 0;
	options.want_debug = 0;
	options.feat_shorter_advanced_training = 0;
	options.feat_random_nauts =0;    //Naut Randomize, Nikakd, 10/8/10
	options.feat_compat_nauts =10;   //Naut Compatibility, Nikakd, 10/8/10
	options.feat_no_cTraining =1;    //No Capsule Training, Nikakd, 10/8/10
	options.feat_no_backup =1;       //No Backup crew required -Leon
	options.cheat_no_damage=0;       //Damaged Equipment Cheat, Nikakd, 10/8/10
	options.feat_random_eq=0;
	options.feat_eq_new_name =0;
	options.cheat_altasOnMoon=0;
	options.cheat_addMaxS=1;
	options.boosterSafety=0;

	fixpath_options();

	/* now try to read config file, if it exists */
	if (read_config_file() < 0)
		/* if not, then write default config template */
		write_default_config();

	/* first pass: command line options */
	for (pos = 1; pos < argc; ++pos)
	{
		str = argv[pos];

		if (str[0] != '-')
			continue;

		if (!str[1])
			continue;

		if (strcmp(str, "--") == 0)
		{
			shift_argv(argv + pos, argc - pos, 1);
			argc--;
			break;
		}

		/* check what option matches */
		if (strcmp(str, "-h") == 0)
			usage(0);
		else if (strcmp(str, "-i") == 0)
			options.want_intro = 0;
		else if (strcmp(str, "-n") == 0)
			options.want_cheats = 1;
		else if (strcmp(str, "-a") == 0)
			options.want_audio = 0;
		else if (strcmp(str, "-f") == 0)
			options.want_fullscreen = 1;
		else if (strcmp(str, "-v") == 0)
			options.want_debug++;
		else
		{
			ERROR2("unknown option %s", str);
			usage(1);
		}

		shift_argv(argv + pos, argc - pos, 1);
		argc--;
		pos--; /* for loop will advance it again */
	}

	/* second pass: variable assignments */
	for (pos = 1; pos < argc; ++pos)
	{
		/** \todo should use PATH_MAX or something similar here */
		char name[32 + 1], *value;
		int offset = 0;
		int fields = 0;

		fields = sscanf(argv[pos], "%32[A-Z_]=%n", name, &offset);

		/* it is unclear whether %n increments return value */
		if (fields < 1)
			continue;

		value = argv[pos] + offset;

		for (i = 0; i < (int) ARRAY_LENGTH(env_vars); ++i)
		{
			if (strcmp(name, env_vars[i].name) == 0)
			{
				free(*env_vars[i].dest);
				*env_vars[i].dest = xstrdup(value);
				break;
			}
		}

		if (i == (int) ARRAY_LENGTH(env_vars))
			WARNING2("unsupported command line variable `%s'", name);

		/* remove matched string from argv */
		shift_argv(argv + pos, argc - pos, 1);

		/*
		 * now we have one fewer arg, pos points to the next arg,
		 * keep it this way after incrementing it on top of the loop
		 */
		pos--;
		argc--;
	}

	fixpath_options();

	return argc;
}
Пример #19
0
int read_config(char *file, int whinge_on_error) {
    void* o;

    return read_config_file(file, whinge_on_error);
}
Пример #20
0
static int parse_params(int argc, char **argv, enc_params *params, param_list *list)
{
    int i, j;
    FILE *config;
    char **file_params;
    int num_file_params;

    char *tmp;
    int cnt;
    
    for (i = 1; i < argc; i++)
    {
      /* Check if parameter is in the list of known parameters */
      for (j = 0; j < list->num; j++)
      {
        if (strcmp(argv[i], list->params[j].name) == 0)
          break;
      }
      if (j == list->num)
      {
        fprintf(stderr, "Unknown parameter: %s\n", argv[i]);
        return -1;
      }

      /* Parse parameter value according to its type */
      switch (list->params[j].type)
      {

      /* Parameter value is a filename */
      case ARG_FILENAME:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No filename found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        if (strcmp(argv[i-1], "-cf") == 0)
        {
          /* Read the config file and parse it recursively */
          config = fopen(argv[i], "r");
          if (config == NULL)
          {
            fprintf(stderr, "Cannot open config file: %s\n", argv[i]);
            return -1;
          }
          file_params = read_config_file(config, &num_file_params);
          fclose(config);
          if (file_params == NULL)
          {
            return -1;
          }
          if (parse_params(num_file_params, file_params, params, list) < 0)
          {
            return -1;
          }
          delete_config_file_params(file_params);
          }
          else
          {
            if (*((char **)list->params[j].value) != NULL)
            {
              free(*((char **)list->params[j].value));
            }
            *((char **)list->params[j].value) = malloc((strlen(argv[i])+1)*sizeof(char));
            if (*((char **)list->params[j].value) == NULL)
            {
              fprintf(stderr, "Memory allocation failed\n");
              return -1;
            }
            strcpy(*((char **)list->params[j].value), argv[i]);
          }
          break;

      /* Parameter value is a comma-separated list of integers */
      case ARG_INTLIST:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No integer list found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        cnt = 1;
        if ((tmp = strtok(argv[i], ", ")) == NULL)
        {
          fprintf(stderr,"Error reading integer list for parameter: %s\n", argv[i-1]);
          return -1;
        }
        else
        {
          *(((int *)list->params[j].value)+cnt++) = atoi(tmp);
        }
        while ((tmp = strtok(NULL,", ")) != NULL)
        {
           *(((int *)list->params[j].value)+cnt++) = atoi(tmp);
        }
        *(((int *)list->params[j].value)+0) = cnt-1;
        break;
      /* Parameter value is an integer */
      case ARG_INTEGER:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No value found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        *((int *)list->params[j].value) = atoi(argv[i]);
        break;

      /* Parameter value is a floating point value */
      case ARG_FLOAT:
        i++;
        if (i == argc)
        {
          fprintf(stderr, "No value found for parameter: %s\n", argv[i-1]);
          return -1;
        }
        *((float *)list->params[j].value) = (float)atof(argv[i]);
        break;

      /* Parameter is a flag and does not have value */
      case ARG_NONE:
        *((int *)list->params[j].value) = 1;
        break;
      default:
        break;
      }
    }
    return 0;
}
Пример #21
0
int 
main(int argc, char *argv[]) {

    int argn;
    int got_in=0, got_out=0, do_continue=1;
    FILE *in=stdin, *out=stdout;
    struct stat tmpstat;

    pbm_init(&argc, argv);

    printer.version       = DEFAULT_PRINTER;
    printer.x_offset      = DEFAULT_X_OFFSET;
    printer.y_offset      = DEFAULT_Y_OFFSET;
    printer.top_margin    = DEFAULT_TOP_MARGIN;
    printer.left_margin   = DEFAULT_LEFT_MARGIN;
    printer.right_margin  = DEFAULT_RIGHT_MARGIN;
    printer.bottom_margin = DEFAULT_BOTTOM_MARGIN;
    printer.DPI           = DEFAULT_DPI;
    Width = USWIDTH;
    Height = USHEIGHT;
    set_printer_specific_defaults();

    if(!stat(defaultcfgfile,&tmpstat))
        read_config_file(defaultcfgfile);

    for(argn=1; argn<argc; argn++)
    {
        if(!strcmp(argv[argn],"-h"))
        {
            show_usage(*argv);
            return 0;
        }
        else if(!strcmp(argv[argn],"-d"))
            dump_config();
        else if(argn+1<argc)
        {
            do_continue=1;
            if(!strcmp(argv[argn],"-v"))
                parm_version(argv[++argn]);
            else if(!strcmp(argv[argn],"-x"))
                printer.x_offset+=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-y"))
                printer.y_offset+=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-t"))
                printer.top_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-l"))
                printer.left_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-r"))
                printer.right_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-b"))
                printer.bottom_margin=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-d"))
                printer.DPI=atoi(argv[++argn]);
            else if(!strcmp(argv[argn],"-s"))
            {
                argn++;
                if(!strcmp(argv[argn],"us"))
                {
                    Width = USWIDTH;
                    Height = USHEIGHT;
                }
                else if(!strcmp(argv[argn],"a4"))
                {
                    Width = A4WIDTH;
                    Height = A4HEIGHT;
                }
                else
                    pm_error("unknown paper size %s",argv[argn]);
            }
            else if(!strcmp(argv[argn],"-f"))
                read_config_file(argv[++argn]);
            else do_continue=0;
            if(do_continue) continue;
        }

        if(!got_in)
        {
            if (strcmp (argv[argn], "-") == 0)
                in = stdin;
            else if ((in = fopen (argv[argn], "rb")) == NULL)
                pm_error("main(): couldn't open file '%s'", 
                         argv[argn]);
            got_in=1;
        }
        else if(!got_out)
        {
            if (strcmp (argv[argn], "-") == 0)
                out = stdout;
            else if ((out = fopen (argv[argn], "wb")) == NULL)
                pm_error("main(): couldn't open file '%s'", 
                         argv[argn]);
            got_out=1;
        }
        else
            pm_error("main(): unrecognized parameter '%s'", argv[argn]);
    }

    Pwidth=(Width+7)/8;
    printer.fptr=out;

    return print_pbm (in);
}
Пример #22
0
/* read in the configuration file */
int read_config_file(char *filename){
	FILE *fp;
	char config_file[MAX_FILENAME_LENGTH];
	char input_buffer[MAX_INPUT_BUFFER];
	char *input_line;
	char *temp_buffer;
	char *varname;
	char *varvalue;
	int line=0;
	int len=0;
	int x=0;


	/* open the config file for reading */
	fp=fopen(filename,"r");

	/* exit if we couldn't open the config file */
	if(fp==NULL){
		syslog(LOG_ERR,"Unable to open config file '%s' for reading\n",filename);
		return ERROR;
	        }

	while(fgets(input_buffer,MAX_INPUT_BUFFER-1,fp)){

		line++;
		input_line=input_buffer;

		/* skip leading whitespace */
		while(isspace(*input_line))
			++input_line;

		/* trim trailing whitespace */
		len=strlen(input_line);
		for(x=len-1;x>=0;x--){
			if(isspace(input_line[x]))
				input_line[x]='\x0';
			else
				break;
		        }

		/* skip comments and blank lines */
		if(input_line[0]=='#')
			continue;
		if(input_line[0]=='\x0')
			continue;
		if(input_line[0]=='\n')
			continue;

		/* get the variable name */
		varname=strtok(input_line,"=");
		if(varname==NULL){
			syslog(LOG_ERR,"No variable name specified in config file '%s' - Line %d\n",filename,line);
			return ERROR;
		        }

		/* get the variable value */
		varvalue=strtok(NULL,"\n");
		if(varvalue==NULL){
			syslog(LOG_ERR,"No variable value specified in config file '%s' - Line %d\n",filename,line);
			return ERROR;
		        }

		/* allow users to specify directories to recurse into for config files */
		else if(!strcmp(varname,"include_dir")){

			strncpy(config_file,varvalue,sizeof(config_file)-1);
			config_file[sizeof(config_file)-1]='\x0';

			/* strip trailing / if necessary */
			if(config_file[strlen(config_file)-1]=='/')
				config_file[strlen(config_file)-1]='\x0';

			/* process the config directory... */
			if(read_config_dir(config_file)==ERROR)
				syslog(LOG_ERR,"Continuing with errors...");
			}

		/* allow users to specify individual config files to include */
		else if(!strcmp(varname,"include") || !strcmp(varname,"include_file")){

			/* process the config file... */
			if(read_config_file(varvalue)==ERROR)
				syslog(LOG_ERR,"Continuing with errors...");
		        }

		else if(!strcmp(varname,"server_port"))
			server_port=strdup(varvalue);

		else if(!strcmp(varname,"command_prefix"))
			command_prefix=strdup(varvalue);

		else if(!strcmp(varname,"server_address")){
			server_address=strdup(varvalue);
                        }

                else if(!strcmp(varname,"allowed_hosts"))
			allowed_hosts=strdup(varvalue);

		else if(strstr(input_line,"command[")){
			temp_buffer=strtok(varname,"[");
			temp_buffer=strtok(NULL,"]");
			if(temp_buffer==NULL){
				syslog(LOG_ERR,"Invalid command specified in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
			add_command(temp_buffer,varvalue);
		        }

		else if(strstr(input_buffer,"debug")){
			debug=atoi(varvalue);
			if(debug>0)
				debug=TRUE;
			else 
				debug=FALSE;
		        }

                else if(!strcmp(varname,"nrpe_user"))
			nrpe_user=strdup(varvalue);

                else if(!strcmp(varname,"nrpe_group"))
			nrpe_group=strdup(varvalue);
		
		else if(!strcmp(varname,"dont_blame_nrpe"))
			allow_arguments=(atoi(varvalue)==1)?TRUE:FALSE;

 		else if(!strcmp(varname,"command_timeout")){
			command_timeout=atoi(varvalue);
			if(command_timeout<1){
				syslog(LOG_ERR,"Invalid command_timeout specified in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
		        }

 		else if(!strcmp(varname,"connection_timeout")){
			connection_timeout=atoi(varvalue);
			if(connection_timeout<1){
				syslog(LOG_ERR,"Invalid connection_timeout specified in config file '%s' - Line %d\n",filename,line);
				return ERROR;
			        }
		        }

		else if(!strcmp(varname,"allow_weak_random_seed"))
			allow_weak_random_seed=(atoi(varvalue)==1)?TRUE:FALSE;

		else if(!strcmp(varname,"pid_file"))
			pid_file=strdup(varvalue);

		else if(!strcmp(varname,"log_facility")){
			if((get_log_facility(varvalue))==OK){
				/* re-open log using new facility */
				closelog();
				openlog("nrpe",LOG_PID,log_facility); 
				}
			else
				syslog(LOG_WARNING,"Invalid log_facility specified in config file '%s' - Line %d\n",filename,line);
			}

		else{
			syslog(LOG_WARNING,"Unknown option specified in config file '%s' - Line %d\n",filename,line);
			continue;
		        }

	        }


	/* close the config file */
	fclose(fp);

	return OK;
	}
Пример #23
0
int main (int argc, char *argv[])
{
#ifdef HAVE_ICONV
	char *locale_charset;
#endif
	int status = OK;

	program_name = base_name (argv[0]);
	if (STREQ (program_name, APROPOS_NAME)) {
		am_apropos = 1;
		argp_program_version = "apropos " PACKAGE_VERSION;
	} else {
		struct argp_option *optionp;
		am_apropos = 0;
		argp_program_version = "whatis " PACKAGE_VERSION;
		for (optionp = (struct argp_option *) whatis_argp.options;
		     optionp->name || optionp->key || optionp->arg ||
		     optionp->flags || optionp->doc || optionp->group;
		     ++optionp) {
			if (!optionp->name)
				continue;
			if (STREQ (optionp->name, "exact") ||
			    STREQ (optionp->name, "and"))
				optionp->flags |= OPTION_HIDDEN;
		}
	}

	init_debug ();
	pipeline_install_post_fork (pop_all_cleanups);
	init_locale ();

	internal_locale = setlocale (LC_MESSAGES, NULL);
	/* Use LANGUAGE only when LC_MESSAGES locale category is
	 * neither "C" nor "POSIX". */
	if (internal_locale && strcmp (internal_locale, "C") &&
	    strcmp (internal_locale, "POSIX"))
		multiple_locale = getenv ("LANGUAGE");
	internal_locale = xstrdup (internal_locale ? internal_locale : "C");

	if (argp_parse (am_apropos ? &apropos_argp : &whatis_argp, argc, argv,
			0, 0, 0))
		exit (FAIL);

	read_config_file (user_config_file != NULL);

	/* close this locale and reinitialise if a new locale was 
	   issued as an argument or in $MANOPT */
	if (locale) {
		free (internal_locale);
		internal_locale = setlocale (LC_ALL, locale);
		if (internal_locale)
			internal_locale = xstrdup (internal_locale);
		else
			internal_locale = xstrdup (locale);

		debug ("main(): locale = %s, internal_locale = %s\n",
		       locale, internal_locale);
		if (internal_locale) {
			setenv ("LANGUAGE", internal_locale, 1);
			locale_changed ();
			multiple_locale = NULL;
		}
	}

	/* sort out the internal manpath */
	if (manp == NULL)
		manp = locale_manpath (get_manpath (alt_systems));
	else
		free (get_manpath (NULL));

	create_pathlist (manp, manpathlist);

	display_seen = hashtable_create (&null_hashtable_free);

#ifdef HAVE_ICONV
	locale_charset = xasprintf ("%s//IGNORE", get_locale_charset ());
	conv_to_locale = iconv_open (locale_charset, "UTF-8");
	free (locale_charset);
#endif /* HAVE_ICONV */

	if (regex_opt) {
		int i;
		preg = XNMALLOC (num_keywords, regex_t);
		for (i = 0; i < num_keywords; ++i)
			xregcomp (&preg[i], keywords[i],
				  REG_EXTENDED | REG_NOSUB | REG_ICASE);
	}

	if (!search ((const char **) keywords, num_keywords))
		status = NOT_FOUND;

	if (regex_opt) {
		int i;
		for (i = 0; i < num_keywords; ++i)
			regfree (&preg[i]);
		free (preg);
	}

#ifdef HAVE_ICONV
	if (conv_to_locale != (iconv_t) -1)
		iconv_close (conv_to_locale);
#endif /* HAVE_ICONV */
	hashtable_free (display_seen);
	free_pathlist (manpathlist);
	free (manp);
	free (internal_locale);
	free (program_name);
	exit (status);
}
Пример #24
0
int main(int argc, char **argv){
	int result=OK;
	int x;
	char buffer[MAX_INPUT_BUFFER];
	char *env_string=NULL;
#ifdef HAVE_SSL
	DH *dh;
	char seedfile[FILENAME_MAX];
	int i,c;
#endif

	/* set some environment variables */
	asprintf(&env_string,"NRPE_MULTILINESUPPORT=1");
	putenv(env_string);
	asprintf(&env_string,"NRPE_PROGRAMVERSION=%s",PROGRAM_VERSION);
	putenv(env_string);

	/* process command-line args */
	result=process_arguments(argc,argv);

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE){

		printf("\n");
		printf("NRPE - Nagios Remote Plugin Executor\n");
		printf("Copyright (c) 1999-2008 Ethan Galstad ([email protected])\n");
		printf("Version: %s\n",PROGRAM_VERSION);
		printf("Last Modified: %s\n",MODIFICATION_DATE);
		printf("License: GPL v2 with exemptions (-l for more info)\n");
#ifdef HAVE_SSL
		printf("SSL/TLS Available: Anonymous DH Mode, OpenSSL 0.9.6 or higher required\n");
#endif
#ifdef HAVE_LIBWRAP
		printf("TCP Wrappers Available\n");
#endif
		printf("\n");
#ifdef ENABLE_COMMAND_ARGUMENTS
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - COMMAND ARGUMENTS ARE SUPPORTED! **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
#ifndef HAVE_LIBWRAP
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - TCP WRAPPERS ARE NOT AVAILABLE!  **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
	        }

	if(show_license==TRUE)
		display_license();

	else if(result!=OK || show_help==TRUE){

		printf("Usage: nrpe [-n] -c <config_file> <mode>\n");
		printf("\n");
		printf("Options:\n");
		printf(" -n            = Do not use SSL\n");
		printf(" <config_file> = Name of config file to use\n");
		printf(" <mode>        = One of the following two operating modes:\n");  
		printf("   -i          =    Run as a service under inetd or xinetd\n");
		printf("   -d          =    Run as a standalone daemon\n");
		printf("\n");
		printf("Notes:\n");
		printf("This program is designed to process requests from the check_nrpe\n");
		printf("plugin on the host(s) running Nagios.  It can run as a service\n");
		printf("under inetd or xinetd (read the docs for info on this), or as a\n");
		printf("standalone daemon. Once a request is received from an authorized\n");
		printf("host, NRPE will execute the command/plugin (as defined in the\n");
		printf("config file) and return the plugin output and return code to the\n");
		printf("check_nrpe plugin.\n");
		printf("\n");
		}

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE)
		exit(STATE_UNKNOWN);


	/* open a connection to the syslog facility */
	/* facility name may be overridden later */
	get_log_facility(NRPE_LOG_FACILITY);
        openlog("nrpe",LOG_PID,log_facility); 

	/* make sure the config file uses an absolute path */
	if(config_file[0]!='/'){

		/* save the name of the config file */
		strncpy(buffer,config_file,sizeof(buffer));
		buffer[sizeof(buffer)-1]='\x0';

		/* get absolute path of current working directory */
		strcpy(config_file,"");
		getcwd(config_file,sizeof(config_file));

		/* append a forward slash */
		strncat(config_file,"/",sizeof(config_file)-2);
		config_file[sizeof(config_file)-1]='\x0';

		/* append the config file to the path */
		strncat(config_file,buffer,sizeof(config_file)-strlen(config_file)-1);
		config_file[sizeof(config_file)-1]='\x0';
	        }

	/* read the config file */
	result=read_config_file(config_file);	

	/* exit if there are errors... */
	if(result==ERROR){
		syslog(LOG_ERR,"Config file '%s' contained errors, aborting...",config_file);
		return STATE_CRITICAL;
		}

        /* generate the CRC 32 table */
        generate_crc32_table();

	/* initialize macros */
	for(x=0;x<MAX_COMMAND_ARGUMENTS;x++)
		macro_argv[x]=NULL;

#ifdef HAVE_SSL
	/* initialize SSL */
	if(use_ssl==TRUE){
		SSL_library_init();
		SSLeay_add_ssl_algorithms();
		meth=SSLv23_server_method();
		SSL_load_error_strings();

		/* use week random seed if necessary */
		if(allow_weak_random_seed && (RAND_status()==0)){

			if(RAND_file_name(seedfile,sizeof(seedfile)-1))
				if(RAND_load_file(seedfile,-1))
					RAND_write_file(seedfile);

			if(RAND_status()==0){
				syslog(LOG_ERR,"Warning: SSL/TLS uses a weak random seed which is highly discouraged");
				srand(time(NULL));
				for(i=0;i<500 && RAND_status()==0;i++){
					for(c=0;c<sizeof(seedfile);c+=sizeof(int)){
						*((int *)(seedfile+c))=rand();
					        }
					RAND_seed(seedfile,sizeof(seedfile));
					}
				}
			}

		if((ctx=SSL_CTX_new(meth))==NULL){
			syslog(LOG_ERR,"Error: could not create SSL context.\n");
			exit(STATE_CRITICAL);
		        }

		/* ADDED 01/19/2004 */
		/* use only TLSv1 protocol */
		SSL_CTX_set_options(ctx,SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

		/* use anonymous DH ciphers */
		SSL_CTX_set_cipher_list(ctx,"ADH");
		dh=get_dh512();
		SSL_CTX_set_tmp_dh(ctx,dh);
		DH_free(dh);
		if(debug==TRUE)
			syslog(LOG_INFO,"INFO: SSL/TLS initialized. All network traffic will be encrypted.");
	        }
	else{
		if(debug==TRUE)
			syslog(LOG_INFO,"INFO: SSL/TLS NOT initialized. Network encryption DISABLED.");
	        }
#endif

	/* if we're running under inetd... */
	if(use_inetd==TRUE){

		/* make sure we're not root */
		check_privileges();

		/* redirect STDERR to /dev/null */
		close(2);
		open("/dev/null",O_WRONLY);

		/* handle the connection */
		handle_connection(0);
	        }

	/* else daemonize and start listening for requests... */
	else if(fork()==0){
		
		/* we're a daemon - set up a new process group */
		setsid();

		/* close standard file descriptors */
		close(0);
		close(1);
		close(2);

		/* redirect standard descriptors to /dev/null */
		open("/dev/null",O_RDONLY);
		open("/dev/null",O_WRONLY);
		open("/dev/null",O_WRONLY);

		chdir("/");
		/*umask(0);*/

		/* handle signals */
		signal(SIGQUIT,sighandler);
		signal(SIGTERM,sighandler);
		signal(SIGHUP,sighandler);

		/* log info to syslog facility */
		syslog(LOG_NOTICE,"Starting up daemon");

		/* write pid file */
		if(write_pid_file()==ERROR)
			return STATE_CRITICAL;
		
		/* drop privileges */
		drop_privileges(nrpe_user,nrpe_group);

		/* make sure we're not root */
		check_privileges();

		do{

			/* reset flags */
			sigrestart=FALSE;
			sigshutdown=FALSE;

			/* wait for connections */
			wait_for_connections();

			/* free all memory we allocated */
			free_memory();

			if(sigrestart==TRUE){

				/* read the config file */
				result=read_config_file(config_file);	

				/* exit if there are errors... */
				if(result==ERROR){
					syslog(LOG_ERR,"Config file '%s' contained errors, bailing out...",config_file);
					return STATE_CRITICAL;
				        }
			        }
	
		        }while(sigrestart==TRUE && sigshutdown==FALSE);

		/* remove pid file */
		remove_pid_file();

		syslog(LOG_NOTICE,"Daemon shutdown\n");
	        }

#ifdef HAVE_SSL
	if(use_ssl==TRUE)
		SSL_CTX_free(ctx);
#endif

	/* We are now running in daemon mode, or the connection handed over by inetd has
	   been completed, so the parent process exits */
        return STATE_OK;
	}
Пример #25
0
static void init_core_client(int argc, char** argv) {
    setbuf(stdout, 0);
    setbuf(stderr, 0);

    config.clear();
    gstate.parse_cmdline(argc, argv);

#ifdef _WIN32
    if (!config.allow_multiple_clients) {
        chdir_to_data_dir();
    }
#endif

#ifndef _WIN32
    if (g_use_sandbox)
        // Set file creation mask to be writable by both user and group and
        // world-executable but neither world-readable nor world-writable
        // Our umask will be inherited by all our child processes
        //
        umask (6);
#endif

    // Initialize the BOINC Diagnostics Framework
    int flags =
#ifdef _DEBUG
        BOINC_DIAG_MEMORYLEAKCHECKENABLED |
#endif
        BOINC_DIAG_DUMPCALLSTACKENABLED |
        BOINC_DIAG_HEAPCHECKENABLED |
        BOINC_DIAG_TRACETOSTDOUT;

    if (gstate.redirect_io || gstate.executing_as_daemon || gstate.detach_console) {
        flags |=
            BOINC_DIAG_REDIRECTSTDERR |
            BOINC_DIAG_REDIRECTSTDOUT;
    }

    diagnostics_init(flags, "stdoutdae", "stderrdae");

#ifdef _WIN32
    // Specify which allocation will cause a debugger to break.  Use a previous
    // memory leak detection report which looks like this:
    //   {650} normal block at 0x000000000070A6F0, 24 bytes long.
    //   Data: <  N     P p     > 80 1E 4E 00 00 00 00 00 50 AE 70 00 00 00 00 00
    //_CrtSetBreakAlloc(650);
    //_CrtSetBreakAlloc(651);
    //_CrtSetBreakAlloc(652);
    //_CrtSetBreakAlloc(653);
    //_CrtSetBreakAlloc(654);
#endif

    read_config_file(true);

    // Set the max file sizes of the logs based on user preferences.
    //
    diagnostics_set_max_file_sizes(
        config.max_stdout_file_size, config.max_stderr_file_size
    );

    // Win32 - detach from console if requested
#ifdef _WIN32
	if (gstate.detach_console) {
		FreeConsole();
	}
#endif

    // Unix: install signal handlers
#ifndef _WIN32
    // Handle quit signals gracefully
    boinc_set_signal_handler(SIGHUP, signal_handler);
    boinc_set_signal_handler(SIGINT, signal_handler);
    boinc_set_signal_handler(SIGQUIT, signal_handler);
    boinc_set_signal_handler(SIGTERM, signal_handler);
#ifdef SIGPWR
    boinc_set_signal_handler(SIGPWR, signal_handler);
#endif
#endif
}
Пример #26
0
int main(int argc, char **argv)
{
	struct ctrlproxyd_config *config;
	GOptionContext *pc;
	const char *config_file = DEFAULT_CONFIG_FILE;
	gboolean version = FALSE;
	gboolean foreground = FALSE;
	gboolean isdaemon = TRUE;
	pid_t pid;
	GOptionEntry options[] = {
		{"config-file", 'c', 0, G_OPTION_ARG_STRING, &config_file, "Configuration file", "CONFIGFILE"},
		{"foreground", 'F', 0, G_OPTION_ARG_NONE, &foreground, ("Stay in the foreground") },
		{"inetd", 'I', 0, G_OPTION_ARG_NONE, &inetd, ("Run in inetd mode")},
		{"version", 'v', 0, G_OPTION_ARG_NONE, &version, ("Show version information")},
		{ NULL }
	};
	GError *error = NULL;
	daemon_listener = g_new0(struct irc_listener, 1);

	signal(SIGINT, signal_quit);
	signal(SIGTERM, signal_quit);
#ifdef SIGPIPE
	signal(SIGPIPE, SIG_IGN);
#endif
#ifdef SIGHUP
	signal(SIGHUP, SIG_IGN);
#endif
#ifdef SIGSEGV
	signal(SIGSEGV, signal_crash);
#endif

	main_loop = g_main_loop_new(NULL, FALSE);

	pc = g_option_context_new("");
	g_option_context_add_main_entries(pc, options, NULL);

	if (!g_option_context_parse(pc, &argc, &argv, &error)) {
		fprintf(stderr, "%s\n", error->message);
		g_error_free(error);
		return 1;
	}

	g_option_context_free(pc);

	if (version) {
		printf("ctrlproxy %s\n", VERSION);
		printf("(c) 2002-2009 Jelmer Vernooij et al. <*****@*****.**>\n");
		return 0;
	}

	global_daemon_config = config = read_config_file(config_file);
	if (config == NULL) {
		return 1;
	}

	pid = read_pidfile(PIDFILE);
	if (pid != -1) {
		fprintf(stderr, "ctrlproxyd already running at pid %d!\n", pid);
		return 1;
	}

	isdaemon = (!foreground && !inetd);

	if (gethostname(my_hostname, NI_MAXHOST) != 0) {
		fprintf(stderr, "Can't figure out hostname of local host!\n");
		return 1;
	}

	if (isdaemon) {
#if defined(HAVE_DAEMON) || defined(HAVE_FORK)
#ifdef SIGTTOU
		signal(SIGTTOU, SIG_IGN);
#endif

#ifdef SIGTTIN
		signal(SIGTTIN, SIG_IGN);
#endif

#ifdef SIGTSTP
		signal(SIGTSTP, SIG_IGN);
#endif
		if (daemon(1, 0) < 0) {
			fprintf(stderr, "Unable to daemonize\n");
			return -1;
		}
#else
		fprintf(stderr, "Daemon mode not compiled in\n");
		return -1;
#endif
	}

	openlog("ctrlproxyd", 0, LOG_DAEMON);

	daemon_listener->iconv = (GIConv)-1;
	if (foreground)
		daemon_listener->log_fn = listener_stderr;
	else
		daemon_listener->log_fn = listener_syslog;
	daemon_listener->ops = &daemon_ops;
	daemon_listener->ssl = config->ssl;
	daemon_listener->ssl_credentials = config->ssl_credentials;

	if (inetd) {
		GIOChannel *io = g_io_channel_unix_new(0);
		listener_new_pending_client(daemon_listener, io);
	} else {
		write_pidfile(PIDFILE);

		if (!listener_start_tcp(daemon_listener, config->address, config->port))
			return 1;
	}

	foreach_daemon_user(config, daemon_listener, daemon_user_start_if_exists);

	g_main_loop_run(main_loop);

	daemon_clients_exit();

	return 0;
}
Пример #27
0
jintArray Java_com_zokama_androlirc_Lirc_getIrBuffer( JNIEnv* env, jobject thiz,
		jstring dev, jstring cmd, jint min_buf_size)
{
/* variables */
	char * remote_name = (char *)(*env)->GetStringUTFChars(env, dev, NULL);
	char * code_name = (char *)(*env)->GetStringUTFChars(env, cmd, NULL);

	int     length;
	lirc_t* signals;
	jbyteArray result;

	lirc_t  freq;
	char msg[255];


/* Check config */
	if(!read_config_file(LIRCDCFGFILE)) return 0;


/* Prepare send - using lirc/daemons/transmit.h*/
	struct ir_remote * remote = get_ir_remote(devices, remote_name);
	struct ir_ncode * code = get_code_by_name(remote, code_name);

	if(!init_send(remote, code))
		return NULL;

	length = send_buffer.wptr;
	signals = send_buffer.data;

	if (length <= 0 || signals == NULL)
	{
		ZLOG_INFO("nothing to send");
		return NULL;
	}

	/*carrier frequency */
	freq = remote->freq ? remote->freq : DEFAULT_FREQ;

	sprintf(msg, "Using carrier frequency %i", freq);
	ZLOG_INFO(msg);


/* Generate audio buffer - Derived from lirc/daemons/hw_audio.c */
	int i, j=0, signalPhase=0, carrierPos=0, out;
	int currentSignal=0;
	unsigned char outptr[SAMPLERATE*5];

	/* Insert space before the ir code */
	for(j=0; j<5000; j++)
	{
		outptr[j] = 128;
	}

	for(i = 0; i<length; i++)
	{
		/* invert the phase */
		signalPhase = signalPhase ? 0 : 1;

		for(currentSignal=signals[i]; currentSignal>0;
				currentSignal -= 1000000.0 / SAMPLERATE)
		{
			if (signalPhase)
			{
				/* write carrier */
				out = rint(sin(carrierPos / (180.0 / PI)) * 127.0 + 128.0);
			}
			else
			{
				out = 128;
			}

			/* one channel is inverted, so both channels
			   can be used to double the voltage */
			outptr[j++] = out;
			outptr[j++] = 256 - out;

			/* increase carrier position */
			/* carrier frequency is halved */
			carrierPos += (double)freq / SAMPLERATE * 360.0 / 2.0;

			if (carrierPos >= 360.0)
				carrierPos -= 360.0;
		}
	}

	/* Fill with space if buffer is too small */
	if (j < min_buf_size)
	{
		for (j; j<min_buf_size; j++)
		{
			outptr[j] = 128;
			sprintf(msg, "filling buffer: %d/%d",j, min_buf_size);
				ZLOG_INFO(msg);
		}
	}

	sprintf(msg, "Buffer size: %d bytes (min: %d)",j, min_buf_size);
	ZLOG_INFO(msg);


/* Return audio buffer*/
	result = (*env)->NewByteArray(env, j);
	if (result == NULL)
	{
		return NULL;
	}

	(*env)->SetByteArrayRegion(env, result, 0, j, outptr);
	return result;
}
Пример #28
0
int main(int argc, char **argv) {
  long cookie_expire;
  int ret = 1;

  config = config_new();

  if (curl_init() != 0) {
    fprintf(stderr, "Error: An error occurred while initializing curl\n");
    goto finish;
  }

  ret = parseargs(argc, argv);
  if (ret != 0) {
    return 1;
  }

  if (config->category) {
    config->catnum = category_is_valid(config->category);
    if (config->catnum < 0) {
      usage_categories();
      goto finish;
    }
  } else {
    config->catnum = 1;
  }

  if (optind == argc) {
    fprintf(stderr, "error: no packages specified (use -h for help)\n");
    goto finish;
  }

  /* We can't read the config file without having verbosity set, but the
   * command line options need to take precedence over the config.  file.
   * Therefore, if ((user && pass) || cookie file) is supplied on the command
   * line, we won't read the config file.
   */
  if (!(config->user || config->cookie_file)) {
    read_config_file();
  }

  if (cookie_setup() != 0) {
    goto finish;
  }

  cookie_expire = cookie_expire_time(config->cookie_file, AUR_DOMAIN, AUR_COOKIE_NAME);
  if (cookie_expire > 0) {
    if (time(NULL) < cookie_expire) {
      config->cookie_valid = 1;
    } else {
      fprintf(stderr, "Your cookie has expired. Gathering user and password...\n");
    }
  }

  if (!config->cookie_valid) {
    if (!config->cmdline_user && !config->user) {
      config->user = read_stdin("Enter username", AUR_USER_MAX, 1);
      if (!config->user || !strlen(config->user)) {
        fprintf(stderr, "error: invalid username supplied\n");
        goto finish;
      }
    }

    if (!config->password || (config->cmdline_user && !config->cmdline_passwd)) {
      printf("[%s] ", config->user);
      config->password = read_stdin("Enter password", AUR_PASSWORD_MAX, 0);
    }
  }

  if (config->cookie_valid || aur_login() == 0) {
    char *csrf_token;

    /* booo, stupid hacks. curl doesn't prime curl_slist of cookies
     * we want via CURLINFO_COOKIELIST until we call perform at least
     * once. */
    prime_cookielist();

    csrf_token = get_csrf_token();
    if (csrf_token == NULL) {
      fprintf(stderr, "failed to obtain CSRF token for uploading\n");
      goto finish;
    }

    ret = 0;

    while (optind < argc) {
      int r = aur_upload(argv[optind++], csrf_token);
      if (r != 0) {
        ret = r;
      }
    }
    free(csrf_token);
  }

finish:
  if (config->cookie_file && !config->cookie_persist) {
    debug("Deleting file %s\n", config->cookie_file);
    unlink(config->cookie_file);
  }

  config_free(config);
  curl_cleanup();

  return ret;
}
Пример #29
0
static int read_config_file(const char *name, int rcf_count)
{
  char  tmp[TIM_MAXPATH];
  char *w[MAXWORDS], *cp;
  MidToneBank *bank;
  int i, j, k, line, r, words;

  if (rcf_count >= MAX_RCFCOUNT)
  {
    DEBUG_MSG("Probable source loop in configuration files\n");
    return -1;
  }

  if (!(rcf_fp[rcf_count]=timi_openfile(name)))
    return -1;

  bank = NULL;
  line = 0;
  r = -1; /* start by assuming failure, */

  while (timi_fgets(tmp, sizeof(tmp), rcf_fp[rcf_count]))
  {
    line++;
    words=0;
    w[0]=strtok(tmp, " \t\240");
    if (!w[0]) continue;

    /* Originally the TiMidity++ extensions were prefixed like this */
    if (strcmp(w[0], "#extension") == 0)
    {
      w[0]=strtok(NULL, " \t\240");
      if (!w[0]) continue;
    }

    if (*w[0] == '#')
      continue;

    while (w[words] && *w[words] != '#') {
      if (++words == MAXWORDS) break;
      w[words]=strtok(NULL, " \t\240");
    }

    /* TiMidity++ adds a number of extensions to the config file format.
     * Many of them are completely irrelevant to SDL_sound, but at least
     * we shouldn't choke on them.
     *
     * Unfortunately the documentation for these extensions is often quite
     * vague, gramatically strange or completely absent.
     */
    if (!strcmp(w[0], "comm")      /* "comm" program second        */ ||
        !strcmp(w[0], "HTTPproxy") /* "HTTPproxy" hostname:port    */ ||
        !strcmp(w[0], "FTPproxy")  /* "FTPproxy" hostname:port     */ ||
        !strcmp(w[0], "mailaddr")  /* "mailaddr" your-mail-address */ ||
        !strcmp(w[0], "opt")       /* "opt" timidity-options       */  )
    {
      /* + "comm" sets some kind of comment -- the documentation is too
       *   vague for me to understand at this time.
       * + "HTTPproxy", "FTPproxy" and "mailaddr" are for reading data
       *   over a network, rather than from the file system.
       * + "opt" specifies default options for TiMidity++.
       *
       * Quite useless for us, so they can safely remain no-ops.
       */
    }
    else if (!strcmp(w[0], "timeout")) /* "timeout" program second */
    {
      /* Specifies a timeout value of the program. A number of seconds
       * before TiMidity kills the note. No urgent need for it.
       */
      DEBUG_MSG("FIXME: Implement \"timeout\" in TiMidity config.\n");
    }
    else if (!strcmp(w[0], "copydrumset")  /* "copydrumset" drumset */ ||
	     !strcmp(w[0], "copybank")) /* "copybank" bank       */
    {
      /* Copies all the settings of the specified drumset or bank to
       * the current drumset or bank. May be useful later, but not a
       * high priority.
       */
       DEBUG_MSG("FIXME: Implement \"%s\" in TiMidity config.\n", w[0]);
    }
    else if (!strcmp(w[0], "undef")) /* "undef" progno */
    {
      /* Undefines the tone "progno" of the current tone bank (or
       * drum set?). Not a high priority.
       */
      DEBUG_MSG("FIXME: Implement \"undef\" in TiMidity config.\n");
    }
    else if (!strcmp(w[0], "altassign")) /* "altassign" prog1 prog2 ... */
    {
      /* Sets the alternate assign for drum set. Whatever that's
       * supposed to mean.
       */
      DEBUG_MSG("FIXME: Implement \"altassign\" in TiMidity config.\n");
    }
    else if (!strcmp(w[0], "soundfont") ||
	     !strcmp(w[0], "font"))
    {
      /* "soundfont" sf_file "remove"
       * "soundfont" sf_file ["order=" order] ["cutoff=" cutoff]
       *                     ["reso=" reso] ["amp=" amp]
       * "font" "exclude" bank preset keynote
       * "font" "order" order bank preset keynote
       */
      DEBUG_MSG("FIXME: Implmement \"%s\" in TiMidity config.\n", w[0]);
    }
    else if (!strcmp(w[0], "progbase"))
    {
      /* The documentation for this makes absolutely no sense to me, but
       * apparently it sets some sort of base offset for tone numbers.
       */
      DEBUG_MSG("FIXME: Implement \"progbase\" in TiMidity config.\n");
    }
    else if (!strcmp(w[0], "map")) /* "map" name set1 elem1 set2 elem2 */
    {
      /* This one is used by the "eawpats". Looks like it's used
       * for remapping one instrument to another somehow.
       */
      DEBUG_MSG("FIXME: Implement \"map\" in TiMidity config.\n");
    }
    /* Standard TiMidity config */
    else if (!strcmp(w[0], "dir"))
    {
      if (words < 2)
      {
	DEBUG_MSG("%s: line %d: No directory given\n", name, line);
	goto fail;
      }
      for (i=1; i<words; i++) {
	if (timi_add_pathlist(w[i], strlen(w[i])) < 0)
	  goto fail;
      }
    }
    else if (!strcmp(w[0], "source"))
    {
      if (words < 2)
      {
	DEBUG_MSG("%s: line %d: No file name given\n", name, line);
	goto fail;
      }
      for (i=1; i<words; i++)
      {
	r = read_config_file(w[i], rcf_count + 1);
	if (r != 0)
	  goto fail;
      }
      r = -1; /* not finished yet, */
    }
    else if (!strcmp(w[0], "default"))
    {
      if (words != 2)
      {
	DEBUG_MSG("%s: line %d: Must specify exactly one patch name\n",
		name, line);
	goto fail;
      }
      strncpy(def_instr_name, w[1], 255);
      def_instr_name[255]='\0';
    }
    else if (!strcmp(w[0], "drumset"))
    {
      if (words < 2)
      {
	DEBUG_MSG("%s: line %d: No drum set number given\n", name, line);
	goto fail;
      }
      i=atoi(w[1]);
      if (i<0 || i>127)
      {
	DEBUG_MSG("%s: line %d: Drum set must be between 0 and 127\n",
		name, line);
	goto fail;
      }
      if (!master_drumset[i])
      {
	master_drumset[i] = (MidToneBank *) timi_calloc(sizeof(MidToneBank));
	if (!master_drumset[i]) goto fail;
	master_drumset[i]->tone = (MidToneBankElement *) timi_calloc(128 * sizeof(MidToneBankElement));
	if (!master_drumset[i]->tone) goto fail;
      }
      bank=master_drumset[i];
    }
    else if (!strcmp(w[0], "bank"))
    {
      if (words < 2)
      {
	DEBUG_MSG("%s: line %d: No bank number given\n", name, line);
	goto fail;
      }
      i=atoi(w[1]);
      if (i<0 || i>127)
      {
	DEBUG_MSG("%s: line %d: Tone bank must be between 0 and 127\n",
		name, line);
	goto fail;
      }
      if (!master_tonebank[i])
      {
	master_tonebank[i] = (MidToneBank *) timi_calloc(sizeof(MidToneBank));
	if (!master_tonebank[i]) goto fail;
	master_tonebank[i]->tone = (MidToneBankElement *) timi_calloc(128 * sizeof(MidToneBankElement));
	if (!master_tonebank[i]->tone) goto fail;
      }
      bank=master_tonebank[i];
    }
    else
    {
      if ((words < 2) || (*w[0] < '0' || *w[0] > '9'))
      {
	DEBUG_MSG("%s: line %d: syntax error\n", name, line);
	goto fail;
      }
      i=atoi(w[0]);
      if (i<0 || i>127)
      {
	DEBUG_MSG("%s: line %d: Program must be between 0 and 127\n",
		name, line);
	goto fail;
      }
      if (!bank)
      {
	DEBUG_MSG("%s: line %d: Must specify tone bank or drum set before assignment\n",
		name, line);
	goto fail;
      }
      timi_free(bank->tone[i].name);
      bank->tone[i].name=(char *) timi_calloc(strlen(w[1])+1);
      if (!bank->tone[i].name) goto fail;
      strcpy(bank->tone[i].name,w[1]);
      bank->tone[i].note=bank->tone[i].amp=bank->tone[i].pan=
      bank->tone[i].strip_loop=bank->tone[i].strip_envelope=
      bank->tone[i].strip_tail=-1;

      for (j=2; j<words; j++)
      {
	if (!(cp=strchr(w[j], '=')))
	{
	  DEBUG_MSG("%s: line %d: bad patch option %s\n", name, line, w[j]);
	  goto fail;
	}
	*cp++=0;
	if (!strcmp(w[j], "amp"))
	{
	  k=atoi(cp);
	  if ((k<0 || k>MAX_AMPLIFICATION) || (*cp < '0' || *cp > '9'))
	  {
	    DEBUG_MSG("%s: line %d: amplification must be between 0 and %d\n",
		    name, line, MAX_AMPLIFICATION);
	    goto fail;
	  }
	  bank->tone[i].amp=k;
	}
	else if (!strcmp(w[j], "note"))
	{
	  k=atoi(cp);
	  if ((k<0 || k>127) || (*cp < '0' || *cp > '9'))
	  {
	    DEBUG_MSG("%s: line %d: note must be between 0 and 127\n",
		    name, line);
	    goto fail;
	  }
	  bank->tone[i].note=k;
	}
	else if (!strcmp(w[j], "pan"))
	{
	  if (!strcmp(cp, "center"))
	    k=64;
	  else if (!strcmp(cp, "left"))
	    k=0;
	  else if (!strcmp(cp, "right"))
	    k=127;
	  else
	    k=((atoi(cp)+100) * 100) / 157;
	  if ((k<0 || k>127) || (k==0 && *cp!='-' && (*cp < '0' || *cp > '9')))
	  {
	    DEBUG_MSG("%s: line %d: panning must be left, right, center, or between -100 and 100\n",
		    name, line);
	    goto fail;
	  }
	  bank->tone[i].pan=k;
	}
	else if (!strcmp(w[j], "keep"))
	{
	  if (!strcmp(cp, "env"))
	    bank->tone[i].strip_envelope=0;
	  else if (!strcmp(cp, "loop"))
	    bank->tone[i].strip_loop=0;
	  else
	  {
	    DEBUG_MSG("%s: line %d: keep must be env or loop\n", name, line);
	    goto fail;
	  }
	}
	else if (!strcmp(w[j], "strip"))
	{
	  if (!strcmp(cp, "env"))
	    bank->tone[i].strip_envelope=1;
	  else if (!strcmp(cp, "loop"))
	    bank->tone[i].strip_loop=1;
	  else if (!strcmp(cp, "tail"))
	    bank->tone[i].strip_tail=1;
	  else
	  {
	    DEBUG_MSG("%s: line %d: strip must be env, loop, or tail\n",
		    name, line);
	    goto fail;
	  }
	}
	else
	{
	  DEBUG_MSG("%s: line %d: bad patch option %s\n", name, line, w[j]);
	  goto fail;
	}
      }
    }
  }

  r = 0; /* we're good. */
fail:
  fclose(rcf_fp[rcf_count]);
  rcf_fp[rcf_count] = NULL;
  return r;
}
Пример #30
0
int main(int argc, char **argv)
   {
   console_init(Version) ;

   //***********************************************************
   //  Check for NDIR environment variable
   //***********************************************************

   //  get program filename
   int startIdx = 1 ;
   char exename[PATH_MAX] ;

   // for (int j = 1; j < argc; j++) {
   //    printf("0: %s\n", argv[j]) ;
   // }

   //  interesting lessons from WinNT 4.0:
   //  If the OS is WinNT 4.0, and;
   //  If the executable file is located in the current directory,
   //  THEN:
   //    argv[0] does NOT contain the fully-qualified
   //    path of the EXE, it *only* contains the EXE name.
   //    In all other situations, argv[0] is fully qualified!!
   //  
   //  P.S.  While we're here, derive default INI filename also
   // printf("argv0=%s\n", argv[0]) ;
   char* strptr = strrchr(argv[0], '\\') ;
   //  no path present
   if (strptr == 0) {
      SearchPath(NULL, argv[0], ".exe", PATH_MAX, ininame, NULL) ;
      strptr = strrchr(ininame, '\\') ;
      if (strptr != 0) 
         strcpy(strptr, "\\ndir.ini") ;

      strcpy(exename, argv[0]) ;
      // ininame[0] = 0 ;  //  ONLY support current location
   }
   else {
      //  pick up INI filename
      strcpy(ininame, argv[0]) ;
      strptr = strrchr(ininame, '\\') ;
      if (strptr == 0)
         return 1;
      strcpy(strptr, "\\ndir.ini") ;
      
      //  now process exe name for getenv()
      strptr++ ;  //lint !e613:  skip backslash
      strcpy(exename, strptr) ;  //lint !e613
      strptr = strchr(exename, '.') ;
      if (strptr != 0) 
         *strptr = 0 ;  //  strip the extension
   }

   char* options = getenv(exename) ; 
   if (options != 0) {
      argv[0] = options ;
      startIdx = 0 ;
   }
// printf("ininame=%s\n", ininame) ;
// getchar() ;

   // for (int j = startIdx; j < argc; j++) {
   //    printf("1: %s\n", argv[j]) ;
   // }
   //***********************************************************
   //  first read default settings
   //***********************************************************
   read_config_file() ;

   //***********************************************************
   //  override defaults with command line and environment vars
   //***********************************************************
   parse_command_args(startIdx, argc, argv) ;
   verify_flags() ;  //  this may add extensions if -x is given

   //***********************************************************
   //  Execute the requested command
   //***********************************************************
   // output_html_header("ndir32");
   display_logo() ;

   if (n.help)
      info(helptxt) ;
   else if (n.info)
      info(idtxt) ;
   else if (n.drive_summary)
      display_drive_summary() ;
   else {
      //  If no filespec was given, insert current path with *.*
      if (tcount==0)
         insert_target_filespec(".") ;

      sort_target_paths() ;      //  LFN: okay
      process_filespecs() ;
   }

   // output_html_footer();
   error_exit(DATA_OKAY, NULL) ;
   return 0 ;
   }