int main()
{
   pid = getpid();
   int key  = ftok(".",'a');
   shm_id = init_shm(key,sizeof(pid_t),IPC_CREAT | 0666);
   
   
   shmptr = (pid_t*)shmat(shm_id,NULL,0);

   sem_id= init_sem(key,1,IPC_CREAT|0666);

   semctl(sem_id,0,SETVAL,1);
   create_shared_objects();
   
   signal(SIGUSR1, sig_handler);
   printf("Enter Number to send from c1 to c2 :  ");
   
   scanf("%d",shm_c1);
   P(sem_id);
   kill(*shmptr,SIGUSR1);
   *shmptr = pid;
   V(sem_id);

   while(1)
     sleep(1);
   
   
}
int main(int argc, char **argv)
{
	_u32 shm_int = 0;
	shm_buf = init_shm(SHARE_M_KEY, 1024);
	if(!shm_buf)
	{
		fprintf(stderr, "init_shm error!\n");
		exit(1);
	}

	//shm_int = *(_u32 *)shm_buf;

	while(TRUE)
	{
		if(shm_int == *(_u32 *)shm_buf)
		{
			system("pkill xserver");
			fprintf(stderr, "watchdog detected xserver down!! xserver will be up by xmanager now!\n");
			system("./xserver &");
		}
		else
		{
			shm_int = *(_u32 *)shm_buf;
		}	
		sleep(3);
	}

	printf("manager exit.\n");
	return 0;
}
Beispiel #3
0
VhostClient* new_vhost_client(const char* path)
{
    VhostClient* vhost_client = (VhostClient*) calloc(1, sizeof(VhostClient));
    int idx = 0;

    //TODO: handle errors here

    vhost_client->client = new_client(path);

    vhost_client->page_size = VHOST_CLIENT_PAGE_SIZE;

    // Create and attach shm to memory regions
    vhost_client->memory.nregions = VHOST_CLIENT_VRING_NUM;
    for (idx = 0; idx < vhost_client->memory.nregions; idx++) {
        void* shm = init_shm(VHOST_SOCK_NAME, vhost_client->page_size, idx);
        if (!shm) {
            fprintf(stderr, "Creatig shm %d failed\n", idx);
            free(vhost_client->client);
            free(vhost_client);
            return 0;
        }
        vhost_client->memory.regions[idx].guest_phys_addr = (uintptr_t) shm;
        vhost_client->memory.regions[idx].memory_size = vhost_client->page_size;
        vhost_client->memory.regions[idx].userspace_addr = (uintptr_t) shm;
    }

    // init vrings on the shm (through memory regions)
    if (vring_table_from_memory_region(vhost_client->vring_table_shm, VHOST_CLIENT_VRING_NUM,
            &vhost_client->memory) != 0) {
        // TODO: handle error here
    }

    return vhost_client;
}
Beispiel #4
0
int	init(t_env* env)
{
	init_env(env);
	tputs(env->cl, 1, id_put);
	init_shm(env);
	init_cadre(env);
	init_player(env);
	return (0);
}
Beispiel #5
0
int BC_Resources::initialize_display(BC_WindowBase *window)
{
// Set up IPC cleanup handlers
//	bc_init_ipc();

// Test for shm.  Must come before yuv test
	init_shm(window);
	return 0;
}
int main() {
    signal(SIGTERM, handler);
    signal(SIGINT, handler);
    signal(SIGQUIT, handler);
    init_shm();
    initialize_online();
    server();
    return EXIT_SUCCESS;
}
Beispiel #7
0
static int32_t
xmms_visualization_client_init_shm (xmms_visualization_t *vis, int32_t id, const char *shmidstr, xmms_error_t *err)
{
	int shmid;

	XMMS_DBG ("Trying to init shm!");

	if (sscanf (shmidstr, "%d", &shmid) != 1) {
		xmms_error_set (err, XMMS_ERROR_INVAL, "couldn't parse shmid");
		return -1;
	}
	return init_shm (vis, id, shmid, err);
}
Beispiel #8
0
int main(int argc, char *argv[]) {
	Display *d = XOpenDisplay(NULL);
	if (!d) {
		printf("Unable to open display\n");
		return;
	}
#ifdef USB_PIXEL
	usb_dev_handle *handle = NULL;

	int usb_present = open_usb(&handle);
	if (!handle) {
		printf("Unable to open usb device, proceeding anyway...\n");
	}
#endif
	int radius = RADIUS;

	init_shm(d, radius);
	init_xinput(d);

	int x = -1;
	int y = -1;
	int old_x = -1;
	int old_y = -1;
	struct rgb_color color;
	color.alpha = 255;
	uint8_t buf[3];
	while(1) {
		wait_for_movement(d, &x, &y);
		if (x != old_x || y != old_y) {
			refresh_image(d, x, y, radius);
			get_pixel_color(d, x, y, &color, radius);
			printf("%d/%d\t(%d/%d/%d)\n", x, y, color.red, color.green, color.blue);
#ifdef USB_PIXEL
			if (usb_present) {
				buf[0] = color.red;
				buf[1] = color.green;
				buf[2] = color.blue;
				int8_t sent = usb_control_msg(handle, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_ENDPOINT_OUT, CUSTOM_RQ_SET_RGB, 0, 0, buf, 3, 100);
				if (sent < 0) {
					printf("Lost contact to USB device\n");
					usb_present = 0;
					handle = NULL;
				}
			}
#endif
			old_x = x;
			old_y = y;
		}
	}
	XCloseDisplay(d);
}
Beispiel #9
0
void reset_all_systems (void)
{
	init_eventtab ();

#ifdef WITH_PPC
	uae_ppc_reset(is_hardreset());
#endif
#ifdef PICASSO96
	picasso_reset ();
#endif
#ifdef SCSIEMU
	scsi_reset ();
	scsidev_reset ();
	scsidev_start_threads ();
#endif
#ifdef A2065
	a2065_reset ();
#endif
#ifdef SANA2
	netdev_reset ();
	netdev_start_threads ();
#endif
#ifdef WITH_PCI
	pci_reset();
#endif
#ifdef FILESYS
	filesys_prepare_reset ();
	filesys_reset ();
#endif
	init_shm ();
	memory_reset ();
#if defined (BSDSOCKET)
	bsdlib_reset ();
#endif
#ifdef FILESYS
	filesys_start_threads ();
	hardfile_reset ();
#endif
#ifdef UAESERIAL
	uaeserialdev_reset ();
	uaeserialdev_start_threads ();
#endif
#ifdef PARALLEL_PORT
	initparallel ();
#endif
	native2amiga_reset ();
	dongle_reset ();
	sampler_init ();
	uae_int_requested = 0;
}
Beispiel #10
0
int mod_register(char *path, int *dlflags, void *p1, void *p2)
{
	if(!shm_initialized() && init_shm()<0)
		return -1;

#ifdef USE_SCTP
	/* shm is used, be sure it is initialized */
	if(sctp_mod_pre_init()<0)
		return -1;
	return 0;
#else
	LOG(L_CRIT, "sctp core support not enabled\n");
	return -1;
#endif
}
Beispiel #11
0
void reset_all_systems (void)
{
	init_eventtab ();

#ifdef PICASSO96
	picasso_reset ();
#endif
#ifdef SCSIEMU
	scsi_reset ();
	scsidev_reset ();
	scsidev_start_threads ();
#endif
#ifdef A2065
	a2065_reset ();
#endif
#ifdef SANA2
	netdev_reset ();
	netdev_start_threads ();
#endif
#ifdef FILESYS
	filesys_prepare_reset ();
	filesys_reset ();
#endif
#ifdef NATMEM_OFFSET
	init_shm ();
#endif
	memory_reset ();
#if defined (BSDSOCKET)
	bsdlib_reset ();
#endif
#ifdef FILESYS
	filesys_start_threads ();
	hardfile_reset ();
#endif
#ifdef UAESERIAL
	uaeserialdev_reset ();
	uaeserialdev_start_threads ();
#endif
#if defined (PARALLEL_PORT)
	initparallel ();
#endif
	native2amiga_reset ();
	dongle_reset ();
#ifdef SAMPLER
	sampler_init ();
#endif
}
Beispiel #12
0
int lua_apr_shm_attach(lua_State *L)
{
  apr_status_t status;
  lua_apr_shm *object;
  const char *filename;

  filename = luaL_checkstring(L, 1);

  object = new_object(L, &lua_apr_shm_type);
  status = apr_pool_create(&object->pool, NULL);
  if (status != APR_SUCCESS)
    return push_error_status(L, status);
  status = apr_shm_attach(&object->handle, filename, object->pool);
  if (status != APR_SUCCESS)
    return push_error_status(L, status);
  init_shm(L, object);

  return 1;
}
Beispiel #13
0
int mod_register(char *path, int *dlflags, void *p1, void *p2)
{
	if (tls_disable) {
		LOG(L_WARN, "tls support is disabled "
				"(set enable_tls=1 in the config to enable it)\n");
		return 0;
	}

	/* shm is used, be sure it is initialized */
	if(!shm_initialized() && init_shm()<0)
		return -1;

	if(tls_pre_init()<0)
		return -1;

	register_tls_hooks(&tls_h);

	return 0;
}
Beispiel #14
0
int biterc_newsession(const char *tmpdir, size_t shm_size)
{
   biterc_session_t *session = NULL;
   int biter_session;
   int result;

   if (biter_cur_session >= BITER_MAX_SESSIONS) {
      biter_lasterror = "Exceeded maximum number of sessions";
      goto error;
   }
   
   biter_session = biter_cur_session++;
   session = sessions + biter_session;

   result = init_shm(tmpdir, shm_size, session);
   if (result == -1)
      goto error;

   result = init_locks(session);
   if (result == -1)
      goto error;

   result = setup_ids(session);
   if (result == -1)
      goto error;

   result = biter_connect(tmpdir, session);
   if (result == -1)
      goto error;
   
   result = init_heap(session);
   if (result == -1)
      goto error;

   return biter_session;

  error:
   return -1;
}
Beispiel #15
0
/*
 * Early initialization of emulator, parsing of command-line options,
 * and loading of config files, etc.
 *
 * TODO: Need better cohesion! Break this sucker up!
 */
static int do_preinit_machine (int argc, char **argv)
{
    if (! graphics_setup ()) {
	exit (1);
    }
    if (restart_config[0]) {
#ifdef FILESYS
	free_mountinfo (currprefs.mountinfo);
#endif
	default_prefs (&currprefs, 0);
	fix_options ();
    }

#ifdef NATMEM_OFFSET
    init_shm ();
#endif

#ifdef FILESYS
    rtarea_init ();
    hardfile_install ();
#endif

    if (restart_config[0])
	parse_cmdline_and_init_file (argc, argv);
    else
	currprefs = changed_prefs;

    uae_inithrtimer ();

    machdep_init ();

    if (! audio_setup ()) {
	write_log ("Sound driver unavailable: Sound output disabled\n");
	currprefs.produce_sound = 0;
    }
    inputdevice_init ();

    return 1;
}
Beispiel #16
0
int lua_apr_shm_create(lua_State *L)
{
  apr_status_t status;
  lua_apr_shm *object;
  const char *filename;
  apr_size_t reqsize;

  filename = lua_isnil(L, 1) ? NULL : luaL_checkstring(L, 1);
  reqsize = luaL_checkinteger(L, 2);

  object = new_object(L, &lua_apr_shm_type);
  if (object == NULL)
    return push_error_memory(L);
  status = apr_pool_create(&object->pool, NULL);
  if (status != APR_SUCCESS)
    return push_error_status(L, status);
  status = apr_shm_create(&object->handle, reqsize, filename, object->pool);
  if (status != APR_SUCCESS)
    return push_error_status(L, status);
  init_shm(L, object);

  return 1;
}
Beispiel #17
0
static int real_main2 (int argc, TCHAR **argv)
{
#if (defined (_WIN32) || defined (_WIN64)) && !defined (NO_WIN32_EXCEPTION_HANDLER)
	extern int EvalException (LPEXCEPTION_POINTERS blah, int n_except);
	__try
#endif
	{

#ifdef USE_SDL
	int result = (SDL_Init (SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) == 0);
	if (result)
		atexit (SDL_Quit);
#endif
	config_changed = 1;
	if (restart_config[0]) {
		default_prefs (&currprefs, 0);
		fixup_prefs (&currprefs);
	}

	if (! graphics_setup ()) {
		write_log ("Graphics Setup Failed\n");
		exit (1);
	}

#ifdef NATMEM_OFFSET
	preinit_shm ();
#endif

	if (restart_config[0])
		parse_cmdline_and_init_file (argc, argv);
	else
		currprefs = changed_prefs;

	uae_inithrtimer ();

	if (!machdep_init ()) {
		write_log ("Machine Init Failed.\n");
		restart_program = 0;
		return -1;
	}

	if (console_emulation) {
		consolehook_config (&currprefs);
		fixup_prefs (&currprefs);
	}

	if (! setup_sound ()) {
		write_log ("Sound driver unavailable: Sound output disabled\n");
		currprefs.produce_sound = 0;
	}
	inputdevice_init ();

	changed_prefs = currprefs;
	no_gui = ! currprefs.start_gui;
	if (restart_program == 2)
		no_gui = 1;
	else if (restart_program == 3)
		no_gui = 0;
	restart_program = 0;
	if (! no_gui) {
		int err = gui_init ();
		currprefs = changed_prefs;
		config_changed = 1;
		if (err == -1) {
			write_log ("Failed to initialize the GUI\n");
			return -1;
		} else if (err == -2) {
			return 1;
		}
	}

#ifdef NATMEM_OFFSET
	init_shm ();
#endif

#ifdef JIT
	if (!(currprefs.cpu_model >= 68020 && currprefs.address_space_24 == 0 && currprefs.cachesize))
		canbang = 0;
#endif

	fixup_prefs (&currprefs);
	changed_prefs = currprefs;
	target_run ();
	/* force sound settings change */
	currprefs.produce_sound = 0;

#ifdef AUTOCONFIG
	/* Install resident module to get 8MB chipmem, if requested */
	rtarea_setup ();
#endif
#ifdef FILESYS
	rtarea_init ();
	uaeres_install ();
	hardfile_install ();
#endif
	savestate_init ();
#ifdef SCSIEMU
	scsi_reset ();
	scsidev_install ();
#endif
#ifdef SANA2
	netdev_install ();
#endif
#ifdef UAESERIAL
	uaeserialdev_install ();
#endif
	keybuf_init (); /* Must come after init_joystick */

#ifdef AUTOCONFIG
	expansion_init ();
#endif
#ifdef FILESYS
	filesys_install ();
#endif
	target_startup_sequence (&currprefs);
	memory_init ();
	memory_reset ();

#ifdef AUTOCONFIG
#if defined (BSDSOCKET)
	bsdlib_install ();
#endif
	emulib_install ();
	uaeexe_install ();
	native2amiga_install ();
#endif

	custom_init (); /* Must come after memory_init */
#ifdef SERIAL_PORT
	serial_init ();
#endif
	DISK_init ();

	reset_frame_rate_hack ();
	init_m68k (); /* must come after reset_frame_rate_hack (); */

	gui_update ();

	if (graphics_init ()) {
#ifdef DEBUGGER
		setup_brkhandler ();
		if (currprefs.start_debugger && debuggable ())
			activate_debugger ();
#endif

		if (!init_audio ()) {
			if (sound_available && currprefs.produce_sound > 1) {
				write_log ("Sound driver unavailable: Sound output disabled\n");
			}
			currprefs.produce_sound = 0;
		}
		start_program ();
	}

    }
#if (defined (_WIN32) || defined (_WIN64)) && !defined (NO_WIN32_EXCEPTION_HANDLER)
#ifdef JIT
    __except( EvalException( GetExceptionInformation(), GetExceptionCode() ) )
#else
	__except (DummyException (GetExceptionInformation (), GetExceptionCode ()))
#endif
	{
		// EvalException does the good stuff...
	}
#endif
	return 0;
}
Beispiel #18
0
static void real_main2 (int argc, char **argv)
{
#if defined (NATMEM_OFFSET) && defined( _WIN32 ) && !defined( NO_WIN32_EXCEPTION_HANDLER )
    extern int EvalException ( LPEXCEPTION_POINTERS blah, int n_except );
    __try
#endif
    {

    if (! graphics_setup ()) {
	exit (1);
    }

    if (restart_config[0]) {
#ifdef FILESYS
	free_mountinfo (currprefs.mountinfo);
        currprefs.mountinfo = alloc_mountinfo ();
#endif
	default_prefs (&currprefs, 0);
	fix_options ();
    }

#ifdef NATMEM_OFFSET
    init_shm ();
#endif

#ifdef FILESYS
    rtarea_init ();
    hardfile_install ();
#endif

    if (restart_config[0])
        parse_cmdline_and_init_file (argc, argv);
    else
	currprefs = changed_prefs;

    uae_inithrtimer ();
    sleep_test ();

    machdep_init ();

    if (! setup_sound ()) {
	write_log ("Sound driver unavailable: Sound output disabled\n");
	currprefs.produce_sound = 0;
    }
    inputdevice_init ();

    changed_prefs = currprefs;
    no_gui = ! currprefs.start_gui;

    if (restart_program == 2)
	no_gui = 1;
    else if (restart_program == 3)
	no_gui = 0;

    if (! no_gui) {
	int err = gui_init ();
	struct uaedev_mount_info *mi = currprefs.mountinfo;
	currprefs = changed_prefs;
	currprefs.mountinfo = mi;
	if (err == -1) {
	    write_log ("Failed to initialize the GUI\n");
	    if (restart_program == 3) {
	       restart_program = 0;
	       return;
	    }
	} else if (err == -2) {
	    restart_program = 0;
	    return;
	}
    }

    restart_program = 0;

#ifdef JIT
    if (!(( currprefs.cpu_level >= 2 ) && ( currprefs.address_space_24 == 0 ) && ( currprefs.cachesize )))
	canbang = 0;
#endif

#ifdef _WIN32
    logging_init(); /* Yes, we call this twice - the first case handles when the user has loaded
		       a config using the cmd-line.  This case handles loads through the GUI. */
#endif
    fix_options ();
    changed_prefs = currprefs;

#ifdef SAVESTATE
    savestate_init ();
#endif
#ifdef SCSIEMU
    scsidev_install ();
#endif
#ifdef AUTOCONFIG
    /* Install resident module to get 8MB chipmem, if requested */
    rtarea_setup ();
#endif

    keybuf_init (); /* Must come after init_joystick */

#ifdef AUTOCONFIG
    expansion_init ();
#endif
    memory_init ();
    memory_reset ();

#ifdef FILESYS
    filesys_install ();
#endif
#ifdef AUTOCONFIG
    bsdlib_install ();
    emulib_install ();
    uaeexe_install ();
    native2amiga_install ();
#endif

    if (custom_init ()) { /* Must come after memory_init */
#ifdef SERIAL_PORT
	serial_init ();
#endif
	DISK_init ();

	reset_frame_rate_hack ();
	init_m68k(); /* must come after reset_frame_rate_hack (); */

	gui_update ();

	if (graphics_init ()) {

#ifdef DEBUGGER
	    setup_brkhandler ();

	    if (currprefs.start_debugger && debuggable ())
		activate_debugger ();
#endif

#ifdef WIN32
#ifdef FILESYS
	    filesys_init (); /* New function, to do 'add_filesys_unit()' calls at start-up */
#endif
#endif
	    if (sound_available && currprefs.produce_sound > 1 && ! init_audio ()) {
		write_log ("Sound driver unavailable: Sound output disabled\n");
		currprefs.produce_sound = 0;
	    }

	    start_program ();
	}
    }

    }
#if defined (NATMEM_OFFSET) && defined( _WIN32 ) && !defined( NO_WIN32_EXCEPTION_HANDLER )
    __except( EvalException( GetExceptionInformation(), GetExceptionCode() ) )
    {
	// EvalException does the good stuff...
    }
#endif
}
Beispiel #19
0
int main() { 
  struct sigaction action;
  /* autres variables (a completer) */
  int semid,i;
    
  setbuf(stdout, NULL);

  /* Creation du segment de memoire partagee */

  // A completer
  if ( (nb_recepteurs = init_shm(sizeof(t_segpart))) == NULL) 
    {
      perror("init_shm");
      exit(1);
    }
  nb_recepteurs->a = 0;
  
  /* creation des semaphores */ 

  // A completer
  if ((semid = creer_sem(NR+2)) == -1) 
    {
      perror("creer_sem");
      exit(1);
    }
 
  /* initialisation des semaphores */ 

  // A completer
  init_un_sem(EMET,1);
  init_un_sem(RECEPT1,0);
  init_un_sem(RECEPT2,0);
  init_un_sem(RECEPT3,0);
  init_un_sem(RECEPT4,0);
  init_un_sem(RECEPT5,0);
  init_un_sem(NBRECEPT,1);

  /* creation des processus emetteurs */ 
  for (i=0; i < NE ;i++)
    {
      if ((emet_pid[i] = fork()) == -1)
	{
	  perror("fork");
	  exit(0);
	}
      else if (emet_pid[i] == 0)
	{
	  emettre(i);
	}
    }

  // A completer - les pid des processus crees doivent
  // etre stockes dans le tableau emet_pid

  /* creation des processus recepteurs */ 

  // A completer - les pid des processus crees doivent
  // etre stockes dans le tableau recep_pid
  for (i=0; i < NR ;i++)
    {
      if ((recep_pid[i] = fork()) == -1)
	{
	  perror("fork");
	  exit(0);
	}
      else if (recep_pid[i] == 0)
	{
	  reception(i+1);
	}
    }

  /* redefinition du traitement de Ctrl-C pour arreter le programme */ 

  sigemptyset(&action.sa_mask);
  action.sa_flags = 0;
  action.sa_handler = handle_sigint;
  sigaction(SIGINT, &action, 0); 
    
  pause();                    /* attente du Ctrl-C  */
  return EXIT_SUCCESS;
} 
Beispiel #20
0
int main(int argc, char* argv[])
{
	int ret = EXIT_SUCCESS;
	int childstatus;
	pid_t pid;
	const char taskname[13]="trinity-main";

	outputstd("Trinity " VERSION "  Dave Jones <*****@*****.**>\n");

	progname = argv[0];

	initpid = getpid();

	page_size = getpagesize();
	num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
	max_children = num_online_cpus;	/* possibly overridden in params. */

	if (init_random() == FALSE)
		exit(EXIT_FAILURE);

	set_seed(0);

	select_syscall_tables();

	create_shm();

	/* We do this before the parse_args because --fds will need to
	 * operate on it when implemented.
	 */
	setup_fd_providers();

	parse_args(argc, argv);

	init_uids();

	change_tmp_dir();

	init_logging();

	init_shm();

	kernel_taint_initial = check_tainted();
	if (kernel_taint_initial != 0)
		output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n");

	if (munge_tables() == FALSE) {
		ret = EXIT_FAILURE;
		goto out;
	}

	if (show_syscall_list == TRUE) {
		dump_syscall_tables();
		goto out;
	}

	init_syscalls();

	if (show_ioctl_list == TRUE) {
		dump_ioctls();
		goto out;
	}

	do_uid0_check();

	if (do_specific_domain == TRUE)
		find_specific_domain(specific_domain_optarg);

	setup_initial_mappings();

	parse_devices();

	pids_init();

	setup_main_signals();

	/* check if we ctrl'c or something went wrong during init. */
	if (shm->exit_reason != STILL_RUNNING)
		goto cleanup_fds;

	init_watchdog();

	/* do an extra fork so that the watchdog and the children don't share a common parent */
	fflush(stdout);
	pid = fork();
	if (pid == 0) {
		shm->mainpid = getpid();

		setup_main_signals();

		no_bind_to_cpu = RAND_BOOL();

		output(0, "Main thread is alive.\n");
		prctl(PR_SET_NAME, (unsigned long) &taskname);
		set_seed(0);

		if (open_fds() == FALSE) {
			if (shm->exit_reason != STILL_RUNNING)
				panic(EXIT_FD_INIT_FAILURE);	// FIXME: Later, push this down to multiple EXIT's.

			exit_main_fail();
		}

		if (dropprivs == TRUE)	//FIXME: Push down into child processes later.
			drop_privs();

		main_loop();

		shm->mainpid = 0;
		_exit(EXIT_SUCCESS);
	}

	/* wait for main loop process to exit. */
	(void)waitpid(pid, &childstatus, 0);

	/* wait for watchdog to exit. */
	waitpid(watchdog_pid, &childstatus, 0);

	output(0, "Ran %ld syscalls. Successes: %ld  Failures: %ld\n",
		shm->stats.total_syscalls_done - 1, shm->stats.successes, shm->stats.failures);

cleanup_fds:

	close_sockets();

	destroy_initial_mappings();

	shutdown_logging();

	ret = set_exit_code(shm->exit_reason);
out:

	exit(ret);
}
void create_shared_objects()
{
int c1 = init_shm(KEY_C1, 1, IPC_CREAT | 0666);
   
   shm_c1 = (int*)shmat(c1, NULL, 0);
}
Beispiel #22
0
int main(int argc, char* argv[])
{
	int ret = EXIT_SUCCESS;
	const char taskname[13]="trinity-main";

	outputstd("Trinity " VERSION "  Dave Jones <*****@*****.**>\n");

	progname = argv[0];

	mainpid = getpid();

	page_size = getpagesize();
	num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
	max_children = num_online_cpus;	/* possibly overridden in params. */

	if (init_random() == FALSE)
		exit(EXIT_FAILURE);

	select_syscall_tables();

	create_shm();

	/* We do this before the parse_args because --fds will need to
	 * operate on the providers list when implemented.
	 */
	setup_fd_providers();

	parse_args(argc, argv);

	init_uids();

	change_tmp_dir();

	init_logging();

	init_shm();

	kernel_taint_initial = check_tainted();
	if (kernel_taint_initial != 0)
		output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n");

	if (munge_tables() == FALSE) {
		ret = EXIT_FAILURE;
		goto out;
	}

	if (show_syscall_list == TRUE) {
		dump_syscall_tables();
		goto out;
	}

	if (show_ioctl_list == TRUE) {
		dump_ioctls();
		goto out;
	}

	if (show_unannotated == TRUE) {
		show_unannotated_args();
		goto out;
	}

	init_syscalls();

	do_uid0_check();

	if (do_specific_domain == TRUE)
		find_specific_domain(specific_domain_optarg);

	pids_init();

	init_object_lists(OBJ_GLOBAL);

	setup_initial_mappings();

	parse_devices();

	/* FIXME: Some better object construction method needed. */
	create_futexes();
	create_sysv_shms();


	setup_main_signals();

	no_bind_to_cpu = RAND_BOOL();

	prctl(PR_SET_NAME, (unsigned long) &taskname);

	if (open_fds() == FALSE) {
		if (shm->exit_reason != STILL_RUNNING)
			panic(EXIT_FD_INIT_FAILURE);	// FIXME: Later, push this down to multiple EXIT's.

		_exit(EXIT_FAILURE);
	}

	if (dropprivs == TRUE)	//FIXME: Push down into child processes later.
		drop_privs();

	main_loop();

	destroy_global_objects();

	output(0, "Ran %ld syscalls. Successes: %ld  Failures: %ld\n",
		shm->stats.total_syscalls_done - 1, shm->stats.successes, shm->stats.failures);

	shutdown_logging();

	ret = set_exit_code(shm->exit_reason);
out:

	exit(ret);
}
Beispiel #23
0
int main(int argc, char **argv) {

	int i;
	char *logfile_name=NULL;
	unsigned int seed=0;
	int sample_rate,paranoid,kernel_watchdog;
	FILE *fff;
	struct utsname uname_info;
	char cpuinfo[BUFSIZ];
	int seed_specified=0;
	int c,j,missing=0;
	time_t timer;
	char buffer[26];
	struct tm* tm_info;
	struct timeval current_time;
	long long interval_start=0;
	double rate;

	/*********************************/
	/* Parse command line parameters */
	/*********************************/

	while ((c=getopt(argc, argv,"hvl:r:s:t:"))!=-1) {
		switch(c) {
			case 'h':	/* help */
				usage(argv[0],1);
				exit(0);
				break;
			case 'v':	/* version */
				usage(argv[0],0);
				exit(0);
				break;
			case 'l':	/* log */
				logging=TYPE_ALL;
				logfile_name=strdup(optarg);
				break;
			case 'r':	/* seed */
				seed=atoi(optarg);
				seed_specified=1;
				printf("Using user-specified random seed of %d\n",seed);
				break;
			case 's':	/* stop */
				stop_after=atoi(optarg);
				break;

			case 't':	/* type */
				type=0;

				for(j=0;j<strlen(optarg);j++) {
					switch(optarg[j]) {
					case 'O': type|=TYPE_OPEN; break;
					case 'C': type|=TYPE_CLOSE; break;
					case 'I': type|=TYPE_IOCTL; break;
					case 'R': type|=TYPE_READ; break;
					case 'M': type|=TYPE_MMAP; break;
					case 'F': type|=TYPE_FORK; break;
					case 'Q': type|=TYPE_TRASH_MMAP; break;
					case 'W': type|=TYPE_WRITE; break;
					case 'P': type|=TYPE_PRCTL; break;
					case 'p': type|=TYPE_POLL; break;
					case 'A': type|=TYPE_ACCESS; break;
					case 'o': type|=TYPE_OVERFLOW; break;
					case 'i': type|=TYPE_MILLION; break;
					default: printf("Unknown type %c\n",
							optarg[j]);
					}
				}
				break;
			default:
				usage(argv[0],1);
				exit(1);
				break;
		}

	}

	/****************/
	/* Open logfile */
	/****************/

	if (logging) {

		if (!strcmp(logfile_name,"-")) {
			log_fd=1;		/* stdout */
		}
		else {
			log_fd=open(logfile_name,O_WRONLY|O_CREAT,0660);
			if (log_fd<0) {
				fprintf(stderr,"Error opening %s: %s\n",
					logfile_name,strerror(errno));
				exit(1);
			}
			fprintf(stderr,"Warning! Using a named log file might disrupt determinism due to the extra file descriptor created.  Consider logging to stdout instead\n\n");
		}
	}

	/****************/
	/* Print banner */
	/****************/

	printf("\n*** perf_fuzzer %s *** by Vince Weaver\n\n",VERSION);

	/*****************/
	/* Print OS info */
	/*****************/

	uname(&uname_info);

	printf("\t%s version %s %s\n",
		uname_info.sysname,uname_info.release,uname_info.machine);

	/*****************/
	/* Print cpuinfo */
	/*****************/

	get_cpuinfo(cpuinfo);
	printf("\tProcessor: %s\n",cpuinfo);

	/*****************/
	/* Print options */
	/*****************/

	if (stop_after)	printf("\tStopping after %d\n",stop_after);
	/* TODO: Make these configurable */
	printf("\tWatchdog enabled with timeout %ds\n",WATCHDOG_TIMEOUT);
	printf("\tWill auto-exit if signal storm detected\n");

	/**********************/
	/* Print logging info */
	/**********************/
	if (logging) {
		printf("\tLogging to file: %s\n",logfile_name);
		printf("\tLogging perf_event_open() failures: %s\n",
			LOG_FAILURES?"yes":"no");
		printf("\tRunning fsync after every syscall: %s\n",
			FSYNC_EVERY?"yes":"no");
	}

	/************************************/
	/* Seed the random number generator */
	/************************************/

	/* should read /dev/urandom instead? */
	if (!seed) {
		seed=time(NULL);
		printf("\tSeeding RNG from time %d\n",seed);
	}
	else {
		printf("\tSeeding RNG with supplied seed %d\n",seed);
	}
	srand(seed);

	/* Write seed to disk so we can find it later */
	fff=fopen("last.seed","w");
	if (fff!=NULL) {
		fprintf(fff,"%d\n",seed);
		fclose(fff);
	}

	if (logging) {
		sprintf(log_buffer,"S %d\n",seed);
		write(log_fd,log_buffer,strlen(log_buffer));
	}

	/************************/
	/* setup watchdog timer */
	/************************/

	/* FIXME: make optional */
        struct sigaction watchdog;

        memset(&watchdog, 0, sizeof(struct sigaction));
        watchdog.sa_sigaction = alarm_handler;
        watchdog.sa_flags = SA_SIGINFO | SA_RESTART;

        if (sigaction( SIGALRM, &watchdog, NULL) < 0) {
                printf("Error setting up alarm handler\n");
        }

        alarm(WATCHDOG_TIMEOUT);

	/******************************/
	/* Initialize data structures */
	/******************************/

	/* Clear errnos count */
	for(i=0;i<MAX_ERRNOS;i++) {
		stats.open_errno_count[i]=0;
		stats.fork_errno_count[i]=0;
	}

	/* Clear type counts */
	for(i=0;i<MAX_OPEN_TYPE;i++) {
		stats.open_type_success[i]=0;
		stats.open_type_fail[i]=0;
	}

	/* Save our pid so we can re-map on replay */
	if (logging) {
		sprintf(log_buffer,"G %d\n",getpid());
		write(log_fd,log_buffer,strlen(log_buffer));
	}

	/* Save the content of /proc/sys/kernel/perf_event_max_sample_rate */
	/* If it has been changed, a replay might not be perfect */
	sample_rate=get_sample_rate();
	if (logging) {
		sprintf(log_buffer,"r %d\n",sample_rate);
		write(log_fd,log_buffer,strlen(log_buffer));
	}

	/* Check kernel watchdog */
	kernel_watchdog=get_kernel_watchdog_value();

	/* Check paranoid setting */
	paranoid=get_paranoid_value();

	/*******************************/
	/* Print reproduce information */
	/*******************************/

	printf("\n\tTo reproduce, try:\n");
	printf("\t\techo %d > /proc/sys/kernel/nmi_watchdog\n",
		kernel_watchdog);
	printf("\t\techo %d > /proc/sys/kernel/perf_event_paranoid\n",
		paranoid);
	printf("\t\techo %d > /proc/sys/kernel/perf_event_max_sample_rate\n",
		sample_rate);

	printf("\t\t");
	for(i=0;i<argc;i++) {
		printf("%s ",argv[i]);
	}

	if (!seed_specified) printf("-r %d",seed);

	printf("\n\n");



	/* Print what we are actually fuzzing */
	/* Sometimes I comment out code and forget */

	missing=0;

	printf("\tFuzzing the following syscalls: ");
	if (type&TYPE_MMAP)  printf("mmap "); else missing++;
	if (type&TYPE_OPEN)  printf("perf_event_open "); else missing++;
	if (type&TYPE_CLOSE) printf("close "); else missing++;
	if (type&TYPE_READ)  printf("read "); else missing++;
	if (type&TYPE_WRITE) printf("write "); else missing++;
	if (type&TYPE_IOCTL) printf("ioctl "); else missing++;
	if (type&TYPE_FORK)  printf("fork "); else missing++;
	if (type&TYPE_PRCTL) printf("prctl "); else missing++;
	if (type&TYPE_POLL)  printf("poll "); else missing++;
	printf("\n");

	if (missing) {
		printf("\t*NOT* Fuzzing the following syscalls: ");
		if (!(type&TYPE_MMAP)) printf("mmap ");
		if (!(type&TYPE_OPEN)) printf("perf_event_open ");
		if (!(type&TYPE_CLOSE)) printf("close ");
		if (!(type&TYPE_READ)) printf("read ");
		if (!(type&TYPE_WRITE)) printf("write ");
		if (!(type&TYPE_IOCTL)) printf("ioctl ");
		if (!(type&TYPE_FORK)) printf("fork ");
		if (!(type&TYPE_PRCTL)) printf("prctl ");
		if (!(type&TYPE_POLL)) printf("poll ");
		printf("\n");
	}

	missing=0;

	printf("\tAlso attempting the following: ");
	if (type&TYPE_OVERFLOW) printf("signal-handler-on-overflow "); else missing++;
	if (type&TYPE_MILLION) printf("busy-instruction-loop "); else missing++;
	if (type&TYPE_ACCESS) printf("accessing-perf-proc-and-sys-files "); else missing++;
	if (type&TYPE_TRASH_MMAP) printf("trashing-the-mmap-page "); else missing++;
	printf("\n");

	if (missing) {
		printf("\t*NOT* attempting the following: ");
		if (!(type&TYPE_OVERFLOW)) printf("signal-handler-on-overflow ");
		if (!(type&TYPE_MILLION)) printf("busy-instruction-loop ");
		if (!(type&TYPE_ACCESS)) printf("accessing-perf-proc-and-sys-files ");
		if (!(type&TYPE_TRASH_MMAP)) printf("trashing-the-mmap-page ");
		printf("\n");
	}

	if (attempt_determinism) {
		printf("\n\tAttempting more deterministic results by:\n\t");
		printf("waitpid-after-killing-child ");
		printf("disabling-overflow-signal-handler ");
		printf("\n");

		/* Disable overflows if trying for determinism */
		if (attempt_determinism) {
			type&=~TYPE_OVERFLOW;
		}
	}

	/******************************************/
	/* Set up to match trinity setup, vaguely */
	/******************************************/

	page_size=getpagesize();
	//printf("Page size=%d\n",page_size);
	num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);

	create_shm();
	create_shm_arrays();
	init_shm();

//	init_shared_pages();

	syscall_perf_event_open.init();

	/* Initialize PMU names if possible */
	/* This depends on trinity exporting the values */
	if (pmus!=NULL) {
		for(i=0;i<num_pmus;i++) {
			if (pmus[i].type<MAX_OPEN_TYPE) {
				stats_set_pmu_name(pmus[i].type,pmus[i].name);
			}
		}
	}


	/************************/
	/* Set up SIGIO handler */
	/************************/

	/* In theory we shouldn't get SIGIO as we set up SIGRT for overflow */
	/* But if the RT queue overflows we will get a SIGIO */
	memset(&sigio, 0, sizeof(struct sigaction));
	sigio.sa_sigaction = sigio_handler;
	sigio.sa_flags = SA_SIGINFO;

	if (sigaction( SIGIO, &sigio, NULL) < 0) {
		printf("Error setting up SIGIO signal handler\n");
     	}


	/* Set up SIGQUIT handler */
	memset(&sigquit, 0, sizeof(struct sigaction));
	sigquit.sa_sigaction = sigquit_handler;
	sigquit.sa_flags = SA_SIGINFO;

	if (sigaction( SIGQUIT, &sigquit, NULL) < 0) {
		printf("Error setting up SIGQUIT signal handler\n");
     	}


	/* Initialize Event Structure */
	for(i=0;i<NUM_EVENTS;i++) {
		event_data[i].active=0;
		event_data[i].fd=0;
		event_data[i].read_size=rand();
	}

	/* Sleep to make it easier to ftrace/ptrace */
	printf("\n\tPid=%d, sleeping 1s\n\n",getpid());
	sleep(1);

	/* Print start time */

	time(&timer);
	tm_info = localtime(&timer);

	strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
	printf("==================================================\n");
	printf("Starting fuzzing at %s\n",buffer);
	printf("==================================================\n");


	gettimeofday(&current_time,NULL);
	interval_start=current_time.tv_sec;

	/****************/
	/* MAIN LOOP	*/
	/****************/

	while(1) {

		switch(rand()%11) {
			case 0:	if (type&TYPE_OPEN) {
					open_random_event(type&TYPE_MMAP,
							type&TYPE_OVERFLOW);
				}
				break;
			case 1: if (type&TYPE_CLOSE) {
//					if (rand()%3==0)
						close_random_event();
				}
				break;
			case 2: if (type&TYPE_IOCTL) {
					ioctl_random_event();
				}
				break;
			case 3: if (type&TYPE_PRCTL) {
					prctl_random_event();
				}
				break;
			case 4: if (type&TYPE_READ) {
					read_random_event();
				}
				break;
			case 5: if (type&TYPE_WRITE) {
					write_random_event();
				}
				break;
			case 6: if (type&TYPE_ACCESS) {
					access_random_file();
				}
				break;
			case 7: if (type&TYPE_FORK) {
					fork_random_event();
				}
				break;
			case 8: if (type&TYPE_POLL) {
					poll_random_event();
				}
				break;
			case 9:if (type&TYPE_MMAP) {
					mmap_random_event(type);
				}
				break;
			default:
				if (type&TYPE_MILLION) {
					run_a_million_instructions();
				}
				break;
		}

#if FSYNC_EVERY
		if (logging) fsync(log_fd);
#endif

		if (throttle_close_event) {
			printf("Closing stuck event %d\n",
				throttle_close_event);
			close_event(throttle_close_event,1);
			throttle_close_event=0;
		}

		next_overflow_refresh=rand()%2;
		next_refresh=rand_refresh();
		stats.total_iterations++;
		watchdog_counter++;

		if ((stop_after) && (stats.total_iterations>=stop_after)) {
			long long end_count;

			end_count=stats.total_iterations%
                                        STATUS_UPDATE_INTERVAL;
			if ((end_count==0) && (stats.total_iterations>0)) {
				end_count=STATUS_UPDATE_INTERVAL;
			}

			gettimeofday(&current_time,NULL);
			rate=((double)(end_count))/
				(current_time.tv_sec-interval_start);

			dump_summary(stderr,1,rate);

			/* Kill child, doesn't happen automatically? */
			if (already_forked) {
				int status;
				kill(forked_pid,SIGKILL);
				waitpid(forked_pid, &status, 0);
			}
			return 0;
		}

		/* Print status update every 10000 iterations      */
		/* Don't print if logging to stdout as it clutters */
		/* up the trace file.				   */
		if (stats.total_iterations%STATUS_UPDATE_INTERVAL==0) {

			gettimeofday(&current_time,NULL);
			rate=((double)STATUS_UPDATE_INTERVAL)/
				(current_time.tv_sec-interval_start);

			if (log_fd!=1) {
				dump_summary(stderr,1,rate);
			}
			else {
				dump_summary(stderr,0,rate);
			}

			interval_start=current_time.tv_sec;
		}
//		fsync(log_fd);
	}

	return 0;

}
Beispiel #24
0
int initialize_server()
{
    int r;
    int f,s;

    if (use_interfaces) {
        f = s = -1;
        if ((first_interface == -1)&&(second_interface == -1))
        {
            // get the first two interfaces (exclude loopback)
            for (r=0;r<sock_no;r++)
            {
                if (!sock_info[r].is_lo)
                {
                    //break;
                    if (f != -1) //the second
		    {
			s = r;
			LOG("Using [%.*s]:%d as alternate bind address\n",sock_info[r].name.len,sock_info[r].name.s,default_port);
			break;
		    }
                    else
		    {
		        LOG("Using [%.*s]:%d as main bind address\n",sock_info[r].name.len,sock_info[r].name.s,default_port);
			f = r;
		    }
                }
                else
                {
                    LOG("NOT using [%.*s]:%d as main bind address.Loopback reason.\n",sock_info[r].name.len,sock_info[r].name.s,default_port);
                }
            }
        }
        else
        {
            // we set the interfaces by command line argument -i
            f = first_interface;
            s = second_interface;
        }

        if ((f == -1)||(s == -1))
	{
	    LOG("Unable to obtain two (2) addresses.\n");
	    return -1;
	}
    }
    else
    {
        /* use IP addresses specified on the command line */
	if (ip2socket_info(&sock_info[0], first_address) == -1) {
	   LOG("Cannot initialize first IP address");
	   return -1;
	}

	if (ip2socket_info(&sock_info[1], second_address) == -1) {
	   LOG("Cannot initialize second IP address");
	   return -1;
	}

	sock_no = 2;
        f = 0; s = 1;
    }

    //saving the ports
    if ((bind_address = duplicate_sock_info(&sock_info[f])) == NULL) goto init_error1;
    bind_address->port_no = default_port;

    if ((bind_address_port = duplicate_sock_info(&sock_info[f])) == NULL) goto init_error1;
    bind_address_port->port_no = default_alternate_port;

    if ((alternate_address = duplicate_sock_info(&sock_info[s])) == NULL) goto init_error1;
    alternate_address->port_no = default_port;

    if ((alternate_address_port = duplicate_sock_info(&sock_info[s])) == NULL) goto init_error1;
    alternate_address_port->port_no = default_alternate_port;

    if (udp_init(bind_address) == -1)
        {
            LOG("Unable to udp_init bind_address\n");
            //goto error;
	    return -1;
        }
    if (udp_init(bind_address_port) == -1)
        {
            LOG("Unable to udp_init bind_address_port\n");
            //goto error;
	    return -2;
        }
    if (udp_init(alternate_address) == -1)
        {
            LOG("Unable to udp_init alternate_address\n");
            //goto error;
	    return -1;
        }
    if (udp_init(alternate_address_port) == -1)
        {
            LOG("Unable to udp_init alternate_address_port\n");
            //goto error;
	    return -2;
        }

    LOG("udp_init succeeded\n");
#ifdef USE_TLS
    if (init_shm(1) < 0)
	{
	    LOG("init_server:failing init_shm\n");
	    cleanup(0);
	    return -1;
	}
#endif
    LOG("initializing server ... ok\n");
    return 0;
init_error1:
    cleanup(0);
    return -1;
}
Beispiel #25
0
static int real_main2 (int argc, TCHAR **argv)
{

#ifdef USE_SDL
	SDL_Init (SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE);
#endif
	set_config_changed ();
	if (restart_config[0]) {
		default_prefs (&currprefs, true, 0);
		fixup_prefs (&currprefs, true);
	}

	if (! graphics_setup ()) {
		exit (1);
	}

#ifdef NATMEM_OFFSET
	//preinit_shm ();
#endif

	if (restart_config[0])
		parse_cmdline_and_init_file (argc, argv);
	else
		currprefs = changed_prefs;

	if (!machdep_init ()) {
		restart_program = 0;
		return -1;
	}

	if (console_emulation) {
		consolehook_config (&currprefs);
		fixup_prefs (&currprefs, true);
	}

	if (! setup_sound ()) {
		write_log (_T("Sound driver unavailable: Sound output disabled\n"));
		currprefs.produce_sound = 0;
	}
	inputdevice_init ();

	changed_prefs = currprefs;
	no_gui = ! currprefs.start_gui;
	if (restart_program == 2)
		no_gui = 1;
	else if (restart_program == 3)
		no_gui = 0;
	restart_program = 0;
	if (! no_gui) {
		int err = gui_init ();
		currprefs = changed_prefs;
		set_config_changed ();
		if (err == -1) {
			write_log (_T("Failed to initialize the GUI\n"));
			return -1;
		} else if (err == -2) {
			return 1;
		}
	}

	memset (&gui_data, 0, sizeof gui_data);
	gui_data.cd = -1;
	gui_data.hd = -1;
	gui_data.md = (currprefs.cs_cd32nvram || currprefs.cs_cdtvram) ? 0 : -1;
	logging_init (); /* Yes, we call this twice - the first case handles when the user has loaded
						 a config using the cmd-line.  This case handles loads through the GUI. */

#ifdef NATMEM_OFFSET
	init_shm ();
#endif
#ifdef WITH_LUA
	uae_lua_init ();
#endif
#ifdef PICASSO96
	picasso_reset ();
#endif

#if 0
#ifdef JIT
	if (!(currprefs.cpu_model >= 68020 && currprefs.address_space_24 == 0 && currprefs.cachesize))
		canbang = 0;
#endif
#endif

	fixup_prefs (&currprefs, true);
#ifdef RETROPLATFORM
	rp_fixup_options (&currprefs);
#endif
	changed_prefs = currprefs;
	target_run ();
	/* force sound settings change */
	currprefs.produce_sound = 0;

	savestate_init ();
	keybuf_init (); /* Must come after init_joystick */

	memory_hardreset (2);
	memory_reset ();

#ifdef AUTOCONFIG
	native2amiga_install ();
#endif
	custom_init (); /* Must come after memory_init */
#ifdef SERIAL_PORT
	serial_init ();
#endif
	DISK_init ();
#ifdef WITH_PPC
	uae_ppc_reset(true);
#endif

	reset_frame_rate_hack ();
	init_m68k (); /* must come after reset_frame_rate_hack (); */

	gui_update ();

	if (graphics_init (true)) {
		setup_brkhandler ();
		if (currprefs.start_debugger && debuggable ())
			activate_debugger ();

		if (!init_audio ()) {
			if (sound_available && currprefs.produce_sound > 1) {
				write_log (_T("Sound driver unavailable: Sound output disabled\n"));
			}
			currprefs.produce_sound = 0;
		}
		start_program ();
	}
	return 0;
}
Beispiel #26
0
int main( int argc , char *argv[]) {
	signal(SIGINT, ctrlHandler);


	n_linhas = linhas("localdns.txt");

	#ifdef DEBUG
	printf("Verificacao dos ficheiros presentes.\n");
	#endif

	if(verifica_ficheiros("localdns.txt") == 0) {
		printf("Ficheiro localdns.txt inexistente!\n");
		exit(1);
	}
	if(verifica_ficheiros("config.txt") == 0) {
		printf("Ficheiro config.txt inexistente!\n");
		exit(1);
	}

	#ifdef DEBUG
	printf("Inicializacoes.\n");
	#endif
	unsigned char buf[65536], *reader, *reader2, qname;
	int sockfd, stop;
	struct DNS_HEADER *dns = NULL;
	struct stats stat;

	struct sockaddr_in servaddr, dest;
	socklen_t len;

	int i, np, r;

	cfg_process = 1;
	stats_process = 1;

	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);

	#ifdef DEBUG
	printf("Criacao das Filas Normal e Prioridade e da lista de Domains locais.\n");
	#endif
	Fila fila_normal = cria_fila();
	Fila fila_prioridade = cria_fila();

	Local l_domains = cria_lista();

	// Hora de arranque do Servidor
	time_t clk = time(NULL);
	strcpy(stat.data_hora_arranque, ctime(&clk));

	// Inicializaco Memoria Partilhada
	init_shm();
	
	ptr_config->flag = 0;

	printf("[PAI - MAIN] PID Main = %d PID DO MEU PAI = %d\n", getpid(), getppid());

	char* data;

	#ifdef DEBUG
	printf("Criacao processo de configuracoes.\n");
	#endif
	if ((cfg_process = fork()) == 0) {
		signal(SIGUSR1, handler_CFG);
		#ifdef DEBUG
		printf("RELEASE CFG.\n");
		printf("Mapeamento de localdns.txt.\n");
		#endif
		mapear("localdns.txt");
		#ifdef DEBUG
		printf("Leitura de config.txt para estrutura em memoria partilhada.\n");
		#endif
		file2memory("config.txt");
		if(signal(SIGALRM, SIG_IGN) == SIG_ERR) {
			perror("SIGALRM Ignore error");
			exit(1);
		}
	} else {
		usleep(200000);

		if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
			perror("Signal ignore error");
			exit(1);
		}

		#ifdef DEBUG
		printf("RELEASE MAIN.\n");
		#endif

		#ifdef DEBUG
		printf("Extrair enderecos e ip's locais do mmap\n");
		#endif
		token_mmap(l_domains, ptr_config->data);

		// Check arguments
		if(argc <= 1) {
			printf("Usage: %s <port>\n", argv[0]);
			exit(1);
		}
		
		// Get server UDP port number
		int port = atoi(argv[1]);
		
		if(port <= 0) {
			printf("Usage: %s <port>\n", argv[0]);
			exit(1);
		}

		// ****************************************
		// Create socket & bind
		// ****************************************
		// Create UDP socket
	    sockfd = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP); //UDP packet for DNS queries
		if (sockfd < 0) {
   	      printf("ERROR opening socket.\n");
			 exit(1);
		}

		// Prepare UDP to bind port
		bzero(&servaddr,sizeof(servaddr));
		servaddr.sin_family = AF_INET;
		servaddr.sin_addr.s_addr=htonl(INADDR_ANY); 
		servaddr.sin_port=htons(port);
		
		// ****************************************
		// Receive questions
		// ****************************************

		// Bind application to UDP port
		int res = bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
		
		if(res < 0) {
	         printf("Error binding to port %d.\n", servaddr.sin_port);
			 
			 if(servaddr.sin_port <= 1024) {
				 printf("To use ports below 1024 you may need additional permitions. Try to use a port higher than 1024.\n");
			 } else {
				 printf("Please make sure this UDP port is not being used.\n");
			 }
			 exit(1);
		}


		#ifdef DEBUG
		printf("Criacao named pipe para as estatisticas\n.");
		#endif
		char* n_pipe = ptr_config->Named_pipe;
		if(verifica_ficheiros(n_pipe) == 1) {
			printf("Named pipe ja existente! A eliminar...\n");
			unlink(n_pipe);
		}
		if(((np = mkfifo(n_pipe, O_CREAT|O_EXCL|0600)<0)) && (errno != EEXIST)) {
			perror("mkfifo");
			exit(1);
		} 
		if (np != 0) {
			fprintf(stderr, "Impossivel criar fifo %s\n", n_pipe);
			return 1;
		}
		if((np = open(n_pipe, O_RDWR)) < 0) {
			perror("Opening Named Pipe");
			exit(1);
		}
	}

	#ifdef DEBUG
	printf("A sair = %d\n", getpid());
	#endif

	#ifdef DEBUG
	printf("Criacao Processo de estatisticas\n");
	#endif
	if(cfg_process != 0) {
		stats_process = fork();
		if(stats_process == 0) {
			if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
				perror("Signal ignore error");
				exit(1);
			}
			#ifdef DEBUG
			printf("RELEASE STATS.\n");
			#endif
		} else {
			usleep(200000);
			if(signal(SIGALRM, SIG_IGN) == SIG_ERR) {
				perror("SIGALRM Ignore error");
				exit(1);
			}
		}
	}

	#ifdef DEBUG 
	printf("Quem chega primeiro = %d\n", getpid()); 
	#endif

	if(cfg_process != 0 && stats_process != 0) {
		#ifdef DEBUG
		printf("A preencher struct para argumento da funcao do thread.\n");
		#endif
		struct thread_data t_data;
		t_data.normal = fila_normal;
		t_data.prioridade = fila_prioridade;
		t_data.domains = l_domains;

		int N_THREADS = ptr_config->N_threads;

		p_threads = malloc(sizeof(*p_threads) * N_THREADS);

		#ifdef DEBUG
		printf("A criar a pool de threads.\n");
		#endif

		for(i=0;i < N_THREADS;i++) {
			pthread_create(p_threads+i, NULL, requester, (void*)&t_data);
		}
		usleep(50000);

		printf("\n\n-- Waiting for DNS message --\n\n");
	}

	while(1) {
		if((cfg_process == 0) && (ptr_config->saida == 1)) {	// MODO MANUNTENCAO
			file2memory("config.txt");
			ptr_config->saida = 0;
			usleep(100000);
			printf("\n-- Waiting for DNS message --\n");
		}
		if(cfg_process != 0 && stats_process != 0) {		// GESTOR PEDIDOS
			usleep(200000);
			
			len = sizeof(dest);

			// Thread blocking!
			if(recvfrom (sockfd, (unsigned char*)buf, 65536 , 0 , (struct sockaddr*)&dest , &len) < 0) {
				perror("Error in recvfrom");
				exit(1);
			}

			printf("DNS message received\n");

			// Process received message
			dns = (struct DNS_HEADER*) buf;
			qname = (unsigned char)buf[sizeof(struct DNS_HEADER)];
			reader = &buf[sizeof(struct DNS_HEADER)];

			// We only need to process the questions
			// We only process DNS messages with one question
			// Get the query fields according to the RFC specification
			struct QUERY query;
			if(ntohs(dns->q_count) == 1) {
				// Get NAME
				query.name = convertRFC2Name(reader,buf,&stop);
				reader = reader + stop;
				
				// Get QUESTION structure
				query.ques = (struct QUESTION*)(reader);
				reader = reader + sizeof(struct QUESTION);
				
				// Check question type. We only need to process A records.
				if(ntohs(query.ques->qtype) == 1) {
					printf("A record request.\n\n");
				} else {
					printf("NOT A record request!! Ignoring DNS message!\n");
					continue;
				}	
			} else {
				printf("\n\nDNS message must contain one question!! Ignoring DNS message!\n\n");
				continue;
			}

			#ifdef DEBUG
			printf("ID PEDIDO = %d\n", dns->id);
			#endif


			/***** VALIDAR PEDIDO *****/
			valido = 0;

			// 1. Verificar se e' localDomain (Se for, vai para a lista prioritaria)
			// TRABALHO DOS THREADS...
			if(strstr(query.name, ptr_config->localDomain) != NULL) {
				valido = 1;
				stat.pedidos_local += 1;
				insere_pedido(fila_prioridade, receber_info(query.name, &dest, dns->id, sockfd));
			} else if(ptr_config->flag % 2 == 0) {	// 2. Verificar se é um dos dominios autorizados (ptr_config->domains[])
				for(i=0; i < ptr_config->n_domains; i++) {
					if(strstr(query.name, ptr_config->domains[i]) != NULL) {
						valido = 1;
						stat.pedidos_externos += 1;
						insere_pedido(fila_normal, receber_info(query.name, &dest, dns->id, sockfd));
						break;
					}
				}
			}

			#ifdef DEBUG
			imprimir_fila(fila_normal);
			imprimir_fila(fila_prioridade);
			#endif

			if(valido == 1) {
				#ifdef DEBUG
				printf("A ENVIAR SINAL PARA A THREAD...\n");
				#endif
				pthread_cond_signal(&cond);		
			} else {	
				if(ptr_config->flag % 2 != 0) {
					printf("Durante o modo de manuntencao apenas pedidos locais sao aceites!\n");
					printf("A enviar 0.0.0.0...\n");	
				} else {
					printf("Pedido negado!\nDe momento os dominios aceites sao:\n");
					for(i=0;i<ptr_config->n_domains;i++) {
						printf("-> Dominio %d = %s\n",i,ptr_config->domains[i]);
					}
				}
				sendReply(dns->id, query.name, inet_addr("0.0.0.0"), sockfd, dest);
				printf("\n\n-- Waiting for DNS message --\n\n");
			}

			if(valido == 0) {
				stat.pedidos_negados += 1;
			}
			stat.total_pedidos += 1;

			// Enviar dados das ESTATISTICAS para o named pipe aqui
			#ifdef DEBUG
			printf("A escrever estatisticas para o named pipe\n.");
			#endif
			write(np, &stat, sizeof(struct stats));
		}
		if (stats_process == 0 && cfg_process != 0) {	// STATS Process
			signal(SIGALRM, handler_alarm);

			Config* ptr;
			if ((ptr = shmat(shmID, NULL, 0)) == (Config *) -1) {
				perror("error in shmat");
				exit(1);
			}

			struct stats st;
			char* n_pipe = ptr_config->Named_pipe;

			if((r = open(n_pipe, O_RDONLY)) < 0) {
				perror("Child open Named pipe");
				exit(1);
			}

			read(r, &st, sizeof(struct stats));
			linha(st.data_hora_arranque);

			time_t clk2 = time(NULL);
			strcpy(st.data_info, ctime(&clk2));
			linha(st.data_info);

			t_p = st.total_pedidos;
			p_n = st.pedidos_negados;
			p_l = st.pedidos_local;
			p_e = st.pedidos_externos;
			strcpy(d_a, st.data_hora_arranque);
			strcpy(u_i, st.data_info);

			alarm(FREQ);
		}
	}

	return 0;
}
Beispiel #27
0
int main(void)
{
    int pid;
    int i, rc;
    char mbuff[64];
    struct deamon_shm *shm;

    pid = fork();

    if(pid < 0) {
        printf("fork failed.\n");
        return -1;
    } else if(pid > 0) {
        printf("parent thread exit.\n");
        return 0;
    }

    /* set child thread */
    setsid();

    /* ch dir */
    chdir("/tmp");

    fd = open("deamon_test.log", O_RDWR | O_CREAT | O_APPEND);
    if(fd < 0) {
        perror("open failed: ");
        return -1;
    }

    /* close fd */
    for(i = 0; i < 3; i++)
        close(i);

    /* register signal */
    signal(SIGTERM, kill_signal);

    shm = init_shm();
    if(!shm) {
        logd("init shm failed.\n");
        return -1;
    }

    this_running = 1;
    while(this_running++) {
        if(shm->state == 1) {
            shm->state = 2;
            sprintf(mbuff, "shm: %s\n", shm->data);
            write(fd, mbuff, strlen(mbuff));
            shm->state = 0;
            if(strcmp(shm->data, "deamon_exit") == 0)
                this_running = 0;
        }
        sprintf(mbuff, "loopping : shm state = %d, data = %s\n", shm->state, shm->data);
        write(fd, mbuff, strlen(mbuff));
        sleep(5);
    }

    shmdt(shm);
    shmctl(shmid, IPC_RMID, 0);

    sprintf(mbuff, "loop end\n");
    write(fd, mbuff, strlen(mbuff));

    close(fd);

    return 0;
}
Beispiel #28
0
static int real_main2 (int argc, TCHAR **argv)
{
#ifdef USE_SDL
	int result = (SDL_Init (SDL_INIT_TIMER | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) == 0);
	if (result)
		atexit (SDL_Quit);
#endif
	set_config_changed ();
	if (restart_config[0]) {
		default_prefs (&currprefs, 0);
		fixup_prefs (&currprefs);
	}

	if (! graphics_setup ()) {
		write_log (_T("Graphics Setup Failed\n"));
		exit (1);
	}

	if (restart_config[0])
		parse_cmdline_and_init_file (argc, argv);
	else
		currprefs = changed_prefs;

//	uae_inithrtimer ();

	if (!machdep_init ()) {
		write_log (_T("Machine Init Failed.\n"));
		restart_program = 0;
		return -1;
	}

	if (console_emulation) {
		consolehook_config (&currprefs);
		fixup_prefs (&currprefs);
	}

	if (! setup_sound ()) {
		write_log (_T("Sound driver unavailable: Sound output disabled\n"));
		currprefs.produce_sound = 0;
	}
	inputdevice_init ();

	changed_prefs = currprefs;
	no_gui = ! currprefs.start_gui;

	if (restart_program == 2)
		no_gui = 1;
	else if (restart_program == 3)
		no_gui = 0;

	restart_program = 0;
	if (! no_gui && currprefs.start_gui) {
		int err = gui_init ();
		currprefs = changed_prefs;
		set_config_changed ();
		if (err == -1) {
			write_log (_T("Failed to initialize the GUI\n"));
			return -1;
		} else if (err == -2) {
			return 1;
		}
	}

	memset (&gui_data, 0, sizeof gui_data);
	gui_data.cd = -1;
	gui_data.hd = -1;
	gui_data.md = -1;

#ifdef NATMEM_OFFSET
	init_shm ();
#endif

#ifdef PICASSO96
	picasso_reset ();
#endif

	fixup_prefs (&currprefs);

#ifdef RETROPLATFORM
	rp_fixup_options (&currprefs);
#endif

	changed_prefs = currprefs;
	target_run ();
	/* force sound settings change */
	currprefs.produce_sound = 0;

	savestate_init ();
	keybuf_init (); /* Must come after init_joystick */

	memory_hardreset (2);
	memory_reset ();

#ifdef AUTOCONFIG
	native2amiga_install ();
#endif

	custom_init (); /* Must come after memory_init */

#ifdef SERIAL_PORT
	serial_init ();
#endif

	DISK_init ();

	reset_frame_rate_hack ();
	init_m68k (); /* must come after reset_frame_rate_hack (); */

	gui_update ();

	if (graphics_init ()) {

#ifdef DEBUGGER
		setup_brkhandler ();
		if (currprefs.start_debugger && debuggable ())
			activate_debugger ();
#endif

		if (!init_audio ()) {
			if (sound_available && currprefs.produce_sound > 1) {
				write_log (_T("Sound driver unavailable: Sound output disabled\n"));
			}
			currprefs.produce_sound = 0;
		}
		start_program ();
	}

	return 0;
}
Beispiel #29
0
int main(int argc, char **argv)
{
	if (argc > 1)
	{
		if (strcasecmp(argv[1], "-v") == 0)
		{
			fprintf(stdout, "compile time [%s %s]\n", __DATE__, __TIME__);
			return -1;
		}
	}

	if (myconfig_init(argc, argv))
	{
		fprintf(stderr, "myconfig_init error [%s]\n", strerror(errno));
		return -1;
	}

	EnterDaemonMode();
	t_path_info path;
	memset(&path, 0, sizeof(path));

	if (init_para(&path))
		return -1;

	int ret = init_shm(&path);
	if (ret < 0)
	{
		LOG(fplog, LOG_ERROR, "init_shm err %m\n");
		report_2_nm(CDC_SHM_INIT_ERR, ID, LN);
		return -1;
	}

	LOG(fplog, LOG_NORMAL, "cdc start ok!\n");
	if (ret == 0 )
	{
		if (cdc_sub(&path, CDC_PLUS))
		{
			LOG(fplog, LOG_ERROR, "init_plus err %m\n");
			report_2_nm(CDC_NORMAL_ERR, ID, LN);
			return -1;
		}
	}
	LOG(fplog, LOG_NORMAL, "plus dir process ok!\n");

	time_t cur = time(NULL);
	time_t last = 0;
	int shm_sync_time = myconfig_get_intval("shm_synctime", 3600);

	while (1)
	{
		cdc_sub(&path, CDC_REALTIME);
		cur = time(NULL);
		if (cur - last >= shm_sync_time)
		{
			last = cur;
			do_sync_2_disk(&path);
		}
		sleep(10);
	}

	logclose(fplog);
	return 0;
}
Beispiel #30
0
static int real_main2 (int argc, TCHAR **argv)
{

#ifdef USE_SDL
	SDL_Init (SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE);
#endif
	config_changed = 1;
	if (restart_config[0]) {
		default_prefs (&currprefs, 0);
		fixup_prefs (&currprefs);
	}

	if (! graphics_setup ()) {
		exit (1);
	}

#ifdef NATMEM_OFFSET
	preinit_shm ();
#endif

	if (restart_config[0])
		parse_cmdline_and_init_file (argc, argv);
	else
		currprefs = changed_prefs;

	if (!machdep_init ()) {
		restart_program = 0;
		return -1;
	}

	if (console_emulation) {
		consolehook_config (&currprefs);
		fixup_prefs (&currprefs);
	}

	if (! setup_sound ()) {
		write_log (L"Sound driver unavailable: Sound output disabled\n");
		currprefs.produce_sound = 0;
	}
	inputdevice_init ();

	changed_prefs = currprefs;
	no_gui = ! currprefs.start_gui;
	if (restart_program == 2)
		no_gui = 1;
	else if (restart_program == 3)
		no_gui = 0;
	restart_program = 0;
	if (! no_gui) {
		int err = gui_init ();
		currprefs = changed_prefs;
		config_changed = 1;
		if (err == -1) {
			write_log (L"Failed to initialize the GUI\n");
			return -1;
		} else if (err == -2) {
			return 1;
		}
	}

	logging_init (); /* Yes, we call this twice - the first case handles when the user has loaded
						 a config using the cmd-line.  This case handles loads through the GUI. */

#ifdef NATMEM_OFFSET
	init_shm ();
#endif

#ifdef JIT
	if (!(currprefs.cpu_model >= 68020 && currprefs.address_space_24 == 0 && currprefs.cachesize))
		canbang = 0;
#endif

	fixup_prefs (&currprefs);
	changed_prefs = currprefs;
	target_run ();
	/* force sound settings change */
	currprefs.produce_sound = 0;

#ifdef AUTOCONFIG
	rtarea_setup ();
#endif
#ifdef FILESYS
	rtarea_init ();
	uaeres_install ();
	hardfile_install ();
#endif
	savestate_init ();
#ifdef SCSIEMU
	scsi_reset ();
	scsidev_install ();
#endif
#ifdef SANA2
	netdev_install ();
#endif
#ifdef UAESERIAL
	uaeserialdev_install ();
#endif
	keybuf_init (); /* Must come after init_joystick */

#ifdef AUTOCONFIG
	expansion_init ();
#endif
#ifdef FILESYS
	filesys_install ();
#endif
	memory_init ();
	memory_reset ();

#ifdef AUTOCONFIG
#if defined (BSDSOCKET)
	bsdlib_install ();
#endif
	emulib_install ();
	uaeexe_install ();
	native2amiga_install ();
#endif

	custom_init (); /* Must come after memory_init */
#ifdef SERIAL_PORT
	serial_init ();
#endif
	DISK_init ();

	reset_frame_rate_hack ();
	init_m68k (); /* must come after reset_frame_rate_hack (); */

	gui_update ();

	if (graphics_init ()) {
		setup_brkhandler ();
		if (currprefs.start_debugger && debuggable ())
			activate_debugger ();

		if (!init_audio ()) {
			if (sound_available && currprefs.produce_sound > 1) {
				write_log (L"Sound driver unavailable: Sound output disabled\n");
			}
			currprefs.produce_sound = 0;
		}
		start_program ();
	}
	return 0;
}