Пример #1
0
int
main(int argc, char *argv[])
{
    int fd;
    int sleep_time_s;

    sleep_time_s = 10;
    if (argc > 1) {
        sleep_time_s = strtoul(argv[1], NULL, 0);
    }

    /* Create pid_file and lock it */
    fd = create_pid_file("t_create_pid_file",
            "/tmp/t_create_pid_file.pid", 0);
    if (fd == -1) {
        perror("create_pid_file");
        exit(EXIT_FAILURE);
    }

    /* Do something. */
    sleep(sleep_time_s);

    /* For termination, delete pid file. */
    if (unlink("/tmp/t_create_pid_file.pid") == -1) {
        perror("unlink");
        exit(EXIT_FAILURE);
    }

    exit(EXIT_SUCCESS);
}
Пример #2
0
gboolean daemon_init(hsb_daemon_config *my_daemon, gboolean background)
{
	int fd ;
	const char *work_dir = get_work_dir();

	if ( background == TRUE )
		if ( -1 == daemon(0,0) )
			return FALSE;

	umask(0022);
	mkdir(work_dir, 0755);

	if ( -1 == chdir(work_dir) )
		return FALSE ;

	if (total_cfg_read() == FALSE)
		return FALSE;

	if (create_pid_file(my_daemon->pid_file)) 
		return FALSE;

	fd = unix_socket_new_listen( my_daemon->unix_listen_path ) ;
	if (-1 == fd)
	{
		unlink(my_daemon->pid_file);
		unlink(my_daemon->unix_listen_path);
		return FALSE;
	} 

	my_daemon->unix_listen_fd = fd;

	return TRUE;
}
Пример #3
0
int daemonize() {
   pid_t pid;
   int fd;

   pid = fork();

   if ( pid > 0 ) {
      exit_clean(0); /* parent */
   }

   use_syslog = 1;
   if ( pid < 0 ) {
      return ERROR;
   }

   /* new process group */
   setsid();

   /* close file handles */
   if ( (fd = open("/dev/null", O_RDWR)) >= 0 ) {
      dup2(fd, 0);
      dup2(fd, 1);
      dup2(fd, 2);
      if ( fd > 2 ) {
         close(fd);
      }
   }

   if ( pidfile ) {
      return create_pid_file(pidpath, pidfile);
   }

   return SUCCESS;
}
Пример #4
0
int daemonize()
{
    pid_t pid;
    int fd;

    pid = fork();

    if (pid > 0) {
        exit(0);    /* Parent */
    }

    if (pid < 0) {
        return ERROR;
    }

    setsid();

    if ((fd = open("/dev/null", O_RDWR)) >= 0) {
        dup2(fd, 0);
        dup2(fd, 1);
        dup2(fd, 2);
        if (fd > 2) {
            close(fd);
        }
    }

    if (config.pidfile) {
        return create_pid_file(config.pidfile);
    }

    return SUCCESS;
}
Пример #5
0
static int __init make_umid_setup(void)
{
	/* one function with the ordering we need ... */
	make_uml_dir();
	make_umid(printf);
	return create_pid_file();
}
Пример #6
0
int parrot_daemon(void) 
{
    /*
     * Creates a daemon out the Parrot process.  Parrot will continue to run
     * threads separated from any controlling terminal.  This is the standard 
     * method for creating a daemon in a linux/gnu enviroment.  Fork twice,
     * setting the file mode, create a new session ID, and finally change to 
     * the "/" or root directory.
     */
   
    pid_t pid = fork();

    if (pid == -1) {
        log_error(__FILE__, "parrot_daemon", "fork", __LINE__, errno);
        return -1;
    }

    if (pid > 0) 
        exit(0);         // if pid is greater than 0 than we are in the parent

    umask(0);
    pid_t sid = setsid();

    if (sid == -1) {
        log_error(__FILE__, "parrot_daemon", "setsid", __LINE__, errno);
        return -1;
    }

    if ((chdir("/")) == -1) {
        log_error(__FILE__, "parrot_daemon", "chdir", __LINE__, errno);
        return -1;
    }

    pid = fork();

    if (pid == -1) {
        log_error(__FILE__, "parrot_daemon", "fork", __LINE__, errno);
        return -1;
    }

    if (pid > 0)
        exit(0);

    int pid_file_ret = create_pid_file();

    if (pid_file_ret == -1) {
        log_error(__FILE__, "parrot_daemon", "create_pid_file", __LINE__, errno);
        return -1;
    }

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    return 0;
}
Пример #7
0
int main (int argc, char **argv) { 

    leave_suid();
    
    if ( (program = strrchr(argv[0], '/')) == 0 ) 
        program = argv[0]; 
    else 
        program ++;
    
    parse_args(argc, argv);

    debug("start up");

    initlog(program, facility, logfile);

    debug("init log"); 
    
#ifndef NO_FORK
    
    if (daemon_mode) { 
        if (daemon(0, 0)) 
            av_shutdown(1); 
    } 
#endif

    set_signals(); 
    signal(SIGPIPE, SIG_IGN);
    
    if (create_pid_file())          /* bug - don't call shutdown - it removes pidfile */ 
        av_shutdown(1);

    notice("started");

    if ( !no_check && (drweb_ver = dw_getversion()) != -1 ) {
        notice("drwebd %d.%d found", drweb_ver/100, drweb_ver % 100);
    }
    else {
        no_check = 1;
    }

    if ( !no_check && (drweb_id = dw_getid()) != NULL ) {
        notice("drwebd id = <%s>", drweb_id );
    }

    if ( !no_check ) {
        dw_getbaseinfo();
    }

    main_loop();

    av_shutdown(0);
    

    return 0;
}
Пример #8
0
/**
 * Do needed steps to start showing the gui
 */
static int setup ()
{
    // Create pid file
    int pfd = create_pid_file ( pidfile );
    if ( pfd >= 0 ) {
        // Request truecolor visual.
        x11_create_visual_and_colormap ( );
        textbox_setup ();
    }
    return pfd;
}
Пример #9
0
int daemonize(const char *name)
{
	int ret;
	pid_t pid, sid;

	pid = fork();
	if (pid < 0)
		return pid;
	if (pid > 0)
		exit(EXIT_SUCCESS);

	sid = setsid();
	if (sid < 0)
		return sid;

	//setup_signal_handler();

	pid = fork();
	if (pid < 0)
		return pid;
	if (pid > 0)
		exit(EXIT_SUCCESS);

	/* always succeeds */
	umask(0);
	
	ret = chdir(getenv("HOME"));
	if (ret < 0) {
		ret = chdir("/");
		if (ret < 0)
			return ret;
	}

	// NOTE: if other file descriptors are used close them here
	ret = close(STDIN_FILENO);
	if (ret < 0)
		return ret;

	ret = close(STDOUT_FILENO);
	if (ret < 0)
		return ret;

	ret = close(STDERR_FILENO);
	if (ret < 0)
		return ret;

	ret = create_pid_file(name);
	if (ret < 0)
		return ret;

	close(ret);

	return 0;
}
Пример #10
0
static int process_ctx_init_impl(const char *argv0, int daemonize,
				struct logc *lc)
{
	char err[512] = { 0 };
	size_t err_len = sizeof(err);

	configure_glitch_log(lc);
	g_fast_log_mgr = fast_log_mgr_init(g_fast_log_dumpers);
	if (IS_ERR(g_fast_log_mgr)) {
		glitch_log("fast_log_mgr_init failed with error %d",
			PTR_ERR(g_fast_log_mgr));
		g_fast_log_mgr = NULL;
		goto error_close_glitchlog;
	}
	if (lc->fast_log == JORM_INVAL_STR)
		configure_fast_log(getenv("REDFISH_LOG"));
	else
		configure_fast_log(lc->fast_log);
	signal_init(argv0, err, err_len, lc);
	if (err[0]) {
		glitch_log("signal_init error: %s\n", err);
		goto error_free_fast_log_mgr;
	}
	if (daemonize) {
		if (daemon(0, 0) < 0) {
			int ret = errno;
			glitch_log("daemon(3) error %d\n", ret);
			goto error_signal_shutdown;
		}
	}
	create_pid_file(lc, err, err_len);
	if (err[0]) {
		glitch_log("create_pid_file error: %s\n", err);
		goto error_signal_shutdown;
	}
	return 0;

error_signal_shutdown:
	signal_shutdown();
error_free_fast_log_mgr:
	fast_log_mgr_release(g_fast_log_mgr);
	g_fast_log_mgr = NULL;
error_close_glitchlog:
	close_glitch_log();
	return 1;
}
Пример #11
0
int main(int argc,char **argv)
{
	init_param(argc,argv);
	init_signal(); //注册关闭信号
	printf("using config file %s\n",g_config_file);
	init_config(g_config_file,&set_config_item);
	//return 0;
	g_status = SERVER_STATUS_RUN; //设置服务器的状态
	pthread_mutex_init(&g_lrumc_lock,NULL);
	create_pid_file();
	prepare_crypt_table();
	g_lrumc = init_lrumc(g_lrumc_config,g_segment_num);
	g_epoll_socket = create_epoll_socket();//创建socket句柄
	g_thread = create_epoll_thread(g_thread_num,g_epoll_socket,thread_func);//创建thread句柄
	start_epoll_socket(g_epoll_socket,g_port);//开始监听
	return 0;	
}
Пример #12
0
static int create_server(void)
{
	if (create_pid_file(IMAGE_SERVER_PROC) < 0) {
		APP_ERROR("create_pid_file");
		return -1;
	}
	if (init_server() < 0) {
		APP_ERROR("init_server");
		return -1;
	}

#if 0
#ifndef CONFIG_AMBARELLA_IMAGE_SERVER_DAEMON
	if (start_server() < 0) {
		APP_ERROR("start_server");
		return -1;
	}
#endif
#endif
	APP_INFO("[Done] create image_server\n");
	return 0;
}
Пример #13
0
static void start_daemon(const char *progname, struct a6o_daemon_options *opts)
{
	struct a6o_conf *conf;
	struct armadito *armadito;
	int server_sock;
	struct server *server;
	a6o_error *error = NULL;
	GMainLoop *loop;

	loop = g_main_loop_new(NULL, FALSE);

	log_init(opts->s_log_level, !opts->no_daemon);

	if (!opts->no_daemon)
		daemonize();

	if (opts->pid_file != NULL)
		create_pid_file(opts->pid_file);

	a6o_log(ARMADITO_LOG_SERVICE, ARMADITO_LOG_LEVEL_NONE, "starting %s%s", progname, opts->no_daemon ? "" : " in daemon mode");

	conf = a6o_conf_new();
	load_conf(conf);
	load_conf_dir(conf);

	armadito = a6o_open(conf, &error);
	if (armadito == NULL) {
		a6o_error_print(error, stderr);
		exit(EXIT_FAILURE);
	}

	server_sock = create_server_socket(opts);

	server = server_new(armadito, server_sock, opts->ipc_type);

	g_main_loop_run(loop);
}
Пример #14
0
int main(int argc, char *argv[])
{
        /* Initialize various components. */
        init_common();
        init_driver();

        if (parse_arguments(argc, argv) != OK) {
                printf("usage: %s -d <address> -wmin # -wmax # -l # [-w #] [-p #] [-c #] [-i #] [-o #] [-n #] [-q %%] [-r %%] [-e %%] [-t %%] [-seed #] [-altered 0] [-spread #] [-z]",
                        argv[0]);
#ifdef STANDALONE
#ifdef LIBPQ
                printf(" -z #");
#endif /* LIBPQ */
#endif /* STANDALONE */
                printf("\n\n");
#ifdef STANDALONE
                printf("-dbname <connect_string>\n");
                printf("\tdatabase connect string\n");
#ifdef LIBPQ
                printf("-z #\n");
                printf("\tpostmaster listener port\n");
#endif /* LIBPQ */
#ifdef LIBMYSQL
		printf("-z #\n");
		printf("\tmysql server listener port\n");
#endif /* LIBMYSQL */
#ifdef LIBDRIZZLE
		printf("-z #\n");
		printf("\tdrizzle server listener port\n");
#endif /* LIBDRIZZLE */
#else /* STANDALONE */
                printf("-d <address>\n");
                printf("\tnetwork address where client program is running\n");
                printf("-p #\n");
                printf("\tclient port, default %d\n", CLIENT_PORT);
#endif /* STANDALONE */
                printf("\n");
                printf("-l #\n");
                printf("\tthe duration of the run in seconds\n");
                printf("\n");
                printf("-wmin #\n");
                printf("\tlower warehouse id\n");
                printf("-wmax #\n");
                printf("\tupper warehouse id\n");
                printf("-w #\n");
                printf("\twarehouse cardinality, default 1\n");
                printf("-c #\n");
                printf("\tcustomer cardinality, default %d\n", CUSTOMER_CARDINALITY);
                printf("-i #\n");
                printf("\titem cardinality, default %d\n", ITEM_CARDINALITY);
                printf("-o #\n");
                printf("\torder cardinality, default %d\n", ORDER_CARDINALITY);
                printf("-n #\n");
                printf("\tnew-order cardinality, default %d\n", NEW_ORDER_CARDINALITY);
                printf("\n");
                printf("-q %%\n");
                printf("\tmix percentage of Payment transaction, default %0.2f\n",
                        MIX_PAYMENT);
                printf("-r %%\n");
                printf("\tmix percentage of Order-Status transaction, default %0.2f\n",
                        MIX_ORDER_STATUS);
                printf("-e %%\n");
                printf("\tmix percentage of Delivery transaction, default %0.2f\n",
                        MIX_DELIVERY);
                printf("-t %%\n");
                printf("\tmix percentage of Stock-Level transaction, default %0.2f\n",
                        MIX_STOCK_LEVEL);
                printf("\n");
                printf("-ktd #\n");
                printf("\tdelivery keying time, default %d s\n", KEY_TIME_DELIVERY);
                printf("-ktn #\n");
                printf("\tnew-order keying time, default %d s\n", KEY_TIME_NEW_ORDER);
                printf("-kto #\n");
                printf("\torder-status keying time, default %d s\n",
                        KEY_TIME_ORDER_STATUS);
                printf("-ktp #\n");
                printf("\tpayment keying time, default %d s\n", KEY_TIME_PAYMENT);
                printf("-kts #\n");
                printf("\tstock-level keying time, default %d s\n",
                        KEY_TIME_STOCK_LEVEL);
                printf("-ttd #\n");
                printf("\tdelivery thinking time, default %d ms\n",
                        THINK_TIME_DELIVERY);
                printf("-ttn #\n");
                printf("\tnew-order thinking time, default %d ms\n",
                        THINK_TIME_NEW_ORDER);
                printf("-tto #\n");
                printf("\torder-status thinking time, default %d ms\n",
                        THINK_TIME_ORDER_STATUS);
                printf("-ttp #\n");
                printf("\tpayment thinking time, default %d ms\n", THINK_TIME_PAYMENT);
                printf("-tts #\n");
                printf("\tstock-level thinking time, default %d ms\n",
                        THINK_TIME_STOCK_LEVEL);
                printf("\n");
                printf("-tpw #\n");
                printf("\tterminals started per warehouse, default 10\n");

                printf("\n");
                printf("-seed #\n");
                printf("\trandom number seed\n");
                printf("-altered [0/1]\n");
                printf("\trun with a thread per user, -altered 1\n");
                printf("-sleep #\n");
                printf("\tnumber of milliseconds to sleep between terminal creation\n");
                printf("-spread #\n");
                printf("\tfancy warehouse skipping trick for low i/o runs\n");

                printf("-z #\n");
                printf("\tperform database integrity check\n");
#ifdef STANDALONE
                printf("\nDriver is in STANDALONE mode.\n");
#endif /* STANDALONE */

                return 1;
        }
        create_pid_file();

        if(init_logging() != OK || init_driver_logging() != OK) {
                printf("cannot init driver\n");
                return 1;
        };

        /* Sanity check on the parameters. */
        if (w_id_min > w_id_max) {
                printf("wmin cannot be larger than wmax\n");
                return 1;
        }
        if (w_id_max > table_cardinality.warehouses) {
                printf("wmax cannot be larger than w\n");
                return 1;
        }

        if (recalculate_mix() != OK) {
                printf("invalid transaction mix: -e %0.2f. -r %0.2f. -q %0.2f. -t %0.2f. causes new-order mix of %0.2f.\n",
                        transaction_mix.delivery_actual,
                        transaction_mix.order_status_actual,
                        transaction_mix.payment_actual,
                        transaction_mix.stock_level_actual,
                        transaction_mix.new_order_actual);
                return 1;
        }

        /* Double check database table cardinality. */
        printf("\n");
        printf("database table cardinalities:\n");
        printf("warehouses = %d\n", table_cardinality.warehouses);
        printf("districts = %d\n", table_cardinality.districts);
        printf("customers = %d\n", table_cardinality.customers);
        printf("items = %d\n", table_cardinality.items);
        printf("orders = %d\n", table_cardinality.orders);
        printf("stock = %d\n", table_cardinality.items);
        printf("new-orders = %d\n", table_cardinality.new_orders);
        printf("\n");

        /* Double check the transaction mix. */
        printf("transaction mix:\n");
        printf("new-order mix %0.2f\n", transaction_mix.new_order_actual);
        printf("payment mix %0.2f\n", transaction_mix.payment_actual);
        printf("order-status mix %0.2f\n", transaction_mix.order_status_actual);
        printf("delivery mix %0.2f\n", transaction_mix.delivery_actual);
        printf("stock-level mix %0.2f\n", transaction_mix.stock_level_actual);
        printf("\n");

        /* Double check the transaction threshold. */
        printf("transaction thresholds:\n");
        printf("new-order threshold %0.2f\n",
                transaction_mix.new_order_threshold);
        printf("payment threshold %0.2f\n", transaction_mix.payment_threshold);
        printf("order-status threshold %0.2f\n",
                transaction_mix.order_status_threshold);
        printf("delivery threshold %0.2f\n",
                transaction_mix.delivery_threshold);
        printf("stock-level threshold %0.2f\n",
                transaction_mix.stock_level_threshold);
        printf("\n");

        /* Double check the keying time. */
        printf("delivery keying time %d s\n", key_time.delivery);
        printf("new_order keying time %d s\n", key_time.new_order);
        printf("order-status keying time %d s\n", key_time.order_status);
        printf("payment keying time %d s\n", key_time.payment);
        printf("stock-level keying time %d s\n", key_time.stock_level);
        printf("\n");

        /* Double check the thinking time. */

        printf("delivery thinking time %d ms\n", think_time.delivery);
        printf("new_order thinking time %d ms\n", think_time.new_order);
        printf("order-status thinking time %d ms\n", think_time.order_status);
        printf("payment thinking time %d ms\n", think_time.payment);
        printf("stock-level thinking time %d ms\n", think_time.stock_level);
        printf("\n");

        printf("w_id range %d to %d\n", w_id_min, w_id_max);
        printf("\n");

        printf("%d terminals per warehouse\n", terminals_per_warehouse);
        printf("\n");

        printf("%d second steady state duration\n", duration);
        printf("\n");

        if (perform_integrity_check && integrity_terminal_worker() != OK) {
           printf("You used wrong parameters or something wrong with database.\n");
           return 1;
        }

        start_driver();

        return 0;
}
Пример #15
0
int run_network(void*(*func)(void*)){
    struct sockaddr_in sockserv,sockclient;
    int clientfd;
    int socketfd;
    socklen_t clientsocklen;
    pthread_t children[NUMTHREADS];
    struct threadData data[NUMTHREADS];
    int i,j;
    stop = 0;
    #ifdef DETACHED_THREADS
    pthread_attr_t attr;
    #endif
    fd_set rfds;
    struct timeval tv;
    int retval;
    int sec;
    int usec;
    int port;

    clientfd = socketfd  = 0; 
    
    bzero(&sockserv,sizeof(sockserv));
    sec = 0;
    usec = 10;
    port = determine_port();

    socketfd = createSocket();
    BOOT_LOG_STR("Socket Creation: ", strerror(errno));
    setupSockAndBind(socketfd, &sockserv, port); 
    BOOT_LOG_STR("Socket Bind: ", strerror(errno));
    listen(socketfd,NUMTHREADS);
    BOOT_LOG_STR("Socket Listen: ", strerror(errno));

    BOOT_LOG_NUM("Server listening on port: ", port);
    BOOT_LOG_NUM("Green Serv Process ID: ", getpid());
    create_pid_file();

    clientsocklen = sizeof socketfd;

    #ifdef DETACHED_THREADS
    BOOT_LOG_STR("Detached threads is defined", "");
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    #endif

    signal(SIGINT, stop_server);
    signal(SIGTERM, stop_server);
    signal(SIGQUIT, stop_server);
    signal(SIGHUP, stop_server);    

    FD_ZERO(&rfds);
    FD_SET(socketfd, &rfds);
    tv.tv_sec = sec;
    tv.tv_usec = usec;


    i=j=0;
    if(errno != 13){
        while(stop == 0){
            for(i=0; i < NUMTHREADS && stop == 0; i++){
                retval = select((socketfd+1)/*see "man select_tut"*/, &rfds, NULL, NULL, &tv);
                /* Reset select */
                tv.tv_sec = sec;
                tv.tv_usec = usec;
                if(retval == -1 || ! FD_ISSET(socketfd, &rfds)){
                    /* From select_tut: 
                     *
                     *   After select() has returned, readfds will  be  cleared
                     *   of all file descriptors except for those that are immediately 
                     *   available for reading.
                     *
                     *  Because we always want to monitor the setwe add the socket back in.
                     */
                    FD_SET(socketfd, &rfds);
                    i--;
                    continue;
                }
                FD_SET(socketfd, &rfds);

                /* We have yet to recieve anything or check for the header */
                clientfd = accept(socketfd,(struct sockaddr*)&sockclient,&clientsocklen);
                if(clientfd != -1){
                    data[i].clientfd = clientfd;
                    #ifndef DETACHED_THREADS
                        pthread_create(&children[i],NULL,func,&data[i]);
                    #else
                        NETWORK_LOG_LEVEL_2("Spawning detached thread");
                        pthread_create(&children[i],&attr,func,&data[i]);
                    #endif
                }else{
                    NETWORK_LOG_LEVEL_1("Connection shutdown.");
                    NETWORK_LOG_LEVEL_2("Invalid file descriptor from client connection.");
                    NETWORK_LOG_LEVEL_2("If shutting down server ignore previous warning.");
                    i--; /* Move thread index back one */
                }                
            }           
            /*Gobble Up the resources (if not detaching threads)
             *If you do want to detach threads change the define. 
             *in net.h
            */
            #ifndef DETACHED_THREADS
            NETWORK_LOG_LEVEL_1("Pausing to Join threads. One moment...");
            for(j=0; j < NUMTHREADS && j < i; ++j){
                pthread_join(children[j],NULL);
            }
            #endif
        }
    }
    #ifdef DETACHED_THREADS
    pthread_attr_destroy(&attr);
    #endif
    close(socketfd);
    remove_pid_file();
    BOOT_LOG_STR("Exiting Server...", "");
    wait(NULL);
    return 0;
}
Пример #16
0
int main (int argc, char *argv[])
{
        HTTPMgmt *httpmgmt;
        HTTPStreaming *httpstreaming;
        GMainLoop *loop;
        GOptionContext *ctx;
        GError *err = NULL;
        gboolean foreground;
        struct rlimit rlim;
        GDateTime *datetime;
        gchar exe_path[512], *date;

        ctx = g_option_context_new (NULL);
        g_option_context_add_main_entries (ctx, options, NULL);
        g_option_context_add_group (ctx, gst_init_get_option_group ());
        if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
                g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
                exit (1);
        }
        g_option_context_free (ctx);
        GST_DEBUG_CATEGORY_INIT (GSTREAMILL, "gstreamill", 0, "gstreamill log");

        if (version) {
                print_version_info ();
                exit (0);
        }

        /* stop gstreamill. */
        if (stop) {
                gchar *pid_str;
                gint pid;

                g_file_get_contents (PID_FILE, &pid_str, NULL, NULL);
                if (pid_str == NULL) {
                        g_print ("File %s not found, check if gstreamill is running.\n", PID_FILE);
                        exit (1);
                }
                pid = atoi (pid_str);
                g_free (pid_str);
                g_print ("stoping gstreamill with pid %d ...\n", pid);
                kill (pid, SIGTERM);
                exit (0);
        }

        /* readlink exe path before setuid, on CentOS, readlink exe path after setgid/setuid failure on permission denied */
        memset (exe_path, '\0', sizeof (exe_path));
        if (readlink ("/proc/self/exe", exe_path, sizeof (exe_path)) == -1) {
                g_print ("Read /proc/self/exe error: %s", g_strerror (errno));
                exit (2);
        }

        if (prepare_gstreamill_run_dir () != 0) {
                g_print ("Can't create gstreamill run directory\n");
                exit (3);
        }
/*
        if (set_user_and_group () != 0) {
                g_print ("set user and group failure\n");
                exit (4);
        }
*/
        if (job_file != NULL) {
                /* gstreamill command with job, run in foreground */
                foreground = TRUE;

        } else {
                /* gstreamill command without job, run in background */
                foreground = FALSE;
        }

        if (gst_debug_get_default_threshold () < GST_LEVEL_WARNING) {
                gst_debug_set_default_threshold (GST_LEVEL_WARNING);
        }

        /* initialize ts segment static plugin */
        if (!gst_plugin_register_static (GST_VERSION_MAJOR,
                                         GST_VERSION_MINOR,
                                         "tssegment",
                                         "ts segment plugin",
                                         ts_segment_plugin_init,
                                         "0.1.0",
                                         "GPL",
                                         "GStreamer",
                                         "GStreamer",
                                         "http://gstreamer.net/")) {
                GST_ERROR ("registe tssegment error");
                exit (17);
        }

        /* subprocess, create_job_process */
        if (shm_name != NULL) {
                gint fd;
                gchar *job_desc, *p;
                Job *job;
                gchar *log_path, *name;
                gint ret;

                /* set subprocess maximum of core file */
                rlim.rlim_cur = 0;
                rlim.rlim_max = 0;
                if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
                        GST_ERROR ("setrlimit error: %s", g_strerror (errno));
                }

                /* read job description from share memory */
                job_desc = NULL;
                fd = shm_open (shm_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
                if (ftruncate (fd, job_length) == -1) {
                        exit (5);
                }
                p = mmap (NULL, job_length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
                job_desc = g_strdup (p);

                if ((job_desc != NULL) && (!jobdesc_is_valid (job_desc))) {
                        exit (6);
                }

                /* initialize log */
                name = (gchar *)jobdesc_get_name (job_desc);
                if (!jobdesc_is_live (job_desc)) {
                        gchar *p;

                        p = jobdesc_get_log_path (job_desc);
                        log_path = g_build_filename (p, "gstreamill.log", NULL);
                        g_free (p);

                } else {
                        log_path = g_build_filename (log_dir, name, "gstreamill.log", NULL);
                }
                ret = init_log (log_path);
                g_free (log_path);
                if (ret != 0) {
                        exit (7);
                }

                /* launch a job. */
                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : job %s starting ***\n\n", date, name);
                g_date_time_unref (datetime);
                g_free (date);
                job = job_new ("name", name, "job", job_desc, NULL);
                job->is_live = jobdesc_is_live (job_desc);
                job->eos = FALSE;
                loop = g_main_loop_new (NULL, FALSE);

                GST_INFO ("Initializing job ...");
                if (job_initialize (job, TRUE) != 0) {
                        GST_ERROR ("initialize job failure, exit");
                        exit (8);
                }
                GST_INFO ("Initializing job done");

                GST_INFO ("Initializing job's encoders output ...");
                if (job_encoders_output_initialize (job) != 0) {
                        GST_ERROR ("initialize job encoders' output failure, exit");
                        exit (8);
                }
                GST_INFO ("Initializing job's encoders output done");

                GST_INFO ("Starting job ...");
                if (job_start (job) != 0) {
                        GST_ERROR ("start livejob failure, exit");
                        exit (9);
                }
                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : job %s started ***\n\n", date, name);
                g_date_time_unref (datetime);
                g_free (date);
                g_free (name);
                g_free (job_desc);

                signal (SIGPIPE, SIG_IGN);
                signal (SIGUSR1, sighandler);
                signal (SIGTERM, stop_job);

                g_main_loop_run (loop);

        } else {
                /* set parent process maximum of core file */
                rlim.rlim_cur = RLIM_INFINITY;
                rlim.rlim_max = RLIM_INFINITY;
                if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
                        GST_ERROR ("setrlimit error: %s", g_strerror (errno));
                }
        }

        /* run in background? */
        if (!foreground) {
                gchar *path;
                gint ret;

                /* pid file exist? */
                if (g_file_test (PID_FILE, G_FILE_TEST_EXISTS)) {
                        g_print ("file %s found, gstreamill already running !!!\n", PID_FILE);
                        exit (10);
                }

                /* media directory */
                path = g_strdup_printf ("%s/dvr", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create DVR directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create DVR directory failure: %s", path);
                        }
                }
                g_free (path);
                path = g_strdup_printf ("%s/transcode/in", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create transcode directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create transcode directory failure: %s", path);
                        }
                }
                g_free (path);
                path = g_strdup_printf ("%s/transcode/out", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create transcode directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create transcode directory failure: %s", path);
                        }
                }
                g_free (path);

                /* log to file */
                path = g_build_filename (log_dir, "gstreamill.log", NULL);
                ret = init_log (path);
                g_free (path);
                if (ret != 0) {
                        g_print ("Init log error, ret %d.\n", ret);
                        exit (11);
                }

                /* daemonize */
                if (daemon (0, 0) != 0) {
                        fprintf (_log->log_hd, "Failed to daemonize");
                        remove_pid_file ();
                        exit (1);
                }

                /* create pid file */
                if (create_pid_file () != 0) {
                        exit (1);
                }

                /* customize signal */
                signal (SIGUSR1, sighandler);
                signal (SIGTERM, stop_gstreamill);

                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : gstreamill started ***\n\n", date);
                g_free (date);
                g_date_time_unref (datetime);
        }

        /* ignore SIGPIPE */
        signal (SIGPIPE, SIG_IGN);

        loop = g_main_loop_new (NULL, FALSE);

        /* gstreamill */
        gstreamill = gstreamill_new ("daemon", !foreground, "log_dir", log_dir, "exe_path", exe_path, NULL);
        if (gstreamill_start (gstreamill) != 0) {
                GST_ERROR ("start gstreamill error, exit.");
                remove_pid_file ();
                exit (12);
        }

        /* httpstreaming, pull */
        httpstreaming = httpstreaming_new ("gstreamill", gstreamill, "address", http_streaming, NULL);
        if (httpstreaming_start (httpstreaming, 10) != 0) {
                GST_ERROR ("start httpstreaming error, exit.");
                remove_pid_file ();
                exit (13);
        }

        if (!foreground) {
                /* run in background, management via http */
                httpmgmt = httpmgmt_new ("gstreamill", gstreamill, "address", http_mgmt, NULL);
                if (httpmgmt_start (httpmgmt) != 0) {
                        GST_ERROR ("start http mangment error, exit.");
                        remove_pid_file ();
                        exit (14);
                }

        } else {
                /* run in foreground, start job */
                gchar *job, *p, *result;
                JSON_Value *val;
                JSON_Object *obj;

                /* ctrl-c, stop gstreamill */
                signal (SIGINT, stop_gstreamill);

                /* ctrl-\, stop gstreamill */
                signal (SIGQUIT, stop_gstreamill);

                if (!g_file_get_contents (job_file, &job, NULL, NULL)) {
                        GST_ERROR ("Read job file %s error.", job_file);
                        exit (15);
                }
                p = gstreamill_job_start (gstreamill, job);
                val = json_parse_string (p);
                obj = json_value_get_object (val);
                result = (gchar *)json_object_get_string (obj, "result");
                GST_INFO ("start job result: %s.", result);
                if (g_strcmp0 (result, "success") != 0) {
                        exit (16);
                }
                json_value_free (val);
                g_free (p);
        }

        g_main_loop_run (loop);

        return 0;
}
Пример #17
0
int
main (int    argc,
      char **argv)
{
        GOptionContext  *context;
        GError          *error;
        int              ret;
        gboolean         res;
        guint            id;
        static gboolean     debug            = FALSE;
        static gboolean     no_daemon        = FALSE;
        static gboolean     do_timed_exit    = FALSE;
        static GOptionEntry entries []   = {
                { "debug", 0, 0, G_OPTION_ARG_NONE, &debug, N_("Enable debugging code"), NULL },
                { "no-daemon", 0, 0, G_OPTION_ARG_NONE, &no_daemon, N_("Don't become a daemon"), NULL },
                { "timed-exit", 0, 0, G_OPTION_ARG_NONE, &do_timed_exit, N_("Exit after a time - for debugging"), NULL },
                { NULL }
        };

        /* Setup for i18n */
        setlocale(LC_ALL, "");
 
#ifdef ENABLE_NLS
        bindtextdomain(PACKAGE, LOCALEDIR);
        textdomain(PACKAGE);
#endif

        ret = 1;

#if !GLIB_CHECK_VERSION(2, 32, 0)
        if (! g_thread_supported ()) {
                g_thread_init (NULL);
        }
#endif

#if !GLIB_CHECK_VERSION(2, 36, 0)
        g_type_init ();
#endif

        if (! ck_is_root_user ()) {
                g_warning (_("You must be root to run this program"));
                exit (1);
        }

        context = g_option_context_new (_("Console kit daemon"));
        g_option_context_add_main_entries (context, entries, NULL);
        error = NULL;
        res = g_option_context_parse (context, &argc, &argv, &error);
        g_option_context_free (context);
        if (! res) {
                g_warning ("%s", error->message);
                g_clear_error (&error);
                goto out;
        }

#ifdef CONSOLEKIT_DEBUGGING
        /* compiling with --enable-debug=full turns debugging on */
        debug = TRUE;
#endif

        if (debug) {
                g_setenv ("G_DEBUG", "fatal_criticals", FALSE);
                g_log_set_always_fatal (G_LOG_LEVEL_CRITICAL);
        }

        if (! no_daemon && daemon (0, 0)) {
                g_error ("Could not daemonize: %s", g_strerror (errno));
                g_clear_error (&error);
        }

        setup_debug_log (debug);

        setup_termination_signals ();

        g_debug ("initializing console-kit-daemon %s", VERSION);

        id = g_bus_own_name (G_BUS_TYPE_SYSTEM,
                             CK_DBUS_NAME,
                             G_BUS_NAME_OWNER_FLAGS_NONE,
                             bus_acquired, name_acquired, name_lost,
                             NULL, NULL);

        create_pid_file ();

        loop = g_main_loop_new (NULL, FALSE);

        if (do_timed_exit) {
                g_timeout_add (1000 * 30, (GSourceFunc) timed_exit_cb, loop);
        }

        g_main_loop_run (loop);

        g_bus_unown_name (id);

        g_main_loop_unref (loop);

        ret = 0;

 out:

        return ret;
}
Пример #18
0
void
XboxdrvDaemon::run()
{
  try 
  {
    create_pid_file();

    init_uinput();

    USBSubsystem usb_subsystem;

    UdevSubsystem udev_subsystem;
    udev_subsystem.set_device_callback(boost::bind(&XboxdrvDaemon::process_match, this, _1));

    boost::scoped_ptr<DBusSubsystem> dbus_subsystem;
    if (m_opts.dbus != Options::kDBusDisabled)
    {
      DBusBusType dbus_bus_type;

      switch(m_opts.dbus)
      {
        case Options::kDBusAuto:
          if (getuid() == 0)
          {
            dbus_bus_type = DBUS_BUS_SYSTEM;
          }
          else
          {
            dbus_bus_type = DBUS_BUS_SESSION;
          }
          break;

        case Options::kDBusSession:
          dbus_bus_type = DBUS_BUS_SESSION;
          break;

        case Options::kDBusSystem:
          dbus_bus_type = DBUS_BUS_SYSTEM;
          break;

        case Options::kDBusDisabled:
        default:
          assert(!"should never happen");
          break;
      }

      dbus_subsystem.reset(new DBusSubsystem("org.seul.Xboxdrv", dbus_bus_type));
      dbus_subsystem->register_xboxdrv_daemon(this);
      dbus_subsystem->register_controller_slots(m_controller_slots);
    }
    
    log_debug("launching into main loop");
    g_main_loop_run(m_gmain);
    log_debug("main loop exited");

    // get rid of active ControllerThreads before the subsystems shutdown
    m_inactive_controllers.clear();
    m_controller_slots.clear();
  }
  catch(const std::exception& err)
  {
    log_error("fatal exception: " << err.what());
  }
}
Пример #19
0
/* The code */
int	main (int argc, char* argv [])
{
	char*	interfaceName;
	char	buffer [MAXLEN];
	ulong	ledVal;	
	char*	tmpPointer;
	char**	list;
	pid_t	pid;
	int	sleeptime;
	int	wasInDeepSleep;
	struct timeval sleeptimeval;
	
	interfaceName = NULL;
	sleeptime = 0;
	handle_my_argvs(&interfaceName, &sleeptime, argc, argv);
	check_sanity();	/* Checks and maybe changes the option flags. */
#ifdef DEBUG
	opt_b = TRUE;	/* We are debugging so don't go to the background */
#endif
	if (opt_v && !opt_q)
		fprintf(stderr,
		    "%s version %s, GPL (c) 1997 [email protected]\n",
		    MYNAME, VERSION);
	strcpy(pidFileName, _PATH_TMP);
	strcpy(rootPidFileName, _PATH_VARRUN);
	strcat(pidFileName, MYNAME); /* Was argv[0]. Probs coz/if path. */
	strcat(rootPidFileName, MYNAME);
	strcat(pidFileName, ".pid");
	strcat(rootPidFileName, ".pid");
	if (opt_k) {
		return kill_old_process();
	}
	if (opt_h) {
		usage(argv[0]);
		return 0;
	}
	if (! opt_q) {
		printf("Setting keyboard LEDs based on %s %s %s %s\n",
		    "changes of Receive/Transmit\npackets of", interfaceName,
		    "in", devFileName);
		printf("Delay between updates is %d milliseconds.\n",
		    sleeptime);
	}
	if (! find_device_line(buffer, interfaceName) && !opt_q) {
		printf(
		    "There is currently no such interface as %s in %s.\n%s\n",
		    interfaceName, devFileName,
		    "Maybe later there will be. Kill me (-k) if ya want.");
	}
	
	if(! opt_b) {
		if (-1 == (pid = fork())) {
			perror("tleds: fork");
			return 1;
		}
	} else {
		pid = getpid();
	}
	if (pid) {
		create_pid_file(pid, argv[0]);
		if (! opt_q)
			printf("Running in %sground. Pid: %ld\n",
				(opt_b ? "fore" : "back"),
				(long)pid);
		if (! opt_b)
			exit(0);
	}
	if (atexit(my_exit)) {
		perror("tleds: atexit() failed");
		return 1;
	}
	if (! opt_b) {
		signal(SIGUSR1, parent_wants_me_dead);
	}
	signal(SIGHUP, SIG_IGN);
	signal(SIGTERM, my_signal_handler);
	signal(SIGINT, my_signal_handler);
	signal(SIGQUIT, my_signal_handler);
	signal(SIGTSTP, my_signal_handler); 
	signal(SIGUSR2, SIG_IGN);
	signal(SIGPIPE, my_signal_handler);
	if (! geteuid()) {	/* We are running as EUID root - CONSOLE */
		if (-1 == (keyboardDevice = open(KEYBOARDDEVICE, O_RDONLY))) {
			perror("tleds");
			fprintf(stderr, "%s:%s", KEYBOARDDEVICE, TERMINATESTR);
			exit(1);
		}
	} else {		/* EUID not root */
#if (! REMOVE_X_CODE)
		if (! (myDisplay = XOpenDisplay(NULL))		/* X  */
	  		&& ioctl(0, KDGETLED, &ledVal) ) { 	/* VT */
			perror(
			   "tleds: Can't open X DISPLAY on the current host.");
#else
		if (ioctl(0, KDGETLED, &ledVal) ) {
			perror("tleds: KDGETLED");
			fprintf(stderr,
				"Error reading current led setting.\n%s\n",
				"Maybe stdin is not a VT?");
#endif
			fprintf(stderr, TERMINATESTR);
			exit (1);
		}
	}
	sleeptimeval.tv_sec = (int)((long)sleeptime * 1000L) / 1000000L;
	sleeptimeval.tv_usec = (int)((long)sleeptime * 1000L) % 1000000L;
	wasInDeepSleep = TRUE;
	
	/* The main loop */
	while (1) {
		if ((tmpPointer = find_device_line(buffer, interfaceName))) {
			if (wasInDeepSleep) {
				wasInDeepSleep = FALSE;
				detach_vt_leds(TRUE);
			}
			list = split_on_blank(tmpPointer);
			report_traffic(list);
			my_sleep(sleeptimeval);
		} else {
			if (! wasInDeepSleep) {
				wasInDeepSleep = TRUE;
				detach_vt_leds(FALSE);
				previousActive = (ushort)(MAXVT + 1);
			}
			sleep(DEEPSLEEP);
		}
	}
	return 0;	/* Yeah right, never gets this far. */
}

char*	find_device_line (char* buffer, char* netDeviceName)
{
	static long	fileOffset = 0L; 
	register FILE*	devFile;
	
	if (! (devFile = fopen(devFileName, "r")) ) {
		perror(devFileName);
		exit(1);
	}
	/* Skip two lines. (the header) */
	/* Two choices how to do this. Didn't find any differences in speed. */
#if 0
	fgets(buffer, MAXLEN, devFile);
	fgets(buffer, MAXLEN, devFile);
#else
	if (fileOffset) {
		fseek(devFile, fileOffset, SEEK_SET);
	} else {
		fgets(buffer, MAXLEN, devFile);
		fileOffset += (long)strlen(buffer);
		fgets(buffer, MAXLEN, devFile);
		fileOffset += (long)strlen(buffer);
	}
#endif

	while ( fgets(buffer, MAXLEN, devFile) ) {
		while(isblank(*buffer))
			buffer++;
		if (buffer == strstr(buffer, netDeviceName)) {
			fclose(devFile);
			return buffer;
		}
	}
	fclose(devFile);
	return NULL;
}

void	my_sleep (struct timeval sleeptimeval)
{
#if 1
	select(1, NULL, NULL, NULL, &sleeptimeval);
#else
	usleep(sleeptimeval.tv_usec);
#endif
}
Пример #20
0
int main (int argc, char *argv[])
{
   int ch;
   bool no_signals = false;
   bool test_config = false;
   pthread_t thid;
   char *uid = NULL;
   char *gid = NULL;

   start_heap = sbrk(0);
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");

   init_stack_dump();
   my_name_is(argc, argv, "bareos-sd");
   init_msg(NULL, NULL);
   daemon_start_time = time(NULL);

   /* Sanity checks */
   if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
      Emsg2(M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
         TAPE_BSIZE, B_DEV_BSIZE);
   }
   if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
      Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
   }

   while ((ch = getopt(argc, argv, "c:d:fg:mpstu:v?")) != -1) {
      switch (ch) {
      case 'c':                    /* configuration file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'f':                    /* run in foreground */
         foreground = true;
         break;

      case 'g':                    /* set group id */
         gid = optarg;
         break;

      case 'm':                    /* print kaboom output */
         prt_kaboom = true;
         break;

      case 'p':                    /* proceed in spite of I/O errors */
         forge_on = true;
         break;

      case 's':                    /* no signals */
         no_signals = true;
         break;

      case 't':
         test_config = true;
         break;

      case 'u':                    /* set uid */
         uid = optarg;
         break;

      case 'v':                    /* verbose */
         verbose++;
         break;

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

   if (argc) {
      if (configfile != NULL) {
         free(configfile);
      }
      configfile = bstrdup(*argv);
      argc--;
      argv++;
   }
   if (argc)
      usage();

   /*
    * See if we want to drop privs.
    */
   if (geteuid() == 0) {
      drop(uid, gid, false);
   }

   if (!no_signals) {
      init_signals(terminate_stored);
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   my_config = new_config_parser();
   parse_sd_config(my_config, configfile, M_ERROR_TERM);

   if (init_crypto() != 0) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
   }

   if (!check_resources()) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
   }

   init_reservations_lock();

   if (test_config) {
      terminate_stored(0);
   }

   my_name_is(0, (char **)NULL, me->hdr.name);     /* Set our real name */

   if (!foreground) {
      daemon_start();                 /* become daemon */
      init_stack_dump();              /* pick up new pid */
   }

   create_pid_file(me->pid_directory, "bareos-sd",
                   get_first_port_host_order(me->SDaddrs));
   read_state_file(me->working_directory, "bareos-sd",
                   get_first_port_host_order(me->SDaddrs));
   read_crypto_cache(me->working_directory, "bareos-sd",
                     get_first_port_host_order(me->SDaddrs));

   set_jcr_in_tsd(INVALID_JCR);

   /*
    * Make sure on Solaris we can run concurrent, watch dog + servers + misc
    */
   set_thread_concurrency(me->max_concurrent_jobs * 2 + 4);
   lmgr_init_thread(); /* initialize the lockmanager stack */

   load_sd_plugins(me->plugin_directory, me->plugin_names);

   cleanup_old_files();

   /* Ensure that Volume Session Time and Id are both
    * set and are both non-zero.
    */
   VolSessionTime = (uint32_t)daemon_start_time;
   if (VolSessionTime == 0) { /* paranoid */
      Jmsg0(NULL, M_ABORT, 0, _("Volume Session Time is ZERO!\n"));
   }

   /*
    * Start the device allocation thread
    */
   create_volume_lists();             /* do before device_init */
   if (pthread_create(&thid, NULL, device_initialization, NULL) != 0) {
      berrno be;
      Emsg1(M_ABORT, 0, _("Unable to create thread. ERR=%s\n"), be.bstrerror());
   }

   start_watchdog();                  /* start watchdog thread */
   if (me->jcr_watchdog_time) {
      init_jcr_subsystem(me->jcr_watchdog_time); /* start JCR watchdogs etc. */
   }

#if HAVE_NDMP
   /* Seperate thread that handles NDMP connections */
   if (me->ndmp_enable) {
      start_ndmp_thread_server(me->NDMPaddrs,
                               me->max_concurrent_jobs * 2 + 1,
                               &ndmp_workq);
   }
#endif

   /* Single server used for Director/Storage and File daemon */
   sock_fds = New(alist(10, not_owned_by_alist));
   bnet_thread_server_tcp(me->SDaddrs,
                      me->max_concurrent_jobs * 2 + 1,
                      sock_fds,
                      &dird_workq,
                      me->nokeepalive,
                      handle_connection_request);
   exit(1);                           /* to keep compiler quiet */
}
Пример #21
0
int main(int argc, char **argv)
{
    XEvent event;

    config_init();
    parse_cli_options(argc, argv);
    config_read();

    mixer_init(config.mixer_device, config.verbose, (const char **)config.exclude_channel);
    mixer_set_channel(0);

    display = XOpenDisplay(config.display_name);
    if (display == NULL) {
	const char *name;

	if (config.display_name) {
	    name = config.display_name;
	} else {
	    name = getenv("DISPLAY");
	    if (name == NULL) {
		fprintf(stderr, "wmix:error: Unable to open display, variable $DISPLAY not set\n");
		return EXIT_FAILURE;
	    }
	}
	fprintf(stderr, "wmix:error: Unable to open display \"%s\"\n", name);
	return EXIT_FAILURE;
    }
    display_width = (float)DisplayWidth(display, DefaultScreen(display)) / 4.0;
    display_height = (float)DisplayHeight(display, DefaultScreen(display)) / 2.0;

    dockapp_init(display);
    new_window("wmix", 64, 64);
    new_osd(DisplayWidth(display, DefaultScreen(display)) - 200, 60);

    if (config.mmkeys)
	    mmkey_install(display);

    config_release();

    blit_string("wmix " VERSION);
    scroll_text(3, 4, 57, true);
    ui_update();

    /* add click regions */
    add_region(1, 37, 36, 25, 25);	/* knob */
    add_region(2, 4, 42, 27, 15);	/* balancer */
    add_region(3, 2, 26, 7, 10);	/* previous channel */
    add_region(4, 10, 26, 7, 10);	/* next channel */
    add_region(5, 39, 14, 20, 7);	/* mute toggle */
    add_region(6, 4, 14, 13, 7);	/* rec toggle */
    add_region(10, 3, 4, 56, 7);	/* re-scroll current channel name */

    /* setup up/down signal handler */
    create_pid_file();
    signal(SIGUSR1, (void *) signal_catch);
    signal(SIGUSR2, (void *) signal_catch);

    while (true) {
	if (button_pressed || slider_pressed || (XPending(display) > 0)) {
	    XNextEvent(display, &event);
	    switch (event.type) {
		case KeyPress:
		    if (key_press_event(&event.xkey))
			idle_loop = 0;
		    break;
		case Expose:
		    redraw_window();
		    break;
		case ButtonPress:
		    button_press_event(&event.xbutton);
		    idle_loop = 0;
		    break;
		case ButtonRelease:
		    button_release_event(&event.xbutton);
		    idle_loop = 0;
		    break;
		case MotionNotify:
		    /* process cursor change, or drag events */
		    motion_event(&event.xmotion);
		    idle_loop = 0;
		    break;
		case LeaveNotify:
		    /* go back to standard cursor */
		    if ((!button_pressed) && (!slider_pressed))
			set_cursor(NORMAL_CURSOR);
		    break;
		case DestroyNotify:
		    XCloseDisplay(display);
		    return EXIT_SUCCESS;
		default:
		    break;
	    }
	} else {
	    usleep(100000);
	    scroll_text(3, 4, 57, false);
	    /* rescroll message after some delay */
	    if (idle_loop++ > 256) {
		scroll_text(3, 4, 57, true);
		idle_loop = 0;
	    }
	    /* get rid of OSD after a few seconds of idle */
	    if ((idle_loop > 15) && osd_mapped() && !button_pressed) {
		unmap_osd();
		idle_loop = 0;
	    }
	    if (mixer_is_changed())
		ui_update();
	}
    }
    return EXIT_SUCCESS;
}
Пример #22
0
int main (int argc, char *argv[]) {

	int x_state=0;
	int y_state=0;

	int foreground = 0;
	int opt;

	pid_t pid;
	ssize_t res;

	unsigned char buffer[8];

	struct input_event ev[6];
	struct input_event ev_button[22];
	struct input_event ev_sync;

	conf_data conf;
	conf = config_parse();

	while ((opt = getopt(argc, argv, "hfs:u:?")) != EOF) {
		switch (opt) {
			case 'h':
				usage();
				break;
			case 'f':
				foreground=1;
				break;
			case 's':
				sprintf(conf.joystick_device, "%s", optarg);
				break;
			case 'u':
				sprintf(conf.uinput_device, "%s", optarg);
				break;
			default:
				usage();
				break;
		}
	}

	if (!running_as_root()) {
		fprintf(stderr,"this program must be run as root user\n");
		exit (-1);
	}

	printf("stjoy v%s ", VERSION);
	fflush(stdout);

	if (!foreground) {

		if ((pid = fork()) < 0)
			exit(1);
		else
			if (pid != 0)
			exit(0);

		/* daemon running here */
		setsid();
		if (chdir("/") != 0) 
			die("Could not chdir");
		umask(0);
		printf("forked into background\n");
	} else
		printf("\n");

	/* create pid file */
	if (!create_pid_file())
		exit(-1);

	if (foreground) {
		printf ("\nConfiguration data:\n");
		printf ("\tjoystick_device=%s\n",conf.joystick_device);
		printf ("\tuinput_device=%s\n",conf.uinput_device);
	}

	// Open joystick port
	open_joystick_port(conf.joystick_device);

	// configure uinput
	setup_uinput_dev(conf.uinput_device);

	// handle signals
	signal_installer();

	// input sync signal:
	memset (&ev_sync, 0, sizeof (struct input_event));
	ev_sync.type = EV_SYN;
	ev_sync.code = 0;
	ev_sync.value = 0;

	// button press signals:
	memset (&ev_button, 0, sizeof (ev_button));

	ev_button[0].type = EV_KEY;
	ev_button[0].code = BTN_A;
	ev_button[0].value = 0;
	ev_button[1].type = EV_KEY;
	ev_button[1].code = BTN_A;
	ev_button[1].value = 1;

	ev_button[2].type = EV_KEY;
	ev_button[2].code = BTN_B;
	ev_button[2].value = 0;
	ev_button[3].type = EV_KEY;
	ev_button[3].code = BTN_B;
	ev_button[3].value = 1;

	ev_button[4].type = EV_KEY;
	ev_button[4].code = BTN_X;
	ev_button[4].value = 0;
	ev_button[5].type = EV_KEY;
	ev_button[5].code = BTN_X;
	ev_button[5].value = 1;

	ev_button[6].type = EV_KEY;
	ev_button[6].code = BTN_Y;
	ev_button[6].value = 0;
	ev_button[7].type = EV_KEY;
	ev_button[7].code = BTN_Y;
	ev_button[7].value = 1;

	ev_button[8].type = EV_KEY;
	ev_button[8].code = BTN_TL;
	ev_button[8].value = 0;
	ev_button[9].type = EV_KEY;
	ev_button[9].code = BTN_TL;
	ev_button[9].value = 1;

	ev_button[10].type = EV_KEY;
	ev_button[10].code = BTN_TR;
	ev_button[10].value = 0;
	ev_button[11].type = EV_KEY;
	ev_button[11].code = BTN_TR;
	ev_button[11].value = 1;

	ev_button[12].type = EV_KEY;
	ev_button[12].code = BTN_SELECT;
	ev_button[12].value = 0;
	ev_button[13].type = EV_KEY;
	ev_button[13].code = BTN_SELECT;
	ev_button[13].value = 1;

	ev_button[14].type = EV_KEY;
	ev_button[14].code = BTN_START;
	ev_button[14].value = 0;
	ev_button[15].type = EV_KEY;
	ev_button[15].code = BTN_START;
	ev_button[15].value = 1;

	ev_button[16].type = EV_KEY;
	ev_button[16].code = BTN_MODE;
	ev_button[16].value = 0;
	ev_button[17].type = EV_KEY;
	ev_button[17].code = BTN_MODE;
	ev_button[17].value = 1;

/*
	ev_button[18].type = EV_ABS;
	ev_button[18].code = ABS_RZ;
	ev_button[18].value = 0;
	ev_button[19].type = EV_ABS;
	ev_button[19].code = ABS_RZ;
	ev_button[19].value = 255;

	ev_button[20].type = EV_ABS;
	ev_button[20].code = ABS_Z;
	ev_button[20].value = 0;
	ev_button[21].type = EV_ABS;
	ev_button[21].code = ABS_Z;
	ev_button[21].value = 255;
*/

	ev_button[18].type = EV_KEY;
	ev_button[18].code = BTN_THUMBL;
	ev_button[18].value = 0;
	ev_button[19].type = EV_KEY;
	ev_button[19].code = BTN_THUMBL;
	ev_button[19].value = 1;

	ev_button[20].type = EV_KEY;
	ev_button[20].code = BTN_THUMBR;
	ev_button[20].value = 0;
	ev_button[21].type = EV_KEY;
	ev_button[21].code = BTN_THUMBR;
	ev_button[21].value = 1;

	// load X,Y into input_events
	memset (ev, 0, sizeof (ev));	//resets object

	ev[0].type = EV_ABS;
	ev[0].code = ABS_HAT0X;
	ev[0].value = 0;
	ev[1].type = EV_ABS;
	ev[1].code = ABS_HAT0X;
	ev[1].value = 1;
	ev[2].type = EV_ABS;
	ev[2].code = ABS_HAT0X;
	ev[2].value = -1;

	ev[3].type = EV_ABS;
	ev[3].code = ABS_HAT0Y;
	ev[3].value = 0;
	ev[4].type = EV_ABS;
	ev[4].code = ABS_HAT0Y;
	ev[4].value = 1;
	ev[5].type = EV_ABS;
	ev[5].code = ABS_HAT0Y;
	ev[5].value = -1;



	while (1) {


		memset (buffer, 0, sizeof (buffer));
		res = read (fd_joystick, &buffer, sizeof (buffer));
		if (res < 0)
			die ("error reading from joystick port");

		if (DEBUG || foreground)
			fprintf (stderr,"PDU:  %.2x %.2x %.2x %.2x %.2x %.2x %.2x %.2x\n", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6], buffer[7] );

		// A
		if (buffer[6]==1 && buffer[7]==0) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[0], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[1], sizeof (struct input_event)) < 0) die ("error: write");
		}

		// B
		if (buffer[6]==1 && buffer[7]==1) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[2], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[3], sizeof (struct input_event)) < 0) die ("error: write");
		}

		// X
		if (buffer[6]==1 && buffer[7]==2) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[4], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[5], sizeof (struct input_event)) < 0) die ("error: write");
		}

		// Y
		if (buffer[6]==1 && buffer[7]==3) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[6], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[7], sizeof (struct input_event)) < 0) die ("error: write");
		}

		// LB <---- cheat!
		if (buffer[6]==1 && buffer[7]==4) {
/*
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[8], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[9], sizeof (struct input_event)) < 0) die ("error: write");
*/
			if (buffer[4]==1 && buffer[5]==0) { // LB button press
				/* DP RIGHT */
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// x/right
				if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// y/down
				if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/right
				if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// press Y
				if (write (fd_uinput, &ev_button[7], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// release Y
				if (write (fd_uinput, &ev_button[6], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/neutral x
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

				/* DP LEFT */
				usleep(100000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// x/left
				if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// y/down
				if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/left
				if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// press Y 
				if (write (fd_uinput, &ev_button[7], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// press X (we can "piano" in the 2nd one)
				if (write (fd_uinput, &ev_button[5], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// release Y
				if (write (fd_uinput, &ev_button[6], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// release X (we can "piano" in the 2nd one)
				if (write (fd_uinput, &ev_button[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/neutral x
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

				// restore x&y state

				if (x_state==0) 
					if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (x_state==1)
					if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				if (x_state==-1)
					if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");

				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

				if (y_state==0)
					if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (y_state==1)
					if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (y_state==-1)
					if (write (fd_uinput, &ev[5], sizeof (struct input_event)) < 0) die ("error: write");

				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

			}
		}

		// RB
		if (buffer[6]==1 && buffer[7]==5) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[10], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[11], sizeof (struct input_event)) < 0) die ("error: write");
		}

		if (buffer[6]==1 && buffer[7]==6) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[12], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[13], sizeof (struct input_event)) < 0) die ("error: write");
		}

		if (buffer[6]==1 && buffer[7]==7) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[14], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[15], sizeof (struct input_event)) < 0) die ("error: write");
		}

		if (buffer[6]==1 && buffer[7]==8) {
			if (buffer[4]==0 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[16], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==1 && buffer[5]==0)
				if (write (fd_uinput, &ev_button[17], sizeof (struct input_event)) < 0) die ("error: write");
		}

		// RT
		if (buffer[6]==2 && buffer[7]==5) {
			if (buffer[4]==1 && buffer[5]==0x80)
				if (write (fd_uinput, &ev_button[18], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==0xff && buffer[5]==0x7f)
				if (write (fd_uinput, &ev_button[19], sizeof (struct input_event)) < 0) die ("error: write");
		}

		// LT <---- cheat!

/* dragon punch */
#if 0
Event: time 1387128747.109831, type 3 (EV_ABS), code 16 (ABS_HAT0X), value 1      <---- x/right
Event: time 1387128747.197553, type 3 (EV_ABS), code 16 (ABS_HAT0X), value 0      <---- x/neutral
Event: time 1387128747.197580, type 3 (EV_ABS), code 17 (ABS_HAT0Y), value 1      <---- y/down
Event: time 1387128747.217594, type 3 (EV_ABS), code 16 (ABS_HAT0X), value -1     <---- x/left
Event: time 1387128747.277551, type 3 (EV_ABS), code 16 (ABS_HAT0X), value 0      <---- x/neutral
Event: time 1387128747.293556, type 3 (EV_ABS), code 16 (ABS_HAT0X), value 1      <---- x/right
Event: time 1387128747.293583, type 1 (EV_KEY), code 307 (BTN_X), value 1         <---- press X
Event: time 1387128747.345564, type 3 (EV_ABS), code 17 (ABS_HAT0Y), value 0      <---- y/neutral
Event: time 1387128747.365552, type 1 (EV_KEY), code 307 (BTN_X), value 0         <---- release X
Event: time 1387128747.381499, type 3 (EV_ABS), code 16 (ABS_HAT0X), value 0      <---- x/neutral
#endif



		if (buffer[6]==2 && buffer[7]==2) {
			/*
			if (buffer[4]==1 && buffer[5]==0x80)
				if (write (fd_uinput, &ev_button[20], sizeof (struct input_event)) < 0) die ("error: write");
			if (buffer[4]==0xff && buffer[5]==0x7f)
				if (write (fd_uinput, &ev_button[21], sizeof (struct input_event)) < 0) die ("error: write");
			*/

			if (buffer[4]==1 && buffer[5]==0x80) {
				/* DP LEFT */
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// x/left
				if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// y/down
				if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/left
				if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// press X
				if (write (fd_uinput, &ev_button[5], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// release X
				if (write (fd_uinput, &ev_button[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/neutral x
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

				/* DP RIGHT */
				usleep(100000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// x/right
				if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// y/down
				if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// x/neutral
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/right
				if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(27);
				// press X
				if (write (fd_uinput, &ev_button[5], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// press Y (we can "piano" in the 2nd one)
				if (write (fd_uinput, &ev_button[7], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(18000);
				// y/neutral
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// release X
				if (write (fd_uinput, &ev_button[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);
				// release Y (we can "piano" in the 2nd one)
				if (write (fd_uinput, &ev_button[6], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(12000);
				// x/neutral x
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

				// restore x&y state

				if (x_state==0) 
					if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				if (x_state==1)
					if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				if (x_state==-1)
					if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");

				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

				if (y_state==0)
					if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				if (y_state==1)
					if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				if (y_state==-1)
					if (write (fd_uinput, &ev[5], sizeof (struct input_event)) < 0) die ("error: write");

				if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");
				usleep(500);

			}

		}



		// x-axis
		if (buffer[6]==2 && buffer[7]==6) {
			if (buffer[4]==0 && buffer[5]==0) {
				if (write (fd_uinput, &ev[0], sizeof (struct input_event)) < 0) die ("error: write");
				x_state=0; //neutral
			}
			if (buffer[4]==0xff && buffer[5]==0x7f) {
				if (write (fd_uinput, &ev[1], sizeof (struct input_event)) < 0) die ("error: write");
				x_state=1; // right
			}
			if (buffer[4]==1 && buffer[5]==0x80) {
				if (write (fd_uinput, &ev[2], sizeof (struct input_event)) < 0) die ("error: write");
				x_state=-1; //left
			}

		}

		// y-axis
		if (buffer[6]==2 && buffer[7]==7) {
			if (buffer[4]==0 && buffer[5]==0) {
				if (write (fd_uinput, &ev[3], sizeof (struct input_event)) < 0) die ("error: write");
				y_state=0; //neutral
			}
			if (buffer[4]==0xff && buffer[5]==0x7f) {
				if (write (fd_uinput, &ev[4], sizeof (struct input_event)) < 0) die ("error: write");
				y_state=1; //up
			}
			if (buffer[4]==1 && buffer[5]==0x80) {
				if (write (fd_uinput, &ev[5], sizeof (struct input_event)) < 0) die ("error: write");
				y_state=-1; // down
			}
		}



		// Sync
		if (write (fd_uinput, &ev_sync, sizeof (struct input_event)) < 0) die ("error state");



	}

	if (ioctl (fd_uinput, UI_DEV_DESTROY) < 0)
		die ("error: ioctl");

	close (fd_uinput);

	return 0;
}
Пример #23
0
int __init make_umid(void)
{
	int fd, err;
	char tmp[256];

	if(umid_setup)
		return 0;

	make_uml_dir();

	if(*umid == '\0'){
		strlcpy(tmp, uml_dir, sizeof(tmp));
		strlcat(tmp, "XXXXXX", sizeof(tmp));
		fd = mkstemp(tmp);
		if(fd < 0){
			printk("make_umid - mkstemp(%s) failed: %s\n",
			       tmp, strerror(errno));
			err = -errno;
			goto err;
		}

		close(fd);

		set_umid(&tmp[strlen(uml_dir)]);

		/* There's a nice tiny little race between this unlink and
		 * the mkdir below.  It'd be nice if there were a mkstemp
		 * for directories.
		 */
		if(unlink(tmp)){
			err = -errno;
			goto err;
		}
	}

	snprintf(tmp, sizeof(tmp), "%s%s", uml_dir, umid);
	err = mkdir(tmp, 0777);
	if(err < 0){
		err = -errno;
		if(err != -EEXIST)
			goto err;

		/* 1   -> this umid is already in use
		 * < 0 -> we couldn't remove the umid directory
		 * In either case, we can't use this umid, so return -EEXIST.
		 */
		if(not_dead_yet(tmp) != 0)
			goto err;

		err = mkdir(tmp, 0777);
	}
	if(err){
		err = -errno;
		printk("Failed to create '%s' - err = %d\n", umid, -errno);
		goto err;
	}

	umid_setup = 1;

	create_pid_file();

	err = 0;
 err:
	return err;
}
Пример #24
0
static SaAisErrorT amf_initialize(SaSelectionObjectT *amf_sel_obj)
{
	SaAisErrorT rc;
	SaAmfCallbacksT amf_callbacks = {0};
	SaVersionT api_ver =
		{.releaseCode = 'B', api_ver.majorVersion = 0x01, api_ver.minorVersion = 0x01};

	amf_callbacks.saAmfCSISetCallback = csi_set_callback;
	amf_callbacks.saAmfCSIRemoveCallback = csi_remove_callback;
	amf_callbacks.saAmfHealthcheckCallback = healthcheck_callback;
	amf_callbacks.saAmfComponentTerminateCallback = terminate_callback;

	rc = saAmfInitialize(&my_amf_hdl, &amf_callbacks, &api_ver);
	if (rc != SA_AIS_OK) {
		syslog(LOG_ERR, " saAmfInitialize FAILED (%u)", rc);
		goto done;
	}

	rc = saAmfSelectionObjectGet(my_amf_hdl, amf_sel_obj);
	if (rc != SA_AIS_OK) {
		syslog(LOG_ERR, "saAmfSelectionObjectGet FAILED (%u)", rc);
		goto done;
	}

	rc = saAmfComponentNameGet(my_amf_hdl, &my_comp_name);
	if (rc != SA_AIS_OK) {
		syslog(LOG_ERR, "saAmfComponentNameGet FAILED (%u)", rc);
		goto done;
	}

	rc = saAmfComponentRegister(my_amf_hdl, &my_comp_name, 0);
	if (rc != SA_AIS_OK) {
		syslog(LOG_ERR, "saAmfComponentRegister FAILED (%u)", rc);
		goto done;
	}
	
done:
	return rc;
}

int main(int argc, char **argv)
{
	SaAisErrorT rc;
	SaSelectionObjectT amf_sel_obj;
	struct pollfd fds[1];
	int logmask;

	if (daemon(0, 0) == -1) {
		syslog(LOG_ERR, "daemon failed: %s", strerror(errno));
		goto done;
	}

	create_pid_file();

	/* Cancel certain signals that would kill us */
	signal(SIGTERM, SIG_IGN);
	signal(SIGHUP, SIG_IGN);
	signal(SIGUSR1, SIG_IGN);
	signal(SIGUSR2, SIG_IGN);

	openlog(basename(argv[0]), LOG_PID, LOG_USER);

	// TBD: Configure logmask from args/vars
	logmask = LOG_UPTO(LOG_INFO);
//	setlogmask(logmask);

	start_script = getenv("STARTSCRIPT");
	if (start_script == NULL) {
		syslog(LOG_ERR, "Variable STARTCRIPT missing");
		goto done;
	}

	stop_script = getenv("STOPSCRIPT");
	if (stop_script == NULL) {
		syslog(LOG_ERR, "Variable STOPSCRIPT missing");
		goto done;
	}

	health_script = getenv("HEALTHCHECKSCRIPT");
	if (health_script == NULL) {
		syslog(LOG_ERR, "Variable HEALTHCHECKSCRIPT missing");
		goto done;
	}

	pidfile = getenv("PIDFILE");

	if (amf_initialize(&amf_sel_obj) != SA_AIS_OK)
		goto done;


	fds[0].fd = amf_sel_obj;
	fds[0].events = POLLIN;

	syslog(LOG_INFO, "'%s' started", getenv("SA_AMF_COMPONENT_NAME"));

	while (1) {
		int res = poll(fds, 1, -1);

		if (res == -1) {
			if (errno == EINTR)
				continue;
			else {
				syslog(LOG_ERR, "poll FAILED - %s", strerror(errno));
				goto done;
			}
		}

		if (fds[0].revents & POLLIN) {
			rc = saAmfDispatch(my_amf_hdl, SA_DISPATCH_ONE);
			if (rc != SA_AIS_OK) {
				syslog(LOG_ERR, "saAmfDispatch FAILED %u", rc);
				goto done;
			}
		}
	}

done:
	return EXIT_FAILURE;
}
Пример #25
0
/******************************************************************************
 *                                                                            *
 * Function: daemon_start                                                     *
 *                                                                            *
 * Purpose: init process as daemon                                            *
 *                                                                            *
 * Parameters: allow_root - allow root permission for application             *
 *             user       - user on the system to which to drop the           *
 *                          privileges                                        *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: it doesn't allow running under 'root' if allow_root is zero      *
 *                                                                            *
 ******************************************************************************/
int	daemon_start(int allow_root, const char *user)
{
	pid_t		pid;
	struct passwd	*pwd;

	if (0 == allow_root && 0 == getuid())	/* running as root? */
	{
		if (NULL == user)
			user = "******";

		pwd = getpwnam(user);

		if (NULL == pwd)
		{
			zbx_error("user %s does not exist", user);
			zbx_error("cannot run as root!");
			exit(EXIT_FAILURE);
		}

		if (0 == pwd->pw_uid)
		{
			zbx_error("User=%s contradicts AllowRoot=0", user);
			zbx_error("cannot run as root!");
			exit(EXIT_FAILURE);
		}

		if (-1 == setgid(pwd->pw_gid))
		{
			zbx_error("cannot setgid to %s: %s", user, zbx_strerror(errno));
			exit(EXIT_FAILURE);
		}

#ifdef HAVE_FUNCTION_INITGROUPS
		if (-1 == initgroups(user, pwd->pw_gid))
		{
			zbx_error("cannot initgroups to %s: %s", user, zbx_strerror(errno));
			exit(EXIT_FAILURE);
		}
#endif

		if (-1 == setuid(pwd->pw_uid))
		{
			zbx_error("cannot setuid to %s: %s", user, zbx_strerror(errno));
			exit(EXIT_FAILURE);
		}

#ifdef HAVE_FUNCTION_SETEUID
		if (-1 == setegid(pwd->pw_gid) || -1 == seteuid(pwd->pw_uid))
		{
			zbx_error("cannot setegid or seteuid to %s: %s", user, zbx_strerror(errno));
			exit(EXIT_FAILURE);
		}
#endif
	}

	if (0 != (pid = zbx_fork()))
		exit(EXIT_SUCCESS);

	setsid();

	signal(SIGHUP, SIG_IGN);

	if (0 != (pid = zbx_fork()))
		exit(EXIT_SUCCESS);

	if (-1 == chdir("/"))	/* this is to eliminate warning: ignoring return value of chdir */
		assert(0);

	umask(0002);

	redirect_std(CONFIG_LOG_FILE);

	if (FAIL == create_pid_file(CONFIG_PID_FILE))
		exit(EXIT_FAILURE);

	atexit(daemon_stop);

	parent_pid = (int)getpid();

	zbx_set_common_signal_handlers();
	set_daemon_signal_handlers();

	/* Set SIGCHLD now to avoid race conditions when a child process is created before */
	/* sigaction() is called. To avoid problems when scripts exit in zbx_execute() and */
	/* other cases, SIGCHLD is set to SIG_DFL in zbx_child_fork(). */
	zbx_set_child_signal_handler();

	return MAIN_ZABBIX_ENTRY();
}
Пример #26
0
Файл: dird.c Проект: AlD/bareos
int main (int argc, char *argv[])
{
   int ch;
   JCR *jcr;
   cat_op mode;
   bool no_signals = false;
   bool test_config = false;
   char *uid = NULL;
   char *gid = NULL;

   start_heap = sbrk(0);
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");

   init_stack_dump();
   my_name_is(argc, argv, "bareos-dir");
   init_msg(NULL, NULL);              /* initialize message handler */
   init_reload();
   daemon_start_time = time(NULL);

   console_command = run_console_command;

   while ((ch = getopt(argc, argv, "c:d:fg:mr:stu:v?")) != -1) {
      switch (ch) {
      case 'c':                    /* specify config file */
         if (configfile != NULL) {
            free(configfile);
         }
         configfile = bstrdup(optarg);
         break;

      case 'd':                    /* set debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         Dmsg1(10, "Debug level = %d\n", debug_level);
         break;

      case 'f':                    /* run in foreground */
         background = false;
         break;

      case 'g':                    /* set group id */
         gid = optarg;
         break;

      case 'm':                    /* print kaboom output */
         prt_kaboom = true;
         break;

      case 'r':                    /* run job */
         if (runjob != NULL) {
            free(runjob);
         }
         if (optarg) {
            runjob = bstrdup(optarg);
         }
         break;

      case 's':                    /* turn off signals */
         no_signals = true;
         break;

      case 't':                    /* test config */
         test_config = true;
         break;

      case 'u':                    /* set uid */
         uid = optarg;
         break;

      case 'v':                    /* verbose */
         verbose++;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (!no_signals) {
      init_signals(terminate_dird);
   }

   if (argc) {
      if (configfile != NULL) {
         free(configfile);
      }
      configfile = bstrdup(*argv);
      argc--;
      argv++;
   }
   if (argc) {
      usage();
   }

   if (configfile == NULL) {
      configfile = bstrdup(CONFIG_FILE);
   }

   /*
    * See if we want to drop privs.
    */
   if (geteuid() == 0) {
      drop(uid, gid, false);                    /* reduce privileges if requested */
   }

   my_config = new_config_parser();
   parse_dir_config(my_config, configfile, M_ERROR_TERM);

   if (init_crypto() != 0) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Cryptography library initialization failed.\n"));
      goto bail_out;
   }

   if (!check_resources()) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
      goto bail_out;
   }

   if (!test_config) {                /* we don't need to do this block in test mode */
      if (background) {
         daemon_start();
         init_stack_dump();              /* grab new pid */
      }
      /* Create pid must come after we are a daemon -- so we have our final pid */
      create_pid_file(me->pid_directory, "bareos-dir",
                      get_first_port_host_order(me->DIRaddrs));
      read_state_file(me->working_directory, "bareos-dir",
                      get_first_port_host_order(me->DIRaddrs));
   }

   set_jcr_in_tsd(INVALID_JCR);
   set_thread_concurrency(me->MaxConcurrentJobs * 2 +
                          4 /* UA */ + 5 /* sched+watchdog+jobsvr+misc */);
   lmgr_init_thread(); /* initialize the lockmanager stack */

   load_dir_plugins(me->plugin_directory, me->plugin_names);

   /*
    * If we are in testing mode, we don't try to fix the catalog
    */
   mode = (test_config) ? CHECK_CONNECTION : UPDATE_AND_FIX;

   if (!check_catalog(mode)) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
      goto bail_out;
   }

   if (test_config) {
      terminate_dird(0);
   }

   if (!initialize_sql_pooling()) {
      Jmsg((JCR *)NULL, M_ERROR_TERM, 0, _("Please correct configuration file: %s\n"), configfile);
      goto bail_out;
   }

   my_name_is(0, NULL, me->name());    /* set user defined name */

   cleanup_old_files();

   p_db_log_insert = (db_log_insert_func)dir_db_log_insert;

#if !defined(HAVE_WIN32)
   signal(SIGHUP, reload_config);
#endif

   init_console_msg(working_directory);

   Dmsg0(200, "Start UA server\n");
   start_UA_server(me->DIRaddrs);

   start_watchdog();                  /* start network watchdog thread */

   if (me->jcr_watchdog_time) {
      init_jcr_subsystem(me->jcr_watchdog_time); /* start JCR watchdogs etc. */
   }

   init_job_server(me->MaxConcurrentJobs);

   dbg_jcr_add_hook(db_debug_print); /* used to debug B_DB connexion after fatal signal */

//   init_device_resources();

   Dmsg0(200, "wait for next job\n");
   /* Main loop -- call scheduler to get next job to run */
   while ( (jcr = wait_for_next_job(runjob)) ) {
      run_job(jcr);                   /* run job */
      free_jcr(jcr);                  /* release jcr */
      set_jcr_in_tsd(INVALID_JCR);
      if (runjob) {                   /* command line, run a single job? */
         break;                       /* yes, terminate */
      }
   }

   terminate_dird(0);

bail_out:
   return 0;
}
Пример #27
0
static int __init make_umid(void)
{
	int fd, err;
	char tmp[256];

	if (umid_setup)
		return 0;

	make_uml_dir();

	if (*umid == '\0') {
		strlcpy(tmp, uml_dir, sizeof(tmp));
		strlcat(tmp, "XXXXXX", sizeof(tmp));
		fd = mkstemp(tmp);
		if (fd < 0) {
			printk(UM_KERN_ERR "make_umid - mkstemp(%s) failed: "
			       "%s\n", tmp, strerror(errno));
			err = -errno;
			goto err;
		}

		close(fd);

		set_umid(&tmp[strlen(uml_dir)]);

		/*
		 * There's a nice tiny little race between this unlink and
		 * the mkdir below.  It'd be nice if there were a mkstemp
		 * for directories.
		 */
		if (unlink(tmp)) {
			err = -errno;
			goto err;
		}
	}

	snprintf(tmp, sizeof(tmp), "%s%s", uml_dir, umid);
	err = mkdir(tmp, 0777);
	if (err < 0) {
		err = -errno;
		if (err != -EEXIST)
			goto err;

		if (umdir_take_if_dead(tmp) < 0)
			goto err;

		err = mkdir(tmp, 0777);
	}
	if (err) {
		err = -errno;
		printk(UM_KERN_ERR "Failed to create '%s' - err = %d\n", umid,
		       errno);
		goto err;
	}

	umid_setup = 1;

	create_pid_file();

	err = 0;
 err:
	return err;
}
Пример #28
0
int
main (int argc, char *argv[])
{

    int screensaver = 0, c, brightness_prev = -1, backlight_prev = -1;
    int light = 0, brightness = 255, backlight = 100;
    int foreground = 0, verbose = 0, debug = 0;
    int brightness_restore, backlight_restore, brightness_restoreflag =
        0, backlight_restoreflag = 0;
    int res, dbus_backend = -1, tmp = -1;
    float idletime = 0;
    pid_t pid;
    conf_data conf;
    Display *display = NULL;
    DBusGConnection *connection;
    DBusGProxy *proxy_manager;
    DBusGProxy *proxy_session;
    uid_t uid, euid;
    int light_aux = -1, light_avg = -1;
    int lightvalues[15] = { 0 };
    int countarray[256] = { 0 };
    unsigned int i, index = 0;

    // make sure we are run as a regular user
    uid = getuid ();
    euid = geteuid ();
    if (uid == 0 || euid == 0) {
        fprintf (stderr, "lightum must NOT be run as root.\n");
        exit (1);
    }
    // overwrite defaults with config file
    conf = config_parse ();

    // overwrite config file with command line arguments
    while ((c = getopt (argc, argv, "hxuUlsvfm:n:M:N:p:I:i:d:w:?")) != EOF) {
        switch (c) {
        case 'h':
            usage ("");
            break;
        case 'x':
            conf.manualmode = 1;
            break;
        case 'u':
            conf.ignoreuser = 0;
            break;
        case 'U':
            conf.ignoresession = 1;
            break;
        case 'l':
            conf.fulldim = 1;
            break;
        case 's':
            conf.queryscreensaver = 1;
            break;
        case 'f':
            foreground = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'd':
            debug = atoi (optarg);
            break;
        case 'm':
            conf.maxbrightness = atoi (optarg);
            break;
        case 'n':
            conf.minbrightness = atoi (optarg);
            break;
        case 'M':
            conf.maxbacklight = atoi (optarg);
            break;
        case 'N':
            conf.minbacklight = atoi (optarg);
            break;
        case 'p':
            conf.polltime = atoi (optarg);
            break;
        case 'i':
            conf.idleoff = atoi (optarg);
            break;
        case 'I':
            conf.screenidle = atoi (optarg);
            break;
        case 'w':
            conf.workmode = atoi (optarg);
            break;
        default:
            usage ("ERROR: Unknown OPTION\n");
            break;
        }
    }

    if (verbose)
        printf ("CONFIG:\n\tmanualmode: %d\n", conf.manualmode);
    if (verbose)
        printf ("\tignoreuser: %d\n", conf.ignoreuser);
    if (verbose)
        printf ("\tignoresession: %d\n", conf.ignoresession);
    if (verbose)
        printf ("\tworkmode: %d\n", conf.workmode);
    if (verbose)
        printf ("\tqueryscreensaver: %d\n", conf.queryscreensaver);
    if (verbose)
        printf ("\tmaxbrightness: %d\n", conf.maxbrightness);
    if (verbose)
        printf ("\tminbrightness: %d\n", conf.minbrightness);
    if (verbose)
        printf ("\tmaxbacklight: %d\n", conf.maxbacklight);
    if (verbose)
        printf ("\tminbacklight: %d\n", conf.minbacklight);
    if (verbose)
        printf ("\tpolltime: %d\n", conf.polltime);
    if (verbose)
        printf ("\tidleoff: %d\n", conf.idleoff);
    if (verbose)
        printf ("\tscreenidle: %d\n", conf.screenidle);
    if (verbose)
        printf ("\tfulldim: %d\n\n", conf.fulldim);

    // make sure all config values are correct
    check_config_values (conf);
    if (debug < 0 || debug > 3)
        usage ("ERROR: Wrong value in config variable 'debug'\n");

    // if debug enabled, force verbose mode too
    if (debug > 0)
        verbose = 1;
    // if verbose enabled, force foreground mode too
    if (verbose)
        foreground = 1;

    if (conf.manualmode)
        printf ("lightum v%s running in manual mode ", VERSION);
    else
        printf ("lightum v%s running in auto mode ", VERSION);
    fflush (stdout);

    if (!foreground) {
        if ((pid = fork ()) < 0)
            exit (1);
        else if (pid != 0)
            exit (0);
        /* daemon running here */
        setsid ();
        res = chdir ("/");
        if (res != 0) {
            perror ("Could not chdir");
            exit (1);
        }
        umask (0);
        printf ("forked into background\n");
    } else
        printf ("\n");

    /* create pid file */
    if (!create_pid_file ())
        exit (1);

    /* start with current brightness values */
    if (conf.workmode == 1 || conf.workmode == 3) {
        brightness_restore = get_keyboard_brightness_value ();
    }

    /* start with current backlight values */
    if (conf.workmode == 2 || conf.workmode == 3) {
        backlight_restore = get_screen_backlight_value ();

        // detect dbus backend: 0: gnome, 1: kde
        tmp =
            dbus_set_screen_backlight_value_gnome (acpi_to_dbus_backlight
                                                   (backlight_restore));
        if (tmp == -1) {
            tmp =
                dbus_set_screen_backlight_value_kde (acpi_to_dbus_backlight
                                                     (backlight_restore));
            if (tmp == -1) {
                tmp =
                    set_screen_xbacklight_value (acpi_to_dbus_backlight
                                                 (backlight_restore));
                if (tmp == -1) {
                    fprintf (stderr,
                             "Can't manage screen backlight on this system.\nPlease disable backlight with config option 'workmode='1' or command line switch '-w 1'.\nIf you believe this is an error, open a bug report: https://github.com/poliva/lightum/issues\n");
                    exit (1);
                } else {
                    dbus_backend = 2;
                }
            } else {
                dbus_backend = 1;
            }

        } else {
            dbus_backend = 0;
        }
    }

    if (conf.idleoff != 0 || conf.screenidle != 0) {
        display = XOpenDisplay (NULL);
        if (display == NULL) {
            fprintf (stderr, "Failed to open display\n");
            exit (1);
        }
    }

    signal_installer ();

    if (!conf.ignoresession) {
        connection = get_dbus_connection ();
        proxy_manager = get_dbus_proxy_manager (connection);
        proxy_session = get_dbus_proxy_session (connection, proxy_manager);
    }
    // initialize the light values array
    if (!conf.manualmode) {
        light = get_light_sensor_value ();
        for (i = 0; i < ARRAY_LENGTH (lightvalues); i++)
            lightvalues[i] = light;
        countarray[light] = ARRAY_LENGTH (lightvalues);
    } else {
        for (i = 0; i < ARRAY_LENGTH (lightvalues); i++)
            lightvalues[i] = 0;
    }

    while (1) {

        if (reloadconfig) {
            conf = config_parse ();
            if (verbose)
                printf ("lightum: SIGUSR1 received, configuration reloaded\n");
            check_config_values (conf);
            reloadconfig = 0;
        }

        if (!conf.ignoresession) {
            if (!get_session_active (proxy_session)) {
                if (verbose)
                    printf
                        ("lightum: user session not active, sleeping %d milliseconds.\nIf you believe this is an error, try running lightum with 'ignoresession=1' or '-U' command line switch.\n",
                         conf.polltime);
                usleep (conf.polltime * 1000);
                continue;
            }
        }

        if (!conf.manualmode) {
            light = get_light_sensor_value ();
            if (verbose)
                printf ("light_sensor: %d ", light);

            // to avoid backlight flickering when the light sensor flaps too frequently
            // between two values, we collect lighting values and use the most common
            // value of the collected values

            if (index == ARRAY_LENGTH (lightvalues))
                index = 0;
            lightvalues[index] = light;

            // get the most repetitive value of lightvalues array
            for (i = 0; i < ARRAY_LENGTH (lightvalues); ++i) {
                countarray[lightvalues[i]]++;
            }

            light_avg = -1;
            light_aux = -1;
            for (i = 0; i < ARRAY_LENGTH (countarray); ++i) {
                if (countarray[i] > light_aux) {
                    light_aux = countarray[i];
                    light_avg = i;
                }
                countarray[i] = 0;
            }

            light = light_avg;

            if (verbose)
                printf ("light_avg: %d ", light);
            index++;
        }

        if (conf.idleoff != 0 || conf.screenidle != 0) {
            idletime = get_session_idle_time (display);
            if (verbose)
                printf ("idle_time: %f ", idletime);
        }

        if (!conf.manualmode) {

            if (conf.workmode == 1 || conf.workmode == 3)
                brightness =
                    calculate_keyboard_brightness_value (light,
                                                         conf.maxbrightness,
                                                         conf.minbrightness);
            if (conf.workmode == 2 || conf.workmode == 3)
                backlight =
                    calculate_screen_backlight_value (light, conf.maxbacklight,
                                                      conf.minbacklight);
            if (verbose)
                printf ("auto mode ");

        } else {

            if (verbose)
                printf ("manual mode ");
            if (conf.workmode == 1 || conf.workmode == 3) {
                if (!screensaver) {
                    if (idletime > conf.idleoff) {
                        if (brightness_restoreflag == 0) {
                            brightness_restore =
                                get_keyboard_brightness_value ();
                            brightness_restoreflag = 1;
                            if (debug == 1 || debug == 3)
                                printf ("brightness_restoreflag(%d) ",
                                        brightness_restore);
                        }
                        brightness = conf.minbrightness;
                    } else {
                        brightness = brightness_restore;
                        brightness_restoreflag = 0;
                        if (debug == 1 || debug == 3)
                            printf ("brightness_restored(%d) ",
                                    brightness_restore);
                    }
                }
            }

            if (conf.workmode == 2 || conf.workmode == 3) {
                if (!screensaver) {
                    if (idletime > conf.screenidle) {
                        if (backlight_restoreflag == 0) {
                            backlight_restore = get_screen_backlight_value ();
                            backlight_restoreflag = 1;
                            if (debug == 2 || debug == 3)
                                printf ("backlight_restoreflag(%d) ",
                                        backlight_restore);
                        }
                        if (conf.fulldim)
                            backlight = 1;
                        else
                            backlight = conf.minbacklight;
                    } else {
                        backlight = backlight_restore;
                        backlight_restoreflag = 0;
                        if (debug == 2 || debug == 3)
                            printf ("backlight_restored(%d) ",
                                    backlight_restore);
                    }
                }
            }

        }

        if (conf.workmode == 1 || conf.workmode == 3) {
            if ((conf.idleoff != 0) && (idletime > conf.idleoff)) {
                brightness = conf.minbrightness;
            }
        }

        if (conf.workmode == 2 || conf.workmode == 3) {
            if ((conf.screenidle != 0) && (idletime > conf.screenidle)) {
                if (conf.fulldim)
                    backlight = 1;
                else
                    backlight = conf.minbacklight;
            }
        }

        if (conf.queryscreensaver) {
            screensaver = get_screensaver_active ();
            if (verbose)
                printf ("screensaver: %d ", screensaver);
            if (screensaver) {
                brightness = 0;
                backlight = conf.minbacklight;
            }
        }

        if (conf.workmode == 1 || conf.workmode == 3)
            if (verbose)
                printf ("brightness: %d/%d ", brightness, conf.maxbrightness);

        if (conf.workmode == 2 || conf.workmode == 3)
            if (verbose)
                printf ("backlight: %d/%d ", backlight, conf.maxbacklight);

        // keyboard brightness
        if (conf.workmode == 1 || conf.workmode == 3) {
            if (brightness != brightness_prev) {
                if (!conf.manualmode) {
                    brightness_restore = get_keyboard_brightness_value ();
                    if (brightness_restore < conf.minbrightness)
                        brightness_restore = conf.minbrightness;
                    if (debug == 1 || debug == 3)
                        printf ("\ncurrent brightness: %d\n",
                                brightness_restore);
                    if ((brightness_restore != brightness_prev)
                        && (brightness_restoreflag)) {
                        if (!conf.ignoreuser) {
                            /* make sure maxbrightness is never <4 */
                            if (brightness_restore < 4)
                                conf.maxbrightness = 4;
                            else
                                conf.maxbrightness = brightness_restore;
                            if (verbose)
                                printf
                                    ("-> Detected user brightness change, setting maxbrightness to %d\n",
                                     conf.maxbrightness);
                            brightness_prev = brightness_restore;
                        } else {
                            if (verbose)
                                printf
                                    ("-> Ignoring user brightness change, wants to set maxbrightness to %d\n",
                                     brightness_restore);
                        }
                        brightness =
                            calculate_keyboard_brightness_value (light,
                                                                 conf.
                                                                 maxbrightness,
                                                                 conf.
                                                                 minbrightness);
                    }
                    brightness_restoreflag = 1;
                }
                if (debug == 1 || debug == 3)
                    printf ("-> set keyboard brightness: %d -> %d\n",
                            brightness_prev, brightness);
                fading (brightness_prev, brightness);
                usleep (1500);
                brightness = get_keyboard_brightness_value ();
                brightness_prev = brightness;
            }
            if (!conf.manualmode) {
                tmp = get_keyboard_brightness_value ();
                if (tmp != brightness) {
                    if (verbose)
                        printf
                            ("-> Detected user brightness change, current brightness is set to %d\n",
                             tmp);
                    if (conf.ignoreuser) {
                        if (debug == 1 || debug == 3)
                            printf ("\n*** forcing brightness from %d to %d\n",
                                    tmp, brightness);
                        fading (tmp, brightness);
                    }
                }
            }
        }
        // screen backlight
        if (conf.workmode == 2 || conf.workmode == 3) {
            if (backlight != backlight_prev) {
                if (!conf.manualmode) {
                    backlight_restore = get_screen_backlight_value ();
                    if (debug == 2 || debug == 3)
                        printf ("\ncurrent backlight: %d\n",
                                backlight_restore);
                    if ((backlight_restore != backlight_prev)
                        && (backlight_restoreflag)) {
                        if (!conf.ignoreuser) {
                            if (verbose)
                                printf
                                    ("-> Detected user backlight change, switching to manualmode\n");
                            conf.manualmode = 1;
                            backlight_prev = backlight_restore;
                            backlight = backlight_restore;
                        } else {
                            if (verbose)
                                printf
                                    ("-> Ignoring user backlight change, wants to set maxbacklight to %d\n",
                                     backlight_restore);
                            backlight =
                                calculate_screen_backlight_value (light,
                                                                  conf.
                                                                  maxbacklight,
                                                                  conf.
                                                                  minbacklight);
                        }
                    }
                    backlight_restoreflag = 1;
                }
                if (debug == 2 || debug == 3)
                    printf ("-> set screen backlight: %d -> %d\n",
                            backlight_prev, backlight);
                backlight_fading (backlight_prev, backlight, dbus_backend);
                usleep (1500);
                backlight = get_screen_backlight_value ();
                backlight_prev = backlight;
            }
            if (!conf.manualmode) {
                tmp = get_screen_backlight_value ();
                if (tmp != backlight) {
                    if (verbose)
                        printf
                            ("-> Detected user backlight change, current backlight is set to %d\n",
                             tmp);
                    if (conf.ignoreuser) {
                        if (debug == 2 || debug == 3)
                            printf ("\n*** forcing backlight from %d to %d\n",
                                    tmp, backlight);
                        backlight_fading (tmp, backlight, dbus_backend);
                    }
                }
            }
        }

        if (verbose)
            printf ("\n");

        usleep (conf.polltime * 1000);
    }

    // we should never reach here.
    //if (conf.idleoff != 0) XCloseDisplay(display);
    //dbus_g_connection_unref(connection);
    exit (1);
}
Пример #29
0
int main ( int argc, char * argv [] )
{
	
	cmd_defaults(&cmd,argv[0]);
	
	init_error();
		
	if(!is_path_absolute(argv[0])) {
		wrn_print("Require execution with absolute path(%s)",argv[0]);
		terminate();
	}		
	
	cmd_process(argc,argv,&cmd);	
	
	if(!cmd.no_dump_config)
		dump_cmd(&cmd);
//	if( check_creds(&cmd.creds) == -1 )
//		wrn_print("check_creds failed, program execution compromised");
		
	if( cmd.kill_running || cmd.rexec_running) {
		// dbg_print("Sending %s signal",strsignal(cmd.rexec_running ? SIGHUP : cmd.kill_running ? SIGTERM : 0));
		KILL_FROM_PID_ERRORS(kill_from_pid_file(cmd.pid_file, cmd.rexec_running ? SIGHUP : SIGTERM));
		exit(EXIT_SUCCESS);
	}

	
	if(cmd.logs_enable)
		if(reopen_files() == -1) {
			wrn_print("reopen_files failed");
			terminate();
		}
		
	dbg_print("%s started executinon", argv[0]);
	dbg_print("Running as uid:%ld gid:%ld", (long)getuid(), (long)getgid());
	
	if(cmd.need_daemon) {
		dbg_print("Demonizing..");
		if(become_daemon()) {
			wrn_print("Can't demonize because of error");
			terminate();
		}
	} 
	if(cmd.pid_file) {	
		switch (create_pid_file(cmd.pid_file)) {
	        case -1: 
			wrn_print("creat_pid_file failed");
			terminate();
		case -2:
			wrn_print("An instance of %s is already running",cmd.path);
			exit(EXIT_SUCCESS);		

		}
	}	
	
	if(cmd.exit_after_dump) 
		exit(EXIT_SUCCESS);
		
	block_all_sigs();
	
	main_loop();
	
	wrn_print("suspicious main_loop return...");
	exit(EXIT_FAILURE);
}
Пример #30
0
int main(int argc, char **argv) {
	/* initial configuration, will be overridden by config file and command line options  */

	first_init	= 1;
	running		= 0;	// will be set to != 0 once honeytrap set up itself

	/* save command line arguments */
	arg_c = argc;
	arg_v = argv;


	/* the following are default values - change them in your configuration file */
	
	daemonize		= 1;		// default is to daemonize

#ifdef USE_PCAP_MON
	promisc_mode		= 0;		// no promisc mode
	pcap_offset		= 0;		// will be set after link type is determined
#endif

	log_level		= LOG_NOTICE;	// default log level
	logfile_fd		= STDOUT_FILENO;// default logfile, stdout will be replaced by logfile_fd
	
	u_id			= 0;		// root privileges per default
	g_id			= 0;

	conn_timeout		= 120;		// 2 minutes connect timeout
	read_timeout		= 1;		// 1 second read timeout
	m_read_timeout		= 60;		// 1 minute read timeout for mirror connections
	read_limit		= 0;		// 0 means no read limit
	
	conffile_name		= strdup("/etc/honeytrap/honeytrap.conf");
	pidfile_name		= strdup("/var/run/honeytrap.pid");
	logfile_name		= strdup("/var/log/honeytrap.log");
	response_dir		= strdup("/etc/honeytrap/responses");
	plugin_dir		= strdup("/etc/honeytrap/plugins");

#ifdef USE_PCAP_MON
	dev			= NULL;		// network device pointer
	packet_sniffer		= NULL;		// pcap device pointer
#endif

	portconf_default	= PORTCONF_NONE;

	eventlist		= NULL;		// list of timer-based events


	/* configure honeytrap */
	configure(arg_c, arg_v);

	
	/* daemonize (detach from console) */
	if (daemonize) do_daemonize();


	/* now initialize plugins */
	init_plugins();


	/* create pid file */
	create_pid_file();


	/* create IPC pipe and queue for port infos */
	if (pipe(portinfopipe) == -1) {
		logmsg(LOG_ERR, 0, "  Error - Unable to create port info IPC pipe: %m.\n");
		exit(EXIT_FAILURE);
	}
	if ((portinfoq = queue_new()) == NULL) {
		logmsg(LOG_ERR, 0, "  Error - Unable to create port info IPC pipe: %m.\n");
		exit(EXIT_FAILURE);
	}

	
	/* watch out for incoming connection requests */
	if (start_connection_monitor() < 0) clean_exit(EXIT_SUCCESS);
	
	return(0);
}