Ejemplo n.º 1
0
void raiseio(int sig)
{
    char buf[1024];
    sprintf(buf, "Signal with code %d has been raised by EiC in %s, line %d.\nAborting script execution...", 
        sig, EiC_CurrentFile, EiC_CurrentLine);
    init_signal_handlers();
#ifdef HAWK_TEST
    WRAP_THROW_MESSAGE(errmark, buf);
#else
    // Redirect the signal to EiC
    switch(sig)
    {
    case SIGABRT:
    case SIGFPE:
    case SIGSEGV:
    case SIGINT:
        {
            CHawkApp* app = (CHawkApp*)AfxGetApp();
            HAWK_SIGFUNC func;
            if(app->m_eicSigFuncs.Lookup(sig, func))
            {
                func(sig);
            }
        }

    default:
        WRAP_THROW_MESSAGE(errmark, buf);
    }
#endif /* HAWK_TEST */
}
Ejemplo n.º 2
0
int main(int argc, char *argv[]) {
    char *host=NULL;		/* "hostname" or "user@hostname" */
    char *path;			/* path to socket */
    char *p;
    char *text=NULL;
    char *timeout_str=NULL;
    int timeout = 1;
  
    if (argc<2 || argc>4) {
        fprintf(stderr,
		"%s: unrecognized arguments\n"
		"usage: %s /path/to/socket [text] [timeout]\n"
		"       %s remote_user@remote_host:/path/to/socket [text] [timeout]\n",
		argv[0],  argv[0], argv[0]);
        exit(1);
    }
    p=strdup(argv[1]);
    log_fp=stderr;
    if((path=strchr(p,':')) != NULL) {
	    host=p;
	    *path='\0';
	    path++;
    } else {
	    path=p;
    }
    if (argc >= 3)
        text = argv[2];
    if (argc == 4) {
        timeout_str = argv[3];
        int read_timeout = atoi(timeout_str);
        if (read_timeout > 0)
            timeout = read_timeout;
    }

    init_signal_handlers();

    setlinebuf(stdout);
    setlinebuf(stderr);

    if (host) {
        logprintf(MY_NAME,"connecting through ssh to %s on %s",path,host);
        connect_ssh(host,path,text,timeout_str);
    } else {
        logprintf(MY_NAME,"connecting directly to %s",path);
        init_tty();
        connect_direct(path,text,timeout);
        cleanup_tty();
    }
    if (time_to_die != 0) {
        logprintf(MY_NAME,"got signal %d, exiting",time_to_die);
    }
    return 0;
}
Ejemplo n.º 3
0
void init_server(void){
    if (atc_init() == -1) {
        perror("Could not init");
        exit(-1);
    }

    if (atc_listen(&serverConn) == -1) {
      perror("Could not listen");
      exit(-1); 
    }
    
    init_signal_handlers();
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
    // Prevent config being written to ~/.config/Unknown Organization/pixelpulse2.conf
    QCoreApplication::setOrganizationName("Pixelpulse2");
    QCoreApplication::setApplicationName("Pixelpulse2");

    QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));

    init_signal_handlers(argv[0]);

    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    registerTypes();

    FileIO fileIO;
    BossacWrapper bossacWrapper;
    SessionItem smu_session;
    smu_session.openAllDevices();
    engine.rootContext()->setContextProperty("session", &smu_session);

    QVariantMap versions;
    versions.insert("build_date", BUILD_DATE);
    versions.insert("git_version", GIT_VERSION);
    engine.rootContext()->setContextProperty("versions", versions);
    engine.rootContext()->setContextProperty("fileio", &fileIO);
    engine.rootContext()->setContextProperty("bossac", &bossacWrapper);
    if (argc > 1) {
        if (strcmp(argv[1], "-v") || strcmp(argv[1], "--version")) {
            std::cout << GIT_VERSION << ": Built on " << BUILD_DATE << std::endl;
            return 0;
        }
        engine.load(argv[1]);
    } else {
        engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
    }


    int r = app.exec();
    smu_session.closeAllDevices();

    return r;
}
Ejemplo n.º 5
0
void shalture_init(char *execname, char *log_p)
{
	me.execname = execname;
	me.kline_id = 0;
	me.start = time(NULL);
	CURRTIME = me.start;

	/* set signal handlers */
	init_signal_handlers();

	/* initialize strshare */
	strshare_init();

	/* open log */
	log_path = log_p;

	log_open();
	mowgli_log_set_cb(process_mowgli_log);
}
Ejemplo n.º 6
0
Trick::Executive::Executive() {

    /** @par Detailed Design: */
    the_exec = this ;

    advance_sim_time_job = NULL ;
    attach_debugger = false ;
    curr_job = NULL ;
    debugger_command = std::string("/usr/bin/gdb") ;
    enable_freeze = false ;
    except_return = 0 ;
    exec_command = NoCmd ;
    async_freeze_command = false ;
    freeze_command = false ;
    freeze_on_frame_boundary = false ;
    restart_called = false ;
    initialization_complete = false ;
    /** @li Assign default freeze_frame to be 1 second. */
    freeze_frame = 1.0 ;
    job_call_time_tics = 0 ;
    mode = Initialization ;
    num_classes = 0 ;
    num_sim_objects = 0 ;
    rt_nap = true ;
    scheduled_start_index = 1000 ;
    num_scheduled_job_classes = 0 ;
    signal_caused_term = false ;
    sim_start = 0.0 ;
    /** @li Assign default software frame to be 1 second. */
    software_frame = 1.0;
    frame_count = 0 ;
    stack_trace = true ;
    /** @li Assign default terminate time to MAX_LONG_LONG tics. */
    terminate_time = TRICK_MAX_LONG_LONG - 1;
    time_last_pass_tics = 0 ;
    /** @li Assign default time_tic value to be 1 us. */
    time_tics = 0 ;
    freeze_time_tics = 0 ;
    freeze_frame_count = 0 ;
    old_time_tic_value = 1000000 ;
    time_tic_value = 1000000 ;

    // Set the JobData copy of the time_tic_value to the executive value 
    Trick::JobData::set_time_tic_value(time_tic_value) ;

    // These trap flags are set in init_signal_handlers()
    trap_sigbus = false ;
    trap_sigfpe = false ;
    trap_sigsegv = false ;

    build_date = std::string("unknown") ;
    current_version = std::string("unknown") ;
    version_date_tag = std::string("unknown") ;

    num_all_jobs = 0 ;
    all_jobs_for_checkpoint = NULL ;
    num_sim_objects_in_checkpoint = 0 ;
    sim_objects_for_checkpoint = NULL ;

    software_frame_tics = (long long)(software_frame * time_tic_value) ;
    next_frame_check_tics = software_frame_tics ;

    freeze_frame_tics = (long long)(freeze_frame * time_tic_value) ;
    next_freeze_frame_check_tics = freeze_frame_tics ;

    freeze_job = NULL ;
    advance_sim_time_job = NULL ;
    curr_job = NULL ;

    /** @li Map non-scheduled job class strings to job queues. */
    class_map["default_data"] = num_classes ;
    class_to_queue[num_classes++] = &default_data_queue ;

    class_map["input_processor"] = num_classes ;
    class_to_queue[num_classes++] = &input_processor_queue ;

    class_map["initialization"] = num_classes ;
    class_to_queue[num_classes++] = &initialization_queue ;

    class_map["input_processor_run"] = num_classes ;
    class_to_queue[num_classes++] = &input_processor_run_queue ;

    class_map["top_of_frame"] = num_classes ;
    class_to_queue[num_classes++] = &top_of_frame_queue ;

    class_map["end_of_frame"] = num_classes ;
    class_to_queue[num_classes++] = &end_of_frame_queue ;

    class_map["shutdown"] = num_classes ;
    class_to_queue[num_classes++] = &shutdown_queue ;

    class_map["freeze_init"] = num_classes ;
    class_to_queue[num_classes++] = &freeze_init_queue ;

    class_map["freeze_scheduled"] = num_classes ;
    class_to_queue[num_classes++] = &freeze_scheduled_queue ;

    class_map["freeze_automatic"] = num_classes ;
    class_to_queue[num_classes++] = &freeze_scheduled_queue ;

    class_map["freeze"] = num_classes ;
    class_to_queue[num_classes++] = &freeze_queue ;

    class_map["unfreeze"] = num_classes ;
    class_to_queue[num_classes++] = &unfreeze_queue ;

    class_map["exec_time_tic_changed"] = num_classes ;
    class_to_queue[num_classes++] = &time_tic_changed_queue ;

    // Initialize all of default signal handlers
    init_signal_handlers() ;
}
Ejemplo n.º 7
0
#ifdef SIGPIPE
  result += sethandler( SIGPIPE );
#endif
#ifdef SIGIO
  result += sethandler( SIGIO );
#endif
#ifdef SIGSYS
  result += sethandler( SIGSYS );
#endif
  return result;
}

// Declare a garbage global variable.  Use variable initialization to
// force call to init_signal_handlers().  
int junk_init_var = init_signal_handlers();

#endif // LONGJMP_MODE


/***************************************************************************************
 *                            Function to handle failed tests
 ***************************************************************************************/

// use a function rather than substituting FLAG_ERROR directly
// so we have a convenient place to set a break point
inline void flag_error() 
  { FLAG_ERROR; }


/***************************************************************************************
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
	bool have_conf = false;
	bool have_log = false;
	char buf[32];
	int i, pid, r;
	FILE *pid_file;
	const char *pidfilename = RUNDIR "/atheme.pid";
#ifdef HAVE_GETRLIMIT
	struct rlimit rlim;
#endif
	curr_uplink = NULL;

	mowgli_init();

	/* Prepare gettext */
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);
#endif

	/* change to our local directory */
	if (chdir(PREFIX) < 0)
	{
		perror(PREFIX);
		return 20;
	}

#ifdef HAVE_GETRLIMIT
	/* it appears certian systems *ahem*linux*ahem*
	 * don't dump cores by default, so we do this here.
	 */
	if (!getrlimit(RLIMIT_CORE, &rlim))
	{
		rlim.rlim_cur = rlim.rlim_max;
		setrlimit(RLIMIT_CORE, &rlim);
	}
#endif
	
	/* do command-line options */
	while ((r = getopt(argc, argv, "c:dhrl:np:v")) != -1)
	{
		switch (r)
		{
		  case 'c':
			  config_file = sstrdup(optarg);
			  have_conf = true;
			  break;
		  case 'd':
			  log_force = true;
			  break;
		  case 'h':
			  print_help();
			  exit(EXIT_SUCCESS);
			  break;
		  case 'r':
			  readonly = true;
			  break;
		  case 'l':
			  log_path = sstrdup(optarg);
			  have_log = true;
			  break;
		  case 'n':
			  runflags |= RF_LIVE;
			  break;
		  case 'p':
			  pidfilename = optarg;
			  break;
		  case 'v':
			  print_version();
			  exit(EXIT_SUCCESS);
			  break;
		  default:
			  printf("usage: atheme [-dhnvr] [-c conf] [-l logfile] [-p pidfile]\n");
			  exit(EXIT_SUCCESS);
			  break;
		}
	}

	if (!have_conf)
		config_file = sstrdup(SYSCONFDIR "/atheme.conf");

	if (!have_log)
		log_path = sstrdup(LOGDIR "/atheme.log");

	cold_start = true;

	runflags |= RF_STARTING;

	me.kline_id = 0;
	me.start = time(NULL);
	CURRTIME = me.start;
	srand(arc4random());
	me.execname = argv[0];

	/* set signal handlers */
	init_signal_handlers();

	/* initialize strshare */
	strshare_init();

	/* open log */
	log_open();
	mowgli_log_set_cb(process_mowgli_log);

	slog(LG_INFO, "%s is starting up...", PACKAGE_STRING);

	/* check for pid file */
	if ((pid_file = fopen(pidfilename, "r")))
	{
		if (fgets(buf, 32, pid_file))
		{
			pid = atoi(buf);

			if (!kill(pid, 0))
			{
				fprintf(stderr, "atheme: daemon is already running\n");
				exit(EXIT_FAILURE);
			}
		}

		fclose(pid_file);
	}

#if HAVE_UMASK
	/* file creation mask */
	umask(077);
#endif

        event_init();
        hooks_init();
        init_netio();
        init_socket_queues();
	db_init();

	translation_init();
#ifdef ENABLE_NLS
	language_init();
#endif
	init_nodes();
	init_confprocess();
	init_newconf();
	servtree_init();

	modules_init();
	pcommand_init();

	conf_init();
	if (!conf_parse(config_file))
	{
		slog(LG_ERROR, "Error loading config file %s, aborting",
				config_file);
		exit(EXIT_FAILURE);
	}

	if (config_options.languagefile)
	{
		slog(LG_DEBUG, "Using language: %s", config_options.languagefile);
		if (!conf_parse(config_options.languagefile))
			slog(LG_INFO, "Error loading language file %s, continuing",
					config_options.languagefile);
	}

	authcookie_init();
	common_ctcp_init();

	if (!backend_loaded && authservice_loaded)
	{
		slog(LG_ERROR, "atheme: no backend modules loaded, see your configuration file.");
		exit(EXIT_FAILURE);
	}

	/* we've done the critical startup steps now */
	cold_start = false;

	/* load our db */
	if (db_load)
		db_load();
	else if (backend_loaded)
	{
		slog(LG_ERROR, "atheme: backend module does not provide db_load()!");
		exit(EXIT_FAILURE);
	}
	db_check();

#ifdef HAVE_FORK
	/* fork into the background */
	if (!(runflags & RF_LIVE))
	{
		close(0);
		if (open("/dev/null", O_RDWR) != 0)
		{
			slog(LG_ERROR, "unable to open /dev/null??");
			exit(EXIT_FAILURE);
		}
		if ((i = fork()) < 0)
		{
			slog(LG_ERROR, "can't fork into the background");
			exit(EXIT_FAILURE);
		}

		/* parent */
		else if (i != 0)
		{
			slog(LG_INFO, "pid %d", i);
			slog(LG_INFO, "running in background mode from %s", PREFIX);
			exit(EXIT_SUCCESS);
		}

		/* parent is gone, just us now */
		if (setsid() < 0)
		{
			slog(LG_ERROR, "unable to create new session: %s", strerror(errno));
			exit(EXIT_FAILURE);
		}
		dup2(0, 1);
		dup2(0, 2);
	}
	else
	{
		slog(LG_INFO, "pid %d", getpid());
		slog(LG_INFO, "running in foreground mode from %s", PREFIX);
	}
#else
	slog(LG_INFO, "running in foreground mode from %s", PREFIX);
#endif

#ifdef HAVE_GETPID
	/* write pid */
	if ((pid_file = fopen(pidfilename, "w")))
	{
		fprintf(pid_file, "%d\n", getpid());
		fclose(pid_file);
	}
	else
	{
		fprintf(stderr, "atheme: unable to write pid file\n");
		exit(EXIT_FAILURE);
	}
#endif
	/* no longer starting */
	runflags &= ~RF_STARTING;

	/* we probably have a few open already... */
	me.maxfd = 3;

	/* DB commit interval is configurable */
	if (db_save && !readonly)
		event_add("db_save", db_save, NULL, config_options.commit_interval);

	/* check expires every hour */
	event_add("expire_check", expire_check, NULL, 3600);

	/* check k/x/q line expires every minute */
	event_add("kline_expire", kline_expire, NULL, 60);
	event_add("xline_expire", xline_expire, NULL, 60);
	event_add("qline_expire", qline_expire, NULL, 60);

	/* check authcookie expires every ten minutes */
	event_add("authcookie_expire", authcookie_expire, NULL, 600);

	/* reseed rng a little every five minutes */
	event_add("rng_reseed", rng_reseed, NULL, 293);

	me.connected = false;
	uplink_connect();

	/* main loop */
	io_loop();

	/* we're shutting down */
	hook_call_shutdown();

	if (db_save && !readonly)
		db_save(NULL);

	remove(pidfilename);
	errno = 0;
	if (curr_uplink != NULL && curr_uplink->conn != NULL)
		sendq_flush(curr_uplink->conn);
	connection_close_all();

	me.connected = false;

	/* should we restart? */
	if (runflags & RF_RESTART)
	{
		slog(LG_INFO, "main(): restarting");

#ifdef HAVE_EXECVE
		execv(BINDIR "/atheme-services", argv);
#endif
	}

	slog(LG_INFO, "main(): shutting down");

	log_shutdown();

	return 0;
}
Ejemplo n.º 9
0
Archivo: recpt1.c Proyecto: k-pi/recdvb
int
main(int argc, char **argv)
{
    time_t cur_time;
    pthread_t signal_thread;
    pthread_t reader_thread;
    pthread_t ipc_thread;
    QUEUE_T *p_queue = create_queue(MAX_QUEUE);
    BUFSZ   *bufptr;
    decoder *decoder = NULL;
    splitter *splitter = NULL;
    static thread_data tdata;
    decoder_options dopt = {
        4,  /* round */
        0,  /* strip */
        0   /* emm */
    };
    tdata.dopt = &dopt;
    tdata.lnb = 0;
    tdata.tfd = -1;

    int result;
    int option_index;
    struct option long_options[] = {
#ifdef HAVE_LIBARIB25
        { "b25",       0, NULL, 'b'},
        { "B25",       0, NULL, 'b'},
        { "round",     1, NULL, 'r'},
        { "strip",     0, NULL, 's'},
        { "emm",       0, NULL, 'm'},
        { "EMM",       0, NULL, 'm'},
#endif
        { "LNB",       1, NULL, 'n'},
        { "lnb",       1, NULL, 'n'},
        { "udp",       0, NULL, 'u'},
        { "addr",      1, NULL, 'a'},
        { "port",      1, NULL, 'p'},
        { "http",      1, NULL, 'H'},
        { "dev",       1, NULL, 'd'},
        { "help",      0, NULL, 'h'},
        { "version",   0, NULL, 'v'},
        { "sid",       1, NULL, 'i'},
        { "tsid",      1, NULL, 't'},
        { "lch",       0, NULL, 'c'},
        {0, 0, NULL, 0} /* terminate */
    };

    boolean use_b25 = FALSE;
    boolean use_udp = FALSE;
    boolean use_http = FALSE;
    boolean fileless = FALSE;
    boolean use_stdout = FALSE;
    boolean use_splitter = FALSE;
    boolean use_lch = FALSE;
    char *host_to = NULL;
    int port_to = 1234;
    int port_http = 12345;
    sock_data *sockdata = NULL;
    int dev_num = 0;
    int val;
    char *voltage[] = {"0V", "11V", "15V"};
    char *sid_list = NULL;
    unsigned int tsid = 0;
	int connected_socket, listening_socket;
	unsigned int len;
	char *channel, *pch = NULL;

    while((result = getopt_long(argc, argv, "br:smn:ua:H:p:d:hvitcl:",
                                long_options, &option_index)) != -1) {
        switch(result) {
        case 'b':
            use_b25 = TRUE;
            fprintf(stderr, "using B25...¥n");
            break;
        case 's':
            dopt.strip = TRUE;
            fprintf(stderr, "enable B25 strip¥n");
            break;
        case 'm':
            dopt.emm = TRUE;
            fprintf(stderr, "enable B25 emm processing¥n");
            break;
        case 'u':
            use_udp = TRUE;
            host_to = "localhost";
            fprintf(stderr, "enable UDP broadcasting¥n");
            break;
        case 'H':
            use_http = TRUE;
            port_http = atoi(optarg);
            fprintf(stderr, "creating a http daemon¥n");
            break;
        case 'h':
            fprintf(stderr, "¥n");
            show_usage(argv[0]);
            fprintf(stderr, "¥n");
            show_options();
            fprintf(stderr, "¥n");
            exit(0);
            break;
        case 'v':
            fprintf(stderr, "%s %s¥n", argv[0], version);
            fprintf(stderr, "recorder command for DVB tuner.¥n");
            exit(0);
            break;
        /* following options require argument */
        case 'n':
            val = atoi(optarg);
            switch(val) {
            case 11:
                tdata.lnb = 1;
                break;
            case 15:
                tdata.lnb = 2;
                break;
            default:
                tdata.lnb = 0;
                break;
            }
            fprintf(stderr, "LNB = %s¥n", voltage[tdata.lnb]);
            break;
        case 'r':
            dopt.round = atoi(optarg);
            fprintf(stderr, "set round %d¥n", dopt.round);
            break;
        case 'a':
            use_udp = TRUE;
            host_to = optarg;
            fprintf(stderr, "UDP destination address: %s¥n", host_to);
            break;
        case 'p':
            port_to = atoi(optarg);
            fprintf(stderr, "UDP port: %d¥n", port_to);
            break;
        case 'd':
            dev_num = atoi(optarg);
            fprintf(stderr, "using device: /dev/dvb/adapter%d¥n", dev_num);
            break;
        case 'i':
            use_splitter = TRUE;
            sid_list = optarg;
            break;
        case 't':
            tsid = atoi(optarg);
            if(strlen(optarg) > 2){
                if((optarg[0] == '0') && ((optarg[1] == 'X') ||(optarg[1] == 'x'))){
                    sscanf(optarg+2, "%x", &tsid);
                }
            }
            fprintf(stderr, "tsid = 0x%x¥n", tsid);
            break;
	case 'c':
	    use_lch = TRUE;
	    break;
        }
    }

if(use_http){	// http-server add-
	fprintf(stderr, "run as a daemon..¥n");
	if(daemon(1,1)){
		perror("failed to start");
		return 1;
	}
	fprintf(stderr, "pid = %d¥n", getpid());

	struct sockaddr_in sin;
	int ret;
	int sock_optval = 1;
		
	listening_socket = socket(AF_INET, SOCK_STREAM, 0);
	if ( listening_socket == -1 ){
		perror("socket");
		return 1;
	}
		
	if ( setsockopt(listening_socket, SOL_SOCKET, SO_REUSEADDR,
			&sock_optval, sizeof(sock_optval)) == -1 ){
		perror("setsockopt");
		return 1;
	}
		
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port_http);
	sin.sin_addr.s_addr = htonl(INADDR_ANY);

		
	if ( bind(listening_socket, (struct sockaddr *)&sin, sizeof(sin)) < 0 ){
		perror("bind");
		return 1;
	}
		
	ret = listen(listening_socket, SOMAXCONN);
	if ( ret == -1 ){
		perror("listen");
		return 1;
	}
	fprintf(stderr,"listening at port %d¥n", port_http);
	//set rectime to the infinite
	if(parse_time("-",&tdata.recsec) != 0){
		return 1;
	}
	if(tdata.recsec == -1)
		tdata.indefinite = TRUE;
}else{	// -http-server add
    if(argc - optind < 3) {
        if(argc - optind == 2 && use_udp) {
            fprintf(stderr, "Fileless UDP broadcasting¥n");
            fileless = TRUE;
            tdata.wfd = -1;
        }
        else {
            fprintf(stderr, "Some required parameters are missing!¥n");
            fprintf(stderr, "Try '%s --help' for more information.¥n", argv[0]);
            return 1;
        }
    }

    fprintf(stderr, "pid = %d¥n", getpid());

    if(use_lch){
        set_lch(argv[optind], &pch, &sid_list, &tsid);
        if(sid_list) use_splitter = TRUE;
        fprintf(stderr, "tsid = 0x%x¥n", tsid);
    }
    if(pch == NULL) pch = argv[optind];

    /* tune */
    if(tune(pch, &tdata, dev_num, tsid) != 0)
        return 1;

    /* set recsec */
    if(parse_time(argv[optind + 1], &tdata.recsec) != 0) // no other thread --yaz
        return 1;

    if(tdata.recsec == -1)
        tdata.indefinite = TRUE;

    /* open output file */
    char *destfile = argv[optind + 2];
    if(destfile && !strcmp("-", destfile)) {
        use_stdout = TRUE;
        tdata.wfd = 1; /* stdout */
    }
    else {
        if(!fileless) {
            int status;
            char *path = strdup(argv[optind + 2]);
            char *dir = dirname(path);
            status = mkpath(dir, 0777);
            if(status == -1)
                perror("mkpath");
            free(path);

            tdata.wfd = open(argv[optind + 2], (O_RDWR | O_CREAT | O_TRUNC), 0666);
            if(tdata.wfd < 0) {
                fprintf(stderr, "Cannot open output file: %s¥n",
                        argv[optind + 2]);
                return 1;
            }
        }
    }
}	// http-server add

    /* initialize decoder */
    if(use_b25) {
        decoder = b25_startup(&dopt);
        if(!decoder) {
            fprintf(stderr, "Cannot start b25 decoder¥n");
            fprintf(stderr, "Fall back to encrypted recording¥n");
            use_b25 = FALSE;
        }
    }

while(1){	// http-server add-
	if(use_http){
		struct hostent *peer_host;
		struct sockaddr_in peer_sin;
		pch = NULL;
		sid_list = NULL;

		len = sizeof(peer_sin);

		connected_socket = accept(listening_socket, (struct sockaddr *)&peer_sin, &len);
		if ( connected_socket == -1 ){
			perror("accept");
			return 1;
		}

		peer_host = gethostbyaddr((char *)&peer_sin.sin_addr.s_addr,
				  sizeof(peer_sin.sin_addr), AF_INET);
		if ( peer_host == NULL ){
			fprintf(stderr, "gethostbyname failed¥n");
			return 1;
		}

		fprintf(stderr,"connect from: %s [%s] port %d¥n", peer_host->h_name, inet_ntoa(peer_sin.sin_addr), ntohs(peer_sin.sin_port));

		char buf[256];
		read_line(connected_socket, buf);
		fprintf(stderr,"request command is %s¥n",buf);
		char s0[256],s1[256],s2[256];
		sscanf(buf,"%s%s%s",s0,s1,s2);
		char delim[] = "/";
		channel = strtok(s1,delim);
		char *sidflg = strtok(NULL,delim);
		if(sidflg)
			sid_list = sidflg;
		if(use_lch)
			set_lch(channel, &pch, &sid_list, &tsid);
		if(pch == NULL) pch = channel;
		fprintf(stderr,"channel is %s¥n",channel);

		if(sid_list == NULL){
			use_splitter = FALSE;
			splitter = NULL;
		}else if(!strcmp(sid_list,"all")){
			use_splitter = FALSE;
			splitter = NULL;
		}else{
			use_splitter = TRUE;
		}
	}	// -http-server add

    /* initialize splitter */
    if(use_splitter) {
        splitter = split_startup(sid_list);
        if(splitter->sid_list == NULL) {
            fprintf(stderr, "Cannot start TS splitter¥n");
            return 1;
        }
    }

	if(use_http){	// http-server add-
		char header[100];
		if(use_b25) {
			strcpy(header, "HTTP/1.1 200 OK¥r¥nContent-Type: video/mpeg¥r¥nCache-Control: no-cache¥r¥n¥r¥n");
		}else if(!strcmp(sid_list,"1seg")){
			strcpy(header, "HTTP/1.1 200 OK¥r¥nContent-Type: video/mpeg¥r¥nCache-Control: no-cache¥r¥n¥r¥n");
		}else{
			strcpy(header, "HTTP/1.1 200 OK¥r¥nContent-Type: application/octet-stream¥r¥nCache-Control: no-cache¥r¥n¥r¥n");
		}
		write(connected_socket, header, strlen(header));

		//set write target to http
		tdata.wfd = connected_socket;

		//tune
		if(tune(pch, &tdata, dev_num, tsid) != 0){
			fprintf(stderr, "Tuner cannot start recording¥n");
			continue;
		}
	}else{	// -http-server add
    /* initialize udp connection */
    if(use_udp) {
      sockdata = calloc(1, sizeof(sock_data));
      struct in_addr ia;
      ia.s_addr = inet_addr(host_to);
      if(ia.s_addr == INADDR_NONE) {
            struct hostent *hoste = gethostbyname(host_to);
            if(!hoste) {
                perror("gethostbyname");
                return 1;
            }
            ia.s_addr = *(in_addr_t*) (hoste->h_addr_list[0]);
        }
        if((sockdata->sfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) {
            perror("socket");
            return 1;
        }

        sockdata->addr.sin_family = AF_INET;
        sockdata->addr.sin_port = htons (port_to);
        sockdata->addr.sin_addr.s_addr = ia.s_addr;

        if(connect(sockdata->sfd, (struct sockaddr *)&sockdata->addr,
                   sizeof(sockdata->addr)) < 0) {
            perror("connect");
            return 1;
        }
    }
	}	// http-server add
    /* prepare thread data */
    tdata.queue = p_queue;
    tdata.decoder = decoder;
    tdata.splitter = splitter;
    tdata.sock_data = sockdata;
    tdata.tune_persistent = FALSE;

    /* spawn signal handler thread */
    init_signal_handlers(&signal_thread, &tdata);

    /* spawn reader thread */
    tdata.signal_thread = signal_thread;
    pthread_create(&reader_thread, NULL, reader_func, &tdata);

    /* spawn ipc thread */
    key_t key;
    key = (key_t)getpid();

    if ((tdata.msqid = msgget(key, IPC_CREAT | 0666)) < 0) {
        perror("msgget");
    }
    pthread_create(&ipc_thread, NULL, mq_recv, &tdata);
    fprintf(stderr, "¥nRecording...¥n");

    time(&tdata.start_time);

    /* read from tuner */
    while(1) {
        if(f_exit)
            break;

        time(&cur_time);
        bufptr = malloc(sizeof(BUFSZ));
        if(!bufptr) {
            f_exit = TRUE;
            break;
        }
        bufptr->size = read(tdata.tfd, bufptr->buffer, MAX_READ_SIZE);
        if(bufptr->size <= 0) {
            if((cur_time - tdata.start_time) >= tdata.recsec && !tdata.indefinite) {
                f_exit = TRUE;
                enqueue(p_queue, NULL);
                break;
            }
            else {
                free(bufptr);
                continue;
            }
        }
        enqueue(p_queue, bufptr);

        /* stop recording */
        time(&cur_time);
        if((cur_time - tdata.start_time) >= tdata.recsec && !tdata.indefinite) {
            break;
        }
    }

    /* delete message queue*/
    msgctl(tdata.msqid, IPC_RMID, NULL);

    pthread_kill(signal_thread, SIGUSR1);

    /* wait for threads */
    pthread_join(reader_thread, NULL);
    pthread_join(signal_thread, NULL);
    pthread_join(ipc_thread, NULL);

    /* close tuner */
    if(close_tuner(&tdata) != 0)
        return 1;

    /* release queue */
    destroy_queue(p_queue);
	if(use_http){	// http-server add-
		//reset queue
		p_queue = create_queue(MAX_QUEUE);

		/* close http socket */
		close(tdata.wfd);

		fprintf(stderr,"connection closed. still listening at port %d¥n",port_http);
		f_exit = FALSE;
	}else{	// -http-server add
    /* close output file */
	if(!use_stdout){
		fsync(tdata.wfd);
        close(tdata.wfd);
	}

    /* free socket data */
    if(use_udp) {
        close(sockdata->sfd);
        free(sockdata);
    }

    /* release decoder */
    if(!use_http)
    if(use_b25) {
        b25_shutdown(decoder);
    }
	}	// http-server add
    if(use_splitter) {
        split_shutdown(splitter);
    }

	if(!use_http)	// http-server add
    return 0;
}	// http-server add
}
Ejemplo n.º 10
0
int
main(int argc, char **argv)
{
	pthread_t signal_thread;
	static thread_data tdata;
	int result;
	int option_index;
	struct option long_options[] = {
		{ "bell",	   0, NULL, 'b'},
		{ "help",	   0, NULL, 'h'},
		{ "version",   0, NULL, 'v'},
		{ "list",	   0, NULL, 'l'},
		{ "driver",    1, NULL, 'd'},
		{0, 0, NULL, 0} /* terminate */
	};

	tdata.hModule = NULL;
	tdata.dwSpace = 0;
	tdata.table = NULL;
	char *driver = NULL;
	boolean use_bell = FALSE;

	while((result = getopt_long(argc, argv, "bhvln:d:",
								long_options, &option_index)) != -1) {
		switch(result) {
		case 'b':
			use_bell = TRUE;
			break;
		case 'h':
			fprintf(stderr, "\n");
			show_usage(argv[0]);
			fprintf(stderr, "\n");
			show_options();
			fprintf(stderr, "\n");
			show_channels();
			fprintf(stderr, "\n");
			exit(0);
			break;
		case 'v':
			fprintf(stderr, "%s %s\n", argv[0], version);
			fprintf(stderr, "signal check utility for BonDriver based tuners.\n");
			exit(0);
			break;
		case 'l':
			show_channels();
			exit(0);
			break;
		case 'd':
			driver = optarg;
			break;
		}
	}

	if(argc - optind < 1) {
		fprintf(stderr, "channel must be specified!\n");
		fprintf(stderr, "Try '%s --help' for more information.\n", argv[0]);
		return 1;
	}

	/* set tune_persistent flag */
	tdata.tune_persistent = TRUE;

	/* spawn signal handler thread */
	init_signal_handlers(&signal_thread, &tdata);

	/* tune */
	if(tune(argv[optind], &tdata, driver) != 0)
		return 1;

	while(1) {
		if(f_exit)
			break;
		tdata.pIBon->PurgeTsStream();	// 凡ドラはCh設定時からストリームデータをバッファに溜め込むため追加
		/* show signal strength */
		calc_cn(&tdata, use_bell);
		sleep(1);
	}

	/* wait for signal thread */
	pthread_kill(signal_thread, SIGUSR1);
	pthread_join(signal_thread, NULL);

	/* close tuner */
	if(close_tuner(&tdata) != 0)
		return 1;

	return 0;
}
Ejemplo n.º 11
0
int
main(int argc, char *argv[])  {

      /*
       * Check for error conditions that would
       * prevent us from working correctly
       */
    if (argc < 4)  {
          /* So we don't get debug output from dk_errx */
        fprintf(stderr, "Usage: %s path hostname ip [host ip]\n", argv[0]);
        exit(1);
    }

    if (geteuid() != 0)  {
        dk_errx("This program must be run as root");
    }

    if (getpid() == 1)  {
        dk_errx("This program will not function as a regular init(8)");
    }

/*  This breaks sometimes....
    if (check_ip_exists(argv[3]) == 0)  {
        dk_errx("The ip specified: %s, does not appear to exist on this system",
                argv[3]);
    }
*/

      /*
       * The ever-important process title change:
       * Set the title of the process (us) to the hostname
       * of the jail we are to become.
       */
    setproctitle(argv[2]);


      /* Setup signal handlers */
    init_signal_handlers();


      /* Oh yeah, throw ourselves in that cold wet concrete cell with bubba */
    start_jail(argv[1], argv[2], argv[3]);


      /* Make us go into ye-ole bg */
    daemonize();


      /* actually start the "virtual" machine. */
    start_system();


      /* Go into accept loop */
    if (argc == 5)  {
        network_start(argv[4]);
    }  else  {
        for ( ; ; )  sleep(100000);
    }

    return -1;
}
Ejemplo n.º 12
0
gint main (int argc, char **argv)
{
	int c;

	char *profile = NULL;

	init_signal_handlers(argv[0]);

	opterr = 0;
	while ((c = getopt (argc, argv, "c:p:u:")) != -1)
		switch (c) {
			case 'c':
				ctx = iio_create_network_context(optarg);
				if (!ctx) {
					printf("Failed connecting to remote device: %s\n", optarg);
					exit(-1);
				}
				break;
			case 'u':
				ctx = iio_create_context_from_uri(optarg);
				if (!ctx) {
					printf("Failed connecting to remote device: %s\n", optarg);
					exit(-1);
				}
				break;
			case 'p':
				profile = strdup(optarg);
				break;
			case '?':
				usage(argv[0]);
				break;
			default:
				printf("Unknown command line option\n");
				usage(argv[0]);
				break;
		}

#ifndef __MINGW32__
	/* XXX: Enabling threading when compiling for Windows will lock the UI
	 * as soon as the main window is moved. */
	gdk_threads_init();
#endif
	gtk_init(&argc, &argv);

	signal(SIGTERM, sigterm);
	signal(SIGINT, sigterm);
#ifndef __MINGW32__
	signal(SIGHUP, sigterm);
#endif

	gdk_threads_enter();
	init_application();
	c = load_default_profile(profile, true);
	if (!ctx_destroyed_by_do_quit) {
		if (!ctx)
			connect_dialog(false);

		create_default_plot();
		if (c == 0) {
			if (gtk_check_menu_item_get_active(
					GTK_CHECK_MENU_ITEM(versioncheck_en)))
				version_check_start(NULL);
			gtk_main();
		} else
			application_quit();
	}
	gdk_threads_leave();

	if (profile)
	    free(profile);

	if (c == 0 || c == -ENOTTY)
		return 0;
	else
		return -1;
}
Ejemplo n.º 13
0
void setup_Rmainloop(void)
{
    volatile int doneit;
    volatile SEXP baseEnv;
    SEXP cmd;
    char deferred_warnings[11][250];
    volatile int ndeferred_warnings = 0;

    /* In case this is a silly limit: 2^32 -3 has been seen and
     * casting to intptr_r relies on this being smaller than 2^31 on a
     * 32-bit platform. */
    if(R_CStackLimit > 100000000U) 
	R_CStackLimit = (uintptr_t)-1;
    /* make sure we have enough head room to handle errors */
    if(R_CStackLimit != -1)
	R_CStackLimit = (uintptr_t)(0.95 * R_CStackLimit);

    InitConnections(); /* needed to get any output at all */

    /* Initialize the interpreter's internal structures. */

#ifdef HAVE_LOCALE_H
#ifdef Win32
    {
	char *p, Rlocale[1000]; /* Windows' locales can be very long */
	p = getenv("LC_ALL");
	strncpy(Rlocale, p ? p : "", 1000);
        Rlocale[1000 - 1] = '\0';
	if(!(p = getenv("LC_CTYPE"))) p = Rlocale;
	/* We'd like to use warning, but need to defer.
	   Also cannot translate. */
	if(!setlocale(LC_CTYPE, p))
	    snprintf(deferred_warnings[ndeferred_warnings++], 250,
		     "Setting LC_CTYPE=%s failed\n", p);
	if((p = getenv("LC_COLLATE"))) {
	    if(!setlocale(LC_COLLATE, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_COLLATE=%s failed\n", p);
	} else setlocale(LC_COLLATE, Rlocale);
	if((p = getenv("LC_TIME"))) {
	    if(!setlocale(LC_TIME, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_TIME=%s failed\n", p);
	} else setlocale(LC_TIME, Rlocale);
	if((p = getenv("LC_MONETARY"))) {
	    if(!setlocale(LC_MONETARY, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_MONETARY=%s failed\n", p);
	} else setlocale(LC_MONETARY, Rlocale);
	/* Windows does not have LC_MESSAGES */

	/* We set R_ARCH here: Unix does it in the shell front-end */
	char Rarch[30];
	strcpy(Rarch, "R_ARCH=/");
	strcat(Rarch, R_ARCH);
	putenv(Rarch);
    }
#else /* not Win32 */
    if(!setlocale(LC_CTYPE, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_CTYPE failed, using \"C\"\n");
    if(!setlocale(LC_COLLATE, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_COLLATE failed, using \"C\"\n");
    if(!setlocale(LC_TIME, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_TIME failed, using \"C\"\n");
#ifdef ENABLE_NLS
    if(!setlocale(LC_MESSAGES, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MESSAGES failed, using \"C\"\n");
#endif
    /* NB: we do not set LC_NUMERIC */
#ifdef LC_MONETARY
    if(!setlocale(LC_MONETARY, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MONETARY failed, using \"C\"\n");
#endif
#ifdef LC_PAPER
    if(!setlocale(LC_PAPER, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_PAPER failed, using \"C\"\n");
#endif
#ifdef LC_MEASUREMENT
    if(!setlocale(LC_MEASUREMENT, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MEASUREMENT failed, using \"C\"\n");
#endif
#endif /* not Win32 */
#endif

    /* make sure srand is called before R_tmpnam, PR#14381 */
    srand(TimeToSeed());

    InitArithmetic();
    InitParser();
    InitTempDir(); /* must be before InitEd */
    InitMemory();
    InitStringHash(); /* must be before InitNames */
    InitNames();
    InitBaseEnv();
    InitGlobalEnv();
    InitDynload();
    InitOptions();
    InitEd();
    InitGraphics();
    InitTypeTables(); /* must be before InitS3DefaultTypes */
    InitS3DefaultTypes();
    
    R_Is_Running = 1;
    R_check_locale();

    /* Initialize the global context for error handling. */
    /* This provides a target for any non-local gotos */
    /* which occur during error handling */

    R_Toplevel.nextcontext = NULL;
    R_Toplevel.callflag = CTXT_TOPLEVEL;
    R_Toplevel.cstacktop = 0;
    R_Toplevel.promargs = R_NilValue;
    R_Toplevel.callfun = R_NilValue;
    R_Toplevel.call = R_NilValue;
    R_Toplevel.cloenv = R_BaseEnv;
    R_Toplevel.sysparent = R_BaseEnv;
    R_Toplevel.conexit = R_NilValue;
    R_Toplevel.vmax = NULL;
    R_Toplevel.nodestack = R_BCNodeStackTop;
#ifdef BC_INT_STACK
    R_Toplevel.intstack = R_BCIntStackTop;
#endif
    R_Toplevel.cend = NULL;
    R_Toplevel.intsusp = FALSE;
    R_Toplevel.handlerstack = R_HandlerStack;
    R_Toplevel.restartstack = R_RestartStack;
    R_Toplevel.srcref = R_NilValue;
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    R_ExitContext = NULL;

    R_Warnings = R_NilValue;

    /* This is the same as R_BaseEnv, but this marks the environment
       of functions as the namespace and not the package. */
    baseEnv = R_BaseNamespace;

    /* Set up some global variables */
    Init_R_Variables(baseEnv);

    /* On initial entry we open the base language package and begin by
       running the repl on it.
       If there is an error we pass on to the repl.
       Perhaps it makes more sense to quit gracefully?
    */

#ifdef RMIN_ONLY
    /* This is intended to support a minimal build for experimentation. */
    if (R_SignalHandlers) init_signal_handlers();
#else
    FILE *fp = R_OpenLibraryFile("base");
    if (fp == NULL)
	R_Suicide(_("unable to open the base package\n"));

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (R_SignalHandlers) init_signal_handlers();
    if (!doneit) {
	doneit = 1;
	R_ReplFile(fp, baseEnv);
    }
    fclose(fp);
#endif

    /* This is where we source the system-wide, the site's and the
       user's profile (in that order).  If there is an error, we
       drop through to further processing.
    */
    R_IoBufferInit(&R_ConsoleIob);
    R_LoadProfile(R_OpenSysInitFile(), baseEnv);
    /* These are the same bindings, so only lock them once */
    R_LockEnvironment(R_BaseNamespace, TRUE);
#ifdef NOTYET
    /* methods package needs to trample here */
    R_LockEnvironment(R_BaseEnv, TRUE);
#endif
    /* At least temporarily unlock some bindings used in graphics */
    R_unLockBinding(R_DeviceSymbol, R_BaseEnv);
    R_unLockBinding(R_DevicesSymbol, R_BaseEnv);
    R_unLockBinding(install(".Library.site"), R_BaseEnv);

    /* require(methods) if it is in the default packages */
    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".OptRequireMethods"));
	R_CurrentExpr = findVar(cmd, R_GlobalEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }

    if (strcmp(R_GUIType, "Tk") == 0) {
	char buf[PATH_MAX];

	snprintf(buf, PATH_MAX, "%s/library/tcltk/exec/Tk-frontend.R", R_Home);
	R_LoadProfile(R_fopen(buf, "r"), R_GlobalEnv);
    }

    /* Print a platform and version dependent greeting and a pointer to
     * the copyleft.
     */
    if(!R_Quiet) PrintGreeting();
 
    R_LoadProfile(R_OpenSiteFile(), baseEnv);
    R_LockBinding(install(".Library.site"), R_BaseEnv);
    R_LoadProfile(R_OpenInitFile(), R_GlobalEnv);

    /* This is where we try to load a user's saved data.
       The right thing to do here is very platform dependent.
       E.g. under Unix we look in a special hidden file and on the Mac
       we look in any documents which might have been double clicked on
       or dropped on the application.
    */
    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	R_InitialData();
    }
    else {
    	if (! SETJMP(R_Toplevel.cjmpbuf)) {
	    warning(_("unable to restore saved data in %s\n"), get_workspace_name());
	}
    }
    
    /* Initial Loading is done.
       At this point we try to invoke the .First Function.
       If there is an error we continue. */

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".First"));
	R_CurrentExpr = findVar(cmd, R_GlobalEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }
    /* Try to invoke the .First.sys function, which loads the default packages.
       If there is an error we continue. */

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".First.sys"));
	R_CurrentExpr = findVar(cmd, baseEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }
    {
	int i;
	for(i = 0 ; i < ndeferred_warnings; i++)
	    warning(deferred_warnings[i]);
    }
    if (R_CollectWarnings) {
	REprintf(_("During startup - "));
	PrintWarnings();
    }

    /* trying to do this earlier seems to run into bootstrapping issues. */
    R_init_jit_enabled();
    R_Is_Running = 2;
}
Ejemplo n.º 14
0
/*****************************************************************************
 * main()
 *
 * Parse command line, load patch, start midi_tx, midi_rx, and jack threads.
 *****************************************************************************/
int
main(int argc, char **argv)
{
	char            thread_name[16];
	char            opts[NUM_OPTS * 2 + 1];
	struct option   *op;
	char            *cp;
	char            *p;
	char            *term;
	char            *tokbuf;
	int             c;
	int             j                       = 0;
	int             ret                     = 0;
	int             saved_errno;
	int             argcount                = 0;
	char            **argvals               = argv;
	char            **envp                  = environ;
	char            *argvend                = (char *)argv;
	size_t          argsize;
	unsigned char   rx_channel;

	setlocale(LC_ALL, "C");

	jamrouter_instance = get_instance_num();
	fprintf(stderr, "Starting jamrouter instance %d.\n", jamrouter_instance);

	/* Start debug thread.  debug_class is not set until arguemnts are parsed,
	   so use fprintf() until then. */
	if ((ret = pthread_create(&debug_thread_p, NULL, &jamrouter_debug_thread, NULL)) != 0) {
		fprintf(stderr, "***** ERROR:  Unable to start debug thread.\n");
	}

	/* lock down memory (rt hates page faults) */
	if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
		saved_errno = errno;
		fprintf(stderr, "Unable to unlock memory:  errno=%d (%s)\n",
		        saved_errno, strerror(saved_errno));
	}

	/* init lash client */
#ifndef WITHOUT_LASH
	for (j = 0; j < argc; j++) {
		if ((strcmp(argv[j], "-L") == 0) || (strcmp(argv[j], "--disable-lash") == 0) ||
		    (strcmp(argv[j], "-h") == 0) || (strcmp(argv[j], "--help") == 0) ||
		    (strcmp(argv[j], "-l") == 0) || (strcmp(argv[j], "--list") == 0) ||
		    (strcmp(argv[j], "-v") == 0) || (strcmp(argv[j], "--version") == 0) ||
		    (strcmp(argv[j], "-D") == 0) || (strcmp(argv[j], "--session-dir") == 0) ||
		    (strcmp(argv[j], "-u") == 0) || (strcmp(argv[j], "--uuid") == 0)) {
			lash_disabled = 1;
			break;
		}
	}
	if (!lash_disabled) {
		snprintf(thread_name, 16, "jamrouter%c-lash", ('0' + jamrouter_instance));
		pthread_setname_np(pthread_self(), thread_name);
		if (lash_client_init(&argc, &argv) == 0) {
			lash_poll_event();
		}
		snprintf(thread_name, 16, "jamrouter%c-main", ('0' + jamrouter_instance));
		pthread_setname_np(pthread_self(), thread_name);
	}
#endif

	/* startup initializations */
	init_midi_event_queue();
	init_jack_audio_driver();
	select_midi_driver(NULL, DEFAULT_MIDI_DRIVER);

	/* save original command line for session handling */
	if (jamrouter_cmdline[0] == '\0') {
		jamrouter_cmdline[0] = '\0';
		for (j = 0; j < argc; j++) {
			strcat(&(jamrouter_cmdline[0]), argv[j]);
			strcat(&(jamrouter_cmdline[0]), " ");
		}
		jamrouter_cmdline[strlen(jamrouter_cmdline) - 1] = '\0';
		term = get_color_terminal();
		if (term == NULL) {
			strcpy(jamrouter_full_cmdline, jamrouter_cmdline);
		}
		else {
			snprintf(jamrouter_full_cmdline, 512, "%s -e \"%s \"",
			         term, jamrouter_cmdline);
		}
		argcount = argc;
		argvals  = argv;
	}
	/* command line args supplied by session manager */
	else {
		argcount = 0;
		cp = strdup(jamrouter_cmdline);
		p = cp;
		while ((p = index(p, ' ')) != NULL) {
			p++;
			argcount++;
		}
		if ((argvals = malloc(((size_t)(argcount) + 1UL) *
		                      (size_t)sizeof(char *))) == NULL) {
			fprintf(stderr, "Out of Memory!\n");
			return -1;
		}
		if ((tokbuf = alloca(strlen(jamrouter_cmdline) * 4)) == NULL) {
			fprintf(stderr, "Out of Memory!\n");
			return -1;
		}
		while ((p = strtok_r(cp, " ", &tokbuf)) != NULL) {
			cp = NULL;
			argvals[j++] = p;
		}
		argvals[argcount] = NULL;
	}

	/* build the short option string */
	cp = opts;
	for (op = long_opts; op < &long_opts[NUM_OPTS]; op++) {
		*cp++ = (char) op->val;
		if (op->has_arg) {
			*cp++ = ':';
		}
	}

	/* handle options */
	for (;;) {
		c = getopt_long(argcount, argvals, opts, long_opts, NULL);
		if (c == -1) {
			break;
		}

		switch (c) {
		case 'M':   /* MIDI driver */
			select_midi_driver(optarg, -1);
			break;
		case 'D':   /* MIDI Rx/Tx port/device */
			midi_rx_port_name = strdup(optarg);
			midi_tx_port_name = strdup(optarg);
			break;
		case 'r':   /* MIDI Rx port/device */
			midi_rx_port_name = strdup(optarg);
			break;
		case 't':   /* MIDI Tx port/device */
			midi_tx_port_name = strdup(optarg);
			break;
		case 'x':   /* MIDI Rx latency periods */
			rx_latency_periods = atoi(optarg);
			break;
		case 'X':   /* MIDI Tx latency periods */
			tx_latency_periods = atoi(optarg);
			break;
		case 'g':   /* Tx byte guard time in usec */
			byte_guard_time_usec = atoi(optarg);
			break;
		case 'G':   /* Tx event guard time in usec */
			event_guard_time_usec = atoi(optarg);
			break;
		case 'i':   /* JACK MIDI input port */
			jack_input_port_name = strdup(optarg);
			break;
		case 'o':   /* JACK MIDI output port */
			jack_output_port_name = strdup(optarg);
			break;
		case 'j':   /* Jitter correction mode */
			jitter_correct_mode = 1;
			break;
		case 'z':   /* JACK wake phase within MIDI Rx/Tx period */
			setting_midi_phase_lock = (timecalc_t)(atof(optarg));
			if (setting_midi_phase_lock < (timecalc_t)(0.0625)) {
				setting_midi_phase_lock = (timecalc_t)(0.0625);
			}
			else if (setting_midi_phase_lock > (timecalc_t)(0.9375)) {
				setting_midi_phase_lock = (timecalc_t)(0.9375);
			}
			break;
#ifndef WITHOUT_JACK_DLL
		case '4':   /* JACK DLL timing level 4 */
			jack_dll_level = 4;
			break;
		case '3':   /* JACK DLL timing level 3 */
			jack_dll_level = 3;
			break;
		case '2':   /* JACK DLL timing level 2 */
			jack_dll_level = 2;
			break;
		case '1':   /* JACK DLL timing level 1 */
			jack_dll_level = 1;
			break;
#endif
		case 'k':   /* key to controller mapping */
			if (optarg != NULL) {
				if ((tokbuf = alloca(strlen((const char *)optarg) * 4)) == NULL) {
					jamrouter_shutdown("Out of memory!\n");
				}
				if ((p = strtok_r(optarg, ",", &tokbuf)) != NULL) {
					rx_channel = (atoi(p) - 1) & 0x0F;
					if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
						keymap_tx_channel[rx_channel] = (atoi(p) - 1) & 0x0F;
						if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
							keymap_tx_controller[rx_channel] = atoi(p) & 0x7F;
						}
					}
					JAMROUTER_DEBUG(DEBUG_CLASS_INIT, "Key --> Controller Map:  "
					                "rx_channel=%0d  tx_channel=%d  tx_cc=%d\n",
					                rx_channel + 1,
					                keymap_tx_channel[rx_channel] + 1,
					                keymap_tx_controller[rx_channel]);
				}
			}
			break;
		case 'p':   /* key to pitchbend translation */
			if (optarg != NULL) {
				if ((tokbuf = alloca(strlen((const char *)optarg) * 4)) == NULL) {
					jamrouter_shutdown("Out of memory!\n");
				}
				if ((p = strtok_r(optarg, ",", &tokbuf)) != NULL) {
					rx_channel = (atoi(p) - 1) & 0x0F;
					if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
						pitchmap_tx_channel[rx_channel] = (atoi(p) - 1) & 0x0F;
						if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
							pitchmap_center_note[rx_channel] = atoi(p) & 0x7F;
							if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
								pitchmap_bend_range[rx_channel] = atoi(p) & 0x7F;
							}
						}
					}
					JAMROUTER_DEBUG(DEBUG_CLASS_INIT,
					                "Key --> Pitchbend Map:  "
					                "rx_chan=%0d  tx_chan=%d  center=%d  range=%d\n",
					                rx_channel + 1, pitchmap_tx_channel[rx_channel] + 1,
					                pitchmap_center_note[rx_channel],
					                pitchmap_bend_range[rx_channel]);
				}
			}
			break;
		case 'q':   /* pitchbend to controller translation */
			if (optarg != NULL) {
				if ((tokbuf = alloca(strlen((const char *)optarg) * 4)) == NULL) {
					jamrouter_shutdown("Out of memory!\n");
				}
				if ((p = strtok_r(optarg, ",", &tokbuf)) != NULL) {
					rx_channel = (atoi(p) - 1) & 0x0F;
					if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
						pitchcontrol_tx_channel[rx_channel] = (atoi(p) - 1) & 0x0F;
						if ((p = strtok_r(NULL, ",", &tokbuf)) != NULL) {
							pitchcontrol_controller[rx_channel] = atoi(p) & 0x7F;
						}
					}
					JAMROUTER_DEBUG(DEBUG_CLASS_INIT,
					                "Pitchbend --> Controller Map:  "
					                "rx_chan=%0d  tx_chan=%d  controller=%d\n",
					                rx_channel + 1, pitchcontrol_tx_channel[rx_channel] + 1,
					                pitchcontrol_controller[rx_channel]);
				}
			}
			break;
#ifndef WITHOUT_JUNO
		case 'J':   /* Juno-106 sysex controller translation */
			translate_juno_sysex = 1;
			break;
		case 's':   /* echo sysex translations back to originator */
			echosysex = 1;
			break;
#endif
		case 'e':   /* echo pitchbend and controller translations back to originator */
			echotrans = 1;
			break;
		case 'T':   /* alternate sysex terminator byte */
			sysex_terminator = hex_to_byte(optarg);
			break;
		case 'U':   /* alternate sysex terminator byte */
			sysex_extra_terminator = hex_to_byte(optarg);
			break;
		case 'A':   /* Active-Sensing mode */
			if (strcmp(optarg, "on") == 0) {
				active_sensing_mode = ACTIVE_SENSING_MODE_ON;
			}
			else if (strcmp(optarg, "thru") == 0) {
				active_sensing_mode = ACTIVE_SENSING_MODE_THRU;
			}
			else if (strcmp(optarg, "drop") == 0) {
				active_sensing_mode = ACTIVE_SENSING_MODE_DROP;
			}
			break;
		case 'R':   /* Omit running status byte on MIDI Tx */
			use_running_status = 1;
			break;
		case 'n':   /* Note-On Velocity */
			note_on_velocity = hex_to_byte(optarg);
			break;
		case 'N':   /* Note-Off Velocity */
			note_off_velocity = hex_to_byte(optarg);
			break;
		case 'f':   /* Send multiple Note-Off messages as All-Notes-Off */
			tx_prefer_all_notes_off = 1;
			break;
		case 'F':   /* Tx send real Note-Off instead of Velocity-0-Note-On */
			tx_prefer_real_note_off = 1;
			break;
		case '0':   /* Rx queue real Note-Off instead of Velocity-0-Note-On */
			rx_queue_real_note_off = 1;
			break;
		case 'y':   /* MIDI Rx thread priority */
			if ((midi_rx_thread_priority = atoi(optarg)) <= 0) {
				midi_rx_thread_priority = MIDI_RX_THREAD_PRIORITY;
			}
			break;
		case 'Y':   /* MIDI Tx thread priority */
			if ((midi_tx_thread_priority = atoi(optarg)) <= 0) {
				midi_tx_thread_priority = MIDI_TX_THREAD_PRIORITY;
			}
			break;
		case 'd':   /* debug */
			debug = 1;
			for (j = 0; debug_class_list[j].name != NULL; j++) {
				if (strcmp(debug_class_list[j].name, optarg) == 0) {
					debug_class |= debug_class_list[j].id;
				}
			}
			break;
		case 'v':   /* version */
			printf("jamrouter-%s\n", PACKAGE_VERSION);
			return 0;
		case 'L':   /* disable lash */
			lash_disabled = 1;
			break;
		case 'l':   /* list midi devices */
			scan_midi();
			return 0;
		case 'u':   /* jack session uuid */
			jack_session_uuid = strdup(optarg);
			break;
		case '?':
		case 'h':   /* help */
		default:
			showusage(argv[0]);
			return -1;
		}
	}

	/* Rewrite process title */
	argcount = argc;
	argvals  = argv;
	for (j = 0; j <= argcount; j++) {
		if ((j == 0) || ((argvend + 1) == argvals[j])) {
			argvend = argvals[j] + strlen(argvals[j]);
		}
		else {
			continue;
		}
	}

	/* steal space from first environment entry */
	if (envp[0] != NULL) {
		argvend = envp[0] + strlen (envp[0]);
	}

	/* calculate size we have for process title */
	argsize = (size_t)((char *)argvend - (char *)*argvals - 1);
	memset (*argvals, 0, argsize);

	/* rewrite process title */
	argc = 0;
	snprintf((char *)*argvals, argsize, "jamrouter%d", jamrouter_instance);

	/* signal handlers for clean shutdown */
	init_signal_handlers();

	/* init MIDI system based on selected driver */
	JAMROUTER_DEBUG(DEBUG_CLASS_INIT, "Initializing MIDI:  driver=%s.\n",
	                midi_driver_names[midi_driver]);
	init_sync_info(0, 0);
	init_midi();

	/* initialize JACK audio system based on selected driver */
	snprintf(thread_name, 16, "jamrouter%c-clnt", ('0' + jamrouter_instance));
	pthread_setname_np(pthread_self(), thread_name);
	init_jack_audio();
	while (sample_rate == 0) {
		JAMROUTER_DEBUG(DEBUG_CLASS_INIT,
		                "JACK did not set sample rate.  Re-initializing...\n");
		init_jack_audio();
		usleep(125000);
	}

	/* start the JACK audio system */
	start_jack_audio();

	/* wait for JACK audio to start before starting midi. */
	wait_jack_audio_start();

	snprintf(thread_name, 16, "jamrouter%c-main", ('0' + jamrouter_instance));
	pthread_setname_np(pthread_self(), thread_name);

	/* start MIDI Rx/Tx threads. */
	start_midi_rx();
	wait_midi_rx_start();
	start_midi_tx();
	wait_midi_tx_start();

	/* debug thread not needed once watchdog is running */
	debug_done = 1;
	pthread_join(debug_thread_p, NULL);

	/* Jamrouter watchdog handles restarting threads on config changes,
	   runs driver supplied watchdog loop iterations, and handles debug
	   output. */
	jamrouter_watchdog();
	stop_midi_tx();
	stop_midi_rx();
	stop_jack_audio();
	output_pending_debug();

	/* Wait for threads created directly by JAMROUTER to terminate. */
	if (midi_rx_thread_p != 0) {
		pthread_join(midi_rx_thread_p,  NULL);
	}
	if (midi_tx_thread_p != 0) {
		pthread_join(midi_tx_thread_p,  NULL);
	}
	output_pending_debug();

	return 0;
}
Ejemplo n.º 15
0
int
main(int argc, char *argv[])
{
    int i, optct = 0;
    int rcode;

    ctx = tcpreplay_init();
#ifdef TCPREPLAY
    optct = optionProcess(&tcpreplayOptions, argc, argv);
#elif defined TCPREPLAY_EDIT
    optct = optionProcess(&tcpreplay_editOptions, argc, argv);
#endif
    argc -= optct;
    argv += optct;

    rcode = tcpreplay_post_args(ctx, argc);
    if (rcode <= -2) {
        warnx("%s", tcpreplay_getwarn(ctx));
    } else if (rcode == -1) {
        errx(-1, "Unable to parse args: %s", tcpreplay_geterr(ctx));
    }

#ifdef TCPREPLAY_EDIT
    /* init tcpedit context */
    if (tcpedit_init(&tcpedit, sendpacket_get_dlt(ctx->intf1)) < 0) {
        errx(-1, "Error initializing tcpedit: %s", tcpedit_geterr(tcpedit));
    }

    /* parse the tcpedit args */
    rcode = tcpedit_post_args(tcpedit);
    if (rcode < 0) {
        errx(-1, "Unable to parse args: %s", tcpedit_geterr(tcpedit));
    } else if (rcode == 1) {
        warnx("%s", tcpedit_geterr(tcpedit));
    }

    if (tcpedit_validate(tcpedit) < 0) {
        errx(-1, "Unable to edit packets given options:\n%s",
               tcpedit_geterr(tcpedit));
    }
#endif

    if ((ctx->options->enable_file_cache || 
               ctx->options->preload_pcap) && ! HAVE_OPT(QUIET)) {
        notice("File Cache is enabled");
    }

    /*
     * Setup up the file cache, if required
     */
    if (ctx->options->enable_file_cache || ctx->options->preload_pcap) {
        /* Initialise each of the file cache structures */
        for (i = 0; i < argc; i++) {
            ctx->options->file_cache[i].index = i;
            ctx->options->file_cache[i].cached = FALSE;
            ctx->options->file_cache[i].packet_cache = NULL;
        }
    }

    for (i = 0; i < argc; i++) {
        tcpreplay_add_pcapfile(ctx, argv[i]);

        /* preload our pcap file? */
        if (ctx->options->preload_pcap) {
            preload_pcap_file(ctx, i);
        }
    }

    /* init the signal handlers */
    init_signal_handlers();

    if (gettimeofday(&ctx->stats.start_time, NULL) < 0)
        errx(-1, "gettimeofday() failed: %s",  strerror(errno));

    /* main loop, when not looping forever */
    if (ctx->options->loop > 0) {
        while (ctx->options->loop--) {  /* limited loop */
            if (ctx->options->dualfile) {
                /* process two files at a time for network taps */
                for (i = 0; i < argc; i += 2) {
                    tcpr_replay_index(ctx, i);
                }
            } else {
                /* process each pcap file in order */
                for (i = 0; i < argc; i++) {
                    /* reset cache markers for each iteration */
                    ctx->cache_byte = 0;
                    ctx->cache_bit = 0;
                    tcpr_replay_index(ctx, i);
                }
            }
        }
    }
    else {
        /* loop forever */
        while (1) {
            if (ctx->options->dualfile) {
                /* process two files at a time for network taps */
                for (i = 0; i < argc; i += 2) {
                    tcpr_replay_index(ctx, i);
                }
            } else {
                /* process each pcap file in order */
                for (i = 0; i < argc; i++) {
                    /* reset cache markers for each iteration */
                    ctx->cache_byte = 0;
                    ctx->cache_bit = 0;
                    tcpr_replay_index(ctx, i);
                }
            }
        }
    }

    if (ctx->stats.bytes_sent > 0) {
        if (gettimeofday(&ctx->stats.end_time, NULL) < 0)
            errx(-1, "gettimeofday() failed: %s",  strerror(errno));
        packet_stats(&ctx->stats);
        printf("%s", sendpacket_getstat(ctx->intf1));
        if (ctx->intf2 != NULL)
            printf("%s", sendpacket_getstat(ctx->intf2));
    }
    tcpreplay_close(ctx);
    return 0;
}   /* main() */