Example #1
0
int main(int argc, const char* argv[])
{
   setup_signal(SIGTERM, signal_exit);
   setup_signal(SIGINT, signal_exit);

   atexit(SDL_Quit);

   int result = EXIT_SUCCESS;
   try
   {
      amap::window top;

      amap::ptree config;

      amap::engine::init(config);
      amap::engine::loop(&top);
   }
   catch (const std::exception& e)
   {
      fprintf(stderr, "FATAL: %s\n", e.what());
      result = EXIT_FAILURE;
   }

   amap::engine::cleanup();

   return result;
}
Example #2
0
int main(int argc, char* argv[])
{
    setup_signal(SIGTERM, signal_exit);
    setup_signal(SIGINT, signal_exit);

    /* google log */
    google::InitGoogleLogging(argv[0]);
    google::InstallFailureSignalHandler();
    google::LogToStderr();

    /* libwebsocket log */
    lws_set_log_level(5, libwebsocket_log);

    try
    {
        terra::config c;
        c.set("zmq.broker-queue-endpoint", "tcp://localhost:60400");
        c.set("websocket.interface", "0.0.0.0");
        c.set("websocket.port", "60600");

        terra::engine engine(c);

        while (run)
        {
            engine.dispatch(250);
        }
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "ERROR: " << e.what();
    }

    return EXIT_SUCCESS;
}
Example #3
0
File: main.c Project: EmisFR/burp
void setup_signals(void)
{
	// Ignore SIGPIPE - we are careful with read and write return values.
	signal(SIGPIPE, SIG_IGN);

	setup_signal(SIGHUP, huphandler);
	setup_signal(SIGUSR2, usr2handler);
}
Example #4
0
int main(int argc, char* argv[])
{
    setup_signal(SIGTERM, signal_exit);
    setup_signal(SIGINT, signal_exit);

    /* google log */
    google::InitGoogleLogging(argv[0]);
    google::InstallFailureSignalHandler();
    google::LogToStderr();

    const char* id = "simple-node";
    if (argc > 1)
        id = argv[1];

    try
    {
        terra::message msg;
        msg.set_id(id);
        msg.set_type(terra::message::HEARTBEAT);

        zmq::context_t ctx(1);
        zmq::socket_t socket(ctx, ZMQ_PUB);
        socket.connect("tcp://localhost:60300");

        msg.set_heartbeat(0);

        while (run)
        {
            msg.set_timestamp(terra::timestamp::now());

            zmq::message_t zmq_message(msg.ByteSize());
            msg.SerializeToArray(zmq_message.data(), zmq_message.size());

            LOG(INFO) << "sending message { size = " << zmq_message.size() << " }";
            socket.send(zmq_message);
            msg.set_heartbeat(msg.heartbeat() + 1);

            sleep(2);
        }

        socket.close();
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "ERROR: " << e.what();
    }

    return EXIT_SUCCESS;
}
Example #5
0
int setup_signals(int oldmax_children, int max_children,
	int oldmax_status_children, int max_status_children)
{
	// Ignore SIGPIPE - we are careful with read and write return values.
	signal(SIGPIPE, SIG_IGN);

	chld_setup(oldmax_children, max_children,
		oldmax_status_children, max_status_children);

	setup_signal(SIGCHLD, sigchld_handler);
	setup_signal(SIGHUP, huphandler);
	setup_signal(SIGUSR2, usr2handler);

	return 0;
}
Example #6
0
static void cleanup_tty(void)
{ 
	if(tty && need_tty_reset) {
		restore_tty (&in_orig);
		setup_signal();
	}
}
Example #7
0
/** 
 * Create the Main Frame
 * 
 * @param window   A GtkWindow that you want to create
 */
void setupMainFrame( GtkWidget *window )
{
        MainWindow = window;
        
        gtk_window_set_title( GTK_WINDOW( window ), "身份證字號產生器" );
        gtk_window_set_position( GTK_WINDOW( window ), GTK_WIN_POS_CENTER );
        gtk_window_set_default_size( GTK_WINDOW( window ), 325, 100 );
        gtk_window_set_resizable(GTK_WINDOW(window), FALSE);

        gtk_container_set_border_width( GTK_CONTAINER( window ), 15 );

        /* 產生 vbox */
        vbox = gtk_vbox_new( TRUE, 5 );
        gtk_container_add( GTK_CONTAINER( window ), vbox );
        gtk_widget_show (vbox);

        /* 產生 hbox 1 */
        hbox1 = gtk_hbox_new( FALSE, 10 );

        /* 產生 hbox 2 */
        hbox2 = gtk_hbox_new( FALSE, 10 );

        /* 產生所有需要用到的 label */
        label_id = gtk_label_new( "身份證字號" );
        label_sex = gtk_label_new( "性別" );
        label_area = gtk_label_new( "登記地" );

        /* 產生放置身份證字號的 txt行 */
        lineEdit = gtk_entry_new();

        /* 產生所需要的按鈕 */
        btn_gen = gtk_button_new_with_label( "產生" );
        
        /* 產生所有需要用到的combobox */
        cbox_sex = gtk_combo_box_new_text();
        cbox_area = gtk_combo_box_new_text();

        /* 修正大小  */
        gtk_widget_set_size_request( lineEdit, 180, 20 );
        gtk_widget_set_size_request( btn_gen, 50, 30 );

        
        /* 佈局管理 */
        gtk_box_pack_start( GTK_BOX( hbox1 ), label_id, FALSE, FALSE, 0 );
        gtk_box_pack_start( GTK_BOX( hbox1 ), lineEdit, FALSE, FALSE, 0 );
        gtk_box_pack_start( GTK_BOX( hbox1 ), btn_gen, FALSE, FALSE, 0 );

        gtk_box_pack_start( GTK_BOX( vbox ), hbox1, FALSE, FALSE, 0 );
        gtk_box_pack_start( GTK_BOX( vbox ), hbox2, FALSE, FALSE, 0 );

        gtk_box_pack_end( GTK_BOX( hbox2 ), cbox_area, FALSE, FALSE, 0 );
        gtk_box_pack_end( GTK_BOX( hbox2 ), label_area, FALSE, FALSE, 0 );
        gtk_box_pack_end( GTK_BOX( hbox2 ), cbox_sex, FALSE, FALSE, 0 );
        gtk_box_pack_end( GTK_BOX( hbox2 ), label_sex, FALSE, FALSE, 0 );

        setup_comboBox();
        setup_signal();
}
Example #8
0
void
setup_all_signals(psighandler interrupt, psighandler jc)
{
    /*
     * Catch the four signals that POSIX specifies if they aren't ignored.
     * handle_signal will take care of calling JobInterrupt if appropriate.
     */
    setup_signal(SIGINT, interrupt);
    setup_signal(SIGHUP, interrupt);
    setup_signal(SIGQUIT, interrupt);
    setup_signal(SIGTERM, interrupt);
    setup_signal(SIGTSTP, jc);
    setup_signal(SIGTTOU, jc);
    setup_signal(SIGTTIN, jc);
    setup_signal(SIGWINCH, jc);
    setup_signal(SIGCONT, jc);
    got_signal = 0;
}
Example #9
0
File: main.c Project: Apercu/42sh
int					main(int ac, char **av, char **env)
{
	t_ctx	*ctx;

	ctx = CTX;
	(void)ac;
	(void)av;
	ctx = CTX;
	ft_term_init();
	setup_signal();
	ft_copy_tab(&ctx->env, env);
	ft_load_history(ctx, 0, NULL, NULL);
	ft_aff_prompt();
	ft_loop();
	ft_reset_term();
	return (0);
}
Example #10
0
static void set_raw_tty(int mode)
{
	Terminal in_raw;

	if(mode != tty_mode && mode != -1) {
		if(!handlerIsSet) {
			/* Determine existing TTY settings */
			gtty (STDIN, &in_orig);
			need_tty_reset = 1;

			/* Restore original TTY settings on exit */
			atexit(cleanup_tty);
			handlerIsSet = 1;
		}


		setup_signal();
		signal (SIGALRM, (SIG_CAST) tty_time_out);
	
		/* Change STDIN settings to raw */

		gtty (STDIN, &in_raw);
		if(mode) {
#ifdef USE_SGTTY
			in_raw.sg_flags |= CBREAK;
#else
			in_raw.c_lflag &= ~ICANON;
			in_raw.c_cc[VMIN]=1;
			in_raw.c_cc[VTIME]=0;			
#endif
			stty (STDIN, &in_raw);
		} else {
#ifdef USE_SGTTY
			in_raw.sg_flags &= ~CBREAK;
#else
			in_raw.c_lflag |= ICANON;
#endif
			stty (STDIN, &in_raw);
		}
		tty_mode = mode;
		discard_input(STDIN);
	}
}
Example #11
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    void *kadm_handle;
    kadm5_server_context *server_context;
    kadm5_config_params conf;
    krb5_socket_t signal_fd, listen_fd;
    int log_fd;
    slave *slaves = NULL;
    uint32_t current_version = 0, old_version = 0;
    krb5_keytab keytab;
    int optidx;
    char **files;

    optidx = krb5_program_setup(&context, argc, argv, args, num_args, NULL);

    if(help_flag)
	krb5_std_usage(0, args, num_args);
    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    setup_signal();

    if (config_file == NULL) {
	asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
	if (config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if (ret)
	krb5_err(context, 1, ret, "reading configuration files");

    time_before_gone = parse_time (slave_time_gone,  "s");
    if (time_before_gone < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", slave_time_gone);
    time_before_missing = parse_time (slave_time_missing,  "s");
    if (time_before_missing < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", slave_time_missing);

#ifdef SUPPORT_DETACH
    if (detach_from_console)
	daemon(0, 0);
#endif
    pidfile (NULL);
    krb5_openlog (context, "ipropd-master", &log_facility);
    krb5_set_warn_dest(context, log_facility);

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    ret = krb5_kt_resolve(context, keytab_str, &keytab);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_resolve: %s", keytab_str);

    memset(&conf, 0, sizeof(conf));
    if(realm) {
	conf.mask |= KADM5_CONFIG_REALM;
	conf.realm = realm;
    }
    ret = kadm5_init_with_skey_ctx (context,
				    KADM5_ADMIN_SERVICE,
				    NULL,
				    KADM5_ADMIN_SERVICE,
				    &conf, 0, 0,
				    &kadm_handle);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");

    server_context = (kadm5_server_context *)kadm_handle;

    log_fd = open (server_context->log_context.log_file, O_RDONLY, 0);
    if (log_fd < 0)
	krb5_err (context, 1, errno, "open %s",
		  server_context->log_context.log_file);

    signal_fd = make_signal_socket (context);
    listen_fd = make_listen_socket (context, port_str);

    kadm5_log_get_version_fd (log_fd, &current_version);

    krb5_warnx(context, "ipropd-master started at version: %lu",
	       (unsigned long)current_version);

    while(exit_flag == 0){
	slave *p;
	fd_set readset;
	int max_fd = 0;
	struct timeval to = {30, 0};
	uint32_t vers;

#ifndef NO_LIMIT_FD_SETSIZE
	if (signal_fd >= FD_SETSIZE || listen_fd >= FD_SETSIZE)
	    krb5_errx (context, 1, "fd too large");
#endif

	FD_ZERO(&readset);
	FD_SET(signal_fd, &readset);
	max_fd = max(max_fd, signal_fd);
	FD_SET(listen_fd, &readset);
	max_fd = max(max_fd, listen_fd);

	for (p = slaves; p != NULL; p = p->next) {
	    if (p->flags & SLAVE_F_DEAD)
		continue;
	    FD_SET(p->fd, &readset);
	    max_fd = max(max_fd, p->fd);
	}

	ret = select (max_fd + 1,
		      &readset, NULL, NULL, &to);
	if (ret < 0) {
	    if (errno == EINTR)
		continue;
	    else
		krb5_err (context, 1, errno, "select");
	}

	if (ret == 0) {
	    old_version = current_version;
	    kadm5_log_get_version_fd (log_fd, &current_version);

	    if (current_version > old_version) {
		krb5_warnx(context,
			   "Missed a signal, updating slaves %lu to %lu",
			   (unsigned long)old_version,
			   (unsigned long)current_version);
		for (p = slaves; p != NULL; p = p->next) {
		    if (p->flags & SLAVE_F_DEAD)
			continue;
		    send_diffs (context, p, log_fd, database, current_version);
		}
	    }
	}

	if (ret && FD_ISSET(signal_fd, &readset)) {
#ifndef NO_UNIX_SOCKETS
	    struct sockaddr_un peer_addr;
#else
	    struct sockaddr_storage peer_addr;
#endif
	    socklen_t peer_len = sizeof(peer_addr);

	    if(recvfrom(signal_fd, (void *)&vers, sizeof(vers), 0,
			(struct sockaddr *)&peer_addr, &peer_len) < 0) {
		krb5_warn (context, errno, "recvfrom");
		continue;
	    }
	    --ret;
	    assert(ret >= 0);
	    old_version = current_version;
	    kadm5_log_get_version_fd (log_fd, &current_version);
	    if (current_version > old_version) {
		krb5_warnx(context,
			   "Got a signal, updating slaves %lu to %lu",
			   (unsigned long)old_version,
			   (unsigned long)current_version);
		for (p = slaves; p != NULL; p = p->next) {
		    if (p->flags & SLAVE_F_DEAD)
			continue;
		    send_diffs (context, p, log_fd, database, current_version);
		}
	    } else {
		krb5_warnx(context,
			   "Got a signal, but no update in log version %lu",
			   (unsigned long)current_version);
	    }
        }

	for(p = slaves; p != NULL; p = p->next) {
	    if (p->flags & SLAVE_F_DEAD)
	        continue;
	    if (ret && FD_ISSET(p->fd, &readset)) {
		--ret;
		assert(ret >= 0);
		if(process_msg (context, p, log_fd, database, current_version))
		    slave_dead(context, p);
	    } else if (slave_gone_p (p))
		slave_dead(context, p);
	    else if (slave_missing_p (p))
		send_are_you_there (context, p);
	}

	if (ret && FD_ISSET(listen_fd, &readset)) {
	    add_slave (context, keytab, &slaves, listen_fd);
	    --ret;
	    assert(ret >= 0);
	}
	write_stats(context, slaves, current_version);
    }

    if(exit_flag == SIGINT || exit_flag == SIGTERM)
	krb5_warnx(context, "%s terminated", getprogname());
#ifdef SIGXCPU
    else if(exit_flag == SIGXCPU)
	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
#endif
    else
	krb5_warnx(context, "%s unexpected exit reason: %ld",
		   getprogname(), (long)exit_flag);

    write_master_down(context);

    return 0;
}
Example #12
0
int
main(int argc, char *argv[]) {
	int i, use_ewmh_dock=0;
	char *action_string = NULL;
	char *endptr, *fnpre = NULL;

	/* default values */
	dzen.title_win.name = "dzen title";
	dzen.slave_win.name = "dzen slave";
	dzen.cur_line  = 0;
	dzen.ret_val   = 0;
	dzen.title_win.x = dzen.slave_win.x = 0;
	dzen.title_win.y = 0;
	dzen.title_win.width = dzen.slave_win.width = 0;
	dzen.title_win.alignment = ALIGNCENTER;
	dzen.slave_win.alignment = ALIGNLEFT;
	dzen.fnt = FONT;
	dzen.bg  = BGCOLOR;
	dzen.fg  = FGCOLOR;
	dzen.slave_win.max_lines  = 0;
	dzen.running = True;
	dzen.xinescreen = 0;
	dzen.tsupdate = 0;
	dzen.line_height = 0;
	dzen.title_win.expand = noexpand;

	/* Connect to X server */
	x_connect();
	x_read_resources();

	/* cmdline args */
	for(i = 1; i < argc; i++)
		if(!strncmp(argv[i], "-l", 3)){
			if(++i < argc) {
				dzen.slave_win.max_lines = atoi(argv[i]);
				if(dzen.slave_win.max_lines)
					init_input_buffer();
			}
		}
		else if(!strncmp(argv[i], "-geometry", 10)) {
			if(++i < argc) {
				int t;
				int tx, ty;
				unsigned int tw, th;

				t = XParseGeometry(argv[i], &tx, &ty, &tw, &th);

				if(t & XValue)
					dzen.title_win.x = tx;
				if(t & YValue) {
					dzen.title_win.y = ty;
					if(!ty && (t & YNegative))
						/* -0 != +0 */
						dzen.title_win.y = -1;
				}
				if(t & WidthValue)
					dzen.title_win.width = (signed int) tw;
				if(t & HeightValue)
					dzen.line_height = (signed int) th;
			}
		}
		else if(!strncmp(argv[i], "-u", 3)){
			dzen.tsupdate = True;
		}
		else if(!strncmp(argv[i], "-expand", 8)){
			if(++i < argc) {
				switch(argv[i][0]){
					case 'l':
						dzen.title_win.expand = left;
						break;
					case 'c':
						dzen.title_win.expand = both;
						break;
					case 'r':
						dzen.title_win.expand = right;
						break;
					default:
						dzen.title_win.expand = noexpand;
				}
			}
		}
		else if(!strncmp(argv[i], "-p", 3)) {
			dzen.ispersistent = True;
			if (i+1 < argc) {
				dzen.timeout = strtoul(argv[i+1], &endptr, 10);
				if(*endptr)
					dzen.timeout = 0;
				else
					i++;
			}
		}
		else if(!strncmp(argv[i], "-ta", 4)) {
			if(++i < argc) dzen.title_win.alignment = alignment_from_char(argv[i][0]);
		}
		else if(!strncmp(argv[i], "-sa", 4)) {
			if(++i < argc) dzen.slave_win.alignment = alignment_from_char(argv[i][0]);
		}
		else if(!strncmp(argv[i], "-m", 3)) {
			dzen.slave_win.ismenu = True;
			if(i+1 < argc) {
				if( argv[i+1][0] == 'v') {
					++i;
					break;
				}
				dzen.slave_win.ishmenu = (argv[i+1][0] == 'h') ? ++i, True : False;
			}
		}
		else if(!strncmp(argv[i], "-fn", 4)) {
			if(++i < argc) dzen.fnt = argv[i];
		}
		else if(!strncmp(argv[i], "-e", 3)) {
			if(++i < argc) action_string = argv[i];
		}
		else if(!strncmp(argv[i], "-title-name", 12)) {
			if(++i < argc) dzen.title_win.name = argv[i];
		}
		else if(!strncmp(argv[i], "-slave-name", 12)) {
			if(++i < argc) dzen.slave_win.name = argv[i];
		}
		else if(!strncmp(argv[i], "-bg", 4)) {
			if(++i < argc) dzen.bg = argv[i];
		}
		else if(!strncmp(argv[i], "-fg", 4)) {
			if(++i < argc) dzen.fg = argv[i];
		}
		else if(!strncmp(argv[i], "-x", 3)) {
			if(++i < argc) dzen.title_win.x = dzen.slave_win.x = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-y", 3)) {
			if(++i < argc) dzen.title_win.y = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-w", 3)) {
			if(++i < argc) dzen.slave_win.width = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-h", 3)) {
			if(++i < argc) dzen.line_height= atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-tw", 4)) {
			if(++i < argc) dzen.title_win.width = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-fn-preload", 12)) {
			if(++i < argc) {
				fnpre = estrdup(argv[i]);
			}
		}
#ifdef DZEN_XINERAMA
		else if(!strncmp(argv[i], "-xs", 4)) {
			if(++i < argc) dzen.xinescreen = atoi(argv[i]);
		}
#endif
		else if(!strncmp(argv[i], "-dock", 6))
			use_ewmh_dock = 1;
		else if(!strncmp(argv[i], "-v", 3)) {
			printf("dzen-"VERSION", (C)opyright 2007-2009 Robert Manea\n");
			printf(
			"Enabled optional features: "
#ifdef DZEN_XMP
			" XPM "
#endif
#ifdef DZEN_XFT
			" XFT"
#endif
#ifdef DZEN_XINERAMA
			" XINERAMA "
#endif
			"\n"
			);
			return EXIT_SUCCESS;
		}
		else
			eprint("usage: dzen2 [-v] [-p [seconds]] [-m [v|h]] [-ta <l|c|r>] [-sa <l|c|r>]\n"
                   "             [-x <pixel>] [-y <pixel>] [-w <pixel>] [-h <pixel>] [-tw <pixel>] [-u]\n"
				   "             [-e <string>] [-l <lines>]  [-fn <font>] [-bg <color>] [-fg <color>]\n"
				   "             [-geometry <geometry string>] [-expand <left|right>] [-dock]\n"
				   "             [-title-name <string>] [-slave-name <string>]\n"
#ifdef DZEN_XINERAMA
				   "             [-xs <screen>]\n"
#endif
				  );

	if(dzen.tsupdate && !dzen.slave_win.max_lines)
		dzen.tsupdate = False;

	if(!dzen.title_win.width)
		dzen.title_win.width = dzen.slave_win.width;

	if(!setlocale(LC_ALL, "") || !XSupportsLocale())
		puts("dzen: locale not available, expect problems with fonts.\n");

	if(action_string)
		fill_ev_table(action_string);
	else {
		if(!dzen.slave_win.max_lines) {
			char edef[] = "button3=exit:13";
			fill_ev_table(edef);
		}
		else if(dzen.slave_win.ishmenu) {
			char edef[] = "enterslave=grabkeys;leaveslave=ungrabkeys;"
				"button4=scrollup;button5=scrolldown;"
				"key_Left=scrollup;key_Right=scrolldown;"
				"button1=menuexec;button3=exit:13;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
		else {
			char edef[]  = "entertitle=uncollapse,grabkeys;"
				"enterslave=grabkeys;leaveslave=collapse,ungrabkeys;"
				"button1=menuexec;button2=togglestick;button3=exit:13;"
				"button4=scrollup;button5=scrolldown;"
				"key_Up=scrollup;key_Down=scrolldown;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
	}

	if((find_event(onexit) != -1)
			&& (setup_signal(SIGTERM, catch_sigterm) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGTERM\n");

	if((find_event(sigusr1) != -1)
			&& (setup_signal(SIGUSR1, catch_sigusr1) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR1\n");

	if((find_event(sigusr2) != -1)
		&& (setup_signal(SIGUSR2, catch_sigusr2) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR2\n");

	if(setup_signal(SIGALRM, catch_alrm) == SIG_ERR)
		fprintf(stderr, "dzen: error hooking SIGALARM\n");

	if(dzen.slave_win.ishmenu &&
			!dzen.slave_win.max_lines)
		dzen.slave_win.max_lines = 1;


	x_create_windows(use_ewmh_dock);

	if(!dzen.slave_win.ishmenu)
		x_map_window(dzen.title_win.win);
	else {
		XMapRaised(dzen.dpy, dzen.slave_win.win);
		for(i=0; i < dzen.slave_win.max_lines; i++)
			XMapWindow(dzen.dpy, dzen.slave_win.line[i]);
	}

	/* Reposition the window back to where it should be */
	XMoveWindow(dzen.dpy,dzen.title_win.win,dzen.title_win.x,dzen.title_win.y);

	if( fnpre != NULL )
		font_preload(fnpre);

	do_action(onstart);

	/* main loop */
	event_loop();

	do_action(onexit);
	clean_up();

	if(dzen.ret_val)
		return dzen.ret_val;

	return EXIT_SUCCESS;
}
Example #13
0
int main(int argc, char **argv) {
	int only_root, auth = 0, chpid;
	uid_t uid;
	userinfo_t *as, root, user;

	oldvt = oldsysrq = vt.nr = vt.fd = -1;
	vt.ios = NULL;
	root.name = "root";

	parse_options(argc, argv);

	if (geteuid() != 0) {
		fprintf(stderr, "physlock: must be root!\n");
		return 1;
	}

	setup_signal(SIGTERM, sa_handler_exit);
	setup_signal(SIGQUIT, sa_handler_exit);
	setup_signal(SIGHUP, SIG_IGN);
	setup_signal(SIGINT, SIG_IGN);
	setup_signal(SIGUSR1, SIG_IGN);
	setup_signal(SIGUSR2, SIG_IGN);

	vt_init();
	get_current_vt(&oldvt);

	if (options->only_lock) {
		lock_vt_switch();
		vt_destroy();
		return 0;
	} else if (options->only_unlock) {
		unlock_vt_switch();
		vt_destroy();
		return 0;
	}

	if (options->disable_sysrq) {
		oldsysrq = get_sysrq_state(SYSRQ_PATH);
		if (oldsysrq > 0)
			set_sysrq_state(SYSRQ_PATH, 0);
	}

	if (options->user) {
		user.name = options->user;
	} else {
		uid = getuid();
		get_uname(&user, uid);
	}

	get_pwhash(&root);
	only_root = strcmp(user.name, root.name) == 0;
	if (!only_root) {
		get_pwhash(&user);
		authenticate(&user, ""); /* test authentication */
	}

	acquire_new_vt(&vt);
	lock_vt_switch();
	secure_vt(&vt);

	if (options->detach) {
		chpid = fork();
		if (chpid < 0)
			die("could not spawn background process: %s", strerror(errno));
		else if (chpid > 0)
			return 0;
		else
			setsid();
	}

	if (options->cmd)
		handle_cmd(1);

	while (!auth) {
		as = &root;
		flush_vt(&vt);
		if (!only_root) {
			tty_echo_on(&vt);
			while (1) {
				prompt(vt.ios, "\nUnlock as [%s/%s]: ", user.name, root.name);
				if (!*buf || !strcmp(buf, user.name)) {
					as = &user;
					break;
				} else if (!strcmp(buf, root.name)) {
					break;
				}
			}
			tty_echo_off(&vt);
		} else {
			prompt(vt.ios, "\nPress [Enter] to unlock.\n");
		}

		prompt(vt.ios, "%s's password: "******"\nAuthentication failed\n");
			sleep(AUTH_FAIL_TIMEOUT);
		}
	}

	if (options->crypt)
		add_passphrase(buf, options->fnek, vt.ios);

	if (options->cmd)
		handle_cmd(0);

	sleep(1);

	cleanup();

	return 0;
}
Example #14
0
int main(int argc,char **argv)
{
	const char *name;
	int i;

	init_privs();
#ifdef __EMX__
	_wildcard(&argc,&argv);
#endif

/*#define PRIV_TEST*/

#ifdef PRIV_TEST
	{ 
		int euid;
		char command[100];
	
		printf("INIT: %d %d\n", getuid(), geteuid());
		drop_privs();
		printf("DROP: %d %d\n", getuid(), geteuid());
		reclaim_privs();
		printf("RECLAIM: %d %d\n", getuid(), geteuid());
		euid = geteuid();
		if(argc & 1) {
			drop_privs();
			printf("DROP: %d %d\n", getuid(), geteuid());
		}
		if(!((argc-1) & 2)) {
			destroy_privs();
			printf("DESTROY: %d %d\n", getuid(), geteuid());
		}
		sprintf(command, "a.out %d", euid);
		system(command);
		return 1;
	}
#endif


#ifdef __EMX__
       _wildcard(&argc,&argv);
#endif 


	/* check whether the compiler lays out structures in a sane way */
	if(sizeof(struct partition) != 16 ||
	   sizeof(struct directory) != 32 ||
	   sizeof(struct vfat_subentry) !=32) {
		fprintf(stderr,"Mtools has not been correctly compiled\n");
		fprintf(stderr,"Recompile it using a more recent compiler\n");
		return 137;
	}

#ifdef __EMX__
       argv[0] = _getname(argv[0]); _remext(argv[0]); name = argv[0];
#else  
	name = _basename(argv[0]);
#endif

#if 0
	/* this allows the different tools to be called as "mtools -c <command>"
	** where <command> is mdir, mdel, mcopy etcetera
	** Mainly done for the BeOS, which doesn't support links yet.
	*/

	if(argc >= 3 && 
	   !strcmp(argv[1], "-c") &&
	   !strcmp(name, "mtools")) {
		argc-=2;
		argv+=2;
		name = argv[0];
	}
#endif

	/* print the version */
	if(argc >= 2 && 
	   (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") ==0)) {
		printf("%c%s version %s, dated %s\n", 
		       toupper(name[0]), name+1,
		       mversion, mdate);
		printf("configured with the following options: ");
#ifdef USE_XDF
		printf("enable-xdf ");
#else
		printf("disable-xdf ");
#endif
#ifdef USING_VOLD
		printf("enable-vold ");
#else
		printf("disable-vold ");
#endif
#ifdef USING_NEW_VOLD
		printf("enable-new-vold ");
#else
		printf("disable-new-vold ");
#endif
#ifdef DEBUG
		printf("enable-debug ");
#else
		printf("disable-debug ");
#endif
#ifdef USE_RAWTERM
		printf("enable-raw-term ");
#else
		printf("disable-raw-term ");
#endif
		printf("\n");
		return 0;
	}

	if (argc >= 2 && strcmp(name, "mtools") == 0) {
		/* mtools command ... */
		argc--;
		argv++;
		name = argv[0];
	}
	progname = argv[0];

	read_config();
	setup_signal();
	for (i = 0; i < NDISPATCH; i++) {
		if (!strcmp(name,dispatch[i].cmd)
		    || (name[0] == 'm' && !strcmp(name+1,dispatch[i].cmd)))
			dispatch[i].fn(argc, argv, dispatch[i].type);
	}
	if (strcmp(name,"mtools"))
		fprintf(stderr,"Unknown mtools command '%s'\n",name);
	fprintf(stderr,"Usage: mtools [-V] command [-options] arguments ...\n");
	fprintf(stderr,"Supported commands:");
	for (i = 0; i < NDISPATCH; i++) {
		fprintf(stderr, i%8 == 0 ? "\n\t" : ", ");
		fprintf(stderr, "%s", dispatch[i].cmd);
	}
	putc('\n', stderr);
	fprintf(stderr, "Use 'mtools command -?' for help per command\n");

	return 1;
}
Example #15
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    void *kadm_handle;
    kadm5_server_context *server_context;
    kadm5_config_params conf;
    krb5_socket_t signal_fd, listen_fd;
    int log_fd;
    slave *slaves = NULL;
    uint32_t current_version = 0, old_version = 0;
    uint32_t current_tstamp = 0;
    krb5_keytab keytab;
    char **files;
    int aret;
    int optidx = 0;
    int restarter_fd = -1;
    struct stat st;

    setprogname(argv[0]);

    if (getarg(args, num_args, argc, argv, &optidx))
        krb5_std_usage(1, args, num_args);

    if (help_flag)
	krb5_std_usage(0, args, num_args);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    if (detach_from_console && daemon_child == -1)
        roken_detach_prep(argc, argv, "--daemon-child");
    rk_pidfile(NULL);

    ret = krb5_init_context(&context);
    if (ret)
        errx(1, "krb5_init_context failed: %d", ret);

    setup_signal();

    if (config_file == NULL) {
	aret = asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
	if (aret == -1 || config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if (ret)
	krb5_err(context, 1, ret, "reading configuration files");

    time_before_gone = parse_time (slave_time_gone,  "s");
    if (time_before_gone < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", slave_time_gone);
    time_before_missing = parse_time (slave_time_missing,  "s");
    if (time_before_missing < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", slave_time_missing);

    krb5_openlog(context, "ipropd-master", &log_facility);
    krb5_set_warn_dest(context, log_facility);

    ret = krb5_kt_register(context, &hdb_get_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    ret = krb5_kt_resolve(context, keytab_str, &keytab);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_resolve: %s", keytab_str);

    memset(&conf, 0, sizeof(conf));
    if(realm) {
	conf.mask |= KADM5_CONFIG_REALM;
	conf.realm = realm;
    }
    ret = kadm5_init_with_skey_ctx (context,
				    KADM5_ADMIN_SERVICE,
				    NULL,
				    KADM5_ADMIN_SERVICE,
				    &conf, 0, 0,
				    &kadm_handle);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");

    server_context = (kadm5_server_context *)kadm_handle;

    log_fd = open (server_context->log_context.log_file, O_RDONLY, 0);
    if (log_fd < 0)
	krb5_err (context, 1, errno, "open %s",
		  server_context->log_context.log_file);

    if (fstat(log_fd, &st) == -1)
        krb5_err(context, 1, errno, "stat %s",
                 server_context->log_context.log_file);

    if (flock(log_fd, LOCK_SH) == -1)
        krb5_err(context, 1, errno, "shared flock %s",
                 server_context->log_context.log_file);
    kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
                             &current_version, &current_tstamp);
    flock(log_fd, LOCK_UN);

    signal_fd = make_signal_socket (context);
    listen_fd = make_listen_socket (context, port_str);

    krb5_warnx(context, "ipropd-master started at version: %lu",
	       (unsigned long)current_version);

    roken_detach_finish(NULL, daemon_child);
    restarter_fd = restarter(context, NULL);

    while (exit_flag == 0){
	slave *p;
	fd_set readset;
	int max_fd = 0;
	struct timeval to = {30, 0};
	uint32_t vers;
        struct stat st2;;

#ifndef NO_LIMIT_FD_SETSIZE
	if (signal_fd >= FD_SETSIZE || listen_fd >= FD_SETSIZE ||
            restarter_fd >= FD_SETSIZE)
	    krb5_errx (context, IPROPD_RESTART, "fd too large");
#endif

	FD_ZERO(&readset);
	FD_SET(signal_fd, &readset);
	max_fd = max(max_fd, signal_fd);
	FD_SET(listen_fd, &readset);
	max_fd = max(max_fd, listen_fd);
        if (restarter_fd > -1) {
            FD_SET(restarter_fd, &readset);
            max_fd = max(max_fd, restarter_fd);
        }

	for (p = slaves; p != NULL; p = p->next) {
	    if (p->flags & SLAVE_F_DEAD)
		continue;
	    FD_SET(p->fd, &readset);
	    max_fd = max(max_fd, p->fd);
	}

	ret = select (max_fd + 1,
		      &readset, NULL, NULL, &to);
	if (ret < 0) {
	    if (errno == EINTR)
		continue;
	    else
		krb5_err (context, IPROPD_RESTART, errno, "select");
	}

        if (stat(server_context->log_context.log_file, &st2) == -1) {
            krb5_warn(context, errno, "could not stat log file by path");
            st2 = st;
        }

        if (st2.st_dev != st.st_dev || st2.st_ino != st.st_ino) {
            (void) close(log_fd);

            log_fd = open(server_context->log_context.log_file, O_RDONLY, 0);
            if (log_fd < 0)
                krb5_err(context, 1, IPROPD_RESTART_SLOW, "open %s",
                          server_context->log_context.log_file);

            if (fstat(log_fd, &st) == -1)
                krb5_err(context, IPROPD_RESTART_SLOW, errno, "stat %s",
                         server_context->log_context.log_file);

            if (flock(log_fd, LOCK_SH) == -1)
                krb5_err(context, IPROPD_RESTART, errno, "shared flock %s",
                         server_context->log_context.log_file);
            kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
                                     &current_version, &current_tstamp);
            flock(log_fd, LOCK_UN);
        }

	if (ret == 0) {
            /* Recover from failed transactions */
            if (kadm5_log_init_nb(server_context) == 0)
                kadm5_log_end(server_context);

	    if (flock(log_fd, LOCK_SH) == -1)
                krb5_err(context, IPROPD_RESTART, errno,
                         "could not lock log file");
	    kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
                                     &current_version, &current_tstamp);
	    flock(log_fd, LOCK_UN);

	    if (current_version > old_version) {
		krb5_warnx(context,
			   "Missed a signal, updating slaves %lu to %lu",
			   (unsigned long)old_version,
			   (unsigned long)current_version);
		for (p = slaves; p != NULL; p = p->next) {
		    if (p->flags & SLAVE_F_DEAD)
			continue;
		    send_diffs (server_context, p, log_fd, database,
                                current_version, current_tstamp);
		}
                old_version = current_version;
	    }
	}

        if (ret && FD_ISSET(restarter_fd, &readset)) {
            exit_flag = SIGTERM;
            break;
        }

	if (ret && FD_ISSET(signal_fd, &readset)) {
#ifndef NO_UNIX_SOCKETS
	    struct sockaddr_un peer_addr;
#else
	    struct sockaddr_storage peer_addr;
#endif
	    socklen_t peer_len = sizeof(peer_addr);

	    if(recvfrom(signal_fd, (void *)&vers, sizeof(vers), 0,
			(struct sockaddr *)&peer_addr, &peer_len) < 0) {
		krb5_warn (context, errno, "recvfrom");
		continue;
	    }
	    --ret;
	    assert(ret >= 0);
	    old_version = current_version;
	    if (flock(log_fd, LOCK_SH) == -1)
                krb5_err(context, IPROPD_RESTART, errno, "shared flock %s",
                         server_context->log_context.log_file);
	    kadm5_log_get_version_fd(server_context, log_fd, LOG_VERSION_LAST,
                                     &current_version, &current_tstamp);
	    flock(log_fd, LOCK_UN);
	    if (current_version != old_version) {
                /*
                 * If current_version < old_version then the log got
                 * truncated and we'll end up doing full propagations.
                 *
                 * Truncating the log when the current version is
                 * numerically small can lead to race conditions.
                 * Ideally we should identify log versions as
                 * {init_or_trunc_time, vno}, then we could not have any
                 * such race conditions, but this would either require
                 * breaking backwards compatibility for the protocol or
                 * adding new messages to it.
                 */
		krb5_warnx(context,
			   "Got a signal, updating slaves %lu to %lu",
			   (unsigned long)old_version,
			   (unsigned long)current_version);
		for (p = slaves; p != NULL; p = p->next) {
		    if (p->flags & SLAVE_F_DEAD)
			continue;
		    send_diffs (server_context, p, log_fd, database,
                                current_version, current_tstamp);
		}
	    } else {
		krb5_warnx(context,
			   "Got a signal, but no update in log version %lu",
			   (unsigned long)current_version);
	    }
        }

	for(p = slaves; p != NULL; p = p->next) {
	    if (p->flags & SLAVE_F_DEAD)
	        continue;
	    if (ret && FD_ISSET(p->fd, &readset)) {
		--ret;
		assert(ret >= 0);
		if(process_msg (server_context, p, log_fd, database,
				current_version, current_tstamp))
		    slave_dead(context, p);
	    } else if (slave_gone_p (p))
		slave_dead(context, p);
	    else if (slave_missing_p (p))
		send_are_you_there (context, p);
	}

	if (ret && FD_ISSET(listen_fd, &readset)) {
	    add_slave (context, keytab, &slaves, listen_fd);
	    --ret;
	    assert(ret >= 0);
	}
	write_stats(context, slaves, current_version);
    }

    if(exit_flag == SIGINT || exit_flag == SIGTERM)
	krb5_warnx(context, "%s terminated", getprogname());
#ifdef SIGXCPU
    else if(exit_flag == SIGXCPU)
	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
#endif
    else
	krb5_warnx(context, "%s unexpected exit reason: %ld",
		   getprogname(), (long)exit_flag);

    write_master_down(context);

    return 0;
}
Example #16
0
int
main(int argc, char **argv)
{
    krb5_error_code ret;
    krb5_context context;
    krb5_auth_context auth_context;
    void *kadm_handle;
    kadm5_server_context *server_context;
    kadm5_config_params conf;
    int master_fd;
    krb5_ccache ccache;
    krb5_principal server;
    char **files;
    int optidx = 0;
    time_t reconnect_min;
    time_t backoff;
    time_t reconnect_max;
    time_t reconnect;
    time_t before = 0;

    const char *master;

    setprogname(argv[0]);

    if(getarg(args, num_args, argc, argv, &optidx))
	usage(1);

    if(help_flag)
	usage(0);
    if(version_flag) {
	print_version(NULL);
	exit(0);
    }

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    setup_signal();

    if (config_file == NULL) {
	asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context));
	if (config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if (ret)
	krb5_err(context, 1, ret, "reading configuration files");

    argc -= optidx;
    argv += optidx;

    if (argc != 1)
	usage(1);

    master = argv[0];

#ifdef SUPPORT_DETACH
    if (detach_from_console)
	daemon(0, 0);
#endif
    pidfile (NULL);
    krb5_openlog (context, "ipropd-slave", &log_facility);
    krb5_set_warn_dest(context, log_facility);

    ret = krb5_kt_register(context, &hdb_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    time_before_lost = parse_time (server_time_lost,  "s");
    if (time_before_lost < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", server_time_lost);

    memset(&conf, 0, sizeof(conf));
    if(realm) {
	conf.mask |= KADM5_CONFIG_REALM;
	conf.realm = realm;
    }
    ret = kadm5_init_with_password_ctx (context,
					KADM5_ADMIN_SERVICE,
					NULL,
					KADM5_ADMIN_SERVICE,
					&conf, 0, 0,
					&kadm_handle);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");

    server_context = (kadm5_server_context *)kadm_handle;

    ret = kadm5_log_init (server_context);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_log_init");

    get_creds(context, keytab_str, &ccache, master);

    ret = krb5_sname_to_principal (context, master, IPROP_NAME,
				   KRB5_NT_SRV_HST, &server);
    if (ret)
	krb5_err (context, 1, ret, "krb5_sname_to_principal");

    auth_context = NULL;
    master_fd = -1;

    krb5_appdefault_time(context, config_name, NULL, "reconnect-min",
			 10, &reconnect_min);
    krb5_appdefault_time(context, config_name, NULL, "reconnect-max",
			 300, &reconnect_max);
    krb5_appdefault_time(context, config_name, NULL, "reconnect-backoff",
			 10, &backoff);
    reconnect = reconnect_min;

    while (!exit_flag) {
	time_t now, elapsed;
	int connected = FALSE;

	now = time(NULL);
	elapsed = now - before;

	if (elapsed < reconnect) {
	    time_t left = reconnect - elapsed;
	    krb5_warnx(context, "sleeping %d seconds before "
		       "retrying to connect", (int)left);
	    sleep(left);
	}
	before = now;

	master_fd = connect_to_master (context, master, port_str);
	if (master_fd < 0)
	    goto retry;

	reconnect = reconnect_min;

	if (auth_context) {
	    krb5_auth_con_free(context, auth_context);
	    auth_context = NULL;
	    krb5_cc_destroy(context, ccache);
	    get_creds(context, keytab_str, &ccache, master);
	}
	ret = krb5_sendauth (context, &auth_context, &master_fd,
			     IPROP_VERSION, NULL, server,
			     AP_OPTS_MUTUAL_REQUIRED, NULL, NULL,
			     ccache, NULL, NULL, NULL);
	if (ret) {
	    krb5_warn (context, ret, "krb5_sendauth");
	    goto retry;
	}

	krb5_warnx(context, "ipropd-slave started at version: %ld",
		   (long)server_context->log_context.version);

	ret = ihave (context, auth_context, master_fd,
		     server_context->log_context.version);
	if (ret)
	    goto retry;

	connected = TRUE;

	while (connected && !exit_flag) {
	    krb5_data out;
	    krb5_storage *sp;
	    int32_t tmp;
	    fd_set readset;
	    struct timeval to;

#ifndef NO_LIMIT_FD_SETSIZE
	    if (master_fd >= FD_SETSIZE)
		krb5_errx (context, 1, "fd too large");
#endif

	    FD_ZERO(&readset);
	    FD_SET(master_fd, &readset);

	    to.tv_sec = time_before_lost;
	    to.tv_usec = 0;

	    ret = select (master_fd + 1,
			  &readset, NULL, NULL, &to);
	    if (ret < 0) {
		if (errno == EINTR)
		    continue;
		else
		    krb5_err (context, 1, errno, "select");
	    }
	    if (ret == 0)
		krb5_errx (context, 1, "server didn't send a message "
			   "in %d seconds", time_before_lost);

	    ret = krb5_read_priv_message(context, auth_context, &master_fd, &out);
	    if (ret) {
		krb5_warn (context, ret, "krb5_read_priv_message");
		connected = FALSE;
		continue;
	    }

	    sp = krb5_storage_from_mem (out.data, out.length);
	    krb5_ret_int32 (sp, &tmp);
	    switch (tmp) {
	    case FOR_YOU :
		receive (context, sp, server_context);
		ret = ihave (context, auth_context, master_fd,
			     server_context->log_context.version);
		if (ret)
		    connected = FALSE;
		break;
	    case TELL_YOU_EVERYTHING :
		ret = receive_everything (context, master_fd, server_context,
					  auth_context);
		if (ret)
		    connected = FALSE;
		break;
	    case ARE_YOU_THERE :
		send_im_here (context, master_fd, auth_context);
		break;
	    case NOW_YOU_HAVE :
	    case I_HAVE :
	    case ONE_PRINC :
	    case I_AM_HERE :
	    default :
		krb5_warnx (context, "Ignoring command %d", tmp);
		break;
	    }
	    krb5_storage_free (sp);
	    krb5_data_free (&out);

	}
    retry:
	if (connected == FALSE)
	    krb5_warnx (context, "disconnected for server");
	if (exit_flag)
	    krb5_warnx (context, "got an exit signal");

	if (master_fd >= 0)
	    close(master_fd);

	reconnect += backoff;
	if (reconnect > reconnect_max)
	    reconnect = reconnect_max;
    }

    if (0);
#ifndef NO_SIGXCPU
    else if(exit_flag == SIGXCPU)
	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
#endif
    else if(exit_flag == SIGINT || exit_flag == SIGTERM)
	krb5_warnx(context, "%s terminated", getprogname());
    else
	krb5_warnx(context, "%s unexpected exit reason: %ld",
		       getprogname(), (long)exit_flag);
    
    return 0;
}
Example #17
0
/*
 * main
 */
int
main(int argc, char *argv[])
{
	struct stat sb;
	BOOL result;
	int rv = 1;
	int ch;
	int i, drvmax;

	progname = argv[0];

	toolkit_initialize();
	toolkit_arginit(&argc, &argv);

	while ((ch = getopt_long(argc, argv, "c:C:t:vh", longopts, NULL)) != -1) {
		switch (ch) {
		case 'c':
			if (stat(optarg, &sb) < 0 || !S_ISREG(sb.st_mode)) {
				fprintf(stderr, "Can't access %s.\n", optarg);
				exit(1);
			}
			milstr_ncpy(modulefile, optarg, sizeof(modulefile));

			/* resume/statsave dir */
			file_cpyname(statpath, modulefile, sizeof(statpath));
			file_cutname(statpath);
			break;

		case 'C':
			if (stat(optarg, &sb) < 0 || !S_ISREG(sb.st_mode)) {
				fprintf(stderr, "Can't access %s.\n", optarg);
				exit(1);
			}
			milstr_ncpy(timidity_cfgfile_path, optarg,
			    sizeof(timidity_cfgfile_path));
			break;

		case 't':
			if (stat(optarg, &sb) < 0 || !S_ISREG(sb.st_mode)) {
				fprintf(stderr, "Can't access %s.\n", optarg);
				exit(1);
			}
			milstr_ncpy(fontfilename, optarg, sizeof(fontfilename));
			break;

		case 'v':
			verbose = 1;
			break;

		case 'h':
		case '?':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

	if (modulefile[0] == '\0') {
		char *env = getenv("HOME");
		if (env) {
			/* base dir */
			snprintf(modulefile, sizeof(modulefile),
			    "%s/.np2", env);
			if (stat(modulefile, &sb) < 0) {
				if (mkdir(modulefile, 0700) < 0) {
					perror(modulefile);
					exit(1);
				}
			} else if (!S_ISDIR(sb.st_mode)) {
				fprintf(stderr, "%s isn't directory.\n",
				    modulefile);
				exit(1);
			}

			/* font file */
			snprintf(np2cfg.fontfile, sizeof(np2cfg.fontfile),
			    "%s/font.bmp", modulefile);

			/* resume/statsave dir */
			file_cpyname(statpath, modulefile, sizeof(statpath));
			file_catname(statpath, "/sav/", sizeof(statpath));
			if (stat(statpath, &sb) < 0) {
				if (mkdir(statpath, 0700) < 0) {
					perror(statpath);
					exit(1);
				}
			} else if (!S_ISDIR(sb.st_mode)) {
				fprintf(stderr, "%s isn't directory.\n",
				    statpath);
				exit(1);
			}

			/* config file */
			milstr_ncat(modulefile, "/np2rc", sizeof(modulefile));
			if ((stat(modulefile, &sb) >= 0)
			 && !S_ISREG(sb.st_mode)) {
				fprintf(stderr, "%s isn't regular file.\n",
				    modulefile);
			}
		}
	}
	if (timidity_cfgfile_path[0] == '\0') {
		file_cpyname(timidity_cfgfile_path, modulefile,
		    sizeof(timidity_cfgfile_path));
		file_cutname(timidity_cfgfile_path);
		file_catname(timidity_cfgfile_path, "timidity.cfg",
		    sizeof(timidity_cfgfile_path));
	}

	dosio_init();
	file_setcd(modulefile);
	initload();
	toolwin_readini();
	kdispwin_readini();
	skbdwin_readini();

	rand_setseed((SINT32)time(NULL));

#if defined(GCC_CPU_ARCH_IA32)
	mmxflag = havemmx() ? 0 : MMXFLAG_NOTSUPPORT;
	mmxflag += np2oscfg.disablemmx ? MMXFLAG_DISABLE : 0;
#endif

	TRACEINIT();

	if (fontmng_init() != SUCCESS)
		goto fontmng_failure;

	kdispwin_initialize();
	viewer_init();
	skbdwin_initialize();

	toolkit_widget_create();
	scrnmng_initialize();
	kbdmng_init();
	inputmng_init();
	keystat_initialize();

	scrnmode = 0;
	if (np2cfg.RASTER) {
		scrnmode |= SCRNMODE_HIGHCOLOR;
	}
	if (sysmenu_create() != SUCCESS)
		goto sysmenu_failure;
	if (scrnmng_create(scrnmode) != SUCCESS)
		goto scrnmng_failure;

	if (soundmng_initialize() == SUCCESS) {
		result = soundmng_pcmload(SOUND_PCMSEEK, file_getcd("fddseek.wav"));
		if (!result) {
			result = soundmng_pcmload(SOUND_PCMSEEK, SYSRESPATH "/fddseek.wav");
		}
		if (result) {
			soundmng_pcmvolume(SOUND_PCMSEEK, np2cfg.MOTORVOL);
		}

		result = soundmng_pcmload(SOUND_PCMSEEK1, file_getcd("fddseek1.wav"));
		if (!result) {
			result = soundmng_pcmload(SOUND_PCMSEEK1, SYSRESPATH "/fddseek1.wav");
		}
		if (result) {
			soundmng_pcmvolume(SOUND_PCMSEEK1, np2cfg.MOTORVOL);
		}
	}

	joymng_initialize();
	mousemng_initialize();
	if (np2oscfg.MOUSE_SW) {
		mouse_running(MOUSE_ON);
	}

	commng_initialize();
	sysmng_initialize();
	taskmng_initialize();

	pccore_init();
	S98_init();

	toolkit_widget_show();
	scrndraw_redraw();

	pccore_reset();

	if (!(scrnmode & SCRNMODE_FULLSCREEN)) {
		if (np2oscfg.toolwin) {
			toolwin_create();
		}
		if (np2oscfg.keydisp) {
			kdispwin_create();
		}
		if (np2oscfg.softkbd) {
			skbdwin_create();
		}
	}

#if !defined(CPUCORE_IA32)
	if (np2oscfg.resume) {
		flagload(np2resumeext, "Resume", FALSE);
	}
#endif
	sysmng_workclockreset();

	drvmax = (argc < 4) ? argc : 4;
	for (i = 0; i < drvmax; i++) {
		diskdrv_readyfdd(i, argv[i], 0);
	}

	setup_signal(SIGINT, sighandler);
	setup_signal(SIGTERM, sighandler);

	toolkit_widget_mainloop();
	rv = 0;

	kdispwin_destroy();
	toolwin_destroy();
	skbdwin_destroy();

	pccore_cfgupdate();

	mouse_running(MOUSE_OFF);
	joymng_deinitialize();
	S98_trash();

#if !defined(CPUCORE_IA32)
	if (np2oscfg.resume) {
		flagsave(np2resumeext);
	} else {
		flagdelete(np2resumeext);
	}
#endif

	pccore_term();
	debugwin_destroy();

	soundmng_deinitialize();
	scrnmng_destroy();

scrnmng_failure:
	sysmenu_destroy();

sysmenu_failure:
	fontmng_terminate();

fontmng_failure:
	if (sys_updates & (SYS_UPDATECFG|SYS_UPDATEOSCFG)) {
		initsave();
		toolwin_writeini();
		kdispwin_writeini();
		skbdwin_writeini();
	}

	skbdwin_deinitialize();

	TRACETERM();
	dosio_term();

	viewer_term();
	toolkit_terminate();

	return rv;
}
Example #18
0
int
main(int argc, char *argv[]) {
	int i;
	char *action_string = NULL;
	char *endptr;

	/* default values */
	dzen.cur_line  = 0;
	dzen.ret_val   = 0;
	dzen.title_win.x = dzen.slave_win.x = 0;
	dzen.title_win.y = 0;
	dzen.title_win.width = dzen.slave_win.width = 0;
	dzen.title_win.alignment = ALIGNCENTER;
	dzen.slave_win.alignment = ALIGNLEFT;
	dzen.fnt = FONT;
	dzen.bg  = BGCOLOR;
	dzen.fg  = FGCOLOR;
	dzen.slave_win.max_lines  = 0;
	dzen.running = True;
	dzen.xinescreen = 0;
	dzen.tsupdate = 0;
	dzen.line_height = 0;

	/* cmdline args */
	for(i = 1; i < argc; i++)
		if(!strncmp(argv[i], "-l", 3)){
			if(++i < argc) {
				dzen.slave_win.max_lines = atoi(argv[i]);
				init_input_buffer();
			}
		}
		else if(!strncmp(argv[i], "-u", 3)){
			dzen.tsupdate = True;
		}
		else if(!strncmp(argv[i], "-p", 3)) {
			dzen.ispersistent = True;
			if (i+1 < argc) {
				dzen.timeout = strtoul(argv[i+1], &endptr, 10);
				if(*endptr)
					dzen.timeout = 0;
				else
					i++;
			}
		}
		else if(!strncmp(argv[i], "-ta", 4)) {
			if(++i < argc) dzen.title_win.alignment = argv[i][0];
		}
		else if(!strncmp(argv[i], "-sa", 4)) {
			if(++i < argc) dzen.slave_win.alignment = argv[i][0];
		}
		else if(!strncmp(argv[i], "-m", 3)) {
			dzen.slave_win.ismenu = True;
			if(i+1 < argc) 
				dzen.slave_win.ishmenu = (argv[i+1][0] == 'h') ? ++i, True : False;
		}
		else if(!strncmp(argv[i], "-fn", 4)) {
			if(++i < argc) dzen.fnt = argv[i];
		}
		else if(!strncmp(argv[i], "-e", 3)) {
			if(++i < argc) action_string = argv[i];
		}
		else if(!strncmp(argv[i], "-bg", 4)) {
			if(++i < argc) dzen.bg = argv[i];
		}
		else if(!strncmp(argv[i], "-fg", 4)) {
			if(++i < argc) dzen.fg = argv[i];
		}
		else if(!strncmp(argv[i], "-x", 3)) {
			if(++i < argc) dzen.title_win.x = dzen.slave_win.x = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-y", 3)) {
			if(++i < argc) dzen.title_win.y = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-w", 3)) {
			if(++i < argc) dzen.slave_win.width = atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-h", 3)) {
			if(++i < argc) dzen.line_height= atoi(argv[i]);
		}
		else if(!strncmp(argv[i], "-tw", 4)) {
			if(++i < argc) dzen.title_win.width = atoi(argv[i]);
		}
#ifdef DZEN_XINERAMA
		else if(!strncmp(argv[i], "-xs", 4)) {
			if(++i < argc) dzen.xinescreen = atoi(argv[i]);
		}
#endif
		else if(!strncmp(argv[i], "-v", 3)) 
			eprint("dzen-"VERSION", (C)opyright 2007 Robert Manea\n");
		else
			eprint("usage: dzen2 [-v] [-p [seconds]] [-m [v|h]] [-ta <l|c|r>] [-sa <l|c|r>]\n"
                   "             [-x <pixel>] [-y <pixel>] [-w <pixel>] [-tw <pixel>] [-u] \n"
				   "             [-e <string>] [-l <lines>]  [-fn <font>] [-bg <color>] [-fg <color>]\n"
#ifdef DZEN_XINERAMA
				   "             [-xs <screen>]\n"
#endif
				  );

	if(dzen.tsupdate && !dzen.slave_win.max_lines)
		dzen.tsupdate = False;

	if(!dzen.title_win.width)
		dzen.title_win.width = dzen.slave_win.width;

	if(!setlocale(LC_ALL, "") || !XSupportsLocale())
		puts("dzen: locale not available, expect problems with fonts.\n");

	if(action_string) 
		fill_ev_table(action_string);
	else {
		if(!dzen.slave_win.max_lines) {
			char edef[] = "button3=exit:13";
			fill_ev_table(edef);
		}
		else if(dzen.slave_win.ishmenu) {
			char edef[] = "enterslave=grabkeys;leaveslave=ungrabkeys;"
				"button4=scrollup;button5=scrolldown;"
				"key_Left=scrollup;key_Right=scrolldown;"
				"button1=menuexec;button3=exit:13;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
		else {
			char edef[]  = "entertitle=uncollapse,grabkeys;"
				"enterslave=grabkeys;leaveslave=collapse,ungrabkeys;"
				"button1=menuexec;button2=togglestick;button3=exit:13;"
				"button4=scrollup;button5=scrolldown;"
				"key_Up=scrollup;key_Down=scrolldown;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
	}

	if((find_event(onexit) != -1) 
			&& (setup_signal(SIGTERM, catch_sigterm) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGTERM\n");

	if((find_event(sigusr1) != -1) 
			&& (setup_signal(SIGUSR1, catch_sigusr1) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR1\n");
	
	if((find_event(sigusr2) != -1) 
		&& (setup_signal(SIGUSR2, catch_sigusr2) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR2\n");
	
	if(setup_signal(SIGALRM, catch_alrm) == SIG_ERR)
		fprintf(stderr, "dzen: error hooking SIGALARM\n");

	set_alignment();
	
	if(dzen.slave_win.ishmenu &&
			!dzen.slave_win.max_lines)
		dzen.slave_win.max_lines = 1;

	x_create_windows();
	
	if(!dzen.slave_win.ishmenu)
		x_map_window(dzen.title_win.win);
	else {
		XMapRaised(dzen.dpy, dzen.slave_win.win);
		for(i=0; i < dzen.slave_win.max_lines; i++)
			XMapWindow(dzen.dpy, dzen.slave_win.line[i]);
	}

	do_action(onstart);

	/* main loop */
	event_loop();

	do_action(onexit);
	clean_up();

	if(dzen.ret_val)
		return dzen.ret_val;

	return EXIT_SUCCESS;
}
Example #19
0
int
main(int argc, char *argv[]) {
    int rc;
    uv_loop_t *loop;
    struct sockaddr bind_addr;

    parse_opts(argc, argv);

    if (xsignal) {
        return signal_process(xsignal, pidfile);
    }

    if (!tunnel_mode || !dest_addr || !password) {
        print_usage(argv[0]);
        return 1;
    }

    if (init()) {
        return 1;
    }

    if (daemon_mode) {
        if (daemonize()) {
            return 1;
        }
        if (already_running(pidfile)) {
            logger_stderr("xtunnel already running.");
            return 1;
        }
    }

    loop = uv_default_loop();

    rc = resolve_addr(source_addr, &bind_addr);
    if (rc) {
        logger_stderr("invalid local address");
        return 1;
    }

    rc = resolve_addr(dest_addr, &target_addr);
    if (rc) {
        logger_stderr("invalid target address");
        return 1;
    }

    if (concurrency <= 1) {
        struct server_context ctx;
        uv_tcp_init(loop, &ctx.tcp);
        rc = uv_tcp_bind(&ctx.tcp, &bind_addr, 0);
        if (rc) {
            logger_stderr("bind error: %s", uv_strerror(rc));
            return 1;
        }
        rc = uv_listen((uv_stream_t*)&ctx.tcp, SOMAXCONN, source_accept_cb);
        if (rc == 0) {
            logger_log(LOG_INFO, "listening on %s", source_addr);

            setup_signal(loop, signal_cb, &ctx);

            uv_run(loop, UV_RUN_DEFAULT);

            close_loop(loop);

        } else {
            logger_stderr("listen error: %s", uv_strerror(rc));
        }

    } else {
        struct server_context *servers = calloc(concurrency, sizeof(servers[0]));
        for (int i = 0; i < concurrency; i++) {
            struct server_context *ctx = servers + i;
            ctx->index = i;
            ctx->tcp_fd = create_socket(SOCK_STREAM, 1);
            ctx->accept_cb = source_accept_cb;
            ctx->nameserver_num = -1;
            ctx->local_addr = &bind_addr;
            rc = uv_sem_init(&ctx->semaphore, 0);
            rc = uv_thread_create(&ctx->thread_id, consumer_start, ctx);
        }

        logger_log(LOG_INFO, "listening on %s", source_addr);

        setup_signal(loop, signal_cb, servers);

        uv_run(loop, UV_RUN_DEFAULT);

        close_loop(loop);

        for (int i = 0; i < concurrency; i++) {
            uv_sem_wait(&servers[i].semaphore);
        }
        free(servers);
    }

    if (daemon_mode) {
        delete_pidfile(pidfile);
    }

    return 0;
}
Example #20
0
File: handy.c Project: goneri/burp
/* TODO: make arg1..n an array */
int run_script(const char *script, struct strlist **userargs, int userargc, const char *arg1, const char *arg2, const char *arg3, const char *arg4, const char *arg5, const char *arg6, const char *arg7, const char *arg8, const char *arg9, const char *arg10, struct cntr *cntr, int do_wait, int logfunc)
{
	int a=0;
	int l=0;
	pid_t p;
	FILE *serr=NULL;
	FILE *sout=NULL;
	char *cmd[64]={ NULL };
#ifndef HAVE_WIN32
	int s=0;
#endif
	if(!script) return 0;

	cmd[l++]=(char *)script;
	if(arg1) cmd[l++]=(char *)arg1;
	if(arg2) cmd[l++]=(char *)arg2;
	if(arg3) cmd[l++]=(char *)arg3;
	if(arg4) cmd[l++]=(char *)arg4;
	if(arg5) cmd[l++]=(char *)arg5;
	if(arg6) cmd[l++]=(char *)arg6;
	if(arg7) cmd[l++]=(char *)arg7;
	if(arg8) cmd[l++]=(char *)arg8;
	if(arg9) cmd[l++]=(char *)arg9;
	if(arg10) cmd[l++]=(char *)arg10;
	for(a=0; a<userargc && l<64-1; a++)
		cmd[l++]=userargs[a]->path;
	cmd[l++]=NULL;

#ifndef HAVE_WIN32
	setup_signal(SIGCHLD, run_script_sigchld_handler);
#endif

	fflush(stdout); fflush(stderr);
	if(do_wait)
	{
		if((p=forkchild(NULL,
			&sout, &serr, cmd[0], cmd))==-1) return -1;
	}
	else
	{
		if((p=forkchild_no_wait(NULL,
			&sout, &serr, cmd[0], cmd))==-1) return -1;
		return 0;
	}
#ifdef HAVE_WIN32
	// My windows forkchild currently just executes, then returns.
	return 0;
#else
	s=run_script_select(&sout, &serr, cntr, logfunc);

	// Set SIGCHLD back to default.
	setup_signal(SIGCHLD, SIG_DFL);

	if(s) return -1;

	if(WIFEXITED(run_script_status))
	{
		int ret=WEXITSTATUS(run_script_status);
		logp("%s returned: %d\n", script, ret);
		if(cntr && ret) logw(cntr, "%s returned: %d\n",
			script, ret);
		return ret;
	}
	else if(WIFSIGNALED(run_script_status))
	{
		logp("%s terminated on signal %d\n",
			script, WTERMSIG(run_script_status));
		if(cntr) logw(cntr, "%s terminated on signal %d\n",
			script, WTERMSIG(run_script_status));
	}
	else
	{
		logp("Strange return when trying to run %s\n", script);
		if(cntr) logw(cntr, "Strange return when trying to run %s\n",
			script);
	}
	return -1;
#endif
}
/**
* @brief main method of the program.
* @param argc The number of the arguments of the program.
* @param argv The arguments of the program.
* @return the exit status of the process.
*/
int main(int argc, char* argv[])
{
    (void) setup_signal();

     /** Declare the variables */
    char* username;
    char* password;
    int opt;
    int binr = 0;
    int binl = 0;
    struct data *shared;
    int shmfd;
    sem_t *sem1;
    sem_t *sem2;
    sem_t *sem3;
    char buffer[MAX_DATA+1];
    int command = EMPTY;
    int current_flag = EMPTY;
    
    /** Check the optional arguments */
    while ((opt = getopt(argc, argv, "rl")) != -1)
    {
        switch(opt)
        {
            case 'r':
                binr = 1;
                break;
            case 'l':
                binl = 1;             
                break;

            case '?':
                (void) usage(argv[0]);

            default:
                (void) usage(argv[0]);
        }
    }
    
    /** Check the number of the arguments */
    if(!(argc == 4 && (binr^binl)))
    {
        (void) usage(argv[0]);
    }
    
    username = argv[2];
    password = argv[3]; 
        
    /** Open the semaphores */
    sem1 = sem_open(SEM_1, 0);
    sem2 = sem_open(SEM_2, 0);
    sem3 = sem_open(SEM_3, 0);
    
    if (sem1 == SEM_FAILED || sem2 == SEM_FAILED || sem3 == SEM_FAILED)
    {
        (void) on_error("Problem while executing sem_open(3).");
    } 
    
    /** Create a share memory */
    shmfd = shm_open(SHM_NAME, O_RDWR | O_CREAT, PERMISSION);
    
    if(shmfd == -1)
    {
        (void) on_error("Problem while executing shm_open(3).");
    }
            
    /** Map the data to be shared */
    shared = mmap(NULL, sizeof *shared, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0);
    
    if (shared == MAP_FAILED)
    {
        (void) on_error("Problem while executing mmap(2).");
    }
    
    /** Close the shared memory file descriptor */
    if (close(shmfd) == -1)
    {
        (void) on_error("Problem while executing close(2).");
    }
    
        
    /** critical section */   
    
    if (sem_wait(sem3) == -1)
    {
        if (errno != EINTR) (void) on_error("Problem while executing sem_wait(3).");        
    }
        
    if(binr)
    {
        shared->flag = REGISTER;
    }
    else if(binl)
    {
        shared->flag = LOGIN;
    }
    
    /** Save the arrays in the shared memory */
    (void) save_array(shared->username, username);    
    (void) save_array(shared->password, password);
          
    if (sem_post(sem1) == -1)
    {
        (void) on_error("Problem while executing sem_post(3).");
    }
   
    if (sem_wait(sem2) == -1)
    {        
        if (errno != EINTR) (void) on_error("Problem while executing sem_wait(3).");
    }
      
    current_flag = shared->flag;
 
    if (sem_post(sem3) == -1)
    {
        (void) on_error("Problem while executing sem_post(3).");
    }
      
    if(binr && (current_flag == ERROR))
    {
        (void) on_error("User with this name and password already registered.");
    }
    else if (binl && (current_flag == ERROR))
    {
        (void) on_error("User with this name and password does not exist.");
    }    
    
    while (command != 3 && !want_quit)
    {
        if (sem_wait(sem3) == -1)
        {
            if (errno == EINTR) continue;
            (void) on_error("Problem while executing sem_wait(3).");
        }
        
        if (shared->flag == SERVER_ERROR)
        {
            break;
        }
        
        if (sem_post(sem3) == -1)
        {
            (void) on_error("Problem while executing sem_post(3).");
        }
        
        (void) print_options();
        
        if (read(STDIN_FILENO, buffer, MAX_DATA) == -1)
        {
            (void) on_error("Problem while executing read(2).");
        }
        
        buffer[MAX_DATA] = '\0';
        
        command = (int)strtol(buffer, NULL, 10);
        
        switch (command)
        {
        
            case 1:            
                (void) fprintf(stdout, "\nWrite a new secret:\n");
                
                char buffer[MAX_DATA+1];
    
                if (read(STDIN_FILENO, buffer, MAX_DATA) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing read(2).");
                }
                
                buffer[MAX_DATA] = '\0';
                
                if (sem_wait(sem3) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing sem_wait(3).");
                }
                
                (void) strcpy(shared->username, username);
                (void) strcpy(shared->password, password);
                (void) strcpy(shared->secret, buffer);
                    
                shared->flag = WRITE_SECRET;
                                
                if (sem_post(sem1) == -1 || sem_post(sem3) == -1)
                {
                    (void) on_error("Problem while executing sem_post(3).");
                }
                
                if (sem_wait(sem2) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing sem_wait(3).");
                }
                break;
                
                
            case 2:
                (void) fprintf(stdout, "\nReading the secret:\n");
                
                if (sem_wait(sem3) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing sem_wait(3).");
                }
                                
                (void) strcpy(shared->username, username);
                (void) strcpy(shared->password, password);
                shared->flag = READ_SECRET;
                
                if (sem_post(sem1) == -1)
                {
                    (void) on_error("Problem while executing sem_post(3).");
                }

                if (sem_wait(sem2) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing sem_wait(3).");
                }
                               
                int i = 0;

                if (shared->secret[i] == '\0')
                {
                    (void) fprintf(stdout, "No secret set.");
                }

                while (shared->secret[i] != '\0')
                {
                    (void) fprintf(stdout, "%c", shared->secret[i]);
                    i++;
                }
                
                (void) fprintf(stdout, "\n\n");
                
                if (sem_post(sem3) == -1)
                {
                    (void) on_error("Problem while executing sem_post(3).");
                }
                break;
                
                
            case 3:
                if (sem_wait(sem3) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing sem_wait(3).");
                }
            
                (void) strcpy(shared->username, username);
                (void) strcpy(shared->password, password);
                shared->flag = LOGOUT;
               
                if (sem_post(sem1) == -1 || sem_post(sem3) == -1)
                {
                    (void) on_error("Problem while executing sem_post(3).");
                }
                (void) fprintf(stdout, "\nLogging out...\n\n");
                
                if (sem_wait(sem2) == -1)
                {
                    if (errno == EINTR) continue;
                    (void) on_error("Problem while executing sem_wait(3).");
                }
                break;
                
                
            default:
                (void) fprintf(stdout, "\nInvalid command!\n\n");
                command = EMPTY;
                break;
        }    
    }
    
    /** send error code to the server */
    if (want_quit == 1)
    {
        if (sem_wait(sem3) == -1)
        {
            (void) on_error("Problem while executing sem_wait(3).");
        }
        
        shared->flag = ERROR;
        
        if (sem_post(sem3) == -1)
        {
            (void) on_error("Problem while executing sem_post(3).");
        }
    }    
    
    /** critical section out */
    
    /** Unmap the data */
    if (munmap(shared, sizeof *shared) == -1)
    {
        (void) on_error("Problem while executing munmap(2).");
    }
          
    /** Clse the semaphores */  
    if (sem_close(sem1) == -1)
    {
        (void) on_error("Problem while executing sem_close(3).");
    }
    
    if (sem_close(sem2) == -1)
    {
        (void) on_error("Problem while executing sem_close(3).");
    }
    
    if (sem_close(sem3) == -1)
    {
        (void) on_error("Problem while executing sem_close(3).");
    }
    
    return EXIT_SUCCESS;
}
Example #22
0
int
main(int argc, char **argv)
{
    krb5_error_code ret, ret2;
    krb5_context context;
    krb5_auth_context auth_context;
    void *kadm_handle;
    kadm5_server_context *server_context;
    kadm5_config_params conf;
    int master_fd;
    krb5_ccache ccache;
    krb5_principal server;
    char **files;
    int optidx = 0;
    time_t reconnect_min;
    time_t backoff;
    time_t reconnect_max;
    time_t reconnect;
    time_t before = 0;
    int restarter_fd = -1;

    const char *master;

    setprogname(argv[0]);

    if (getarg(args, num_args, argc, argv, &optidx))
	usage(1);

    if (help_flag)
	usage(0);

    if (version_flag) {
	print_version(NULL);
	exit(0);
    }

    if (detach_from_console && daemon_child == -1)
        roken_detach_prep(argc, argv, "--daemon-child");
    rk_pidfile(NULL);

    ret = krb5_init_context(&context);
    if (ret)
	errx (1, "krb5_init_context failed: %d", ret);

    setup_signal();

    if (config_file == NULL) {
	if (asprintf(&config_file, "%s/kdc.conf", hdb_db_dir(context)) == -1
	    || config_file == NULL)
	    errx(1, "out of memory");
    }

    ret = krb5_prepend_config_files_default(config_file, &files);
    if (ret)
	krb5_err(context, 1, ret, "getting configuration files");

    ret = krb5_set_config_files(context, files);
    krb5_free_config_files(files);
    if (ret)
	krb5_err(context, 1, ret, "reading configuration files");

    argc -= optidx;
    argv += optidx;

    if (argc != 1)
	usage(1);

    master = argv[0];

    if (status_file == NULL) {
	if (asprintf(&status_file,  "%s/ipropd-slave-status", hdb_db_dir(context)) < 0 || status_file == NULL)
	    krb5_errx(context, 1, "can't allocate status file buffer"); 
    }

    krb5_openlog(context, "ipropd-slave", &log_facility);
    krb5_set_warn_dest(context, log_facility);

    slave_status(context, status_file, "bootstrapping");

    ret = krb5_kt_register(context, &hdb_get_kt_ops);
    if(ret)
	krb5_err(context, 1, ret, "krb5_kt_register");

    time_before_lost = parse_time (server_time_lost,  "s");
    if (time_before_lost < 0)
	krb5_errx (context, 1, "couldn't parse time: %s", server_time_lost);

    slave_status(context, status_file, "getting credentials from keytab/database");

    memset(&conf, 0, sizeof(conf));
    if(realm) {
	conf.mask |= KADM5_CONFIG_REALM;
	conf.realm = realm;
    }
    ret = kadm5_init_with_password_ctx (context,
					KADM5_ADMIN_SERVICE,
					NULL,
					KADM5_ADMIN_SERVICE,
					&conf, 0, 0,
					&kadm_handle);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_init_with_password_ctx");

    server_context = (kadm5_server_context *)kadm_handle;

    slave_status(context, status_file, "creating log file");

    ret = server_context->db->hdb_open(context,
                                       server_context->db,
                                       O_RDWR | O_CREAT, 0600);
    if (ret)
	krb5_err (context, 1, ret, "db->open");

    ret = kadm5_log_init (server_context);
    if (ret)
	krb5_err (context, 1, ret, "kadm5_log_init");

    ret = server_context->db->hdb_close (context, server_context->db);
    if (ret)
	krb5_err (context, 1, ret, "db->close");

    get_creds(context, keytab_str, &ccache, master);

    ret = krb5_sname_to_principal (context, master, IPROP_NAME,
				   KRB5_NT_SRV_HST, &server);
    if (ret)
	krb5_err (context, 1, ret, "krb5_sname_to_principal");

    auth_context = NULL;
    master_fd = -1;

    krb5_appdefault_time(context, config_name, NULL, "reconnect-min",
			 10, &reconnect_min);
    krb5_appdefault_time(context, config_name, NULL, "reconnect-max",
			 300, &reconnect_max);
    krb5_appdefault_time(context, config_name, NULL, "reconnect-backoff",
			 10, &backoff);
    reconnect = reconnect_min;

    slave_status(context, status_file, "ipropd-slave started");

    roken_detach_finish(NULL, daemon_child);
    restarter_fd = restarter(context, NULL);

    while (!exit_flag) {
        struct timeval to;
	time_t now, elapsed;
        fd_set readset;
	int connected = FALSE;

#ifndef NO_LIMIT_FD_SETSIZE
        if (restarter_fd >= FD_SETSIZE)
            krb5_errx(context, IPROPD_RESTART, "fd too large");
#endif

        FD_ZERO(&readset);
        if (restarter_fd > -1)
            FD_SET(restarter_fd, &readset);

	now = time(NULL);
	elapsed = now - before;

	if (elapsed < reconnect) {
	    time_t left = reconnect - elapsed;
	    krb5_warnx(context, "sleeping %d seconds before "
		       "retrying to connect", (int)left);
            to.tv_sec = left;
            to.tv_usec = 0;
            if (select(restarter_fd + 1, &readset, NULL, NULL, &to) == 1) {
                exit_flag = SIGTERM;
                continue;
            }
	}
	before = now;

	slave_status(context, status_file, "connecting to master: %s\n", master);

	master_fd = connect_to_master (context, master, port_str);
	if (master_fd < 0)
	    goto retry;

	reconnect = reconnect_min;

	if (auth_context) {
	    krb5_auth_con_free(context, auth_context);
	    auth_context = NULL;
	    krb5_cc_destroy(context, ccache);
	    get_creds(context, keytab_str, &ccache, master);
	}
        if (verbose)
            krb5_warnx(context, "authenticating to master");
	ret = krb5_sendauth (context, &auth_context, &master_fd,
			     IPROP_VERSION, NULL, server,
			     AP_OPTS_MUTUAL_REQUIRED, NULL, NULL,
			     ccache, NULL, NULL, NULL);
	if (ret) {
	    krb5_warn (context, ret, "krb5_sendauth");
	    goto retry;
	}

	krb5_warnx(context, "ipropd-slave started at version: %ld",
		   (long)server_context->log_context.version);

	ret = ihave(context, auth_context, master_fd,
		    server_context->log_context.version);
	if (ret)
	    goto retry;

	connected = TRUE;

        if (verbose)
            krb5_warnx(context, "connected to master");

	slave_status(context, status_file, "connected to master, waiting instructions");

	while (connected && !exit_flag) {
	    krb5_data out;
	    krb5_storage *sp;
	    uint32_t tmp;
            int max_fd;

#ifndef NO_LIMIT_FD_SETSIZE
	    if (master_fd >= FD_SETSIZE)
                krb5_errx(context, IPROPD_RESTART, "fd too large");
            if (restarter_fd >= FD_SETSIZE)
                krb5_errx(context, IPROPD_RESTART, "fd too large");
            max_fd = max(restarter_fd, master_fd);
#endif

	    FD_ZERO(&readset);
	    FD_SET(master_fd, &readset);
            if (restarter_fd != -1)
                FD_SET(restarter_fd, &readset);

	    to.tv_sec = time_before_lost;
	    to.tv_usec = 0;

	    ret = select (max_fd + 1,
			  &readset, NULL, NULL, &to);
	    if (ret < 0) {
		if (errno == EINTR)
		    continue;
		else
		    krb5_err (context, 1, errno, "select");
	    }
	    if (ret == 0) {
		krb5_warnx(context, "server didn't send a message "
                           "in %d seconds", time_before_lost);
		connected = FALSE;
		continue;
	    }

            if (restarter_fd > -1 && FD_ISSET(restarter_fd, &readset)) {
                if (verbose)
                    krb5_warnx(context, "slave restarter exited");
                exit_flag = SIGTERM;
            }

            if (!FD_ISSET(master_fd, &readset))
                continue;

            if (verbose)
                krb5_warnx(context, "message from master");

	    ret = krb5_read_priv_message(context, auth_context, &master_fd, &out);
	    if (ret) {
		krb5_warn(context, ret, "krb5_read_priv_message");
		connected = FALSE;
		continue;
	    }

	    sp = krb5_storage_from_mem (out.data, out.length);
            if (sp == NULL)
                krb5_err(context, IPROPD_RESTART, errno, "krb5_storage_from_mem");
	    ret = krb5_ret_uint32(sp, &tmp);
            if (ret == HEIM_ERR_EOF) {
                krb5_warn(context, ret, "master sent zero-length message");
                connected = FALSE;
                continue;
            }
            if (ret != 0) {
                krb5_warn(context, ret, "couldn't read master's message");
                connected = FALSE;
                continue;
            }

	    ret = server_context->db->hdb_open(context,
					       server_context->db,
					       O_RDWR | O_CREAT, 0600);
	    if (ret)
		krb5_err (context, 1, ret, "db->open while handling a "
			  "message from the master");

            ret = kadm5_log_init(server_context);
            if (ret) {
                krb5_err(context, IPROPD_RESTART, ret, "kadm5_log_init while "
                         "handling a message from the master");
            }
	    ret = server_context->db->hdb_close (context, server_context->db);
	    if (ret)
		krb5_err (context, 1, ret, "db->close while handling a "
			  "message from the master");

	    switch (tmp) {
	    case FOR_YOU :
                if (verbose)
                    krb5_warnx(context, "master sent us diffs");
		ret2 = receive(context, sp, server_context);
                if (ret2)
                    krb5_warn(context, ret2,
                              "receive from ipropd-master had errors");
		ret = ihave(context, auth_context, master_fd,
			    server_context->log_context.version);
		if (ret || ret2)
		    connected = FALSE;

                /*
                 * If it returns an error, receive() may nonetheless
                 * have committed some entries successfully, so we must
                 * update the slave_status even if there were errors.
                 */
                is_up_to_date(context, status_file, server_context);
		break;
	    case TELL_YOU_EVERYTHING :
                if (verbose)
                    krb5_warnx(context, "master sent us a full dump");
		ret = receive_everything(context, master_fd, server_context,
					 auth_context);
                if (ret == 0) {
                    ret = ihave(context, auth_context, master_fd,
                                server_context->log_context.version);
                }
                if (ret)
		    connected = FALSE;
                else
                    is_up_to_date(context, status_file, server_context);
		break;
	    case ARE_YOU_THERE :
                if (verbose)
                    krb5_warnx(context, "master sent us a ping");
		is_up_to_date(context, status_file, server_context);
                ret = ihave(context, auth_context, master_fd,
                            server_context->log_context.version);
                if (ret)
                    connected = FALSE;

		send_im_here(context, master_fd, auth_context);
		break;
	    case YOU_HAVE_LAST_VERSION:
                if (verbose)
                    krb5_warnx(context, "master tells us we are up to date");
		is_up_to_date(context, status_file, server_context);
		break;
	    case NOW_YOU_HAVE :
	    case I_HAVE :
	    case ONE_PRINC :
	    case I_AM_HERE :
	    default :
		krb5_warnx (context, "Ignoring command %d", tmp);
		break;
	    }
	    krb5_storage_free (sp);
	    krb5_data_free (&out);

	}

	slave_status(context, status_file, "disconnected from master");
    retry:
	if (connected == FALSE)
	    krb5_warnx (context, "disconnected for server");

	if (exit_flag)
	    krb5_warnx (context, "got an exit signal");

	if (master_fd >= 0)
	    close(master_fd);

	reconnect += backoff;
	if (reconnect > reconnect_max) {
	    slave_status(context, status_file, "disconnected from master for a long time");
	    reconnect = reconnect_max;
	}
    }

    if (status_file) {
        /* XXX It'd be better to leave it saying we're not here */
	unlink(status_file);
    }

    if (0);
#ifndef NO_SIGXCPU
    else if(exit_flag == SIGXCPU)
	krb5_warnx(context, "%s CPU time limit exceeded", getprogname());
#endif
    else if(exit_flag == SIGINT || exit_flag == SIGTERM)
	krb5_warnx(context, "%s terminated", getprogname());
    else
	krb5_warnx(context, "%s unexpected exit reason: %ld",
		       getprogname(), (long)exit_flag);

    return 0;
}
Example #23
0
int
main(int argc, char *argv[]) {
    int rc;
    uv_loop_t *loop;

    parse_opts(argc, argv);

#if !defined(_WIN32)
    if (xsignal) {
        return signal_process(xsignal, pidfile);
    }
#endif

    if (!password || !server_addr_buf) {
        print_usage(argv[0]);
        return 1;
    }

    init();

#if !defined(_WIN32)
    if (daemon_mode) {
        if (daemonize()) {
            return 1;
        }
        if (already_running(pidfile)) {
            logger_stderr("xsocks already running.");
            return 1;
        }
    }
#endif

    loop = uv_default_loop();

    rc = resolve_addr(local_addr, &bind_addr);
    if (rc) {
        logger_stderr("invalid local address");
        return 1;
    }

    rc = resolve_addr(server_addr_buf, &server_addr);
    if (rc) {
        logger_stderr("invalid server address");
        return 1;
    }

    udprelay_init();

    if (concurrency <= 1) {
        struct server_context ctx;
        ctx.udprelay = 1;
        ctx.udp_fd = create_socket(SOCK_DGRAM, 0);
        ctx.local_addr = &bind_addr;
        ctx.server_addr = &server_addr;

        uv_tcp_init(loop, &ctx.tcp);
        rc = uv_tcp_bind(&ctx.tcp, &bind_addr, 0);
        if (rc) {
            logger_stderr("bind error: %s", uv_strerror(rc));
            return 1;
        }
        rc = uv_listen((uv_stream_t*)&ctx.tcp, 128, client_accept_cb);
        if (rc == 0) {
            logger_log(LOG_INFO, "listening on %s", local_addr);

#if !defined(_WIN32)
            setup_signal(loop, signal_cb, &ctx);
#endif

            udprelay_start(loop, &ctx);

            uv_run(loop, UV_RUN_DEFAULT);

            close_loop(loop);

        } else {
            logger_stderr("listen error: %s", uv_strerror(rc));
        }

    } else {
#if !defined(_WIN32)
        struct server_context *servers = calloc(concurrency, sizeof(servers[0]));
        for (int i = 0; i < concurrency; i++) {
            struct server_context *ctx = servers + i;
            ctx->index = i;
            ctx->tcp_fd = create_socket(SOCK_STREAM, 1);
            ctx->udp_fd = create_socket(SOCK_DGRAM, 1);
            ctx->udprelay = 1;
            ctx->accept_cb = client_accept_cb;
            ctx->local_addr = &bind_addr;
            ctx->server_addr = &server_addr;
            rc = uv_sem_init(&ctx->semaphore, 0);
            rc = uv_thread_create(&ctx->thread_id, consumer_start, ctx);
        }

        logger_log(LOG_INFO, "listening on %s", local_addr);

        setup_signal(loop, signal_cb, servers);

        uv_run(loop, UV_RUN_DEFAULT);

        close_loop(loop);

        for (int i = 0; i < concurrency; i++) {
            uv_sem_wait(&servers[i].semaphore);
        }
        free(servers);
#else
        logger_stderr("don't support multithreading.");
        return 1;
#endif
	}

    udprelay_destroy();

#if !defined(_WIN32)
    if (daemon_mode) {
        delete_pidfile(pidfile);
    }
#endif

    logger_exit();

    return 0;
}
Example #24
0
File: main.c Project: pamolloy/dzen
int main( int ac, char *av[] )
{
	int i;

	set_dzen();	// Default values
	x_connect();
	x_read_resources();
	parse_opts(ac, av);

	if(dzen.tsupdate && !dzen.slave_win.max_lines)
		dzen.tsupdate = False;

	if(!dzen.title_win.width)
		dzen.title_win.width = dzen.slave_win.width;

	if(!setlocale(LC_ALL, "") || !XSupportsLocale())
		puts("dzen: locale not available, expect problems with fonts.\n");

	if(action_string)
		fill_ev_table(action_string);
	else {
		if(!dzen.slave_win.max_lines) {
			char edef[] = "button3=exit:13";
			fill_ev_table(edef);
		}
		else if(dzen.slave_win.ishmenu) {
			char edef[] = "enterslave=grabkeys;leaveslave=ungrabkeys;"
				"button4=scrollup;button5=scrolldown;"
				"key_Left=scrollup;key_Right=scrolldown;"
				"button1=menuexec;button3=exit:13;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
		else {
			char edef[]  = "entertitle=uncollapse,grabkeys;"
				"enterslave=grabkeys;leaveslave=collapse,ungrabkeys;"
				"button1=menuexec;button2=togglestick;button3=exit:13;"
				"button4=scrollup;button5=scrolldown;"
				"key_Up=scrollup;key_Down=scrolldown;"
				"key_Escape=ungrabkeys,exit";
			fill_ev_table(edef);
		}
	}

	if((find_event(onexit) != -1)
			&& (setup_signal(SIGTERM, catch_sigterm) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGTERM\n");

	if((find_event(sigusr1) != -1)
			&& (setup_signal(SIGUSR1, catch_sigusr1) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR1\n");

	if((find_event(sigusr2) != -1)
		&& (setup_signal(SIGUSR2, catch_sigusr2) == SIG_ERR))
		fprintf(stderr, "dzen: error hooking SIGUSR2\n");

	if(setup_signal(SIGALRM, catch_alrm) == SIG_ERR)
		fprintf(stderr, "dzen: error hooking SIGALARM\n");

	x_create_windows(use_ewmh_dock);

	if(!dzen.slave_win.ishmenu)
		x_map_window(dzen.title_win.win);
	else {
		XMapRaised(dzen.dpy, dzen.slave_win.win);
		for(i=0; i < dzen.slave_win.max_lines; i++)
			XMapWindow(dzen.dpy, dzen.slave_win.line[i]);
	}

	if( fnpre != NULL )
		font_preload(fnpre);

	do_action(onstart);

	event_loop();	// Main loop

	do_action(onexit);
	clean_up();

	if(dzen.ret_val)
		return dzen.ret_val;

	exit(EXIT_SUCCESS);
}