Пример #1
0
int _main_(int /*_argc*/, char** /*_argv*/)
{
	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
			, BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
			, 0x303030ff
			, 1.0f
			, 0
			);

	// Create vertex stream declaration.
	PosColorVertex::init();

	const bgfx::Memory* vs_drawstress;
	const bgfx::Memory* fs_drawstress;

	switch (bgfx::getRendererType() )
	{
		case bgfx::RendererType::Direct3D9:
			vs_drawstress = bgfx::makeRef(vs_drawstress_dx9, sizeof(vs_drawstress_dx9) );
			fs_drawstress = bgfx::makeRef(fs_drawstress_dx9, sizeof(fs_drawstress_dx9) );
			break;

		case bgfx::RendererType::Direct3D11:
			vs_drawstress = bgfx::makeRef(vs_drawstress_dx11, sizeof(vs_drawstress_dx11) );
			fs_drawstress = bgfx::makeRef(fs_drawstress_dx11, sizeof(fs_drawstress_dx11) );
			break;

		default:
			vs_drawstress = bgfx::makeRef(vs_drawstress_glsl, sizeof(vs_drawstress_glsl) );
			fs_drawstress = bgfx::makeRef(fs_drawstress_glsl, sizeof(fs_drawstress_glsl) );
			break;
	}

	// Create program from shaders.
	program = bgfx::createProgram(
		  bgfx::createShader(vs_drawstress)
		, bgfx::createShader(fs_drawstress)
		, true /* destroy shaders when program is destroyed */
		);

	const bgfx::Memory* mem;

	// Create static vertex buffer.
	mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) );
	vbh = bgfx::createVertexBuffer(mem, PosColorVertex::ms_decl);

	// Create static index buffer.
	mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) );
	ibh = bgfx::createIndexBuffer(mem);

	imguiCreate(s_droidSansTtf);

#if BX_PLATFORM_EMSCRIPTEN
	emscripten_set_main_loop(&loop, -1, 1);
#else
	while (!mainloop() );
#endif // BX_PLATFORM_EMSCRIPTEN

	// Cleanup.
	imguiDestroy();
	bgfx::destroyIndexBuffer(ibh);
	bgfx::destroyVertexBuffer(vbh);
	bgfx::destroyProgram(program);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}
Пример #2
0
int main(int argc, char **argv) {
  regex_t preg;
  /* command line options */
  int c;
  char *ifout = "";
  char *ifin = "";

#ifndef BCRELAY
  fprintf(stderr,
	  "bcrelay: pptpd was compiled without support for bcrelay, exiting.\n"
	  "         run configure --with-bcrelay, make, and install.\n");
  exit(1);
#endif

        /* open a connection to the syslog daemon */
        openlog("bcrelay", LOG_PID, PPTP_FACILITY);

  while (1) {
                int option_index = 0;

                static struct option long_options[] =
                {
                        {"nolog", 0, 0, 0},
                        {"daemon", 0, 0, 0},
                        {"help", 0, 0, 0},
                        {"incoming", 1, 0, 0},
                        {"outgoing", 1, 0, 0},
                        {"ipsec", 1, 0, 0},
                        {"version", 0, 0, 0},
                        {0, 0, 0, 0}
                };

                c = getopt_long(argc, argv, "ndhi:o:s:v", long_options, &option_index);
                if (c == -1)
                        break;
                /* convert long options to short form */
                if (c == 0)
                        c = "ndhiosv"[option_index];
                switch (c) {
                case 'n':
                        vnologging = 1;
                        break;
                case 'd':
                        vdaemon = 1;
                        break;
                case 'h':
                        showusage(argv[0]);
                        return 0;
                case 'i':
                        ifin = strdup(optarg);
                        break;
                case 'o':
                        ifout = strdup(optarg);
                        break;
                case 's':
                        ipsec = strdup(optarg);
                        // Validate the ipsec parameters
                        regcomp(&preg, "ipsec[0-9]+:[0-9]+.[0-9]+.[0-9]+.255", REG_EXTENDED);
                        if (regexec(&preg, ipsec, 0, NULL, 0)) {
                                syslog(LOG_INFO,"Bad syntax: %s", ipsec);
                                fprintf(stderr, "\nBad syntax: %s\n", ipsec);
                                showusage(argv[0]);
                                return 0;
                        } else {
                                regfree(&preg);
                                break;
                        }
                case 'v':
                        showversion();
                        return 0;
                default:
                        showusage(argv[0]);
                        return 1;
                }
  }
  if (ifin == "") {
       syslog(LOG_INFO,"Incoming interface required!");
       showusage(argv[0]);
       _exit(1);
  }
  if (ifout == "" && ipsec == "") {
       syslog(LOG_INFO,"Listen-mode or outgoing or IPsec interface required!");
       showusage(argv[0]);
       _exit(1);
  } else {
        sprintf(interfaces,"%s|%s", ifin, ifout);
  }

  // If specified, become Daemon.
  if (vdaemon) {
#if HAVE_DAEMON
    closelog();
    freopen("/dev/null", "r", stdin);
    /* set noclose, we want stdout/stderr still attached if we can */
    daemon(0, 1);
    /* returns to child only */
    /* pid will have changed */
    openlog("bcrelay", LOG_PID, PPTP_FACILITY);
#else   /* !HAVE_DAEMON */
    my_daemon(argc, argv);
    /* returns to child if !HAVE_FORK
     * never returns if HAVE_FORK (re-execs without -d)
     */
#endif
  } else {
    syslog(LOG_INFO, "Running as child\n");
  }
  mainloop(argc,argv);
  _exit(0);
}
Пример #3
0
int
main(int argc, char **argv)
{
  int i;
  sigset_t set;
#if ENABLE_MPEGTS
  uint32_t adapter_mask = 0;
#endif
  int  log_level   = LOG_INFO;
  int  log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG;
  const char *log_debug = NULL, *log_trace = NULL;
  gid_t gid = -1;
  uid_t uid = -1;
  char buf[512];
  FILE *pidfile = NULL;
  static struct {
    void *thread_id;
    struct timeval tv;
    uint8_t ru[32];
  } randseed;
  extern int dvb_bouquets_parse;

  main_tid = pthread_self();

  /* Setup global mutexes */
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);
  pthread_mutex_init(&tasklet_lock, NULL);
  pthread_mutex_init(&atomic_lock, NULL);
  pthread_cond_init(&gtimer_cond, NULL);
  pthread_cond_init(&tasklet_cond, NULL);
  TAILQ_INIT(&tasklets);

  /* Defaults */
  tvheadend_webui_port      = 9981;
  tvheadend_webroot         = NULL;
  tvheadend_htsp_port       = 9982;
  tvheadend_htsp_port_extra = 0;
  time(&dispatch_clock);

  /* Command line options */
  int         opt_help         = 0,
              opt_version      = 0,
              opt_fork         = 0,
              opt_firstrun     = 0,
              opt_stderr       = 0,
              opt_syslog       = 0,
              opt_nosyslog     = 0,
              opt_uidebug      = 0,
              opt_abort        = 0,
              opt_noacl        = 0,
              opt_fileline     = 0,
              opt_threadid     = 0,
              opt_libav        = 0,
              opt_ipv6         = 0,
              opt_nosatip      = 0,
              opt_satip_rtsp   = 0,
#if ENABLE_TSFILE
              opt_tsfile_tuner = 0,
#endif
              opt_dump         = 0,
              opt_xspf         = 0,
              opt_dbus         = 0,
              opt_dbus_session = 0,
              opt_nobackup     = 0,
              opt_nobat        = 0;
  const char *opt_config       = NULL,
             *opt_user         = NULL,
             *opt_group        = NULL,
             *opt_logpath      = NULL,
             *opt_log_debug    = NULL,
             *opt_log_trace    = NULL,
             *opt_pidpath      = "/var/run/tvheadend.pid",
#if ENABLE_LINUXDVB
             *opt_dvb_adapters = NULL,
#endif
             *opt_bindaddr     = NULL,
             *opt_subscribe    = NULL,
             *opt_user_agent   = NULL;
  str_list_t  opt_satip_xml    = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  str_list_t  opt_tsfile       = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  cmdline_opt_t cmdline_opts[] = {
    {   0, NULL,        N_("Generic options"),         OPT_BOOL, NULL         },
    { 'h', "help",      N_("Show this page"),          OPT_BOOL, &opt_help    },
    { 'v', "version",   N_("Show version information"),OPT_BOOL, &opt_version },

    {   0, NULL,        N_("Service configuration"),   OPT_BOOL, NULL         },
    { 'c', "config",    N_("Alternate configuration path"), OPT_STR,  &opt_config  },
    { 'B', "nobackup",  N_("Don't backup configuration tree at upgrade"), OPT_BOOL, &opt_nobackup },
    { 'f', "fork",      N_("Fork and run as daemon"),  OPT_BOOL, &opt_fork    },
    { 'u', "user",      N_("Run as user"),             OPT_STR,  &opt_user    },
    { 'g', "group",     N_("Run as group"),            OPT_STR,  &opt_group   },
    { 'p', "pid",       N_("Alternate PID path"),      OPT_STR,  &opt_pidpath },
    { 'C', "firstrun",  N_("If no user account exists then create one with\n"
	                   "no username and no password. Use with care as\n"
	                   "it will allow world-wide administrative access\n"
	                   "to your Tvheadend installation until you create or edit\n"
	                   "the access control from within the Tvheadend web interface."),
      OPT_BOOL, &opt_firstrun },
#if ENABLE_DBUS_1
    { 'U', "dbus",      N_("Enable DBus"),
      OPT_BOOL, &opt_dbus },
    { 'e', "dbus_session", N_("DBus - use the session message bus instead of the system one"),
      OPT_BOOL, &opt_dbus_session },
#endif
#if ENABLE_LINUXDVB
    { 'a', "adapters",  N_("Only use specified DVB adapters (comma separated, -1 = none)"),
      OPT_STR, &opt_dvb_adapters },
#endif
#if ENABLE_SATIP_SERVER
    {   0, "satip_rtsp", N_("SAT>IP RTSP port number for server\n"
                            "(default: -1 = disable, 0 = webconfig, standard port is 554)"),
      OPT_INT, &opt_satip_rtsp },
#endif
#if ENABLE_SATIP_CLIENT
    {   0, "nosatip",    N_("Disable SAT>IP client"),
      OPT_BOOL, &opt_nosatip },
    {   0, "satip_xml",  N_("URL with the SAT>IP server XML location"),
      OPT_STR_LIST, &opt_satip_xml },
#endif
    {   0, NULL,         N_("Server connectivity"),    OPT_BOOL, NULL         },
    { '6', "ipv6",       N_("Listen on IPv6"),         OPT_BOOL, &opt_ipv6    },
    { 'b', "bindaddr",   N_("Specify bind address"),   OPT_STR,  &opt_bindaddr},
    {   0, "http_port",  N_("Specify alternative http port"),
      OPT_INT, &tvheadend_webui_port },
    {   0, "http_root",  N_("Specify alternative http webroot"),
      OPT_STR, &tvheadend_webroot },
    {   0, "htsp_port",  N_("Specify alternative htsp port"),
      OPT_INT, &tvheadend_htsp_port },
    {   0, "htsp_port2", N_("Specify extra htsp port"),
      OPT_INT, &tvheadend_htsp_port_extra },
    {   0, "useragent",  N_("Specify User-Agent header for the http client"),
      OPT_STR, &opt_user_agent },
    {   0, "xspf",       N_("Use XSPF playlist instead of M3U"),
      OPT_BOOL, &opt_xspf },

    {   0, NULL,        N_("Debug options"),           OPT_BOOL, NULL         },
    { 'd', "stderr",    N_("Enable debug on stderr"),  OPT_BOOL, &opt_stderr  },
    { 's', "syslog",    N_("Enable debug to syslog"),  OPT_BOOL, &opt_syslog  },
    { 'S', "nosyslog",  N_("Disable syslog (all messages)"), OPT_BOOL, &opt_nosyslog },
    { 'l', "logfile",   N_("Enable debug to file"),    OPT_STR,  &opt_logpath },
    {   0, "debug",     N_("Enable debug subsystems"),  OPT_STR,  &opt_log_debug },
#if ENABLE_TRACE
    {   0, "trace",     N_("Enable trace subsystems"), OPT_STR,  &opt_log_trace },
#endif
    {   0, "fileline",  N_("Add file and line numbers to debug"), OPT_BOOL, &opt_fileline },
    {   0, "threadid",  N_("Add the thread ID to debug"), OPT_BOOL, &opt_threadid },
#if ENABLE_LIBAV
    {   0, "libav",     N_("More verbose libav log"),  OPT_BOOL, &opt_libav },
#endif
    {   0, "uidebug",   N_("Enable web UI debug (non-minified JS)"), OPT_BOOL, &opt_uidebug },
    { 'A', "abort",     N_("Immediately abort"),       OPT_BOOL, &opt_abort   },
    { 'D', "dump",      N_("Enable coredumps for daemon"), OPT_BOOL, &opt_dump },
    {   0, "noacl",     N_("Disable all access control checks"),
      OPT_BOOL, &opt_noacl },
    {   0, "nobat",     N_("Disable DVB bouquets"),
      OPT_BOOL, &opt_nobat },
    { 'j', "join",      N_("Subscribe to a service permanently"),
      OPT_STR, &opt_subscribe },


#if ENABLE_TSFILE || ENABLE_TSDEBUG
    { 0, NULL, N_("Testing options"), OPT_BOOL, NULL },
    { 0, "tsfile_tuners", N_("Number of tsfile tuners"), OPT_INT, &opt_tsfile_tuner },
    { 0, "tsfile", N_("tsfile input (mux file)"), OPT_STR_LIST, &opt_tsfile },
#endif
#if ENABLE_TSDEBUG
    { 0, "tsdebug", N_("Output directory for tsdebug"), OPT_STR, &tvheadend_tsdebug },
#endif

  };

  /* Get current directory */
  tvheadend_cwd0 = dirname(tvh_strdupa(argv[0]));
  tvheadend_cwd = dirname(tvh_strdupa(tvheadend_cwd0));

  /* Set locale */
  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");
  tvh_gettext_init();

  /* make sure the timezone is set */
  tzset();

  /* Process command line */
  for (i = 1; i < argc; i++) {

    /* Find option */
    cmdline_opt_t *opt
      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);
    if (!opt) {
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 _("invalid option specified [%s]"), argv[i]);
      continue;
    }

    /* Process */
    if (opt->type == OPT_BOOL)
      *((int*)opt->param) = 1;
    else if (++i == argc)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 _("option %s requires a value"), opt->lopt);
    else if (opt->type == OPT_INT)
      *((int*)opt->param) = atoi(argv[i]);
    else if (opt->type == OPT_STR_LIST) {
      str_list_t *strl = opt->param;
      if (strl->num < strl->max)
        strl->str[strl->num++] = argv[i];
    }
    else
      *((char**)opt->param) = argv[i];

    /* Stop processing */
    if (opt_help)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
    if (opt_version)
      show_version(argv[0]);
  }

  /* Additional cmdline processing */
  if (opt_nobat)
    dvb_bouquets_parse = 0;
#if ENABLE_LINUXDVB
  if (!opt_dvb_adapters) {
    adapter_mask = ~0;
  } else {
    char *p, *e;
    char *r = NULL;
    char *dvb_adapters = strdup(opt_dvb_adapters);
    adapter_mask = 0x0;
    i = 0;
    p = strtok_r(dvb_adapters, ",", &r);
    while (p) {
      int a = strtol(p, &e, 10);
      if (*e != 0 || a > 31) {
        fprintf(stderr, _("Invalid adapter number '%s'\n"), p);
        free(dvb_adapters);
        return 1;
      }
      i = 1;
      if (a < 0)
        adapter_mask = 0;
      else
        adapter_mask |= (1 << a);
      p = strtok_r(NULL, ",", &r);
    }
    free(dvb_adapters);
    if (!i) {
      fprintf(stderr, "%s", _("No adapters specified!\n"));
      return 1;
    }
  }
#endif
  if (tvheadend_webroot) {
    char *tmp;
    if (*tvheadend_webroot == '/')
      tmp = strdup(tvheadend_webroot);
    else {
      tmp = malloc(strlen(tvheadend_webroot)+2);
      *tmp = '/';
      strcpy(tmp+1, tvheadend_webroot);
    }
    if (tmp[strlen(tmp)-1] == '/')
      tmp[strlen(tmp)-1] = '\0';
    tvheadend_webroot = tmp;
  }
  tvheadend_webui_debug = opt_uidebug;

  /* Setup logging */
  if (isatty(2))
    log_options |= TVHLOG_OPT_DECORATE;
  if (opt_stderr || opt_syslog || opt_logpath) {
    if (!opt_log_trace && !opt_log_debug)
      log_debug      = "all";
    log_level      = LOG_DEBUG;
    if (opt_stderr)
      log_options   |= TVHLOG_OPT_DBG_STDERR;
    if (opt_syslog)
      log_options   |= TVHLOG_OPT_DBG_SYSLOG;
    if (opt_logpath)
      log_options   |= TVHLOG_OPT_DBG_FILE;
  }
  if (opt_nosyslog)
    log_options &= ~(TVHLOG_OPT_SYSLOG|TVHLOG_OPT_DBG_SYSLOG);
  if (opt_fileline)
    log_options |= TVHLOG_OPT_FILELINE;
  if (opt_threadid)
    log_options |= TVHLOG_OPT_THREAD;
  if (opt_libav)
    log_options |= TVHLOG_OPT_LIBAV;
  if (opt_log_trace) {
    log_level  = LOG_TRACE;
    log_trace  = opt_log_trace;
  }
  if (opt_log_debug)
    log_debug  = opt_log_debug;
    
  tvhlog_init(log_level, log_options, opt_logpath);
  tvhlog_set_debug(log_debug);
  tvhlog_set_trace(log_trace);
  tvhinfo("main", "Log started");
 
  signal(SIGPIPE, handle_sigpipe); // will be redundant later
  signal(SIGILL, handle_sigill);   // see handler..

  /* Set priviledges */
  if(opt_fork || opt_group || opt_user) {
    const char *homedir;
    struct group  *grp = getgrnam(opt_group ?: "video");
    struct passwd *pw  = opt_user ? getpwnam(opt_user) : NULL;

    if(grp != NULL) {
      gid = grp->gr_gid;
    } else {
      gid = 1;
    }

    if (pw != NULL) {
      if (getuid() != pw->pw_uid) {
        gid_t glist[16];
        int gnum;
        gnum = get_user_groups(pw, glist, ARRAY_SIZE(glist));
        if (gnum > 0 && setgroups(gnum, glist)) {
          char buf[256] = "";
          int i;
          for (i = 0; i < gnum; i++)
            snprintf(buf + strlen(buf), sizeof(buf) - 1 - strlen(buf),
                     ",%d", glist[i]);
          tvhlog(LOG_ALERT, "START",
                 "setgroups(%s) failed, do you have permission?", buf+1);
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
  }

  uuid_init();
  config_boot(opt_config, gid, uid);
  tcp_server_preinit(opt_ipv6);
  http_server_init(opt_bindaddr);    // bind to ports only
  htsp_init(opt_bindaddr);	     // bind to ports only
  satip_server_init(opt_satip_rtsp); // bind to ports only

  if (opt_fork)
    pidfile = tvh_fopen(opt_pidpath, "w+");

  if (gid != -1 && (getgid() != gid) && setgid(gid)) {
    tvhlog(LOG_ALERT, "START",
           "setgid(%d) failed, do you have permission?", gid);
    return 1;
  }
  if (uid != -1 && (getuid() != uid) && setuid(uid)) {
    tvhlog(LOG_ALERT, "START",
           "setuid(%d) failed, do you have permission?", uid);
    return 1;
  }

  /* Daemonise */
  if(opt_fork) {
    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    /* Make dumpable */
    if (opt_dump) {
#ifdef PLATFORM_LINUX
      if (chdir("/tmp"))
        tvhwarn("START", "failed to change cwd to /tmp");
      prctl(PR_SET_DUMPABLE, 1);
#else
      tvhwarn("START", "Coredumps not implemented on your platform");
#endif
    }

    umask(0);
  }

  tvheadend_running = 1;

  /* Start log thread (must be done post fork) */
  tvhlog_start();

  /* Alter logging */
  if (opt_fork)
    tvhlog_options &= ~TVHLOG_OPT_STDERR;
  if (!isatty(2))
    tvhlog_options &= ~TVHLOG_OPT_DECORATE;
  
  /* Initialise clock */
  pthread_mutex_lock(&global_lock);
  time(&dispatch_clock);

  /* Signal handling */
  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);
  trap_init(argv[0]);

  /* SSL library init */
  OPENSSL_config(NULL);
  SSL_load_error_strings();
  SSL_library_init();
  /* Rand seed */
  randseed.thread_id = (void *)main_tid;
  gettimeofday(&randseed.tv, NULL);
  uuid_random(randseed.ru, sizeof(randseed.ru));
  RAND_seed(&randseed, sizeof(randseed));

  /* Initialise configuration */
  notify_init();
  idnode_init();
  spawn_init();
  config_init(opt_nobackup == 0);

  /**
   * Initialize subsystems
   */

  epg_in_load = 1;

  tvhthread_create(&tasklet_tid, NULL, tasklet_thread, NULL, "tasklet");

  dbus_server_init(opt_dbus, opt_dbus_session);

  intlconv_init();
  
  api_init();

  fsmonitor_init();

  libav_init();

  tvhtime_init();

  profile_init();

  imagecache_init();

  http_client_init(opt_user_agent);
  esfilter_init();

  bouquet_init();

  service_init();

  dvb_init();

#if ENABLE_MPEGTS
  mpegts_init(adapter_mask, opt_nosatip, &opt_satip_xml,
              &opt_tsfile, opt_tsfile_tuner);
#endif

  channel_init();

  bouquet_service_resolve();

  subscription_init();

  dvr_config_init();

  access_init(opt_firstrun, opt_noacl);

#if ENABLE_TIMESHIFT
  timeshift_init();
#endif

  tcp_server_init();
  webui_init(opt_xspf);
#if ENABLE_UPNP
  upnp_server_init(opt_bindaddr);
#endif

  service_mapper_init();

  descrambler_init();

  epggrab_init();
  epg_init();

  dvr_init();

  dbus_server_start();

  http_server_register();
  satip_server_register();
  htsp_register();

  if(opt_subscribe != NULL)
    subscription_dummy_join(opt_subscribe, 1);

  avahi_init();
  bonjour_init();

  epg_updated(); // cleanup now all prev ref's should have been created
  epg_in_load = 0;

  pthread_mutex_unlock(&global_lock);

  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
         "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s",
         tvheadend_version,
         getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)),
         hts_settings_get_root());

  if(opt_abort)
    abort();

  mainloop();

#if ENABLE_DBUS_1
  tvhftrace("main", dbus_server_done);
#endif
#if ENABLE_UPNP
  tvhftrace("main", upnp_server_done);
#endif
  tvhftrace("main", satip_server_done);
  tvhftrace("main", htsp_done);
  tvhftrace("main", http_server_done);
  tvhftrace("main", webui_done);
  tvhftrace("main", fsmonitor_done);
  tvhftrace("main", http_client_done);
  tvhftrace("main", tcp_server_done);

  // Note: the locking is obviously a bit redundant, but without
  //       we need to disable the gtimer_arm call in epg_save()
  pthread_mutex_lock(&global_lock);
  tvhftrace("main", epg_save);

#if ENABLE_TIMESHIFT
  tvhftrace("main", timeshift_term);
#endif
  pthread_mutex_unlock(&global_lock);

  tvhftrace("main", epggrab_done);
#if ENABLE_MPEGTS
  tvhftrace("main", mpegts_done);
#endif
  tvhftrace("main", descrambler_done);
  tvhftrace("main", service_mapper_done);
  tvhftrace("main", service_done);
  tvhftrace("main", channel_done);
  tvhftrace("main", bouquet_done);
  tvhftrace("main", dvr_done);
  tvhftrace("main", subscription_done);
  tvhftrace("main", access_done);
  tvhftrace("main", epg_done);
  tvhftrace("main", avahi_done);
  tvhftrace("main", bonjour_done);
  tvhftrace("main", imagecache_done);
  tvhftrace("main", lang_code_done);
  tvhftrace("main", api_done);

  tvhtrace("main", "tasklet enter");
  pthread_cond_signal(&tasklet_cond);
  pthread_join(tasklet_tid, NULL);
  tvhtrace("main", "tasklet thread end");
  tasklet_flush();
  tvhtrace("main", "tasklet leave");

  tvhftrace("main", hts_settings_done);
  tvhftrace("main", dvb_done);
  tvhftrace("main", lang_str_done);
  tvhftrace("main", esfilter_done);
  tvhftrace("main", profile_done);
  tvhftrace("main", intlconv_done);
  tvhftrace("main", urlparse_done);
  tvhftrace("main", idnode_done);
  tvhftrace("main", notify_done);
  tvhftrace("main", spawn_done);

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");
  tvhlog_end();

  tvhftrace("main", config_done);

  if(opt_fork)
    unlink(opt_pidpath);
    
#if ENABLE_TSFILE
  free(opt_tsfile.str);
#endif
  free(opt_satip_xml.str);

  /* OpenSSL - welcome to the "cleanup" hell */
  ENGINE_cleanup();
  RAND_cleanup();
  CRYPTO_cleanup_all_ex_data();
  EVP_cleanup();
  CONF_modules_free();
#ifndef OPENSSL_NO_COMP
  COMP_zlib_cleanup();
#endif
  ERR_remove_state(0);
  ERR_free_strings();
#ifndef OPENSSL_NO_COMP
  sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
#endif
  /* end of OpenSSL cleanup code */

#if ENABLE_DBUS_1
  extern void dbus_shutdown(void);
  if (opt_dbus) dbus_shutdown();
#endif
  tvh_gettext_done();
  return 0;
}

/**
 *
 */
void
tvh_str_set(char **strp, const char *src)
{
  free(*strp);
  *strp = src ? strdup(src) : NULL;
}


/**
 *
 */
int
tvh_str_update(char **strp, const char *src)
{
  if(src == NULL)
    return 0;
  free(*strp);
  *strp = strdup(src);
  return 1;
}


/**
 *
 */
void
scopedunlock(pthread_mutex_t **mtxp)
{
  pthread_mutex_unlock(*mtxp);
}
Пример #4
0
int main(int argc, char **argv)
{
	int w, h;

	w = 640;
	h = 480;
	for (;;) {
		int index;
		int c;

		c = getopt_long(argc, argv, short_options, long_options,
				&index);
		if (c < 0)
			break;

		switch (c) {
		case 0:	/* getopt_long() flag */
			break;
		case 'd':
			dev_name = optarg;
			break;
		case 'f':
			if (sscanf(optarg, "%dx%d", &w, &h) != 2) {
				fprintf(stderr, "Invalid image format\n");
				exit(EXIT_FAILURE);
			}
			break;
		case 'g':
			grab = 1;
			break;
		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);
		case 'i':
			info = 1;
			break;
		case 'm':
			switch (optarg[0]) {
			case 'm':
				io = V4L2_MEMORY_MMAP;
				break;
			case 'r':
				io = IO_METHOD_READ;
				break;
			case 'u':
				io = V4L2_MEMORY_USERPTR;
				break;
			default:
				usage(stderr, argc, argv);
				exit(EXIT_FAILURE);
			}
			break;
		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}
	if (optind < argc)
		dev_name = argv[optind];

	open_device();
	init_device(w, h);
	start_capturing();
	if (info) {
		if (io != V4L2_MEMORY_MMAP)
			info = NFRAMES;
		gettimeofday(&cur_time, 0);
	}
#ifdef WITH_GTK
	if (grab)
		get_frame();
	else
		main_frontend(argc, argv);
#else
	mainloop();
#endif
	stop_capturing();
	uninit_device();
	close_device();
	return 0;
}
Пример #5
0
int cli_main(int argc, char* argv[])
{
  const char* server_name = 0;
  const char* env;

  msg_debug_init();
  encr_start();
  prep_sender();
  service = argv[0];
  if (argc > 1
      && argv[1][0] != '-'
      && argv[1][0] != '+') {
    server_name = argv[1];
    ++argv;
    --argc;
  }
  if (argc > 1)
    load_patterns(argv + 1);

  if (server_name == 0
      && (server_name = getenv("SERVER")) == 0)
    die1(1, "Server address not named on command line nor in $SERVER");
  if (!resolve_ipv4name(server_name, &ip))
    die3(1, "Could not resolve '", server_name, "'");

  brandom_init();
  if ((env = getenv("KEYDIR")) != 0)
    keydir = env;
  load_keys(server_name);

  if ((env = getenv("PORT")) != 0)
    port = strtoul(env, 0, 10);
  if (port == 0)
    port = 11014;
  if ((sock = socket_udp()) == -1)
    die1sys(1, "Could not create UDP socket");
  if (!socket_connect4(sock, &ip, port))
    die1sys(1, "Could not bind socket");
  if (!str_ready(&packet, 65535)
      || !str_ready(&rpacket, 4+4+8+256*5))
    die1(1, "Out of memory");

  getenvu("ACK_TIMEOUT", &ack_timeout);
  getenvu("CID_TIMEOUT", &cid_timeout);
  getenvu("RETRANSMITS", &retransmits);
  getenvu("READWAIT", &readwait);
  getenvu("STARTLINES", &startlines);
  if (getenv("EXITONEOF") != 0)
    exitoneof = 1;

  if (getenv("NOFILES") == 0 && getenv("NOFILE") == 0)
    buffer = buffer_file_init();
  else
    buffer = buffer_nofile_init();

  sig_all_catch(sigfn);
  exitasap = 0;

  mainloop();
  return 0;
}
Пример #6
0
int main(int argc, char **argv)
{
    char *env = NULL;
    simulation_data sim;
    simulation_data_ctor(&sim);

#ifdef PARALLEL
    /* Initialize MPI */
    MPI_Init(&argc, &argv);

    /* Create a new communicator. */
    if (MPI_Comm_dup(MPI_COMM_WORLD, &sim.par_comm) != MPI_SUCCESS)
        sim.par_comm = MPI_COMM_WORLD;

    MPI_Comm_rank (sim.par_comm, &sim.par_rank);
    MPI_Comm_size (sim.par_comm, &sim.par_size);
#endif

    /* Initialize environment variables. */
    SimulationArguments(argc, argv);

#ifdef PARALLEL
    /* Install callback functions for global communication. */
    VisItSetBroadcastIntFunction2(visit_broadcast_int_callback, (void*)&sim);
    VisItSetBroadcastStringFunction2(visit_broadcast_string_callback, (void*)&sim);

    /* Tell libsim whether the simulation is parallel. */
    VisItSetParallel(sim.par_size > 1);
    VisItSetParallelRank(sim.par_rank);

    /* Tell libsim which communicator to use. You must pass the address of
     * an MPI_Comm object.
     */
    VisItSetMPICommunicator((void *)&sim.par_comm);
#endif

    /* Only read the environment on rank 0. This could happen before MPI_Init if
     * we are using an MPI that does not like to let us spawn processes but we
     * would not know our processor rank.
     */
    if(sim.par_rank == 0)
        env = VisItGetEnvironment();

    /* Pass the environment to all other processors collectively. */
    VisItSetupEnvironment2(env);
    if(env != NULL)
        free(env);

    /* Write out .sim file that VisIt uses to connect. Only do it
     * on processor 0.
     */
    /* CHANGE 3 */
    if(sim.par_rank == 0)
    {
        /* Write out .sim file that VisIt uses to connect. */
        VisItInitializeSocketAndDumpSimFile(
#ifdef PARALLEL
            "ghostcells_par",
#else
            "ghostcells",
#endif
            "Demonstrate ghost cells on different mesh types",
            "/path/to/where/sim/was/started",
            NULL, NULL, NULL);
    }

    /* Read input problem setup, geometry, data.*/
    read_input_deck(&sim);

    /* Call the main loop. */
    mainloop(&sim);

    simulation_data_dtor(&sim);
#ifdef PARALLEL
    MPI_Finalize();
#endif

    return 0;
}
Пример #7
0
Файл: main.c Проект: huangxw/gx
int main(int argc, char *argv[])
{
    struct sigaction         act, old;
    struct addrinfo          ask, *res;
    struct sockaddr_storage  ss;
    int c, opt, rc, ss_len;
    char host[INET6_ADDRSTRLEN + 1];
    char serv[16];
    const char options[] = "hd" "p:";
    memset(&ask, 0, sizeof(ask));

    /* parse options */
    while(1) {
        if (-1 == (c = getopt(argc, argv, options))) {
            break;
        }

        switch (c) {
            case 'h':
                usage(argv[0]);
                break;
            case 'p':
                listen_port = optarg;
                break;
            default:
                exit(1);
        }
    }

    /* bind to socket */
    memset(&ask, 0, sizeof(ask));
    ask.ai_flags = AI_PASSIVE;

    if (listen_ip) {
        ask.ai_flags |= AI_CANONNAME;
    }

    ask.ai_socktype = SOCK_STREAM;
    ask.ai_family = PF_INET;

    if (0 != (rc = getaddrinfo(listen_ip, listen_port, &ask, &res))) {
        fprintf(stderr, "getaddrinfo (ipv4): %s\n", gai_strerror(rc));
        exit(1);
    }

    if (-1 == (slisten = socket(res->ai_family, res->ai_socktype, res->ai_protocol))) {
        exit(1);
    }

    if (-1 == slisten) {
        exit(1);
    }

    close_on_exec(slisten);
    memcpy(&ss, res->ai_addr, res->ai_addrlen);
    ss_len = res->ai_addrlen;

    if (0 != (rc = getnameinfo((struct sockaddr *)&ss, ss_len,
                               host, INET6_ADDRSTRLEN, serv, 15,
                               NI_NUMERICHOST | NI_NUMERICSERV))) {
        exit(1);
    }

    tcp_port = atoi(serv);
    opt = 1;
    setsockopt(slisten, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    fcntl(slisten, F_SETFL, O_NONBLOCK);

    if (-1 == bind(slisten, (struct sockaddr *) &ss, ss_len)) {
        exit(1);
    }

    if (-1 == listen(slisten, 2 * max_conn)) {
        exit(1);
    }

    init_quote();
    printf("gx start!\n\n");
#if defined(linux)
    printf("###############################\n");
    printf("HOST INFO:\n");
    host_info();
#endif
    printf("###############################\n");
    printf("SERVER INFO:\n");
    /* setup signal handler */
    memset(&act, 0, sizeof(act));
    sigemptyset(&act.sa_mask);
    act.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &act, &old);
    sigaction(SIGCHLD, &act, &old);
    act.sa_handler = catchsig;
    sigaction(SIGHUP, &act, &old);
    sigaction(SIGTERM, &act, &old);
    sigaction(SIGINT, &act, &old);

    /* go! */
    if (nthreads > 1) {
        int i;
        threads = malloc(sizeof(pthread_t) * nthreads);

        for (i = 1; i < nthreads; i++) {
            pthread_create(threads + i, NULL, mainloop, threads + i);
            pthread_detach(threads[i]);
        }
    }

    mainloop(NULL);
    fprintf(stderr, "bye...\n");
    exit(0);
}
Пример #8
0
int main(int argc, char **argv)
{
  int result, index;
  char *bptr, *tptr;
  char *app;
  int i, j, c;
  struct getap_state *gs;

  index = 0;
  app = argv[0];
  i = j = 1;

  tptr = "tgtap%d";
  bptr = "/proc/%d/hw/ioreg/ten_Gbe_v2";

  gs = malloc(sizeof(struct getap_state));
  if(gs == NULL){
    fprintf(stderr, "%s: unable to allocate %d bytes\n", app, sizeof(struct getap_state));
    return EX_USAGE;
  }

  gs->s_address_name[0] = '\0';
  gs->s_gateway_name[0] = '\0';
  gs->s_mac_name[0] = '\0';
  gs->s_port = 0;

  gs->s_verbose = 1;
  gs->s_testing = 0;

  while (i < argc) {
    if (argv[i][0] == '-') {
      c = argv[i][j];
      switch (c) {
        case 'h' :
          usage(app);
          return EX_OK;
        case 'v' :
          gs->s_verbose++;
          j++;
          break;
        case 'T' :
          gs->s_testing++;
          j++;
          break;
        case 'a' :
        case 'g' :
        case 'm' :
        case 'p' :
        case 'n' :
        case 't' : 
        case 'b' : 
          j++;
          if (argv[i][j] == '\0') {
            j = 0;
            i++;
          }
          if (i >= argc) {
            fprintf(stderr, "%s: -%c needs a parameter\n", app, c);
            return EX_USAGE;
          }

          switch(c){
            case 'a' :
              strncpy(gs->s_address_name, argv[i] + j, IP_BUFFER - 1);
              gs->s_address_name[IP_BUFFER - 1] = '\0';
              break;
            case 'g' :
              strncpy(gs->s_gateway_name, argv[i] + j, IP_BUFFER - 1);
              gs->s_gateway_name[IP_BUFFER - 1] = '\0';
              break;
            case 'm' :
              strncpy(gs->s_mac_name, argv[i] + j, MAC_BUFFER - 1);
              gs->s_mac_name[MAC_BUFFER - 1] = '\0';
            case 'p' :
              gs->s_port = atoi(argv[i] + j);
              break;
            case 'n' :
              index = atoi(argv[i] + j);
              break;
            case 't' :
              tptr = NULL;
              strncpy(gs->s_tap_name, argv[i] + j, NAME_BUFFER - 1);
              gs->s_tap_name[NAME_BUFFER - 1] = '\0';
              break;
            case 'b' :
              bptr = NULL;
              strncpy(gs->s_borph_name, argv[i] + j, NAME_BUFFER - 1);
              gs->s_borph_name[NAME_BUFFER - 1] = '\0';
              break;
          }

          i++;
          j = 1;
          break;

        case '\0':
          j = 1;
          i++;
          break;
        default:
          fprintf(stderr, "%s: unknown option -%c\n", app, argv[i][j]);
          return EX_USAGE;
      }
    } else {
      fprintf(stderr, "%s: bad argument %s\n", app, argv[i]);
      return EX_USAGE;
    }
  }

  if(tptr){
    result = snprintf(gs->s_tap_name, NAME_BUFFER - 1, tptr, index); 
    if((result < 0) || (result >= NAME_BUFFER)){
      fprintf(stderr, "unable to expand %s: Value too long\n", tptr);
      return EX_USAGE;
    }
  }
  if(bptr){
    result = snprintf(gs->s_borph_name, NAME_BUFFER - 1, bptr, getpid()); 
    if((result < 0) || (result >= NAME_BUFFER)){
      fprintf(stderr, "unable to expand %s: Value too long\n", bptr);
      return EX_USAGE;
    }
  }
  if(gs->s_address_name[0] == '\0'){
    fprintf(stderr, "%s: need an ip address\n", app);
    return EX_OSERR;
  }

  if(gs->s_gateway_name[0] == '\0'){
    /* risky, gateware may not like it */
    strncpy(gs->s_gateway_name, gs->s_address_name, IP_BUFFER);
  }

  if(gs->s_mac_name[0] == '\0'){
    make_mac(gs);
  }

  if(gs->s_verbose){
    printf("%s: tap interface name: %s\n", app, gs->s_tap_name);
    printf("%s: borph file: %s\n", app, gs->s_borph_name);
    printf("%s: %s file interface \n", app, gs->s_testing ? "testing" : "borph");
    printf("%s: ip address %s\n", app, gs->s_address_name);
    printf("%s: mac address %s\n", app, gs->s_mac_name);
  }

  gs->s_tfd = tap_open(gs->s_tap_name);
  if(gs->s_tfd < 0){
    fprintf(stderr, "%s: unable to set up tap device %s: %s\n", app, gs->s_tap_name, strerror(errno));
    return EX_OSERR;
  }

  if(setup_borph(gs) < 0){
    fprintf(stderr, "%s: unable to initialise borph register file %s: %s\n", app, gs->s_borph_name, strerror(errno));
    return EX_OSERR;
  }

  if(setup_tap(gs)){
    fprintf(stderr, "%s: unable to configure tap device %s\n", app, gs->s_tap_name);
    return EX_OSERR;
  }

  printf("%s: my arp table index %d\n", app, gs->s_index);

  if(gs->s_verbose){
    printf("%s: my network: 0x%08x\n", app, gs->s_network_binary);
  }

  run = 1;

  /* signal stuff */

  mainloop(gs);

  tap_close(gs->s_tfd);
  close(gs->s_bfd);

  return EX_OK;
}
Пример #9
0
int camera_capture (char *img_name, int frame_num) {
#else
int main (int argc, char ** argv) {
#endif
	signal(SIGINT, quit_handler);
	signal(SIGTERM, quit_handler);
	signal(SIGUSR1, pause_handler);

	dev_name = "/dev/video0";
	G_osd_text[0] = 0;
	G_jc.quality = 75;
	#if defined(USE_AS_MODULE)
	type = TYPE_JPEG;
	default_name = img_name;
	G_frames = frame_num;
	#else
	for (;;) {
		int index;
		int c;

		c = getopt_long (argc, argv,
				short_options, long_options,
				&index);

		if (-1 == c)
			break;

		switch (c) {
			case 0: /* getopt_long() flag */
				break;

			case 'd':
				dev_name = optarg;
				break;
			case 'h':
				usage (stdout, argc, argv);
				exit (EXIT_SUCCESS);
			case 'j':
				type = TYPE_JPEG;
				default_name = "output.jpg";
				break;
			case 'J':
				type = TYPE_MJPEG;
				default_name = "output.mjpg";
				break;
			case 'q':
				G_jc.quality = atoi(optarg);
				if (G_jc.quality < 10 || G_jc.quality > 90) {
					fprintf(stderr, "values from 10-90 only\n");
					exit(EXIT_FAILURE);
				}
				break;
			case 'p':
				G_pal = 1;
				G_framerate = 25;
				break;
			case 'v':
				G_svideo = 1;
				break;
			case 'f':
				G_frames = atoi(optarg);
				break;
			default:
				usage (stderr, argc, argv);
				exit (EXIT_FAILURE);
		}
	}
	#endif
	out_name = out_name ? out_name : default_name;

	if (strcmp(out_name, "-") == 0)
		G_fvout = stdout;
	else
		G_fvout = fopen(out_name, "w+");

	if (G_fvout == NULL) {
		fprintf(stderr, "invalid filename %s, exiting\n", out_name);
		exit (EXIT_FAILURE);
	}
#ifdef USE_MP4
	if (remux) {
		if (G_fvout == stdout) {
			fprintf(stderr, "MP4 cannot be used with stdout\n");
			exit (EXIT_FAILURE);
		}
		mp4_file_pointer(remux, G_fvout);
	}
#endif
	if (type != TYPE_JPEG) {
		fprintf(stderr, "Saving video to %s\n", out_name);
	} else {
		fprintf(stderr, "Saving JPG clips in this directory\n");
		fprintf(stderr, "Type ls -al *.jpg after demo stops\n");
	}

	open_device ();

	init_device ();

	atexit(cleanup);

	start_capturing ();
	mainloop ();

	G_aud_cap = 0;

	return 0;
}
Пример #10
0
int main(int argc, char **argv)
{
  aThisApp.start(argc,argv);
  char *fname=(char *)NULL;
  if(aThisApp.argc>1) fname=aThisApp.argv[1];
  if(aThisApp.argc<2) {
    ARequesterFile *ww=new ARequesterFile();
    if(ww) fname=ww->show((char *)"Open file");
    else std::cerr<<"(Didn't get a request window)\n";
    if(ww) delete ww;
    ww=NULL;
  }
  if(!fname) {
    char msg[256];
    sprintf(msg,(char *)"usage: nupac {board filename}",aThisApp.argv[0]);
    ADialogMsg mw((char *)"Error!",msg);
    //return 5;
    return 0;
  }
  char *bname=fname;
  unsigned int t;
  char *temp;
  InitGame();
  for(t=1;t<aThisApp.argc;t++) {
    temp=aThisApp.argv[t];
    if(temp[0]=='-') {
      if(temp[1]=='d') {
        DisplayName=aThisApp.argv[t+1]; t++;  std::cerr<<"Display name is ";
        std::cerr<<DisplayName<<"\n";
      } else
      if(temp[1]=='p') { FOOBAR_PACMOVE=false; } else
      if(temp[1]=='m') { FOOBAR_MONO=1; } else
      if(temp[1]=='s') {
        sscanf(aThisApp.argv[t+1],(char *)"%d",(unsigned int *)&SPEED);
        t++;
        std::cerr<<"New speed is";
        std::cerr<<SPEED<<"\n";
      } else
      std::cerr<<aThisApp.argv[0]<<": bad command option\n";
    }
    else {
      bname=temp;
    }
  }
  std::cerr<<"Initial board is "<<bname<<"\n";
  DoTitle();
  QUITING=false;
  while(!QUITING) {
    std::cerr<<"Looping in main while !QUITING...\n";
    //StartLoading();
    CleanupBitmaps();
    if(bname) ReadBoardFromDisk(bname);
    else boardError=true;
    if(boardError) {
      QUITING=true;
    }
    else {
      ExploreBoard();
      SetupBitmaps();
      if(!QUITING) {
        SetSpriteShapes();
        DrawScreen();
        UpdateScore();  InitRound();
        DIED=true;
        while(DIED) {
          mainloop();
          UpdateScore();  InitRound();
          if(QUITING) DoQuit();
        }
      }
      bname=NextBoard;  boardError=false;
    }
  }
  std::cerr<<"Normal exit\n";
  return 0;
}
Пример #11
0
int main(int argc, char **argv)
{
        /* The Global MIPS State */
        MIPS_state_t mips_state;

        rs232in_fd = rs232out_fd = -1;
        char *serial_input_file = NULL;
        char *serial_output_file = NULL;

        for (;;) {
                int c;
                int option_index = 0;

                c = getopt_long(argc, argv, "tf:i:o:",
                                long_options, &option_index);
                if (c == -1)
                        break;

                switch (c) {
                case 0:
                        break;

                case 'f':
                        printf("file %s\n", filename = optarg);
                        break;

                case 'i': serial_input_file = optarg; break;
                case 'o': serial_output_file = optarg; break;
                case '?':
                        usage(argv[0]);
                        break;

                case 1000: icache_way_lines_log2     = atoi(optarg); break;
                case 1001: icache_words_in_line_log2 = atoi(optarg); break;
                case 1002: dcache_way_lines_log2     = atoi(optarg); break;
                case 1003: dcache_words_in_line_log2 = atoi(optarg); break;

                default:
                        printf ("?? getopt returned character code 0%o ??\n", c);
                }
        }

        if (optind >= argc) {
                usage(argv[0]);
        }

        while (optind < argc) {
                readelf(argv[optind++]);
        }

        int is_bidir = serial_output_file && serial_input_file &&
                strcmp(serial_input_file, serial_output_file) == 0;

        if (serial_input_file) {
                printf("serial input %s\n", serial_input_file);
                rs232in_fd = open(serial_input_file, (is_bidir ? O_RDWR : O_RDONLY) | O_NONBLOCK);
                if (rs232in_fd < 0)
                        perror(optarg), exit(1);

                {
                        /* Turn off echo */
                        struct termios t;
                        if (tcgetattr(rs232in_fd, &t))
                                /*perror("getattr")*/;
                        else {
                                t.c_lflag &= ~(ECHO|ECHOE|ECHOK);
                                if (tcsetattr(rs232in_fd, TCSANOW, &t))
                                        perror("setattr");
                        }
                }
        }

        if (serial_output_file && !is_bidir) {
                printf("serial output %s\n", serial_output_file);
                rs232out_fd = open(serial_output_file, O_WRONLY | O_NONBLOCK);
                if (rs232out_fd < 0)
                        perror(optarg), exit(1);
        }

        if (is_bidir)
                rs232out_fd = rs232in_fd;

        gettimeofday(&stat_start_time, NULL);

        switch (run) {
        case '1':
                if (enable_graphics)
                        start_sdl();
                atexit(print_stats);
                signal(SIGINT, exit);
                mips_state.pc = program_entry;
                init_reg_use_map();

                if (screen) {
                        SDL_CreateThread((int (*)(void *))run_simple, &mips_state);
                        mainloop();
                } else
                        run_simple(&mips_state);
                break;

        case 'b':
        case 'r':
        case 'd':
        case 'm':
                dump_cache_init_files();
                break;

        case 't':
                dump_tinymon();
                exit(0);

        default:
                printf("No XX-run option given\n");
                exit(1);
        }

        if (enable_testcases) {
                printf("Test ");
                if (mips_state.r[7] == 0x1729) {
                        printf("SUCCEED!\n");
                        exit(0);
                } else {
                        printf("FAILED!  r7 = 0x%08x != 0x1729\n", mips_state.r[7]);
                        exit(1);
                }
        }

        exit(0);
}
Пример #12
0
Queue* eventq(void)
{
  return &mainloop()->eventq;
}
Пример #13
0
Queue* drawq(void)
{
  return &mainloop()->drawq;
}
Пример #14
0
uv_loop_t *eventloop(void)
{
  return &mainloop()->uv;
}
Пример #15
0
/**
  @todo Possibility to alter priority of initial module somehow
  */
int main(int argc, char *argv[])
{
    fprintf(stderr, "DSME %s starting up\n", STRINGIFY(PRG_VERSION));

    // do the first kick right away
    if (!dsme_wd_init()) {
        fprintf(stderr, ME "no WD's opened; WD kicking disabled\n");
    }
    dsme_wd_kick();

    trap_terminating_signals();

    // set up signal handler
    signal(SIGHUP,  signal_handler);
    signal(SIGINT,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGPIPE, signal_handler);
    signal(SIGCHLD, signal_handler);
#ifdef DSME_SYSTEMD_ENABLE
    signal(SIGUSR1, signal_handler);
#endif


    // protect from oom
    if (!protect_from_oom()) {
        fprintf(stderr, ME "Couldn't protect from oom: %s\n", strerror(errno));
    }

    // set priority/niceness (will be inherited)
    if (setpriority(PRIO_PROCESS, 0, DSME_NICE) == -1) {
        fprintf(stderr, ME "Couldn't set the priority: %s\n", strerror(errno));
    }

    // set scheduler (will be inherited)
    struct sched_param sch;
    memset(&sch, 0, sizeof(sch));
    sch.sched_priority = sched_get_priority_max(DSME_HB_SCHEDULER);
    if (sched_setscheduler(0, DSME_HB_SCHEDULER, &sch) == -1) {
        fprintf(stderr, ME "Couldn't set the scheduler: %s\n", strerror(errno));
    }

    // lock to ram (will not be inherited)
    if (mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
        fprintf(stderr, ME "Couldn't lock to RAM: %s\n", strerror(errno));
    }


    // parse command line options
    int daemon = 0;
    parse_options(argc, argv, &daemon);

    // daemonize
    if (daemon && daemonize() == -1) {
        return EXIT_FAILURE;
    }

    // set running directory
    if (chdir("/") == -1) {
        fprintf(stderr, ME "chdir failed: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }

    // open communication pipes
    int to_child[2];
    int from_child[2];
    if (pipe(to_child) != 0 || pipe(from_child) != 0) {
        fprintf(stderr, ME "pipe failed: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }

    // fork and exec the dsme server
    pid_t pid;
    if ((pid = fork()) == -1) {
        fprintf(stderr, ME "fork failed: %s\n", strerror(errno));
        return EXIT_FAILURE;
    } else if (pid == 0) {
        // child

        // TODO: lower priority
        // TODO: restore scheduler

        // child gets the pipes in stdin & stdout
        if (dup2(to_child[0], STDIN_FILENO) != STDIN_FILENO) {
            fprintf(stderr, ME "dup2 failed: %s\n", strerror(errno));
            _exit(EXIT_FAILURE);
        }
        if (dup2(from_child[1], STDOUT_FILENO) != STDOUT_FILENO) {
            fprintf(stderr, ME "dup2 failed: %s\n", strerror(errno));
            _exit(EXIT_FAILURE);
        }

        // close all the other descriptors
        int max_fd_count = getdtablesize();
        if (max_fd_count == -1) {
            max_fd_count = 256;
        }
        for (int i = 3; i < max_fd_count; ++i) {
            (void)close(i);
        }

        // exec dsme server core
        char* newargv[argc+1];
        newargv[0] = (char*)DSME_SERVER_PATH;
        for (int i = 1; i < argc; ++i) {
            newargv[i] = argv[i];
        }
        newargv[argc] = 0;
        execv(DSME_SERVER_PATH, newargv);
        fprintf(stderr,
                ME "execv failed: %s: %s\n",
                DSME_SERVER_PATH,
                strerror(errno));
        _exit(EXIT_FAILURE);

    } else {
        // parent

        // close child ends of pipes & set parent ends of pipes non-blocking
        close(to_child[0]);
        close(from_child[1]);
        set_nonblocking(to_child[1]);
        set_nonblocking(from_child[0]);
    }

    /* Before entering the mainloop, clear wakelock that might be set if dsme
     * is restarting after signal / watchdog pingpong failure */
    release_restart_wakelock();

    unsigned sleep_interval = DSME_HEARTBEAT_INTERVAL;
    mainloop(sleep_interval, to_child[1], from_child[0]);
    fprintf(stderr, ME "Exited main loop, quitting\n");

    /* Get wakelock after exiting the mainloop, will be cleared
     * if we make orderly normal exit */
    obtain_restart_wakelock();

    /* Bring down the dsme-server child process
     *
     * Note: The maximum duration we can spend here must be shorter
     *       than both hw watchdog kick period and the time systemd
     *       allows for dsme itself to exit.
     */

    // kick watchdogs so we have time to wait for dsme-server to exit
    dsme_wd_kick();

    if( kill_and_wait(pid, SIGTERM, 8) || kill_and_wait(pid, SIGKILL, 3) ) {
        // clear nowayout states and close watchdog files
        dsme_wd_quit();
    }
    else {
        // leave the nowayout states on so that we will get a wd reboot
        // shortly after dsme exits, but kick the watchdogs one more time
        // to give the system some time to make orderly shutdown
        dsme_wd_kick();
        fprintf(stderr, ME "dsme-server stop failed, leaving watchdogs"
                " active\n");
        dsme_abnormal_exit = true;
    }

    /* Remove the PID file */
    if (remove(DSME_PID_FILE) < 0 && errno != ENOENT) {
        fprintf(stderr, ME "Couldn't remove lockfile: %m\n");
    }

    /* Clear wakelock on normal, successful exit */
    if( dsme_abnormal_exit )
        fprintf(stderr, ME "abnormal exit, leaving wakelock active\n");
    else
        release_restart_wakelock();

    fprintf(stderr, "DSME %s terminating\n", STRINGIFY(PRG_VERSION));
    return dsme_abnormal_exit ? EXIT_FAILURE : EXIT_SUCCESS;
}
Пример #16
0
int main(int argc,char **argv)
{
        int i, c;
        struct sockaddr_in sock;
        socklen_t sock_len;
        int hsocket = 0;

        flags=0;

        while ((c=getopt(argc, argv, "kpms:dti"))!=-1) {
                switch (c) {
                        case 'p': {
                                flags|=DPROFILE;
                                break;
                        }
                        case 'm': {
                                flags|=DMAP;
                                break;
                        }
                        case 's': {
                                strcpy(bank_file_name, optarg);
                                break;
                        }
                        case 'd': {
                                flags|=DSTARTDEBUG;
                                break;
                        }
                        case 't': {
                                flags|=DSOCKETS;
                                break;
                        }
                        case 'i': {
                                flags|=DTIMERINT;
                                break;
                        }
                        case 'k': {
                                flags|=DLIMITEDRUN;
                                break;
                        }
                        default: {
                                usage();
                                return -1;
                                break;
                        }
                }
        }

#ifdef SEG
        for (i=0; i< NUM_SEGS; i++) {
                segments[i] = &mem[i*SEG_SIZE];
        }
#endif
        if (optind<argc) {
                loadImage(argv[optind], flags);
        }
        else {
                printf("%s:Error: No image file specified.\n",argv[0]);
                return -2;
        }
        if (flags&DSOCKETS) {
                /* Open up the socket connection before proceeding */
                printf("Opening socket 6808...");
                fflush(stdout);

                hsocket = socket_init(6808);
                if (hsocket<0) {
                        printf("Failed.\n");
                        return -2;
                }
                else {
                        printf("Done.\n");
                        printf("Waiting for connection...");
                        fflush(stdout);

                        sock_len=sizeof(struct sockaddr_in);
                        tsocket = accept( hsocket, (struct sockaddr *)&sock, &sock_len );
                        if (tsocket==-1) {
                                printf("Failed.\n");
                                return -1;
                        }
                        else {
                                printf("Done.\n");
                        }
                }
        }

        mainloop(flags);

        if (flags&DPROFILE)
                profile();
        if (flags&DSOCKETS) {
                close(tsocket);
                close(hsocket);
        }
        printf("\nrrgb:  Total tstates: %lu.\n", tstates );

        return 0;
}
Пример #17
0
int main()
{
      mainloop();
      system("PAUSE");
      return 0;
}
Пример #18
0
int
main(int argc, char **argv)
{
  int c;
  int forkaway = 0;
  FILE *pidfile;
  struct group *grp;
  struct passwd *pw;
  const char *usernam = NULL;
  const char *groupnam = NULL;
  int logfacility = LOG_DAEMON;
  int createdefault = 0;
  sigset_t set;
  const char *homedir;
  const char *rawts_input = NULL;
  const char *join_transport = NULL;
  const char *confpath = NULL;
  char *p, *endp;
  uint32_t adapter_mask = 0xffffffff;
  int crash = 0;

  // make sure the timezone is set
  tzset();

  while((c = getopt(argc, argv, "Aa:fu:g:c:Chdr:j:s")) != -1) {
    switch(c) {
    case 'a':
      adapter_mask = 0x0;
      p = strtok(optarg, ",");
      if (p != NULL) {
        do {
          int adapter = strtol(p, &endp, 10);
          if (*endp != 0 || adapter < 0 || adapter > 31) {
              fprintf(stderr, "Invalid adapter number '%s'\n", p);
              return 1;
          }
          adapter_mask |= (1 << adapter);
        } while ((p = strtok(NULL, ",")) != NULL);
        if (adapter_mask == 0x0) {
          fprintf(stderr, "No adapters specified!\n");
          return 1;
        }
      } else {
        usage(argv[0]);
      }
      break;
    case 'A':
      crash = 1;
      break;
    case 'f':
      forkaway = 1;
      break;
    case 'u':
      usernam = optarg;
      break;
    case 'g':
      groupnam = optarg;
      break;
    case 'c':
      confpath = optarg;
      break;
    case 'd':
      log_debug_to_console = 1;
      break;
    case 's':
      log_debug_to_syslog = 1;
      break;
    case 'C':
      createdefault = 1;
      break;
    case 'r':
      rawts_input = optarg;
      break;
    case 'j':
      join_transport = optarg;
      break;
    default:
      usage(argv[0]);
    }
  }

  signal(SIGPIPE, handle_sigpipe);

  grp = getgrnam(groupnam ?: "video");
  pw = usernam ? getpwnam(usernam) : NULL;


  if(forkaway) {

    if(daemon(0, 0)) {
      exit(2);
    }

    pidfile = fopen("/var/run/tvheadend.pid", "w+");
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

   if(grp != NULL) {
      setgid(grp->gr_gid);
    } else {
      setgid(1);
    }

   if(pw != NULL) {
      setuid(pw->pw_uid);
    } else {
      setuid(1);
    }

   if(pw != NULL) {
     homedir = pw->pw_dir;
     setenv("HOME", homedir, 1);
   }

    umask(0);
  }

  log_stderr = !forkaway;
  log_decorate = isatty(2);

  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);

  openlog("tvheadend", LOG_PID, logfacility);

  hts_settings_init(confpath);

  pthread_mutex_init(&ffmpeg_lock, NULL);
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);

  pthread_mutex_lock(&global_lock);

  time(&dispatch_clock);

  trap_init(argv[0]);
  
  /**
   * Initialize subsystems
   */
  xmltv_init();   /* Must be initialized before channels */

  service_init();

  channels_init();

  access_init(createdefault);

  tcp_server_init();
#if ENABLE_LINUXDVB
  dvb_init(adapter_mask);
#endif
  iptv_input_init();
#if ENABLE_V4L
  v4l_init();
#endif
  http_server_init();

  webui_init(TVHEADEND_CONTENT_PATH);

  serviceprobe_init();

  cwc_init();

  capmt_init();

  epg_init();

  dvr_init();

  htsp_init();

  ffdecsa_init();
  
  if(rawts_input != NULL)
    rawts_init(rawts_input);

  if(join_transport != NULL)
    subscription_dummy_join(join_transport, 1);

#ifdef CONFIG_AVAHI
  avahi_init();
#endif

  pthread_mutex_unlock(&global_lock);


  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  running = 1;
  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
	 "running as PID:%d UID:%d GID:%d, settings located in '%s'",
	 htsversion_full,
	 getpid(), getuid(), getgid(), hts_settings_get_root());

  if(crash)
    abort();

  mainloop();

  epg_save();

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");

  if(forkaway)
    unlink("/var/run/tvheadend.pid");

  return 0;

}
Пример #19
0
int 
main(int argc, char **argv)
{
    extern int game_is_being_shut_down;
    char *p;
    int i = 0;
    struct svalue *ret;
    extern struct svalue catch_value;
    extern void init_cfuns(void);
    struct gdexception exception_frame;

    (void)setlinebuf(stdout);

    parse_args(argc, argv);
    
    const0.type = T_NUMBER; const0.u.number = 0;
    const1.type = T_NUMBER; const1.u.number = 1;
    constempty.type = T_FUNCTION; constempty.u.func = &funcempty;
    funcempty.funtype = FUN_EMPTY;
    catch_value = const0;
    
    /*
     * Check that the definition of EXTRACT_UCHAR() is correct.
     */
    p = (char *)&i;
    *p = -10;
    if (EXTRACT_UCHAR(p) != 0x100 - 10)
    {
	(void)fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in config.h.\n");
	exit(1);
    }
    set_current_time();

#ifdef PROFILE_LPC
    set_profile_timebase(60.0); /* One minute */
#endif

#if RESERVED_SIZE > 0
    reserved_area = malloc(RESERVED_SIZE);
#endif

    init_random();
    init_tasks();
    query_load_av();
    init_num_args();
    init_machine();
    init_cfuns();
    init_hash();

    /*
     * Set up the signal handling.
     */
    init_signals();

    if (chdir(mudlib_path) == -1) {
        (void)fprintf(stderr, "Bad mudlib directory: %s\n", MUD_LIB);
	exit(1);
    }

    if (setjmp(exception_frame.e_context))
    {
	clear_state();
	add_message("Anomaly in the fabric of world space.\n");
    } 
    else
    {
	exception_frame.e_exception = NULL;
	exception_frame.e_catch = 0;
	exception = &exception_frame;
	auto_ob = 0;
	master_ob = 0;
	
	if ((auto_ob = load_object("secure/auto", 1, 0, 0)) != NULL)
	{
	    add_ref(auto_ob, "main");
	    auto_ob->prog->flags |= PRAGMA_RESIDENT;
	}

	get_simul_efun();
	master_ob = load_object("secure/master", 1, 0, 0);
	if (master_ob)
	{
	    /*
	     * Make sure master_ob is never made a dangling pointer.
	     * Look at apply_master_ob() for more details.
	     */
	    add_ref(master_ob, "main");
	    master_ob->prog->flags |= PRAGMA_RESIDENT;
            resolve_master_fkntab();
	    create_object(master_ob);
            load_parse_information();
	    clear_state();
	}
    }
    exception = NULL;
    if (auto_ob == 0) 
    {
	(void)fprintf(stderr, "The file secure/auto must be loadable.\n");
	exit(1);
    }
    if (master_ob == 0) 
    {
	(void)fprintf(stderr, "The file secure/master must be loadable.\n");
	exit(1);
    }
    set_inc_list(apply_master_ob(M_DEFINE_INCLUDE_DIRS, 0));
    
    {
	struct svalue* ret1;

	ret1 = apply_master_ob(M_PREDEF_DEFINES, 0);
	if (ret1 && ret1->type == T_POINTER)
	{
	    int ii;

	    for (ii = 0; ii < ret1->u.vec->size; ii++)
		if (ret1->u.vec->item[ii].type == T_STRING)
		{
                    add_pre_define(ret1->u.vec->item[ii].u.string);
		}
	}
    }

    if (flag != NULL)
    {
        printf("Applying driver flag: %s\n", flag);
        push_string(flag, STRING_MSTRING);
        (void)apply_master_ob(M_FLAG, 1);

        if (game_is_being_shut_down)
        {
            (void)fprintf(stderr, "Shutdown by master object.\n");
            exit(0);
        }
    }

    /*
     * See to it that the mud name is always defined in compiled files
     */
    ret = apply_master_ob(M_GET_MUD_NAME, 0);

    if (ret && ret->type == T_STRING)
    {
	struct lpc_predef_s *tmp;
		
	tmp = (struct lpc_predef_s *)
	    xalloc(sizeof(struct lpc_predef_s));
	if (!tmp) 
	    fatal("xalloc failed\n");
	tmp->flag = string_copy(ret->u.string);
	tmp->next = lpc_predefs;
	lpc_predefs = tmp;
    }

    ret = apply_master_ob(M_GET_VBFC_OBJECT, 0);
    if (ret && ret->type == T_OBJECT)
    {
	vbfc_object = ret->u.ob;
	INCREF(vbfc_object->ref);
    }
    else
	vbfc_object = 0;

    if (game_is_being_shut_down)
	exit(1);

    init_call_out();
    preload_objects(e_flag);
    (void)apply_master_ob(M_FINAL_BOOT, 0);
    
    mainloop();

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

	#ifdef SOCKS
		SOCKSinit(argv[0]);
	#endif

	if (signal(SIGTERM, trap_handler) == BADSIG)
	{
		syserr("signal SIGTERM");
	}

	if (signal(SIGSEGV, trap_handler) == BADSIG)
	{
		syserr("signal SIGSEGV");
	}

	if (signal(SIGHUP, trap_handler) == BADSIG)
	{
		syserr("signal SIGHUP");
	}

	if (signal(SIGABRT, abort_handler) == BADSIG)
	{
		syserr("signal SIGTERM");
	}

	if (signal(SIGINT, abort_handler) == BADSIG)
	{
		syserr("signal SIGINT");
	}

	if (signal(SIGTSTP, suspend_handler) == BADSIG)
	{
		syserr("signal SIGSTOP");
	}

	if (signal(SIGPIPE, pipe_handler) == BADSIG)
	{
		syserr("signal SIGPIPE");
	}

	if (signal(SIGWINCH, winch_handler) == BADSIG)
	{
		syserr("signal SIGWINCH");
	}

/*
	if (getenv("HOME") != NULL)
	{
		char filename[256];

		sprintf(filename, "%s/%s", getenv("HOME"), HISTORY_FILE);

		read_history(gts, filename);
	}
*/

	srand(time(NULL));

	if (argc > 1)
	{
		int c;

		while ((c = getopt(argc, argv, "e: G h r: s: t: v")) != EOF)
		{
			if (c == 'G')
			{
				greeting = FALSE;
			}
		}

		optind = 1;
	}

	init_tintin(greeting);

	if (argc > 1)
	{
		int c;

		optind = 1;

		while ((c = getopt(argc, argv, "e: G h r: s: t: v")) != EOF)
		{
			switch (c)
			{
				case 'e':
					gtd->ses = script_driver(gtd->ses, -1, optarg);
					break;

				case 'G':
					break;

				case 'h':
					tintin_printf(NULL, "Usage: %s [OPTION]... [FILE]...", argv[0]);
					tintin_printf(NULL, "");
					tintin_printf(NULL, "  -e  Execute given command.");
					tintin_printf(NULL, "  -G  Don't show the greeting screen.");
					tintin_printf(NULL, "  -h  This help section.");
					tintin_printf(NULL, "  -r  Read given file.");
					tintin_printf(NULL, "  -t  Set given title.");
					tintin_printf(NULL, "  -v  Enable verbose mode.");

					restore_terminal();
					exit(1);
					break;

				case 'r':
					gtd->ses = do_read(gtd->ses, optarg);
					break;

				case 't':
					printf("\033]0;%s\007", optarg);
					break;

				case 's':
					srand((unsigned int) atoll(optarg));
					break;

				case 'v':
					do_configure(gtd->ses, "{VERBOSE} {ON}");
					break;

				default:
					tintin_printf(NULL, "Unknown option '%c'.", c);
					break;
			}
		}

		if (argv[optind] != NULL)
		{
			gtd->ses = do_read(gtd->ses, argv[optind]);
		}
	}
	check_all_events(gts, SUB_ARG|SUB_SEC, 0, 2, "PROGRAM START", CLIENT_NAME, CLIENT_VERSION);
	check_all_events(gts, SUB_ARG|SUB_SEC, 0, 2, "SCREEN RESIZE", ntos(gts->cols), ntos(gts->rows));

	mainloop();

	return 0;
}
Пример #21
0
	virtual int Mainloop() {
		return mainloop();
	}
Пример #22
0
/******************************************************************************
 *
 * main(argc, argv) --
 *
 *   Program entry point.
 *
 ******************************************************************************/
int main(int argc, char *argv[])
{
	int sock, res, i;

	/*
	 * Initialize the global parameters
	 */
	global_options.sndhistory       = SNDHISTORY;
	global_options.local_port       = PORT;
	global_options.nworkers         = NWORKERS;
	global_options.nverifiers       = NVERIFIERS;
	global_options.verbose          = 0;
	global_options.keep             = 0;
	global_options.whitelist_server = WLSERVER;
	global_options.whitelist_port   = WLPORT;
	global_options.verify_server    = VFYSERVER;
	global_options.verify_port      = VFYPORT;
	global_options.verify_prog      = VERIFY_PROG;
	global_options.verify_thresh    = VERIFY_THRESH;
	global_options.device           = DEVICE;
	global_options.mode             = MODE_DEFAULT;

	/*
	 * Parse the command line options
	 */
	parse_command_line(argc, argv);

	/*
	 * Initialization
	 */
	set_log_level(global_options.verbose);
	display_config();

	LOG(1, "Creating listening socket...\n");
	sock = listen_on(global_options.local_port);
	LOG(1, "Socket %d now listening.\n", sock);

	/*
	 * Create the other threads
	 */
	pthread_barrier_init(&ginit_barrier, NULL,  2);

	wrk_threads = malloc(sizeof(pthread_t) * global_options.nworkers);
	if (wrk_threads == NULL) {
		fprintf(stderr, "Couldn't allocate space for workers\n");
		abort();
	}

	vfy_threads = malloc(sizeof(pthread_t) * global_options.nverifiers);
	if (vfy_threads == NULL) {
		fprintf(stderr, "Couldn't allocate space for verifiers\n");
		abort();
	}

	if (need_sound()) {
		LOG(1, "Creating sound thread...\n");
		pthread_create(&snd_thread, NULL, snd_thread_fn, NULL);
		
		/*
		 * Need to wait for the sound thread to finish initialization; he sets
		 * some global values that the other threads depend on for their own
		 * initialization.
		 */
		pthread_barrier_wait(&ginit_barrier);
	}

	if (need_whitelist()) {
		LOG(1, "Creating whitelist thread...\n");
		pthread_create(&whl_thread, NULL, whl_thread_fn, NULL);
	}

	LOG(1, "Creating %d worker threads...\n", global_options.nworkers);
	for (i = 0; i < global_options.nworkers; i++)
		pthread_create(&wrk_threads[i], NULL, wrk_thread_fn, NULL);

	/*
	 * Create worker threads based on the server's mode of operaiton
	 */
	LOG(1, "Creating %d %s verification threads...\n",
		global_options.nverifiers,
	        global_options.mode == MODE_REMOTE_VERIFY ? "remote" : "local");

	if (global_options.mode == MODE_REMOTE_VERIFY) {
		for (i = 0; i < global_options.nverifiers; i++)
			pthread_create(&vfy_threads[i], NULL, vfy_thread_remote_fn, NULL);

	} else {
		for (i = 0; i < global_options.nverifiers; i++)
			pthread_create(&vfy_threads[i], NULL, vfy_thread_fn, NULL);
	}

	/*
	 * Turn in to the main thread
	 */
	res = mainloop(sock);

	close(sock);
	return res;
}
Пример #23
0
int main(int argc, char **argv)
{
	int value;
	dev_name = "/dev/video0";

	for (;;) {
		int index;
		int c;

		c = getopt_long(argc, argv,
				short_options, long_options, &index);

		if (-1 == c)
			break;

		switch (c) {
		case 0:	/* getopt_long() flag */
			break;

		case 'd':
			dev_name = optarg;
			break;

		case 'c':
			value = atoi(optarg);
			capture_count = value > 0 ? value : MAX_CAPTURE;
			break;

		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);

		case 'm':
			io = IO_METHOD_MMAP;
			break;

		case 'r':
			io = IO_METHOD_READ;
			break;

		case 'u':
			io = IO_METHOD_USERPTR;
			break;

		case 'i':
			value = atoi(optarg);
			still_capture_interval = value > 0 ? value : CAPTURE_INTERVAL;
			break;

		case 's':
			still_dump_file = 1;
			break;

		case 'x':
			value = atoi(optarg);
			if (value > 0) {
				sw = value;
				still_size_fixed = 1;
			}
			break;

		case 'y':
			value = atoi(optarg);
			if (value > 0) {
				sh = value;
				still_size_fixed = 1;
			}
			break;

		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}

	open_device();

	init_device();

	start_capturing();

	mainloop();

	stop_capturing();

	uninit_device();

	close_device();

	exit(EXIT_SUCCESS);

	return 0;
}
Пример #24
0
int
main(int argc, char **argv)
{
  int i;
  sigset_t set;
#if ENABLE_LINUXDVB
  uint32_t adapter_mask;
#endif

  /* Defaults */
  log_stderr                = 1;
  log_decorate              = isatty(2);
  log_debug_to_syslog       = 0;
  log_debug_to_console      = 0;
  log_debug_to_path         = 0;
  log_path                  = NULL;
  tvheadend_webui_port      = 9981;
  tvheadend_webroot         = NULL;
  tvheadend_htsp_port       = 9982;
  tvheadend_htsp_port_extra = 0;

  /* Command line options */
  int         opt_help         = 0,
              opt_version      = 0,
              opt_fork         = 0,
              opt_firstrun     = 0,
              opt_debug        = 0,
              opt_syslog       = 0,
              opt_uidebug      = 0,
              opt_abort        = 0,
              opt_noacl        = 0,
              opt_ipv6         = 0;
  const char *opt_config       = NULL,
             *opt_user         = NULL,
             *opt_group        = NULL,
             *opt_pidpath      = "/var/run/tvheadend.pid",
#if ENABLE_LINUXDVB
             *opt_dvb_adapters = NULL,
             *opt_dvb_raw      = NULL,
#endif
             *opt_rawts        = NULL,
             *opt_bindaddr     = NULL,
             *opt_subscribe    = NULL;
  cmdline_opt_t cmdline_opts[] = {
    {   0, NULL,        "Generic Options",         OPT_BOOL, NULL         },
    { 'h', "help",      "Show this page",          OPT_BOOL, &opt_help    },
    { 'v', "version",   "Show version infomation", OPT_BOOL, &opt_version },

    {   0, NULL,        "Service Configuration",   OPT_BOOL, NULL         },
    { 'c', "config",    "Alternate config path",   OPT_STR,  &opt_config  },
    { 'f', "fork",      "Fork and run as daemon",  OPT_BOOL, &opt_fork    },
    { 'u', "user",      "Run as user",             OPT_STR,  &opt_user    },
    { 'g', "group",     "Run as group",            OPT_STR,  &opt_group   },
    { 'p', "pid",       "Alternate pid path",      OPT_STR,  &opt_pidpath },
    { 'C', "firstrun",  "If no user account exists then create one with\n"
	                      "no username and no password. Use with care as\n"
	                      "it will allow world-wide administrative access\n"
	                      "to your Tvheadend installation until you edit\n"
	                      "the access-control from within the Tvheadend UI",
      OPT_BOOL, &opt_firstrun },
#if ENABLE_LINUXDVB
    { 'a', "adapters",  "Only use specified DVB adapters (comma separated)",
      OPT_STR, &opt_dvb_adapters },
#endif
    {   0, NULL,         "Server Connectivity",    OPT_BOOL, NULL         },
    { '6', "ipv6",       "Listen on IPv6",         OPT_BOOL, &opt_ipv6    },
    { 'b', "bindaddr",   "Specify bind address",   OPT_STR,  &opt_bindaddr},
    {   0, "http_port",  "Specify alternative http port",
      OPT_INT, &tvheadend_webui_port },
    {   0, "http_root",  "Specify alternative http webroot",
      OPT_STR, &tvheadend_webroot },
    {   0, "htsp_port",  "Specify alternative htsp port",
      OPT_INT, &tvheadend_htsp_port },
    {   0, "htsp_port2", "Specify extra htsp port",
      OPT_INT, &tvheadend_htsp_port_extra },

    {   0, NULL,        "Debug Options",           OPT_BOOL, NULL         },
    { 'd', "debug",     "Enable all debug",        OPT_BOOL, &opt_debug   },
    { 's', "syslog",    "Enable debug to syslog",  OPT_BOOL, &opt_syslog  },
    {   0, "uidebug",   "Enable webUI debug",      OPT_BOOL, &opt_uidebug },
    { 'l', "log",       "Log to file",             OPT_STR,  &log_path    },
    { 'A', "abort",     "Immediately abort",       OPT_BOOL, &opt_abort   },
    {   0, "noacl",     "Disable all access control checks",
      OPT_BOOL, &opt_noacl },
#if ENABLE_LINUXDVB
    { 'R', "dvbraw",    "Use rawts file to create virtual adapter",
      OPT_STR, &opt_dvb_raw },
#endif
    { 'r', "rawts",     "Use rawts file to generate virtual services",
      OPT_STR, &opt_rawts },
    { 'j', "join",      "Subscribe to a service permanently",
      OPT_STR, &opt_subscribe }
  };

  /* Get current directory */
  tvheadend_cwd = dirname(dirname(tvh_strdupa(argv[0])));

  /* Set locale */
  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");

  /* make sure the timezone is set */
  tzset();

  /* Process command line */
  for (i = 1; i < argc; i++) {

    /* Find option */
    cmdline_opt_t *opt
      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);
    if (!opt)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 "invalid option specified [%s]", argv[i]);

    /* Process */
    if (opt->type == OPT_BOOL)
      *((int*)opt->param) = 1;
    else if (++i == argc)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 "option %s requires a value", opt->lopt);
    else if (opt->type == OPT_INT)
      *((int*)opt->param) = atoi(argv[i]);
    else
      *((char**)opt->param) = argv[i];

    /* Stop processing */
    if (opt_help)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
    if (opt_version)
      show_version(argv[0]);
  }

  /* Additional cmdline processing */
  log_debug_to_console  = opt_debug;
  log_debug_to_syslog   = opt_syslog;
  log_debug_to_path     = opt_debug;
  tvheadend_webui_debug = opt_debug || opt_uidebug;
  tvhlog(LOG_INFO, "START", "initialising");
#if ENABLE_LINUXDVB
  if (!opt_dvb_adapters) {
    adapter_mask = ~0;
  } else {
    char *p, *e;
    char *r = NULL;
    char *dvb_adapters = strdup(opt_dvb_adapters);
    adapter_mask = 0x0;
    p = strtok_r(dvb_adapters, ",", &r);
    while (p) {
      int a = strtol(p, &e, 10);
      if (*e != 0 || a < 0 || a > 31) {
        tvhlog(LOG_ERR, "START", "Invalid adapter number '%s'", p);
        free(dvb_adapters);
        return 1;
      }
      adapter_mask |= (1 << a);
      p = strtok_r(NULL, ",", &r);
    }
    if (!adapter_mask) {
      tvhlog(LOG_ERR, "START", "No adapters specified!");
      free(dvb_adapters);
      return 1;
    }
    free(dvb_adapters);
  }
#endif
  if (tvheadend_webroot) {
    char *tmp;
    if (*tvheadend_webroot == '/')
      tmp = strdup(tvheadend_webroot);
    else {
      tmp = malloc(strlen(tvheadend_webroot)+1);
      *tmp = '/';
      strcpy(tmp+1, tvheadend_webroot);
    }
    if (tmp[strlen(tmp)-1] == '/')
      tmp[strlen(tmp)-1] = '\0';
    tvheadend_webroot = tmp;
  }

  signal(SIGPIPE, handle_sigpipe); // will be redundant later

  /* Daemonise */
  if(opt_fork) {
    const char *homedir;
    gid_t gid;
    uid_t uid;
    struct group  *grp = getgrnam(opt_group ?: "video");
    struct passwd *pw  = opt_user ? getpwnam(opt_user) : NULL;
    FILE   *pidfile    = fopen(opt_pidpath, "w+");

    if(grp != NULL) {
      gid = grp->gr_gid;
    } else {
      gid = 1;
    }

    if (pw != NULL) {
      if (getuid() != pw->pw_uid) {
        gid_t glist[10];
        int gnum;
        gnum = get_user_groups(pw, glist, 10);
        if (setgroups(gnum, glist)) {
          tvhlog(LOG_ALERT, "START",
                 "setgroups() failed, do you have permission?");
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
    if ((getgid() != gid) && setgid(gid)) {
      tvhlog(LOG_ALERT, "START",
             "setgid() failed, do you have permission?");
      return 1;
    }
    if ((getuid() != uid) && setuid(uid)) {
      tvhlog(LOG_ALERT, "START",
             "setuid() failed, do you have permission?");
      return 1;
    }

    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    umask(0);
  }

  /* Setup logging */
  log_stderr   = !opt_fork;
  log_decorate = isatty(2);
  openlog("tvheadend", LOG_PID, LOG_DAEMON);

  /* Initialise configuration */
  hts_settings_init(opt_config);

  /* Setup global mutexes */
  pthread_mutex_init(&ffmpeg_lock, NULL);
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);
  pthread_mutex_init(&atomic_lock, NULL);
  pthread_mutex_lock(&global_lock);

  time(&dispatch_clock);

  /* Signal handling */
  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);
  trap_init(argv[0]);
  
  /**
   * Initialize subsystems
   */

#if ENABLE_LIBAV
  libav_init();
#endif

  config_init();

  imagecache_init();

  service_init();

  channels_init();

  subscription_init();

  access_init(opt_firstrun, opt_noacl);

#if ENABLE_LINUXDVB
  muxes_init();
  dvb_init(adapter_mask, opt_dvb_raw);
#endif

  iptv_input_init();

#if ENABLE_V4L
  v4l_init();
#endif

#if ENABLE_TIMESHIFT
  timeshift_init();
#endif

  tcp_server_init(opt_ipv6);
  http_server_init(opt_bindaddr);
  webui_init();

  serviceprobe_init();

#if ENABLE_CWC
  cwc_init();
  capmt_init();
#if (!ENABLE_DVBCSA)
  ffdecsa_init();
#endif
#endif

  epggrab_init();
  epg_init();

  dvr_init();

  htsp_init(opt_bindaddr);

  if(opt_rawts != NULL)
    rawts_init(opt_rawts);

  if(opt_subscribe != NULL)
    subscription_dummy_join(opt_subscribe, 1);

#ifdef CONFIG_AVAHI
  avahi_init();
#endif

  epg_updated(); // cleanup now all prev ref's should have been created

  pthread_mutex_unlock(&global_lock);

  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  running = 1;
  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
	 "running as PID:%d UID:%d GID:%d, settings located in '%s'",
	 tvheadend_version,
	 getpid(), getuid(), getgid(), hts_settings_get_root());

  if(opt_abort)
    abort();

  mainloop();

  // Note: the locking is obviously a bit redundant, but without
  //       we need to disable the gtimer_arm call in epg_save()
  pthread_mutex_lock(&global_lock);
  epg_save(NULL);

#if ENABLE_TIMESHIFT
  timeshift_term();
#endif
  pthread_mutex_unlock(&global_lock);

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");

  if(opt_fork)
    unlink(opt_pidpath);

  return 0;

}
Пример #25
0
int
main (int argc, char * const argv[])
{
    PROG = "aa-start";
    const char *path_repo = "/run/services";
    const char *path_list = NULL;
    int i;

    aa_secs_timeout = DEFAULT_TIMEOUT_SECS;
    for (;;)
    {
        struct option longopts[] = {
            { "double-output",      no_argument,        NULL,   'D' },
            { "help",               no_argument,        NULL,   'h' },
            { "listdir",            required_argument,  NULL,   'l' },
            { "dry-list",           no_argument,        NULL,   'n' },
            { "repodir",            required_argument,  NULL,   'r' },
            { "timeout",            required_argument,  NULL,   't' },
            { "version",            no_argument,        NULL,   'V' },
            { "verbose",            no_argument,        NULL,   'v' },
            { "no-wants",           no_argument,        NULL,   'W' },
            { NULL, 0, 0, 0 }
        };
        int c;

        c = getopt_long (argc, argv, "Dhl:nr:t:VvW", longopts, NULL);
        if (c == -1)
            break;
        switch (c)
        {
            case 'D':
                aa_set_double_output (1);
                break;

            case 'h':
                dieusage (0);

            case 'l':
                unslash (optarg);
                path_list = optarg;
                break;

            case 'n':
                if (mode & AA_MODE_IS_DRY)
                    mode |= AA_MODE_IS_DRY_FULL;
                else
                    mode |= AA_MODE_IS_DRY;
                break;

            case 'r':
                unslash (optarg);
                path_repo = optarg;
                break;

            case 't':
                if (!uint0_scan (optarg, &aa_secs_timeout))
                    aa_strerr_diefu2sys (ERR_IO, "set default timeout to ", optarg);
                break;

            case 'V':
                aa_die_version ();

            case 'v':
                verbose = 1;
                break;

            case 'W':
                no_wants = 1;
                break;

            default:
                dieusage (1);
        }
    }
    argc -= optind;
    argv += optind;

    cols = get_cols (1);
    is_utf8 = is_locale_utf8 ();

    if (!path_list && argc < 1)
        dieusage (1);

    if (aa_init_repo (path_repo, (mode & AA_MODE_IS_DRY) ? AA_REPO_READ : AA_REPO_WRITE) < 0)
        aa_strerr_diefu2sys (ERR_IO, "init repository ", path_repo);

    if (path_list)
    {
        stralloc sa = STRALLOC_ZERO;
        int r;

        if (*path_list != '/' && *path_list != '.')
            stralloc_cats (&sa, LISTDIR_PREFIX);
        stralloc_catb (&sa, path_list, strlen (path_list) + 1);
        r = aa_scan_dir (&sa, 1, it_start, NULL);
        stralloc_free (&sa);
        if (r < 0)
            aa_strerr_diefu3sys (-r, "read list directory ",
                    (*path_list != '/' && *path_list != '.') ? LISTDIR_PREFIX : path_list,
                    (*path_list != '/' && *path_list != '.') ? path_list : "");
    }

    tain_now_g ();

    for (i = 0; i < argc; ++i)
        if (str_equal (argv[i], "-"))
        {
            if (process_names_from_stdin ((names_cb) add_service, NULL) < 0)
                aa_strerr_diefu1sys (ERR_IO, "process names from stdin");
        }
        else
            add_service (argv[i], NULL);

    mainloop (mode, scan_cb);

    if (!(mode & AA_MODE_IS_DRY))
    {
        aa_bs_noflush (AA_OUT, "\n");
        put_title (1, PROG, "Completed.", 1);
        aa_show_stat_nb (nb_already, "Already up", ANSI_HIGHLIGHT_GREEN_ON);
        aa_show_stat_nb (nb_done, "Started", ANSI_HIGHLIGHT_GREEN_ON);
        show_stat_service_names (&ga_timedout, "Timed out", ANSI_HIGHLIGHT_RED_ON);
        show_stat_service_names (&ga_failed, "Failed", ANSI_HIGHLIGHT_RED_ON);
        show_stat_service_names (&ga_depend, "Dependency failed", ANSI_HIGHLIGHT_RED_ON);
        aa_show_stat_names (aa_names.s, &ga_io, "I/O error", ANSI_HIGHLIGHT_RED_ON);
        aa_show_stat_names (aa_names.s, &ga_unknown, "Unknown", ANSI_HIGHLIGHT_RED_ON);
        aa_show_stat_names (aa_names.s, &ga_skipped, "Skipped", ANSI_HIGHLIGHT_YELLOW_ON);
    }

    genalloc_free (int, &ga_timedout);
    genalloc_free (int, &ga_failed);
    genalloc_free (int, &ga_depend);
    genalloc_free (size_t, &ga_io);
    genalloc_free (size_t, &ga_unknown);
    genalloc_free (size_t, &ga_skipped);
    genalloc_free (pid_t, &ga_pid);
    genalloc_free (int, &aa_tmp_list);
    genalloc_free (int, &aa_main_list);
    stralloc_free (&aa_names);
    genalloc_deepfree (struct progress, &ga_progress, free_progress);
    aa_free_services (close_fd);
    genalloc_free (iopause_fd, &ga_iop);
    return rc;
}
Пример #26
0
int main(int arg_c, char **arg_v)
{
  int i, xx;
  char s[25];
  FILE *f;
  struct sigaction sv;
  struct chanset_t *chan;
#ifdef DEBUG
  struct rlimit cdlim;
#endif
#ifdef STOP_UAC
  int nvpair[2];
#endif

/* Make sure it can write core, if you make debug. Else it's pretty
 * useless (dw)
 *
 * Only allow unlimited size core files when compiled with DEBUG defined.
 * This is not a good idea for normal builds -- in these cases, use the
 * default system resource limits instead.
 */
#ifdef DEBUG
  cdlim.rlim_cur = RLIM_INFINITY;
  cdlim.rlim_max = RLIM_INFINITY;
  setrlimit(RLIMIT_CORE, &cdlim);
#endif

#ifdef DEBUG_CONTEXT
  /* Initialise context list */
  for (i = 0; i < 16; i++)
    Context;
#endif

/* Include patch.h header for patch("...") */
#include "patch.h"

  argc = arg_c;
  argv = arg_v;

  /* Version info! */
  egg_snprintf(ver, sizeof ver, "eggdrop v%s", egg_version);
  egg_snprintf(version, sizeof version,
               "Eggdrop v%s (C) 1997 Robey Pointer (C) 2010 Eggheads",
               egg_version);
  /* Now add on the patchlevel (for Tcl) */
  sprintf(&egg_version[strlen(egg_version)], " %u", egg_numver);
  strcat(egg_version, egg_xtra);

/* For OSF/1 */
#ifdef STOP_UAC
  /* Don't print "unaligned access fixup" warning to the user */
  nvpair[0] = SSIN_UACPROC;
  nvpair[1] = UAC_NOPRINT;
  setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
#endif

  /* Set up error traps: */
  sv.sa_handler = got_bus;
  sigemptyset(&sv.sa_mask);
#ifdef SA_RESETHAND
  sv.sa_flags = SA_RESETHAND;
#else
  sv.sa_flags = 0;
#endif
  sigaction(SIGBUS, &sv, NULL);
  sv.sa_handler = got_segv;
  sigaction(SIGSEGV, &sv, NULL);
#ifdef SA_RESETHAND
  sv.sa_flags = 0;
#endif
  sv.sa_handler = got_fpe;
  sigaction(SIGFPE, &sv, NULL);
  sv.sa_handler = got_term;
  sigaction(SIGTERM, &sv, NULL);
  sv.sa_handler = got_hup;
  sigaction(SIGHUP, &sv, NULL);
  sv.sa_handler = got_quit;
  sigaction(SIGQUIT, &sv, NULL);
  sv.sa_handler = SIG_IGN;
  sigaction(SIGPIPE, &sv, NULL);
  sv.sa_handler = got_ill;
  sigaction(SIGILL, &sv, NULL);
  sv.sa_handler = got_alarm;
  sigaction(SIGALRM, &sv, NULL);

  /* Initialize variables and stuff */
  now = time(NULL);
  chanset = NULL;
  egg_memcpy(&nowtm, localtime(&now), sizeof(struct tm));
  lastmin = nowtm.tm_min;
  srandom((unsigned int) (now % (getpid() + getppid())));
  init_mem();
  init_language(1);
  if (argc > 1)
    for (i = 1; i < argc; i++)
      do_arg(argv[i]);

  printf("\n%s\n", version);

#ifndef CYGWIN_HACKS
  /* Don't allow eggdrop to run as root
   * This check isn't useful under cygwin and has been
   * reported to cause trouble in some situations.
   */
  if (((int) getuid() == 0) || ((int) geteuid() == 0))
    fatal("ERROR: Eggdrop will not run as root!", 0);
#endif

#ifndef REPLACE_NOTIFIER
  init_threaddata(1);
#endif
  init_userent();
  init_misc();
  init_bots();
  init_modules();
  if (backgrd)
    bg_prepare_split();
  init_tcl(argc, argv);
  init_language(0);
#ifdef STATIC
  link_statics();
#endif
  strncpyz(s, ctime(&now), sizeof s);
  strcpy(&s[11], &s[20]);
  putlog(LOG_ALL, "*", "--- Loading %s (%s)", ver, s);
  chanprog();
  if (!encrypt_pass) {
    printf(MOD_NOCRYPT);
    bg_send_quit(BG_ABORT);
    exit(1);
  }
  i = 0;
  for (chan = chanset; chan; chan = chan->next)
    i++;
  putlog(LOG_MISC, "*", "=== %s: %d channels, %d users.",
         botnetnick, i, count_users(userlist));
#ifdef TLS
  ssl_init();
#endif
  cache_miss = 0;
  cache_hit = 0;
  if (!pid_file[0])
    egg_snprintf(pid_file, sizeof pid_file, "pid.%s", botnetnick);

  /* Check for pre-existing eggdrop! */
  f = fopen(pid_file, "r");
  if (f != NULL) {
    fgets(s, 10, f);
    xx = atoi(s);
    i = kill(xx, SIGCHLD);      /* Meaningless kill to determine if pid
                                 * is used */
    if (i == 0 || errno != ESRCH) {
      printf(EGG_RUNNING1, botnetnick);
      printf(EGG_RUNNING2, pid_file);
      bg_send_quit(BG_ABORT);
      exit(1);
    }
  }

  /* Move into background? */
  if (backgrd) {
    bg_do_split();
  } else {                        /* !backgrd */
    xx = getpid();
    if (xx != 0) {
      FILE *fp;

      /* Write pid to file */
      unlink(pid_file);
      fp = fopen(pid_file, "w");
      if (fp != NULL) {
        fprintf(fp, "%u\n", xx);
        if (fflush(fp)) {
          /* Let the bot live since this doesn't appear to be a botchk */
          printf(EGG_NOWRITE, pid_file);
          fclose(fp);
          unlink(pid_file);
        } else
          fclose(fp);
      } else
        printf(EGG_NOWRITE, pid_file);
    }
  }

  use_stderr = 0;               /* Stop writing to stderr now */
  if (backgrd) {
    /* Ok, try to disassociate from controlling terminal (finger cross) */
#ifdef HAVE_SETPGID
    setpgid(0, 0);
#endif
    /* Tcl wants the stdin, stdout and stderr file handles kept open. */
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
#ifdef CYGWIN_HACKS
    FreeConsole();
#endif
  }

  /* Terminal emulating dcc chat */
  if (!backgrd && term_z) {
    int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));

    getvhost(&dcc[n].sockname, AF_INET);
    dcc[n].sock = STDOUT;
    dcc[n].timeval = now;
    dcc[n].u.chat->con_flags = conmask;
    dcc[n].u.chat->strip_flags = STRIP_ALL;
    dcc[n].status = STAT_ECHO;
    strcpy(dcc[n].nick, "HQ");
    strcpy(dcc[n].host, "llama@console");
    /* HACK: Workaround not to pass literal "HQ" as a non-const arg */
    dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
    /* Make sure there's an innocuous HQ user if needed */
    if (!dcc[n].user) {
      userlist = adduser(userlist, dcc[n].nick, "none", "-", USER_PARTY);
      dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
    }
    setsock(STDOUT, 0);          /* Entry in net table */
    dprintf(n, "\n### ENTERING DCC CHAT SIMULATION ###\n\n");
    dcc_chatter(n);
  }

  then = now;
  online_since = now;
  autolink_cycle(NULL);         /* Hurry and connect to tandem bots */
  add_help_reference("cmds1.help");
  add_help_reference("cmds2.help");
  add_help_reference("core.help");
  add_hook(HOOK_SECONDLY, (Function) core_secondly);
  add_hook(HOOK_MINUTELY, (Function) core_minutely);
  add_hook(HOOK_HOURLY, (Function) core_hourly);
  add_hook(HOOK_REHASH, (Function) event_rehash);
  add_hook(HOOK_PRE_REHASH, (Function) event_prerehash);
  add_hook(HOOK_USERFILE, (Function) event_save);
  add_hook(HOOK_BACKUP, (Function) backup_userfile);
  add_hook(HOOK_DAILY, (Function) event_logfile);
  add_hook(HOOK_DAILY, (Function) event_resettraffic);
  add_hook(HOOK_LOADED, (Function) event_loaded);

  call_hook(HOOK_LOADED);

  debug0("main: entering loop");
  while (1) {
    mainloop(1);
  }
}
Пример #27
0
int main(int argc, char **argv)
{
        dev_name = "/dev/video0";

        for (;;) {
                int idx;
                int c;

                c = getopt_long(argc, argv,
                                short_options, long_options, &idx);

                if (-1 == c)
                        break;

                switch (c) {
                case 0: /* getopt_long() flag */
                        break;

                case 'd':
                        dev_name = optarg;
                        break;

                case 'h':
                        usage(stdout, argc, argv);
                        exit(EXIT_SUCCESS);

                case 'm':
                        io = IO_METHOD_MMAP;
                        break;

                case 'r':
                        io = IO_METHOD_READ;
                        break;

                case 'u':
                        io = IO_METHOD_USERPTR;
                        break;

                case 'o':
                        out_buf++;
                        break;

                case 'f':
                        force_format=1;
                        break;

		case 'F':
			force_format=2;
			break;

                case 'c':
                        errno = 0;
                        frame_count = strtol(optarg, NULL, 0);
                        if (errno)
                                errno_exit(optarg);
                        break;

                default:
                        usage(stderr, argc, argv);
                        exit(EXIT_FAILURE);
                }
        }

        open_device();
        init_device();
        start_capturing();
        mainloop();
        stop_capturing();
        uninit_device();
        close_device();
        fprintf(stderr, "\n");
        return 0;
}
Пример #28
0
int main(int argc, char **argv) {
	int listen_fd;
	sp_session *session;
	static sp_session_config config;
	static sp_session_callbacks callbacks = {
		.logged_in		= &sess_callback_logged_in,
		.logged_out		= &sess_callback_logged_out,
		.metadata_updated	= &sess_callback_metadata_updated,
		.connection_error	= NULL,
		.message_to_user	= &sess_callback_message_to_user,
		.notify_main_thread	= &sess_callback_notify,
		.music_delivery		= &player_callback_frame_delivery,
		.play_token_lost	= &player_callback_playtoken_lost,
		.log_message		= &sess_callback_log_message,
		.end_of_track		= &player_callback_end_of_track,
		.streaming_error	= NULL,
		.userinfo_updated	= NULL,
		.start_playback		= &player_callback_start_playback,
		.stop_playback		= &player_callback_stop_playback,
		.get_audio_buffer_stats	= &player_callback_get_audio_buffer_stats,
		// libspotify 10
		.offline_status_updated	= &sess_callback_offline_status_updated,
		.offline_error		= &sess_callback_offline_error,
		// libspotify 11
		.credentials_blob_updated	= sess_callback_credentials_blob_updated,
		// libspotify 12
		.connectionstate_updated	= &sess_callback_connectionstate_updated,
		.scrobble_error			= NULL,
		.private_session_mode_changed	= NULL,
	};

	thread_main = pthread_self();

	/* Setup logging to stderr */
	openlog(LIBSPOTIFY_USERAGENT, LOG_PERROR, LOG_USER);

	/**
	 * Filter logging with one of these 
	 *
	setlogmask(LOG_UPTO(LOG_WARNING));
	setlogmask(LOG_UPTO(LOG_NOTICE));
	setlogmask(LOG_UPTO(LOG_DEBUG));
	 */
	setlogmask(LOG_UPTO(LOG_INFO));

	config.api_version = SPOTIFY_API_VERSION;
	config.cache_location = LIBSPOTIFY_CACHE_DIR;
	config.settings_location = LIBSPOTIFY_CACHE_DIR;
	config.application_key = g_appkey;
	config.application_key_size = sizeof(g_appkey);
	config.user_agent = LIBSPOTIFY_USERAGENT;
	config.callbacks = &callbacks;
	config.userdata = app_create();
	config.compress_playlists = 1;
	config.dont_save_metadata_for_playlists = 0;
	config.initially_unload_playlists = 0;
	config.device_id = NULL;

	syslog(LOG_DEBUG, "MAIN: Initializing libspotify");
	if(sp_session_create(&config, &session) != SP_ERROR_OK) {
		syslog(LOG_ERR, "MAIN: Unable to initialize libspotify");
		app_release();
		return -1;
	}

	app_set_session(session);
	if(argc == 4) {
		sp_link *link = sp_link_create_from_string(argv[3]);
		app_set_link(link);
	}

	/* This program will be run on mobile internet connections */
	sp_session_set_connection_type(session, SP_CONNECTION_TYPE_MOBILE_ROAMING);
	sp_session_set_connection_rules(session, SP_CONNECTION_RULE_NETWORK|SP_CONNECTION_RULE_NETWORK_IF_ROAMING|SP_CONNECTION_RULE_ALLOW_SYNC_OVER_MOBILE);
	sp_session_preferred_offline_bitrate(session, SP_BITRATE_160k, 0);

	if(argc < 2) {
		char username[256];

		if(sp_session_remembered_user(session, username, sizeof(username)) > 0)
			syslog(LOG_DEBUG, "MAIN: Attempting to login using stored credentials for user '%s'", username);

		if(sp_session_relogin(session) == SP_ERROR_NO_CREDENTIALS) {
			syslog(LOG_ERR, "MAIN: No credentials stored. Please run: %s <username> <password>", argv[0]);
			app_release();
			return -1;
		}
	}
	else {
		syslog(LOG_DEBUG, "MAIN: Attempting to login using command line credentials");
		sp_session_login(session, argv[1], argc == 3? argv[2]: NULL, 1, get_auth_blob());
	}

	if((listen_fd = net_create(CTRL_TCP_PORT)) < 0) {
		syslog(LOG_ERR, "MAIN: Failed to initialize external network");
		app_release();
		return -1;
	}

	mainloop(session, listen_fd);
	syslog(LOG_INFO, "MAIN: Outside main event loop, good bye!");

	net_release(listen_fd);
	app_release();

	return 0;
}
Пример #29
0
int main(int argc, char **argv)
{
    struct gopherus g;
    struct url start_url;
    char start_url_str[] = "gopher://#welcome";

    memset(&g, '\0', sizeof g);

    /* Load configuration (or defaults) */
    loadcfg(&g.cfg);

    ui_init();

    parse_url(start_url_str, &start_url);

    if (history_add(&g.history, &start_url) != 0) {
        ui_puts("Out of memory.");
        return 2;
    }

    if (argc > 1) { /* if some params have been received, parse them */
        int i;
        int goturl = 0;

        for (i = 1; i < argc; i++) {
            struct url next_url;

            if ((argv[i][0] == '/') || (argv[i][0] == '-')) { /* unknown parameter */
                ui_puts("Gopherus v" VERSION " Copyright (C) Mateusz Viste " DATE);
                ui_puts("");
                ui_puts("Usage: gopherus [url]");
                ui_puts("");
                return 1;
            }
            if (goturl != 0) {
                ui_puts("Invalid parameters list.");
                return 1;
            }
            if (parse_url(argv[1], &next_url) != 0) {
                ui_puts("Invalid URL!");
                return 1;
            }
            goturl = 1;
            history_add(&g.history, &next_url);
            if (g.history == NULL) {
                ui_puts("Out of memory.");
                return 2;
            }
        }
    }

    g.buf = malloc(buffersize);

    if (g.buf == NULL) {
        char message[128];
        sprintf(message, "Out of memory. Could not allocate buffer of %d bytes.", buffersize);
        ui_puts(message);
        return 2;
    }

    if (net_init() != 0) {
        ui_puts("Network subsystem initialization failed!");
        free(g.buf);
        return 3;
    }

    ui_cursor_hide();
    ui_cls();

    mainloop(&g);

    ui_cls();
    ui_cursor_show();

    if (g.statusbar[0] != 0)
        ui_puts(g.statusbar); /* we might have here an error message to show */

    /* Free the main buffer */
    free(g.buf);
    /* unallocate all the history */
    history_flush(g.history);

    return 0;
}
Пример #30
0
void loop()
{
	mainloop();
}