Example #1
0
int
MainHelper::operator()()
{
    parse_standard_options();
    int res = 1;

    try
    {
        setup_logging();
        parse_command_line_arguments();
        check_no_unrecognized();
        print_version_data();

        res = run();
    }
    catch (std::exception& e)
    {
        LOG_FATAL("caught exception: " << e.what());
    }
    catch (...)
    {
        LOG_FATAL("caught unknown exception");
    }

    at_exit();

    google::protobuf::ShutdownProtobufLibrary();

    return res;

}
Example #2
0
  int Main() {
    ScopeExit at_exit(Logger::ExitLogger);
    try {
      Add(std::make_unique<FilesCommand>());
      Add(std::make_unique<MessagesCommand>());
      Add(std::make_unique<NetCommand>());
      Add(std::make_unique<FixCommand>());
      Add(std::make_unique<wwiv::wwivutil::fido::FidoCommand>());

      if (!cmdline_.Parse()) { return 1; }
      const std::string bbsdir(cmdline_.arg("bbsdir").as_string());
      Config config(bbsdir);
      if (!config.IsInitialized()) {
        LOG(ERROR) << "Unable to load CONFIG.DAT.";
        return 1;
      }
      command_config_.reset(new Configuration(bbsdir, &config));
      if (!command_config_->initialized()) {
        LOG(ERROR) << "Unable to load NETWORKS.";
        return 1;
      }
      SetConfigs();
      return cmdline_.Execute();
    } catch (const std::exception& e) {
      LOG(ERROR) << e.what();
    }
    return 1;
  }
Example #3
0
/* ARGSUSED */
static int
linprocfs_mount(struct mount *mp, char *path, caddr_t data, struct ucred *cred)
{
	size_t size;
	int error;

	if (mp->mnt_flag & MNT_UPDATE)
		return (EOPNOTSUPP);

	if (mp->mnt_vfc->vfc_refcount == 1 && (error = at_exit(linprocfs_exit))) {
		kprintf("linprocfs:  cannot register linprocfs_exit with at_exit\n");
		return(error);
	}

	mp->mnt_flag |= MNT_LOCAL;
	mp->mnt_kern_flag |= MNTK_NOSTKMNT;
	mp->mnt_data = 0;
	vfs_getnewfsid(mp);

	vfs_add_vnodeops(mp, &linprocfs_vnode_vops, &mp->mnt_vn_norm_ops);

	size = sizeof("linprocfs") - 1;
	bcopy("linprocfs", mp->mnt_stat.f_mntfromname, size);
	bzero(mp->mnt_stat.f_mntfromname + size, MNAMELEN - size);
	(void)linprocfs_statfs(mp, &mp->mnt_stat, cred);

	return (0);
}
Example #4
0
static void signal_trap(int sig)
{
	Log2(PCSC_LOG_INFO, "Received signal: %d", sig);

	/* do not wait if asked to terminate
	 * avoids waiting after the reader(s) in shutdown for example */
	if (SIGTERM == sig)
	{
		Log1(PCSC_LOG_INFO, "Direct suicide");
		at_exit();
	}

	if (SIGALRM == sig)
	{
		/* normal exit without error */
		ExitValue = EXIT_SUCCESS;
	}

	/* the signal handler is called several times for the same Ctrl-C */
	if (AraKiri == FALSE)
	{
		Log1(PCSC_LOG_INFO, "Preparing for suicide");
		AraKiri = TRUE;

		/* if still in the init/loading phase the AraKiri will not be
		 * seen by the main event loop
		 */
		if (Init)
		{
			Log1(PCSC_LOG_INFO, "Suicide during init");
			at_exit();
		}
	}
	else
	{
		/* if pcscd do not want to die */
		static int lives = 2;

		lives--;
		/* no live left. Something is blocking the normal death. */
		if (0 == lives)
		{
			Log1(PCSC_LOG_INFO, "Forced suicide");
			at_exit();
		}
	}
}
Example #5
0
/**
 * @brief The Server's Message Queue Listener function.
 *
 * An endless loop calls the function \c ProcessEventsServer() to check for
 * messages sent by clients.
 * If the message is valid, \c CreateContextThread() is called to serve this
 * request.
 */
static void SVCServiceRunLoop(void)
{
	int rsp;
	LONG rv;
	uint32_t dwClientID;	/* Connection ID used to reference the Client */

	while (TRUE)
	{
		if (AraKiri)
		{
			/* stop the hotpug thread and waits its exit */
#ifdef USE_USB
			(void)HPStopHotPluggables();
#endif
			(void)SYS_Sleep(1);

			/* now stop all the drivers */
			RFCleanupReaders();
			EHDeinitializeEventStructures();
			ContextsDeinitialize();
			at_exit();
		}

		switch (rsp = ProcessEventsServer(&dwClientID))
		{

		case 0:
			Log2(PCSC_LOG_DEBUG, "A new context thread creation is requested: %d", dwClientID);
			rv = CreateContextThread(&dwClientID);

			if (rv != SCARD_S_SUCCESS)
				Log1(PCSC_LOG_ERROR, "Problem during the context thread creation");
			break;

		case 2:
			/*
			 * timeout in ProcessEventsServer(): do nothing
			 * this is used to catch the Ctrl-C signal at some time when
			 * nothing else happens
			 */
			break;

		case -1:
			Log1(PCSC_LOG_ERROR, "Error in ProcessEventsServer");
			break;

		case -2:
			/* Nothing to do in case of a syscall interrupted
			 * It happens when SIGUSR1 (reload) or SIGINT (Ctrl-C) is received
			 * We just try again */
			break;

		default:
			Log2(PCSC_LOG_ERROR, "ProcessEventsServer unknown retval: %d",
				rsp);
			break;
		}
	}
}
Example #6
0
/*
 * Initialize vnode cache
 */
void
pfs_vncache_load(void)
{
	mtx_init(&pfs_vncache_mutex, "pseudofs_vncache", NULL,
	    MTX_DEF | MTX_RECURSE);
	/* XXX at_exit() can fail with ENOMEN */
	at_exit(pfs_exit);
}
Example #7
0
int
ncp_init(void) {
	ncp_conn_init();
	if (at_exit(ncp_at_exit)) {
		NCPFATAL("can't register at_exit handler\n");
		return ENOMEM;
	}
	ncp_timer_handle = timeout(ncp_timer,NULL,NCP_TIMER_TICK);
	return 0;
}
Example #8
0
int main(int ac, char **av)
{
    parse_args(ac, av);
    setup_sighandler(SIGINT, 0, on_sigint);
    setup_sighandler(SIGALRM, SA_RESTART, update_display);
    alarm(1);
    gl_env.last_update_time = time(NULL);
    gl_env.logtop = new_logtop(gl_env.history_size);
    if (!gl_env.quiet && !gl_env.line_by_line)
        curses_setup();
    run(gl_env.logtop);
    at_exit();
    return EXIT_SUCCESS;
}
Example #9
0
static real
ginvae(arglist *al)	/* like ginv, but enrolling At_reset and At_exit */
{
	static int nginv;
	AmplExports *ae = al->AE;

	if (AEInext < AEIlast) {
		AEInext->n = ++nginv;
		AEInext->ae = ae;
		at_reset(At_reset, AEInext);
		at_exit(At_end, AEInext++);
		}
	return ginv(al);
	}
Example #10
0
void signal_trap(int sig)
{
	/* the signal handler is called several times for the same Ctrl-C */
	if (AraKiri == 0)
	{
		Log1(PCSC_LOG_INFO, "Preparing for suicide");
		AraKiri = 1;

		/* if still in the init/loading phase the AraKiri will not be
		 * seen by the main event loop
		 */
		if (Init)
		{
			Log1(PCSC_LOG_INFO, "Suicide during init");
			at_exit();
		}
	}
}
Example #11
0
File: main.c Project: JelteF/C
/*
 * In this function the input gets checked and the other functions are called
 * in the correct order.
 */
int main (int argc, char **argv) {
    maze_t* maze;
    char *solver[] = {"random solver", "smart random solver", "left wall solver",
                      "right wall solver"
                     };
    walker_t* walker;
    int i, count, dir, printmaze;
    if (argc < 2) {
        printf("The filename of the maze should be passed as an argument\n");
        return 0;
    }

    if (argc > 2) {
        i = atoi(argv[2]);
        if (i < 0) {
            printf("Don't use negative numbers");
            return 0;
        }
    }
    else
        i = 0;

    if (argc > 3) {
        printmaze = atoi(argv[3]);
    }
    else
        printmaze = 1;

    for(; i < AMNT_SOLVERS; i++) {
        srand(SEED);
        dir = NORTH;
        maze = read_maze(argv[1]);
        walker = init_walker(maze);
        count = 0;
        while (count < MAX_STEPS) {
            count++;
            switch(i) {
            case 0:
                dir = random_solver(maze, walker);
                break;
            case 1:
                dir = smart_random_solver_1(maze, walker, dir);
                break;
            case 2:
                dir = left_wall_solver(maze, walker, dir);
                break;
            case 3:
                dir = right_wall_solver(maze, walker, dir);
                break;
            }
            if(printmaze) {
                print_maze(maze, walker->row, walker->col);
                printf("%d\n", count);
            }

            if (at_exit(maze, walker))
                break;
        }
        if (count < MAX_STEPS)
            printf("Found exit using the %s after %d steps\n", solver[i], count);
        printf("Press key to continue\n");
        getchar();
    }
    return 0;

}
Example #12
0
int
gen_rand_network_metrop(Network **RN_p,int real_vec13[14])
{
	int rc=RC_OK;
	int sin_num_of_switchs,dbl_num_of_switchs,num_at_t;
	//int s2,t1,t2;
	int i,j,l;
	int k;  // number of succesful switches
	int w;  // total number of switches
	//int tries; //number of tries to find proper pair of edges to exchange
	//int twin_i,twin_j;
	Network *RN;
	int rand_network_checked=FALSE;
	Res_tbl met_res_tbl;
	//int real_vec13[14];
	int rand_vec13[14];
	//int sub13[14];
	//int add13[14];
	//double E1,E2,dE;
	double E1,E2;
	int	snover,dnover; // maximum # of graph changes at any temperature
	//int nlimit,snlimit,dnlimit; // maximum # of succesful graph changes at any temperature
	int snlimit,dnlimit; // maximum # of succesful graph changes at any temperature
	//int make_change;
	//int numsucc; // how many successful switches already made
	double t;  // the temperature
	int success;
	int dispair=0;
	double dummy;
	int switches_range;
	double *switch_ratio_arr;
	switch_ratio_arr=(double*)calloc(GNRL_ST.rnd_net_num+1,sizeof(double));

	sin_num_of_switchs=0;
	if(G_N->e_sin_num<=1)
			sin_num_of_switchs=0;
		else {
			// num of switches is round(10*(1+rand)*#edges)
			//num of edges in undirfecetd is actually *2 therefore divided by 2
			switches_range=(int)(2*GNRL_ST.r_switch_factor*G_N->e_sin_num);
			sin_num_of_switchs=(int)switches_range+get_rand((int)switches_range);
		}
	if(G_N->e_dbl_num<=1)
			dbl_num_of_switchs=0;
		else {
			// num of switches is round(10*(1+rand)*#edges)
			//num of edges in undirfecetd is actually *2 therefore divided by 2
			switches_range=(int)(2*GNRL_ST.r_switch_factor*G_N->e_dbl_num/2);
			dbl_num_of_switchs=(int)switches_range+get_rand((int)switches_range);
		}

	t=GNRL_ST.t_init;

	if (GNRL_ST.use_stubs_method==TRUE)
	{

		success=0;
		dispair=0;
		while ((success==FALSE)&&(dispair<GEN_NETWORK_DISPAIR))
		{
			//printf("trying ron\n");
			rc=gen_rand_network_stubs_method(&RN);
			if(rc==RC_OK)
				success=TRUE;
			else
				success=FALSE;
			if (success==FALSE)
			{
				//printf("dispair - discard\n");
				dispair++;
			}

		}

		if (dispair==GEN_NETWORK_DISPAIR) // give up try switch method
			gen_rand_network_switches_method_conserve_double_edges(&RN,&dummy);
		else
		{
			success=update_network(RN,G_N);
			if (!success)
			{
				printf("Error - degrees don't match\n");
				at_exit(-1);
			}

			//shuffle_double_edges(RN);

			if (DEBUG_LEVEL>20 && GNRL_ST.out_log_flag)
			{
				fprintf(GNRL_ST.log_fp,"The network :\n\n");
				for (l=1;l<=(*RN).edges_num;l++)
					fprintf(GNRL_ST.log_fp,"%d %d %d\n",(*RN).e_arr[l].t,(*RN).e_arr[l].s,1);
			}
		}
	}

	else

		gen_rand_network_switches_method_conserve_double_edges(&RN, &dummy);



	/**************************************************************/
	/**************************************************************/
	/**************************************************************/
	/* Part II - metropolis algorithm. Perform switches with probability*/
	/**************************************************************/
	/**************************************************************/
	/**************************************************************/

	/**************************************************************/
		/* metropolis parameters depend on num_of _switches*/


	/* otuput real network to _METROP file */



	init_res_tbl(&met_res_tbl);
	list64_init(&met_res_tbl.real);
	met_motifs_search_real(RN,&met_res_tbl,rand_vec13);
	list64_free_mem(met_res_tbl.real);

	E1=energy(real_vec13,rand_vec13);

	w=0;
	if(GNRL_ST.out_metrop_mat_flag) {
		fprintf(GNRL_ST.mat_metrop_fp,"\nreal network\n");
		fprintf(GNRL_ST.mat_metrop_fp,"E=%lf T=%lf\n",E1,t);
		fprintf(GNRL_ST.mat_metrop_fp,"Real triadic census :\n ");
		output13(real_vec13,GNRL_ST.mat_metrop_fp);
		fprintf(GNRL_ST.mat_metrop_fp,"random network\n");
		fprintf(GNRL_ST.mat_metrop_fp,"%lf,%lf \n",E1,t);
		fprintf(GNRL_ST.mat_metrop_fp,"Initial random triadic census :\n ");
		output13(rand_vec13,GNRL_ST.mat_metrop_fp);
	}

/*	nover=sin_num_of_switchs*GNRL_ST.iteration_factor;
	nlimit=nover/10;
	k=0;
	num_at_t=0;
	sin_metrop_switches(&RN,nover,nlimit,GNRL_ST.t_init,real_vec13,rand_vec13);
*/
	if (dbl_num_of_switchs==0)
	{
		snover=sin_num_of_switchs*(int)GNRL_ST.iteration_factor;
		snlimit=snover/10;
		t=sin_metrop_switches(&RN,snover,snlimit,GNRL_ST.t_init,real_vec13,rand_vec13);
	}
	else
	{
		dnover=dbl_num_of_switchs*(int)GNRL_ST.iteration_factor/10;
		dnlimit=dnover/10;
		if (dnover<10)
		{

			dnover=dbl_num_of_switchs;
			dnlimit=dnover;
		}
		t=dbl_metrop_switches(&RN,dnover,dnlimit,GNRL_ST.t_init,real_vec13,rand_vec13);

		snover=sin_num_of_switchs*(int)GNRL_ST.iteration_factor/10;
		snlimit=snover/10;
		k=0;
		num_at_t=0;
		t=sin_metrop_switches(&RN,snover,snlimit,t,real_vec13,rand_vec13);

		if(GNRL_ST.out_metrop_mat_flag) {
			fprintf(GNRL_ST.mat_metrop_fp,"End E\n");
			printf("End E\n");
		}
		for (i=1;i<10;i++)
		{
			E2=energy(real_vec13,rand_vec13);
			if (E2>0)
			{
				t=dbl_metrop_switches(&RN,dnover,dnlimit,t,real_vec13,rand_vec13);
				t=sin_metrop_switches(&RN,snover,snlimit,t,real_vec13,rand_vec13);
			}
		}
	}

	//check that there are no self edges. If there are any then start again
	rand_network_checked = TRUE;
	if(GNRL_ST.calc_self_edges == FALSE){
		for(i=1;i<=RN->vertices_num;i++) {
			if( MatGet(RN->mat,i,i)==1 ) {
				printf("Self edges still exist building random graph again\n");
				rand_network_checked=FALSE;
				free_network_mem(RN);
				break;
			}
		}
	}

	//merge lists to RN->e_arr
	//
	j=0;
	for(i=1;i<=RN->e_dbl_num;i++) {
		RN->e_arr[++j].s=RN->e_arr_dbl[i].s;
		RN->e_arr[j].t=RN->e_arr_dbl[i].t;
	}
	for(i=1;i<=RN->e_sin_num;i++) {
		RN->e_arr[++j].s=RN->e_arr_sin[i].s;
		RN->e_arr[j].t=RN->e_arr_sin[i].t;
	}

	if(DEBUG_LEVEL>1 && GNRL_ST.out_metrop_mat_flag) {
		fprintf(GNRL_ST.mat_metrop_fp,"The network :\n");
		for (i=1;i<=RN->edges_num;i++)
			fprintf(GNRL_ST.mat_metrop_fp,"%d %d %d\n",RN->e_arr[i].t,RN->e_arr[i].s,1);
		fprintf(GNRL_ST.mat_metrop_fp,"End of network\n");
		fprintf(GNRL_ST.mat_metrop_fp,"\n\n");
	}
	if(GNRL_ST.out_metrop_mat_flag) {
		fprintf(GNRL_ST.mat_metrop_fp,"Real triadic census :\n ");
		output13(real_vec13,GNRL_ST.mat_metrop_fp);
		fprintf(GNRL_ST.mat_metrop_fp,"Final random triadic census :\n ");
		output13(rand_vec13,GNRL_ST.mat_metrop_fp);
	}

	*RN_p=RN;
	return RC_OK;
}
Example #13
0
int main(int argc, char **argv)
{
	int rv;
	char setToForeground;
	char HotPlug;
	char *newReaderConfig;
	struct stat fStatBuf;
	int customMaxThreadCounter = 0;
	int customMaxReaderHandles = 0;
	int customMaxThreadCardHandles = 0;
	int opt;
	int limited_rights = FALSE;
	int r;
#ifdef HAVE_GETOPT_LONG
	int option_index = 0;
	static struct option long_options[] = {
		{"config", 1, NULL, 'c'},
		{"foreground", 0, NULL, 'f'},
		{"color", 0, NULL, 'T'},
		{"help", 0, NULL, 'h'},
		{"version", 0, NULL, 'v'},
		{"apdu", 0, NULL, 'a'},
		{"debug", 0, NULL, 'd'},
		{"info", 0, NULL, 0},
		{"error", 0, NULL, 'e'},
		{"critical", 0, NULL, 'C'},
		{"hotplug", 0, NULL, 'H'},
		{"force-reader-polling", optional_argument, NULL, 0},
		{"max-thread", 1, NULL, 't'},
		{"max-card-handle-per-thread", 1, NULL, 's'},
		{"max-card-handle-per-reader", 1, NULL, 'r'},
		{"auto-exit", 0, NULL, 'x'},
		{"reader-name-no-serial", 0, NULL, 'S'},
		{"reader-name-no-interface", 0, NULL, 'I'},
		{NULL, 0, NULL, 0}
	};
#endif
#define OPT_STRING "c:fTdhvaeCHt:r:s:xSI"

	newReaderConfig = NULL;
	setToForeground = FALSE;
	HotPlug = FALSE;

	/*
	 * test the version
	 */
	if (strcmp(PCSCLITE_VERSION_NUMBER, VERSION) != 0)
	{
		printf("BUILD ERROR: The release version number PCSCLITE_VERSION_NUMBER\n");
		printf("  in pcsclite.h (%s) does not match the release version number\n",
			PCSCLITE_VERSION_NUMBER);
		printf("  generated in config.h (%s) (see configure.in).\n", VERSION);

		return EXIT_FAILURE;
	}

	/*
	 * By default we create a daemon (not connected to any output)
	 * so log to syslog to have error messages.
	 */
	DebugLogSetLogType(DEBUGLOG_SYSLOG_DEBUG);

	/* if the process is setuid or setgid it may have some restrictions */
	limited_rights = (getgid() != getegid()) && (getuid() != 0);

	/*
	 * Handle any command line arguments
	 */
#ifdef  HAVE_GETOPT_LONG
	while ((opt = getopt_long (argc, argv, OPT_STRING, long_options, &option_index)) != -1) {
#else
	while ((opt = getopt (argc, argv, OPT_STRING)) != -1) {
#endif
		switch (opt) {
#ifdef  HAVE_GETOPT_LONG
			case 0:
				if (strcmp(long_options[option_index].name,
					"force-reader-polling") == 0)
					HPForceReaderPolling = optarg ? abs(atoi(optarg)) : 1;
				break;
#endif
			case 'c':
				if (limited_rights)
				{
					Log1(PCSC_LOG_CRITICAL, "Can't use a user specified config file");
					return EXIT_FAILURE;
				}
				Log2(PCSC_LOG_INFO, "using new config file: %s", optarg);
				newReaderConfig = optarg;
				break;

			case 'f':
				setToForeground = TRUE;
				/* debug to stdout instead of default syslog */
				DebugLogSetLogType(DEBUGLOG_STDOUT_DEBUG);
				Log1(PCSC_LOG_INFO,
					"pcscd set to foreground with debug send to stdout");
				break;

			case 'T':
				DebugLogSetLogType(DEBUGLOG_STDOUT_COLOR_DEBUG);
				Log1(PCSC_LOG_INFO, "Force colored logs");
				break;

			case 'd':
				DebugLogSetLevel(PCSC_LOG_DEBUG);
				break;

			case 'e':
				DebugLogSetLevel(PCSC_LOG_ERROR);
				break;

			case 'C':
				DebugLogSetLevel(PCSC_LOG_CRITICAL);
				break;

			case 'h':
				print_usage (argv[0]);
				return EXIT_SUCCESS;

			case 'v':
				print_version ();
				return EXIT_SUCCESS;

			case 'a':
				if (limited_rights)
				{
					Log1(PCSC_LOG_CRITICAL, "Can't log APDU (restricted)");
					return EXIT_FAILURE;
				}
				(void)DebugLogSetCategory(DEBUG_CATEGORY_APDU);
				break;

			case 'H':
				/* debug to stdout instead of default syslog */
				DebugLogSetLogType(DEBUGLOG_STDOUT_DEBUG);
				HotPlug = TRUE;
				break;

			case 't':
				customMaxThreadCounter = optarg ? atoi(optarg) : 0;
				if (limited_rights && (customMaxThreadCounter < PCSC_MAX_CONTEXT_THREADS))
					customMaxThreadCounter = PCSC_MAX_CONTEXT_THREADS;
				Log2(PCSC_LOG_INFO, "setting customMaxThreadCounter to: %d",
					customMaxThreadCounter);
				break;

			case 'r':
				customMaxReaderHandles = optarg ? atoi(optarg) : 0;
				if (limited_rights && (customMaxReaderHandles < PCSC_MAX_READER_HANDLES))
					customMaxReaderHandles = PCSC_MAX_READER_HANDLES;
				Log2(PCSC_LOG_INFO, "setting customMaxReaderHandles to: %d",
					customMaxReaderHandles);
				break;

			case 's':
				customMaxThreadCardHandles = optarg ? atoi(optarg) : 0;
				if (limited_rights && (customMaxThreadCardHandles < PCSC_MAX_CONTEXT_CARD_HANDLES))
					customMaxThreadCardHandles = PCSC_MAX_CONTEXT_CARD_HANDLES;
				Log2(PCSC_LOG_INFO, "setting customMaxThreadCardHandles to: %d",
					customMaxThreadCardHandles);
				break;

			case 'x':
				AutoExit = TRUE;
				Log2(PCSC_LOG_INFO, "Auto exit after %d seconds of inactivity",
					TIME_BEFORE_SUICIDE);
				break;

			case 'S':
				Add_Serial_In_Name = FALSE;
				break;

			case 'I':
				Add_Interface_In_Name = FALSE;
				break;

			default:
				print_usage (argv[0]);
				return EXIT_FAILURE;
		}

	}

	if (argv[optind])
	{
		printf("Unknown option: %s\n", argv[optind]);
		print_usage(argv[0]);
		return EXIT_FAILURE;
	}

	/*
	 * Check if systemd passed us any file descriptors
	 */
	rv = sd_listen_fds(0);
	if (rv > 1)
	{
		Log1(PCSC_LOG_CRITICAL, "Too many file descriptors received");
		return EXIT_FAILURE;
	}
	else
	{
		if (rv == 1)
		{
			SocketActivated = TRUE;
			Log1(PCSC_LOG_INFO, "Started by systemd");
		}
		else
			SocketActivated = FALSE;
	}

	/*
	 * test the presence of /var/run/pcscd/pcscd.comm
	 */

	rv = stat(PCSCLITE_CSOCK_NAME, &fStatBuf);

	if (rv == 0)
	{
		pid_t pid;

		/* read the pid file to get the old pid and test if the old pcscd is
		 * still running
		 */
		pid = GetDaemonPid();

		if (pid != -1)
		{
			if (HotPlug)
				return SendHotplugSignal();

			rv = kill(pid, 0);
			if (0 == rv)
			{
				Log1(PCSC_LOG_CRITICAL,
					"file " PCSCLITE_CSOCK_NAME " already exists.");
				Log2(PCSC_LOG_CRITICAL,
					"Another pcscd (pid: %d) seems to be running.", pid);
				return EXIT_FAILURE;
			}
			else
				if (ESRCH == errno)
				{
					/* the old pcscd is dead. make some cleanup */
					clean_temp_files();
				}
				else
				{
					/* permission denied or other error */
					Log2(PCSC_LOG_CRITICAL, "kill failed: %s", strerror(errno));
					return EXIT_FAILURE;
				}
		}
		else
		{
			if (HotPlug)
			{
				Log1(PCSC_LOG_CRITICAL, "file " PCSCLITE_RUN_PID " do not exist");
				Log1(PCSC_LOG_CRITICAL, "Hotplug failed");
				return EXIT_FAILURE;
			}
		}
	}
	else
		if (HotPlug)
		{
			Log1(PCSC_LOG_CRITICAL, "Hotplug failed: pcscd is not running");
			return EXIT_FAILURE;
		}

	/* like in daemon(3): changes the current working directory to the
	 * root ("/") */
	r = chdir("/");
	if (r < 0)
	{
		Log2(PCSC_LOG_CRITICAL, "chdir() failed: %s", strerror(errno));
		return EXIT_FAILURE;
	}

	/*
	 * If this is set to one the user has asked it not to fork
	 */
	if (!setToForeground)
	{
		int pid;
		int fd;

		if (pipe(pipefd) == -1)
		{
			Log2(PCSC_LOG_CRITICAL, "pipe() failed: %s", strerror(errno));
			return EXIT_FAILURE;
		}

		pid = fork();
		if (-1 == pid)
		{
			Log2(PCSC_LOG_CRITICAL, "fork() failed: %s", strerror(errno));
			return EXIT_FAILURE;
		}

		/* like in daemon(3): redirect standard input, standard output
		 * and standard error to /dev/null */
		fd = open("/dev/null", O_RDWR);
		if (fd != -1)
		{
			dup2(fd, STDIN_FILENO);
			dup2(fd, STDOUT_FILENO);
			dup2(fd, STDERR_FILENO);

			/* do not close stdin, stdout or stderr */
			if (fd > 2)
				close(fd);
		}

		if (pid)
		/* in the father */
		{
			char buf;
			int ret;

			/* close write side */
			close(pipefd[1]);

			/* wait for the son to write the return code */
			ret = read(pipefd[0], &buf, 1);
			if (ret <= 0)
				return 2;

			close(pipefd[0]);

			/* exit code */
			return buf;
		}
		else
		/* in the son */
		{
			/* close read side */
			close(pipefd[0]);
		}
	}

	/*
	 * cleanly remove /var/run/pcscd/files when exiting
	 * signal_trap() does just set a global variable used by the main loop
	 */
	(void)signal(SIGQUIT, signal_trap);
	(void)signal(SIGTERM, signal_trap); /* default kill signal & init round 1 */
	(void)signal(SIGINT, signal_trap);	/* sent by Ctrl-C */

	/* exits on SIGALARM to allow pcscd to suicide if not used */
	(void)signal(SIGALRM, signal_trap);

	/*
	 * If PCSCLITE_IPC_DIR does not exist then create it
	 */
	{
		int mode = S_IROTH | S_IXOTH | S_IRGRP | S_IXGRP | S_IRWXU;

		rv = mkdir(PCSCLITE_IPC_DIR, mode);
		if ((rv != 0) && (errno != EEXIST))
		{
			Log2(PCSC_LOG_CRITICAL,
				"cannot create " PCSCLITE_IPC_DIR ": %s", strerror(errno));
			return EXIT_FAILURE;
		}

		/* set mode so that the directory is world readable and
		 * executable even is umask is restrictive
		 * The directory containes files used by libpcsclite */
		(void)chmod(PCSCLITE_IPC_DIR, mode);
	}

	/*
	 * Allocate memory for reader structures
	 */
	rv = RFAllocateReaderSpace(customMaxReaderHandles);
	if (SCARD_S_SUCCESS != rv)
		at_exit();

#ifdef USE_SERIAL
	/*
	 * Grab the information from the reader.conf
	 */
	if (newReaderConfig)
	{
		rv = RFStartSerialReaders(newReaderConfig);
		if (rv != 0)
		{
			Log3(PCSC_LOG_CRITICAL, "invalid file %s: %s", newReaderConfig,
				strerror(errno));
			at_exit();
		}
	}
	else
	{
		rv = RFStartSerialReaders(PCSCLITE_CONFIG_DIR);
		if (rv == -1)
			at_exit();
	}
#endif

	Log1(PCSC_LOG_INFO, "pcsc-lite " VERSION " daemon ready.");

	/*
	 * Record our pid to make it easier
	 * to kill the correct pcscd
	 *
	 * Do not fork after this point or the stored pid will be wrong
	 */
	{
		int f;
		int mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

		f = open(PCSCLITE_RUN_PID, O_RDWR | O_CREAT, mode);
		if (f != -1)
		{
			char pid[PID_ASCII_SIZE];
			ssize_t rr;

			(void)snprintf(pid, sizeof(pid), "%u\n", (unsigned) getpid());
			rr = write(f, pid, strlen(pid) + 1);
			if (rr < 0)
			{
				Log2(PCSC_LOG_CRITICAL,
					"writing " PCSCLITE_RUN_PID " failed: %s",
					strerror(errno));
			}
			(void)close(f);

			/* set mode so that the file is world readable even is umask is
			 * restrictive
			 * The file is used by libpcsclite */
			(void)chmod(PCSCLITE_RUN_PID, mode);
		}
		else
			Log2(PCSC_LOG_CRITICAL, "cannot create " PCSCLITE_RUN_PID ": %s",
				strerror(errno));
	}

	/*
	 * post initialistion
	 */
	Init = FALSE;

	/*
	 * Hotplug rescan
	 */
	(void)signal(SIGUSR1, signal_reload);

	/*
	 * Initialize the comm structure
	 */
	if (SocketActivated)
		rv = ListenExistingSocket(SD_LISTEN_FDS_START + 0);
	else
		rv = InitializeSocket();

	if (rv)
	{
		Log1(PCSC_LOG_CRITICAL, "Error initializing pcscd.");
		at_exit();
	}

	/*
	 * Initialize the contexts structure
	 */
	rv = ContextsInitialize(customMaxThreadCounter, customMaxThreadCardHandles);

	if (rv == -1)
	{
		Log1(PCSC_LOG_CRITICAL, "Error initializing pcscd.");
		at_exit();
	}

	(void)signal(SIGPIPE, SIG_IGN);
	(void)signal(SIGHUP, SIG_IGN);	/* needed for Solaris. The signal is sent
				 * when the shell is existed */

#if !defined(PCSCLITE_STATIC_DRIVER) && defined(USE_USB)
	/*
	 * Set up the search for USB/PCMCIA devices
	 */
	rv = HPSearchHotPluggables();
#ifndef USE_SERIAL
	if (rv)
		at_exit();
#endif

	rv = HPRegisterForHotplugEvents();
	if (rv)
	{
		Log1(PCSC_LOG_ERROR, "HPRegisterForHotplugEvents failed");
		at_exit();
	}

	RFWaitForReaderInit();
#endif

	/*
	 * Set up the power management callback routine
	 */
	(void)PMRegisterForPowerEvents();

	/* initialisation succeeded */
	if (pipefd[1] >= 0)
	{
		char buf = 0;
		ssize_t rr;

		/* write a 0 (success) to father process */
		rr = write(pipefd[1], &buf, 1);
		if (rr < 0)
		{
			Log2(PCSC_LOG_ERROR, "write() failed: %s", strerror(errno));
		}
		close(pipefd[1]);
	}

	SVCServiceRunLoop();

	Log1(PCSC_LOG_ERROR, "SVCServiceRunLoop returned");
	return EXIT_FAILURE;
}

static void at_exit(void)
{
	Log1(PCSC_LOG_INFO, "cleaning " PCSCLITE_IPC_DIR);

	clean_temp_files();

	if (pipefd[1] >= 0)
	{
		char buf;
		ssize_t r;

		/* write the error code to father process */
		buf = ExitValue;
		r = write(pipefd[1], &buf, 1);
		if (r < 0)
		{
			Log2(PCSC_LOG_ERROR, "write() failed: %s", strerror(errno));
		}
		close(pipefd[1]);
	}

	exit(ExitValue);
}
Example #14
0
/*
 * Display the appropriate prompt.
 */
static void
prompt(void)
{
	const char *p;

	if (ungot != NULL) {
		/*
		 * No prompt necessary if commands are from
		 * ungotten chars rather than from the user.
		 */
		return;
	}

	/*
	 * Make sure the screen is displayed.
	 */
	make_display();
	bottompos = position(BOTTOM_PLUS_ONE);

	/*
	 * If we've hit EOF on the last file and the -E flag is set, quit.
	 */
	if (get_quit_at_eof() == OPT_ONPLUS &&
	    eof_displayed() && !(ch_getflags() & CH_HELPFILE) &&
	    next_ifile(curr_ifile) == NULL_IFILE)
		quit(QUIT_OK);

	/*
	 * If the entire file is displayed and the -F flag is set, quit.
	 */
	if (quit_if_one_screen &&
	    entire_file_displayed() && !(ch_getflags() & CH_HELPFILE) &&
	    next_ifile(curr_ifile) == NULL_IFILE)
		quit(QUIT_OK);

	/*
	 * Select the proper prompt and display it.
	 */
	/*
	 * If the previous action was a forward movement,
	 * don't clear the bottom line of the display;
	 * just print the prompt since the forward movement guarantees
	 * that we're in the right position to display the prompt.
	 * Clearing the line could cause a problem: for example, if the last
	 * line displayed ended at the right screen edge without a newline,
	 * then clearing would clear the last displayed line rather than
	 * the prompt line.
	 */
	if (!forw_prompt)
		clear_bot();
	clear_cmd();
	forw_prompt = 0;
	p = prompt_string();
	if (is_filtering())
		putstr("& ");
	if (p == NULL || *p == '\0') {
		putchr(':');
	} else {
		at_enter(AT_STANDOUT);
		putstr(p);
		at_exit();
	}
	clear_eol();
}
Example #15
0
static void on_sigint(int sig)
{
    setup_sighandler(SIGINT, 0, NULL);
    at_exit();
    kill(getpid(), sig);
}
Example #16
0
int
main(int argc, char *argv[]) {
    int rc = 0;
    Network *N = NULL;

    time_measure_start(&GNRL_ST.total_time);

    //process input arguments and init global structure
    rc |= process_input_args(argc, argv);

    if (GNRL_ST.quiet_mode == FALSE)
        printf("mfinder Version %.2f\n\n", VERSION);


    if (rc == RC_ERR)
        at_exit(-1);

    //general initialization
    rc |= gnrl_init();
    if (rc == RC_ERR)
        at_exit(-1);

    // load network from input file
    if (GNRL_ST.quiet_mode == FALSE)
        printf("Loading Network\n");
    load_network(&G_N, input_network_fname);
    duplicate_network(G_N, &N, "real_network");

    init_random_seed();

    if (rc == RC_ERR)
        at_exit(-1);
    if (GNRL_ST.quiet_mode == FALSE)
        printf("Searching motifs size %d\nProcessing Real network...\n", GNRL_ST.mtf_sz);

    //search motifs size n in Real network
    if (GNRL_ST.dont_search_real != TRUE)
        rc |= motifs_search_real(N);
    if (rc == RC_ERR)
        at_exit(-1);

/*
    printf("RES TBL real\n");
    for (l_id = list64_get_next(RES_TBL.real, NULL); l_id != NULL;
            l_id = list64_get_next(RES_TBL.real, l_id))
    {
        printf("id: %d\ncount: %.0f\n", (int)((Motif*)l_id->p)->id,
                ((Motif*)l_id->p)->count);
    }
*/


    if (GNRL_ST.quiet_mode == FALSE)
        printf("Processing Random networks\n");
    if (GNRL_ST.rnd_net_num > 0) {
        // create random networks with same single node statisticfs as the input network
        if (GNRL_ST.r_grassberger == FALSE) {
            //use switches or stubs
            rc |= process_rand_networks(&RES_TBL, GNRL_ST.mtf_sz);
        } else {
            //use grassberger alg
            weights_arr = (double*) calloc(GNRL_ST.rnd_net_num + 1, sizeof (double));
            rc |= process_rand_networks_grassberger(&RES_TBL, GNRL_ST.mtf_sz, weights_arr);
        }
        if (rc == RC_ERR)
            at_exit(-1);
    }

    if (GNRL_ST.quiet_mode == FALSE)
        printf("Calculating Results...\n");
    if (GNRL_ST.rnd_net_num >= 0) {
        //calculate final results and dump them to the results file
        if (!GNRL_ST.r_grassberger) {
            calc_final_results(&RES_TBL, &final_res, &final_res_all, GNRL_ST.rnd_net_num);
        } else {
            //Nadav change for GRASS NEW
            calc_final_results_grassberger(&RES_TBL, FALSE, res_sub_motif, &final_res, &final_res_all, GNRL_ST.rnd_net_num, weights_arr);
        }
    }

    //calculate final results
    time_measure_stop(&GNRL_ST.total_time);
    //output results
    rc |= output_results(final_res, final_res_all);

    free_network_mem(G_N);
    free(G_N);

    final_res_free(final_res);
    final_res_free(final_res_all);

    if (GNRL_ST.r_grassberger)
        free(weights_arr);

    res_tbl_mem_free(&RES_TBL);

    if (GNRL_ST.calc_roles == TRUE) {
        free_mem_role_hash();
        free_roles_res_tbl(GNRL_ST.rnd_net_num);
        free_role_members();
    }

    if (rc == RC_ERR)
        at_exit(-1);

    exit(at_exit(rc));
}
Example #17
0
void lib_shutdown() {
  images_free();
  renderer_enqueue(renderer_shutdown, NULL);
  renderer_enqueue_sync(render_loop_exit, NULL);
  at_exit();
}
Example #18
0
int main(int argc, char **argv)
{
	int rv;
	char setToForeground;
	char HotPlug;
	char *newReaderConfig;
	struct stat fStatBuf;
	int opt;
#ifdef HAVE_GETOPT_LONG
	int option_index = 0;
	static struct option long_options[] = {
		{"config", 1, 0, 'c'},
		{"foreground", 0, 0, 'f'},
		{"help", 0, 0, 'h'},
		{"version", 0, 0, 'v'},
		{"apdu", 0, 0, 'a'},
		{"debug", 0, 0, 'd'},
		{"info", 0, 0, 0},
		{"error", 0, 0, 'e'},
		{"critical", 0, 0, 'C'},
		{"hotplug", 0, 0, 'H'},
		{"force-reader-polling", optional_argument, 0, 0},
		{0, 0, 0, 0}
	};
#endif
#define OPT_STRING "c:fdhvaeCH"

	rv = 0;
	newReaderConfig = NULL;
	setToForeground = 0;
	HotPlug = 0;
	globalArgv = argv;
	
	/*
	 * test the version
	 */
	if (strcmp(PCSCLITE_VERSION_NUMBER, VERSION) != 0)
	{
		printf("BUILD ERROR: The release version number PCSCLITE_VERSION_NUMBER\n");
		printf("  in pcsclite.h (%s) does not match the release version number\n",
			PCSCLITE_VERSION_NUMBER);
		printf("  generated in config.h (%s) (see configure.in).\n", VERSION);

		return EXIT_FAILURE;
	}

	/*
	 * By default we create a daemon (not connected to any output)
	 * The log will go to wherever securityd log output goes.
	 */
	DebugLogSetLogType(DEBUGLOG_NO_DEBUG);

	/*
	 * Handle any command line arguments
	 */
#ifdef  HAVE_GETOPT_LONG
	while ((opt = getopt_long (argc, argv, OPT_STRING, long_options, &option_index)) != -1) {
#else
	while ((opt = getopt (argc, argv, OPT_STRING)) != -1) {
#endif
		switch (opt) {
#ifdef  HAVE_GETOPT_LONG
			case 0:
				if (strcmp(long_options[option_index].name,
					"force-reader-polling") == 0)
					HPForceReaderPolling = optarg ? abs(atoi(optarg)) : 1;
				break;
#endif
			case 'c':
				Log2(PCSC_LOG_INFO, "using new config file: %s", optarg);
				newReaderConfig = optarg;
				break;

			case 'f':
				setToForeground = 1;
				/* debug to stderr instead of default syslog */
				Log1(PCSC_LOG_INFO,
					"pcscd set to foreground with debug send to stderr");
				break;

			case 'd':
				DebugLogSetLogType(DEBUGLOG_STDERR_DEBUG);
				DebugLogSetLevel(PCSC_LOG_DEBUG);
				break;

			case 'e':
				DebugLogSetLogType(DEBUGLOG_STDERR_DEBUG);
				DebugLogSetLevel(PCSC_LOG_ERROR);
				break;

			case 'C':
				DebugLogSetLogType(DEBUGLOG_STDERR_DEBUG);
				DebugLogSetLevel(PCSC_LOG_CRITICAL);
				break;

			case 'h':
				print_usage (argv[0]);
				return EXIT_SUCCESS;

			case 'v':
				print_version ();
				return EXIT_SUCCESS;

			case 'a':
				DebugLogSetCategory(DEBUG_CATEGORY_APDU);
				break;

			case 'H':
				/* debug to stderr instead of default syslog */
				DebugLogSetLogType(DEBUGLOG_STDERR_DEBUG);
				HotPlug = 1;
				break;

			default:
				print_usage (argv[0]);
				return EXIT_FAILURE;
		}

	}

	if (argv[optind])
	{
		printf("Unknown option: %s\n\n", argv[optind]);
		print_usage(argv[0]);
		return EXIT_SUCCESS;
	}

	/*
		If this run of pcscd has the hotplug option, just send a signal to the
		running one and exit
	*/
	
	if (HotPlug)
		return ProcessHotplugRequest();

	/*
	 * test the presence of /var/run/pcsc.comm
	 */

	rv = SYS_Stat(PCSCLITE_CSOCK_NAME, &fStatBuf);

	if (rv == 0)
	{
#ifdef USE_RUN_PID
		pid_t pid;

		/* read the pid file to get the old pid and test if the old pcscd is
		 * still running
		 */
		pid = GetDaemonPid();

		if (pid != -1)
		{
			if (kill(pid, 0) == 0)
			{
				Log2(PCSC_LOG_CRITICAL,
					"Another pcscd (pid: %d) seems to be running.", pid);
				Log1(PCSC_LOG_CRITICAL,
					"Remove " USE_RUN_PID " if pcscd is not running to clear this message.");
				return EXIT_FAILURE;
			}
			else
				/* the old pcscd is dead. Do some cleanup */
				clean_temp_files();
		}
#else
		{
			Log1(PCSC_LOG_CRITICAL,
				"file " PCSCLITE_CSOCK_NAME " already exists.");
			Log1(PCSC_LOG_CRITICAL,
				"Maybe another pcscd is running?");
			Log1(PCSC_LOG_CRITICAL,
				"Remove " PCSCLITE_CSOCK_NAME "if pcscd is not running to clear this message.");
			return EXIT_FAILURE;
		}
#endif
	}

	/*
	 * If this is set to one the user has asked it not to fork
	 */
	if (!setToForeground)
	{
		if (SYS_Daemon(0, 0))
			Log2(PCSC_LOG_CRITICAL, "SYS_Daemon() failed: %s",
				strerror(errno));
	}

	/*
	 * cleanly remove /tmp/pcsc when exiting
	 */
	signal(SIGQUIT, signal_trap);
	signal(SIGTERM, signal_trap);
	signal(SIGINT, signal_trap);
	signal(SIGHUP, signal_trap);

#ifdef USE_RUN_PID
	/*
	 * Record our pid to make it easier
	 * to kill the correct pcscd
	 */
	{
		FILE *f;

		if ((f = fopen(USE_RUN_PID, "wb")) != NULL)
		{
			fprintf(f, "%u\n", (unsigned) getpid());
			fclose(f);
		}
	}
#endif

	/*
	 * If PCSCLITE_IPC_DIR does not exist then create it
	 */
	rv = SYS_Stat(PCSCLITE_IPC_DIR, &fStatBuf);
	if (rv < 0)
	{
		rv = SYS_Mkdir(PCSCLITE_IPC_DIR, S_ISVTX | S_IRWXO | S_IRWXG | S_IRWXU);
		if (rv != 0)
		{
			Log2(PCSC_LOG_CRITICAL,
				"cannot create " PCSCLITE_IPC_DIR ": %s", strerror(errno));
			return EXIT_FAILURE;
		}
	}

	/* cleanly remove /var/run/pcsc.* files when exiting */
	if (atexit(at_exit))
		Log2(PCSC_LOG_CRITICAL, "atexit() failed: %s", strerror(errno));

	/*
	 * Allocate memory for reader structures
	 */
	RFAllocateReaderSpace();

	/*
		Grab the information from the reader.conf. If a file has been specified
		and there is any error, consider it fatal. If no file was explicitly
		specified, ignore if file not present.

		 DBUpdateReaders returns:
		 
		 1	if config file can't be opened
		 -1	if config file is broken
		 0	if all good
	 
		We skip this step if running in 64 bit mode, as serial readers are considered
		legacy code.
	*/

	rv = RFStartSerialReaders(newReaderConfig?newReaderConfig:PCSCLITE_READER_CONFIG);
	if (rv == -1)
	{
		Log3(PCSC_LOG_CRITICAL, "invalid file %s: %s", newReaderConfig,
				strerror(errno));
		at_exit();
	}
	else
	if ((rv == 1) && newReaderConfig)
	{
		Log3(PCSC_LOG_CRITICAL, "file %s can't be opened: %s", 
				 newReaderConfig, strerror(errno));
		at_exit();
	}

	/*
	 * Set the default globals
	 */
	g_rgSCardT0Pci.dwProtocol = SCARD_PROTOCOL_T0;
	g_rgSCardT1Pci.dwProtocol = SCARD_PROTOCOL_T1;
	g_rgSCardRawPci.dwProtocol = SCARD_PROTOCOL_RAW;

	Log1(PCSC_LOG_INFO, "pcsc-lite " VERSION " daemon ready.");

	/*
	 * post initialistion
	 */
	Init = 0;

	/*
	 * signal_trap() does just set a global variable used by the main loop
	 */
	signal(SIGQUIT, signal_trap);
	signal(SIGTERM, signal_trap);
	signal(SIGINT, signal_trap);
	signal(SIGHUP, signal_trap);

	signal(SIGUSR1, signal_reload);

	SVCServiceRunLoop();

	Log1(PCSC_LOG_ERROR, "SVCServiceRunLoop returned");
	return EXIT_FAILURE;
}

void at_exit(void)
{
	Log1(PCSC_LOG_INFO, "cleaning " PCSCLITE_IPC_DIR);

	clean_temp_files();

	SYS_Exit(EXIT_SUCCESS);
}