void sigwinch_handler(int signo)
{
    // TODO (std_string) : may be some reaction
    clear_input_handler();
    install_input_handler();
    install_signal_handlers();
}
void sigtstp_handler(int signo)
{
    // TODO (std_string) : may be use rl_echo_signal_char(int)
    std::cout << "^Z" << std::endl;
    cstate.set_execution_state(EX_FINISH);
    install_signal_handlers();
}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{ 
  char *command_name;
  rlwrap_command_line = unsplit_with(argc, argv, " ");     
  init_completer();

  /* Harvest options and leave optind pointing to first non-option argument: */
  command_name = read_options_and_command_name(argc, argv);

  /* by now, optind points to slave <command>, and &argv[optind] is <command>'s argv. Remember slave command line: */
  command_line = unsplit_with(argc - optind, argv, " ");

  /* if stdin is not a tty, just execute <command>: */ 
  if (!isatty(STDIN_FILENO) && execvp(argv[optind], &argv[optind]) < 0)
    myerror(FATAL|USE_ERRNO, "Cannot execute %s", argv[optind]);	
  init_rlwrap(rlwrap_command_line);
  install_signal_handlers();	
  block_all_signals();
  fork_child(command_name, argv); /* this will unblock most signals most of the time */
  if (filter_command)
    spawn_filter(filter_command);
  
  main_loop();
  return 42;			/* The Answer, but, sadly, we'll never get there.... */
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
	int nproc;
	/*
	 * For each of argv[1] to argv[argc - 1],
	 * create a new child process, add it to the process list.
	 */

	nproc = 0; /* number of proccesses goes here */

	/* Wait for all children to raise SIGSTOP before exec()ing. */
	wait_for_ready_children(nproc);

	/* Install SIGALRM and SIGCHLD handlers. */
	install_signal_handlers();

	if (nproc == 0) {
		fprintf(stderr, "Scheduler: No tasks. Exiting...\n");
		exit(1);
	}


	/* loop forever  until we exit from inside a signal handler. */
	while (pause())
		;

	/* Unreachable */
	fprintf(stderr, "Internal error: Reached unreachable point\n");
	return 1;
}
void sigint_handler(int signo)
{
    // ^C already is shown on screen
    std::cout << std::endl;
    interrupt_command(cstate.get_socketd());
    install_signal_handlers();
}
Exemplo n.º 6
0
int main_loop()
{
	install_signal_handlers();

	for(;;) {
		int pid, status;

		pid = wait(&status);

		if ((pid == -1) && (errno != EINTR))
		{
			perror("wait error");
			return 255;
		}
		else if (pid == child_pid)
		{
			if (WIFEXITED(status)) {
				// normal exit
				return WEXITSTATUS(status);
			} else if (WIFSIGNALED(status)) {
				// killed
				int sig = WTERMSIG(status);
				fprintf(stderr, "killed by signal %d (%s)\n", sig, strsignal(sig));
				return 255;
			} else {
				// unreachable
				fprintf(stderr, "bad exit status");
				fflush(stderr);
				abort();
			}
		}
	}
}
Exemplo n.º 7
0
//
// TODO: Include your function header here
//
int
main(int argc, char *argv[])
{
    int retcode = EXIT_SUCCESS;
    prog_options_t my_opt;

    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();

    // do some checks and initialisations...
    open_logfile(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();

    // TODO: start the proxy server and handle connections...
    // here, as an example, show how to interact with the
    // condition set by the signal handler above
    printf("[%d] Starting proxy server '%s'...\n", getpid(), my_opt.progname);
    server_running = true;
    while(server_running) {
        pause();
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
Exemplo n.º 8
0
int main(
	int argc,
	char *argv[]
)
{
	int server = 0; //listen用socket
	char *port = NULL;
	char *docroot;
	int opt;

	while ((opt = getopt_long(argc, argv, "", longopts, NULL)) != -1)
	{
		switch(opt)
		{
			case 0:
				break;

			case 'c':
				break;

			case 'p':
				port = optarg;
				break;
			case 'h':
				fprintf(stdout, USAGE, argv[0]);
				exit(0);

			case '?':
				fprintf(stderr, USAGE, argv[0]);
				exit(1);
		}
	}

	if(optind != argc - 1)
	{
		fprintf(stderr, USAGE, argv[0]);
		exit(1);
	}

	/* ドキュメントのrootディレクトリを設定 */
	docroot = argv[optind];

	/* シグナル捕捉の設定 */
	install_signal_handlers();

	/* listenソケットの作成 */
	server = listen_socket(port);

	if(!debug_mode)
	{
		openlog(SERVER_NAME, LOG_PID|LOG_NDELAY, LOG_DAEMON);
		/* デーモンプロセスになる */
		become_daemon();
	}

	server_main(server, docroot);
	return 0;
}
int main(int argc, char **argv)
{
  GtkWidget *window, *button, *textview, *vbox;
  GtkWidget *socket, *plug, *socket_box;

  unsigned long     kb_xid;

  gtk_init (&argc, &argv);

  install_signal_handlers();

  kb_xid = launch_keyboard();

  if (!kb_xid)
    {
      perror ("### 'matchbox-keyboard --xid', failed to return valid window ID. ### ");
      exit(-1);
    }

  /* Window */

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gtk_window_set_default_size (GTK_WINDOW (window), 640, 480);
  gtk_container_set_border_width (GTK_CONTAINER (window), 10);

  g_signal_connect (G_OBJECT (window), "destroy",
		    G_CALLBACK (widget_destroy), NULL);

  /* Container and textview */

  vbox = gtk_vbox_new(FALSE, 5);
  gtk_container_add (GTK_CONTAINER (window), vbox);
  
  textview = gtk_text_view_new();
  gtk_box_pack_start (GTK_BOX(vbox), textview, TRUE, TRUE, 2);

  /* Socket ( XEMBED ) stuff */

  socket_box = gtk_event_box_new ();
  gtk_widget_show (socket_box);
  
  socket = gtk_socket_new ();

  gtk_container_add (GTK_CONTAINER (socket_box), socket);
  gtk_box_pack_start (GTK_BOX (vbox), GTK_WIDGET(socket_box), TRUE, TRUE, 0);
  gtk_socket_add_id(GTK_SOCKET(socket), kb_xid); 

  /* FIXME: handle "plug-added" & "plug-removed" signals for socket */

  gtk_widget_show_all (window);

  gtk_main ();

  return 0;
}
Exemplo n.º 10
0
int main(int argc, char *argv[]) {
  int server;
  char *port = NULL;
  char *docroot;
  int do_chroot = 0;
  char *user = NULL;
  char *group = NULL;
  int opt;

  while ((opt = getopt_long(argc, argv, "p:h:", longopts, NULL)) != -1) {
    switch (opt) {
      case 0:
        break;
      case 'c':
        do_chroot = 1;
        break;
      case 'u':
        user = optarg;
        break;
      case 'g':
        group = optarg;
        break;
      case 'p':
        port = optarg;
        break;
      case 'h':
        fprintf(stdout, USAGE, argv[0]);
        exit(0);
      case '?':
        fprintf(stderr, USAGE, argv[0]);
        exit(1);
    }
  }
  if (optind != argc - 1) {
    fprintf(stderr, USAGE, argv[0]);
    exit(1);
  }
  docroot = argv[optind];

  if (do_chroot) {
    setup_environment(docroot, user, group);
    docroot = "";
  }
  install_signal_handlers();
  server = listen_socket(port);
  if (!debug_mode) {
    openlog(SERVER_NAME, LOG_PID|LOG_NDELAY, LOG_DAEMON);
    become_daemon();
  }
  server_main(server, docroot);
  exit(0);
}
Exemplo n.º 11
0
int
main(int argc, char *argv[])
{
	int sockfd;
    int retcode = EXIT_SUCCESS;


    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();
  /*  printf("Server Port: %d\n", my_opt.server_port);
    //printf("Server Address: %d\n", my_opt.server_addr);
    printf("Progname: %s\n", my_opt.progname);
    printf("Root Dir: %s\n", my_opt.root_dir);
    printf("Log File: %s\n", my_opt.log_filename); */

    // do some checks and initialisations...
    open_logfile(&my_opt);
    check_root_dir(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();

    // TODO: start the server and handle clients...

    // here, as an example, show how to interact with the
    // condition set by the signal handler above
    //printf("[%d] Starting server '%s'...\n", getpid(), my_opt.progname);
    server_running = true;
    prog_options_t *opt = &my_opt;
    struct sockaddr_in* struct_port = (struct sockaddr_in*) opt->server_addr->ai_addr;
    sockfd = server_init(ntohs(struct_port->sin_port));

    //printf("Port: %i \n", sockfd);
    while(server_running) {

    	client_connection(sockfd);
        //pause();
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
	pid_t p;
	int i;
	/*
	 * For each of argv[1] to argv[argc - 1],
	 * create a new child process, add it to the process list.
	 */
	current = 0; /* current proccess number goes here */
	nprog = argc - 1; /* number of proccesses goes here */
	childid = malloc((nprog)*sizeof(int));
	alive = malloc((nprog)*sizeof(int));
	for (i=0; i < nprog; i++){
		printf("forking..%d %d\n", argc, i);
		p = fork();
		//if (p<0)...
		if (p == 0){
			do_child(argv[i+1]);
		}
		else{
			childid[i] = (int) p;
			alive[i] = 1;
		}
	}

	/* Wait for all children to raise SIGSTOP before exec()ing. */
	wait_for_ready_children(nprog);
	/* Install SIGALRM and SIGCHLD handlers. */
	install_signal_handlers();

	if (nprog == 0) {
		fprintf(stderr, "Scheduler: No tasks. Exiting...\n");
		exit(1);
	}
	else{
		alarm(SCHED_TQ_SEC);	
		kill(childid[0], SIGCONT);
		
	}


	/* loop forever  until we exit from inside a signal handler. */
	while (pause())
		;

	/* Unreachable */
	fprintf(stderr, "Internal error: Reached unreachable point\n");
	return 1;
}
Exemplo n.º 13
0
/*
 * Read parameters and fork off children that abuse first mmap and then
 * io_setup in the hopes of causing an oops.
 */
int main(int argc, char *argv[]) {
	int i, x, forks, mmap_calls, iosetup_calls;

	if (argc < 4) {
		printf("Usage: %s forks mmap_calls iosetup_calls\n", argv[0]);
		return 1;
	}

	forks = atoi(argv[1]);
	mmap_calls = atoi(argv[2]);
	iosetup_calls = atoi(argv[3]);

	printf("%.5d: forks = %d mmaps = %d iosetups = %d\n", getpid(), forks, mmap_calls, iosetup_calls);

	for (i = 0; i < forks; i++) {
		x = fork();
		if (x == 0) {
			/* new proc, so start pounding */
			printf("%.5d: initializing.\n", getpid());
			seed_random();
			install_signal_handlers();

			printf("%.5d: creating mmaps.\n", getpid());
			mmap_pound(mmap_calls);

			examine_vmsize();

			printf("%.5d: calling iosetup..\n", getpid());
			iosetup_pound(iosetup_calls);

			printf("%.5d: done pounding.\n", getpid());

			return 0;
		} else {
			printf("%.5d: forked pid %.5d.\n", getpid(), x);
		}
	}

	printf("%.5d: waiting for children.\n", getpid());
	for (i = 0; i < forks; i++) {
		wait(NULL);
	}
	printf("%.5d: exiting.\n", getpid());

	return 0;
}
Exemplo n.º 14
0
int
main(int argc, char *argv[])
{
    int retcode = EXIT_SUCCESS;
    prog_options_t my_opt;

    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();

    // do some checks and initialisations...
    open_logfile(&my_opt);
    check_root_dir(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();
    
    // get root_dir to handle it later in child process
    char* root_dir = my_opt.root_dir;

    // start the server and create socket
    printf("[%d] Starting server '%s'...\n", getpid(), my_opt.progname);
    int accepting_socket = passive_tcp(my_opt.server_port, 5);
    struct sockaddr_in from_client;
    
    server_running = true;
    while(server_running) {
        socklen_t from_client_len = sizeof(from_client);
        
        // Accept new Client
        int listening_socket = accept(accepting_socket, (struct sockaddr *) &from_client, &from_client_len);
        
        accept_client(accepting_socket, listening_socket, root_dir);
        
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
Exemplo n.º 15
0
int
main
(
    int argc,
    char *argv[]
)
{
    dbg( "argc=%d, argv=%p\n", argc, argv );

    usage( argc, argv );

    chk_doc_root( argv[1] );

    install_signal_handlers();

    service( stdin, stdout, argv[1] );

    return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[]) {
	int debug = 0;
	
	if (!seed_random()) {
		return 1;
	}

	if (argc > 1 && strcmp(argv[1], "-d") == 0) {
		debug = 1;
	}

	/*
	FILE *fp = fopen("/dev/tty", "w");
	fprintf(fp, "randasys process group is %d\n", getpgrp());
	fclose(fp);
	*/

	install_signal_handlers();

	while(1) {
		callnum = find_syscall();
		args[0] = get_randnum(0, ULONG_MAX);
		args[1] = get_randnum(0, ULONG_MAX);
		args[2] = get_randnum(0, ULONG_MAX);
		args[3] = get_randnum(0, ULONG_MAX);
		args[4] = get_randnum(0, ULONG_MAX);
		args[5] = get_randnum(0, ULONG_MAX);

		if (debug) {
			printf("syscall(%d, 0x%X, 0x%X, 0x%X, 0x%X, 0x%X, 0x%X);       \r",
				callnum, args[0], args[1], args[2], args[3], args[4],
				args[5]);
			fflush(stdout);
		}

		syscall(callnum, args[0], args[1], args[2],
				args[3], args[4], args[5]);
		
	}

	return 0;
}
Exemplo n.º 17
0
int main(int argc, char **argv) {
	if (argc < 2) {
		print_usage();
		return 1;
	}
	install_signal_handlers();
	lua_State* L = launch_lua("./include/main.lua");
	if (!L) {
		return -1;
	}
	lua_pushstring(L, "master");
	for (int i = 0; i < argc; i++) {
		lua_pushstring(L, argv[i]);
	}
	if (lua_pcall(L, argc + 1, 0, 0)) {
		printf("Lua error: %s\n", lua_tostring(L, -1));
		return -1;
	}
	return 0;
}
Exemplo n.º 18
0
Arquivo: main.c Projeto: albfan/rlwrap
int
main(int argc, char **argv)
{ 
  char *command_name;
  
  init_completer();
  command_name = read_options_and_command_name(argc, argv);
  
  /* by now, optind points to <command>, and &argv[optind] is <command>'s argv */
  if (!isatty(STDIN_FILENO) && execvp(argv[optind], &argv[optind]) < 0)
    /* if stdin is not a tty, just execute <command> */ 
    myerror("Cannot execute %s", argv[optind]);	
  init_rlwrap();
  install_signal_handlers();	
  block_all_signals();
  fork_child(command_name, argv);
  if (filter_command)
    spawn_filter(filter_command);
  
  main_loop();
  return 42;			/* not reached, but some compilers are unhappy without this ... */
}
Exemplo n.º 19
0
Arquivo: randasys.c Projeto: 1587/ltp
int main(int argc, char *argv[])
{
	int i;
	int debug = 0, zero_mode = 0;

	if (!seed_random()) {
		return 1;
	}

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-d"))
			debug = 1;
		else if (!strcmp(argv[i], "-z"))
			zero_mode = 1;
	}

	memset(args, 0, sizeof(unsigned long) * 6);

	install_signal_handlers();

	while (1) {
		callnum = find_syscall();
		if (!zero_mode)
			get_big_randnum(&args[0], sizeof(unsigned long) * 6);

		if (debug) {
			printf("syscall(%lu, 0x%lX, 0x%lX, 0x%lX, 0x%lX, "
			       "0x%lX, 0x%lX);       \n",
			       callnum, args[0], args[1], args[2], args[3],
			       args[4], args[5]);
			fflush(stdout);
		}

		syscall(callnum, args[0], args[1], args[2],
			args[3], args[4], args[5]);
	}

	return 0;
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{
  srvr_sockaddr_union_t me;
  curl_socket_t sock = CURL_SOCKET_BAD;
  curl_socket_t msgsock = CURL_SOCKET_BAD;
  int wrotepidfile = 0;
  char *pidname= (char *)".sockfilt.pid";
  bool juggle_again;
  int rc;
  int error;
  int arg=1;
  enum sockmode mode = PASSIVE_LISTEN; /* default */
  const char *addr = NULL;

  while(argc>arg) {
    if(!strcmp("--version", argv[arg])) {
      printf("sockfilt IPv4%s\n",
#ifdef ENABLE_IPV6
             "/IPv6"
#else
             ""
#endif
             );
      return 0;
    }
    else if(!strcmp("--verbose", argv[arg])) {
      verbose = TRUE;
      arg++;
    }
    else if(!strcmp("--pidfile", argv[arg])) {
      arg++;
      if(argc>arg)
        pidname = argv[arg++];
    }
    else if(!strcmp("--logfile", argv[arg])) {
      arg++;
      if(argc>arg)
        serverlogfile = argv[arg++];
    }
    else if(!strcmp("--ipv6", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv6";
      use_ipv6 = TRUE;
#endif
      arg++;
    }
    else if(!strcmp("--ipv4", argv[arg])) {
      /* for completeness, we support this option as well */
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv4";
      use_ipv6 = FALSE;
#endif
      arg++;
    }
    else if(!strcmp("--bindonly", argv[arg])) {
      bind_only = TRUE;
      arg++;
    }
    else if(!strcmp("--port", argv[arg])) {
      arg++;
      if(argc>arg) {
        char *endptr;
        unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
        if((endptr != argv[arg] + strlen(argv[arg])) ||
           ((ulnum != 0UL) && ((ulnum < 1025UL) || (ulnum > 65535UL)))) {
          fprintf(stderr, "sockfilt: invalid --port argument (%s)\n",
                  argv[arg]);
          return 0;
        }
        port = curlx_ultous(ulnum);
        arg++;
      }
    }
    else if(!strcmp("--connect", argv[arg])) {
      /* Asked to actively connect to the specified local port instead of
         doing a passive server-style listening. */
      arg++;
      if(argc>arg) {
        char *endptr;
        unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
        if((endptr != argv[arg] + strlen(argv[arg])) ||
           (ulnum < 1025UL) || (ulnum > 65535UL)) {
          fprintf(stderr, "sockfilt: invalid --connect argument (%s)\n",
                  argv[arg]);
          return 0;
        }
        connectport = curlx_ultous(ulnum);
        arg++;
      }
    }
    else if(!strcmp("--addr", argv[arg])) {
      /* Set an IP address to use with --connect; otherwise use localhost */
      arg++;
      if(argc>arg) {
        addr = argv[arg];
        arg++;
      }
    }
    else {
      puts("Usage: sockfilt [option]\n"
           " --version\n"
           " --verbose\n"
           " --logfile [file]\n"
           " --pidfile [file]\n"
           " --ipv4\n"
           " --ipv6\n"
           " --bindonly\n"
           " --port [port]\n"
           " --connect [port]\n"
           " --addr [address]");
      return 0;
    }
  }

#ifdef WIN32
  win32_init();
  atexit(win32_cleanup);

  setmode(fileno(stdin), O_BINARY);
  setmode(fileno(stdout), O_BINARY);
  setmode(fileno(stderr), O_BINARY);
#endif

  install_signal_handlers();

#ifdef ENABLE_IPV6
  if(!use_ipv6)
#endif
    sock = socket(AF_INET, SOCK_STREAM, 0);
#ifdef ENABLE_IPV6
  else
    sock = socket(AF_INET6, SOCK_STREAM, 0);
#endif

  if(CURL_SOCKET_BAD == sock) {
    error = SOCKERRNO;
    logmsg("Error creating socket: (%d) %s",
           error, strerror(error));
    write_stdout("FAIL\n", 5);
    goto sockfilt_cleanup;
  }

  if(connectport) {
    /* Active mode, we should connect to the given port number */
    mode = ACTIVE;
#ifdef ENABLE_IPV6
    if(!use_ipv6) {
#endif
      memset(&me.sa4, 0, sizeof(me.sa4));
      me.sa4.sin_family = AF_INET;
      me.sa4.sin_port = htons(connectport);
      me.sa4.sin_addr.s_addr = INADDR_ANY;
      if (!addr)
        addr = "127.0.0.1";
      Curl_inet_pton(AF_INET, addr, &me.sa4.sin_addr);

      rc = connect(sock, &me.sa, sizeof(me.sa4));
#ifdef ENABLE_IPV6
    }
    else {
      memset(&me.sa6, 0, sizeof(me.sa6));
      me.sa6.sin6_family = AF_INET6;
      me.sa6.sin6_port = htons(connectport);
      if (!addr)
        addr = "::1";
      Curl_inet_pton(AF_INET6, addr, &me.sa6.sin6_addr);

      rc = connect(sock, &me.sa, sizeof(me.sa6));
    }
#endif /* ENABLE_IPV6 */
    if(rc) {
      error = SOCKERRNO;
      logmsg("Error connecting to port %hu: (%d) %s",
             connectport, error, strerror(error));
      write_stdout("FAIL\n", 5);
      goto sockfilt_cleanup;
    }
    logmsg("====> Client connect");
    msgsock = sock; /* use this as stream */
  }
  else {
    /* passive daemon style */
    sock = sockdaemon(sock, &port);
    if(CURL_SOCKET_BAD == sock) {
      write_stdout("FAIL\n", 5);
      goto sockfilt_cleanup;
    }
    msgsock = CURL_SOCKET_BAD; /* no stream socket yet */
  }

  logmsg("Running %s version", ipv_inuse);

  if(connectport)
    logmsg("Connected to port %hu", connectport);
  else if(bind_only)
    logmsg("Bound without listening on port %hu", port);
  else
    logmsg("Listening on port %hu", port);

  wrotepidfile = write_pidfile(pidname);
  if(!wrotepidfile) {
    write_stdout("FAIL\n", 5);
    goto sockfilt_cleanup;
  }

  do {
    juggle_again = juggle(&msgsock, sock, &mode);
  } while(juggle_again);

sockfilt_cleanup:

  if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
    sclose(msgsock);

  if(sock != CURL_SOCKET_BAD)
    sclose(sock);

  if(wrotepidfile)
    unlink(pidname);

  restore_signal_handlers();

  if(got_exit_signal) {
    logmsg("============> sockfilt exits with signal (%d)", exit_signal);
    /*
     * To properly set the return status of the process we
     * must raise the same signal SIGINT or SIGTERM that we
     * caught and let the old handler take care of it.
     */
    raise(exit_signal);
  }

  logmsg("============> sockfilt quits");
  return 0;
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
  struct sockaddr_in me;
#ifdef ENABLE_IPV6
  struct sockaddr_in6 me6;
#endif /* ENABLE_IPV6 */
  curl_socket_t sock = CURL_SOCKET_BAD;
  curl_socket_t msgsock = CURL_SOCKET_BAD;
  int wrotepidfile = 0;
  int flag;
  unsigned short port = DEFAULT_PORT;
  char *pidname= (char *)".rtsp.pid";
  struct httprequest req;
  int rc;
  int error;
  int arg=1;
  long pid;

  while(argc>arg) {
    if(!strcmp("--version", argv[arg])) {
      printf("rtspd IPv4%s"
             "\n"
             ,
#ifdef ENABLE_IPV6
             "/IPv6"
#else
             ""
#endif
             );
      return 0;
    }
    else if(!strcmp("--pidfile", argv[arg])) {
      arg++;
      if(argc>arg)
        pidname = argv[arg++];
    }
    else if(!strcmp("--logfile", argv[arg])) {
      arg++;
      if(argc>arg)
        serverlogfile = argv[arg++];
    }
    else if(!strcmp("--ipv4", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv4";
      use_ipv6 = FALSE;
#endif
      arg++;
    }
    else if(!strcmp("--ipv6", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv6";
      use_ipv6 = TRUE;
#endif
      arg++;
    }
    else if(!strcmp("--port", argv[arg])) {
      arg++;
      if(argc>arg) {
        char *endptr;
        long lnum = -1;
        lnum = strtol(argv[arg], &endptr, 10);
        if((endptr != argv[arg] + strlen(argv[arg])) ||
           (lnum < 1025L) || (lnum > 65535L)) {
          fprintf(stderr, "rtspd: invalid --port argument (%s)\n",
                  argv[arg]);
          return 0;
        }
        port = (unsigned short)(lnum & 0xFFFFL);
        arg++;
      }
    }
    else if(!strcmp("--srcdir", argv[arg])) {
      arg++;
      if(argc>arg) {
        path = argv[arg];
        arg++;
      }
    }
    else {
      puts("Usage: rtspd [option]\n"
           " --version\n"
           " --logfile [file]\n"
           " --pidfile [file]\n"
           " --ipv4\n"
           " --ipv6\n"
           " --port [port]\n"
           " --srcdir [path]");
      return 0;
    }
  }

#ifdef WIN32
  win32_init();
  atexit(win32_cleanup);
#endif

  install_signal_handlers();

  pid = (long)getpid();

#ifdef ENABLE_IPV6
  if(!use_ipv6)
#endif
    sock = socket(AF_INET, SOCK_STREAM, 0);
#ifdef ENABLE_IPV6
  else
    sock = socket(AF_INET6, SOCK_STREAM, 0);
#endif

  if(CURL_SOCKET_BAD == sock) {
    error = SOCKERRNO;
    logmsg("Error creating socket: (%d) %s",
           error, strerror(error));
    goto server_cleanup;
  }

  flag = 1;
  if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
            (void *)&flag, sizeof(flag))) {
    error = SOCKERRNO;
    logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
           error, strerror(error));
    goto server_cleanup;
  }

#ifdef ENABLE_IPV6
  if(!use_ipv6) {
#endif
    memset(&me, 0, sizeof(me));
    me.sin_family = AF_INET;
    me.sin_addr.s_addr = INADDR_ANY;
    me.sin_port = htons(port);
    rc = bind(sock, (struct sockaddr *) &me, sizeof(me));
#ifdef ENABLE_IPV6
  }
  else {
    memset(&me6, 0, sizeof(me6));
    me6.sin6_family = AF_INET6;
    me6.sin6_addr = in6addr_any;
    me6.sin6_port = htons(port);
    rc = bind(sock, (struct sockaddr *) &me6, sizeof(me6));
  }
#endif /* ENABLE_IPV6 */
  if(0 != rc) {
    error = SOCKERRNO;
    logmsg("Error binding socket on port %hu: (%d) %s",
           port, error, strerror(error));
    goto server_cleanup;
  }

  logmsg("Running %s version on port %d", ipv_inuse, (int)port);

  /* start accepting connections */
  rc = listen(sock, 5);
  if(0 != rc) {
    error = SOCKERRNO;
    logmsg("listen() failed with error: (%d) %s",
           error, strerror(error));
    goto server_cleanup;
  }

  /*
  ** As soon as this server writes its pid file the test harness will
  ** attempt to connect to this server and initiate its verification.
  */

  wrotepidfile = write_pidfile(pidname);
  if(!wrotepidfile)
    goto server_cleanup;

  for (;;) {
    msgsock = accept(sock, NULL, NULL);

    if(got_exit_signal)
      break;
    if (CURL_SOCKET_BAD == msgsock) {
      error = SOCKERRNO;
      logmsg("MAJOR ERROR: accept() failed with error: (%d) %s",
             error, strerror(error));
      break;
    }

    /*
    ** As soon as this server acepts a connection from the test harness it
    ** must set the server logs advisor read lock to indicate that server
    ** logs should not be read until this lock is removed by this server.
    */

    set_advisor_read_lock(SERVERLOGS_LOCK);
    serverlogslocked = 1;

    logmsg("====> Client connect");

#ifdef TCP_NODELAY
    /*
     * Disable the Nagle algorithm to make it easier to send out a large
     * response in many small segments to torture the clients more.
     */
    flag = 1;
    if (setsockopt(msgsock, IPPROTO_TCP, TCP_NODELAY,
                   (void *)&flag, sizeof(flag)) == -1) {
      logmsg("====> TCP_NODELAY failed");
    }
#endif

    /* initialization of httprequest struct is done in get_request(), but due
       to pipelining treatment the pipelining struct field must be initialized
       previously to FALSE every time a new connection arrives. */

    req.pipelining = FALSE;

    do {
      if(got_exit_signal)
        break;

      if(get_request(msgsock, &req))
        /* non-zero means error, break out of loop */
        break;

      if(prevbounce) {
        /* bounce treatment requested */
        if((req.testno == prevtestno) &&
           (req.partno == prevpartno)) {
          req.partno++;
          logmsg("BOUNCE part number to %ld", req.partno);
        }
        else {
          prevbounce = FALSE;
          prevtestno = -1;
          prevpartno = -1;
        }
      }

      send_doc(msgsock, &req);
      if(got_exit_signal)
        break;

      if((req.testno < 0) && (req.testno != DOCNUMBER_CONNECT)) {
        logmsg("special request received, no persistency");
        break;
      }
      if(!req.open) {
        logmsg("instructed to close connection after server-reply");
        break;
      }

      if(req.open)
        logmsg("=> persistant connection request ended, awaits new request");
      /* if we got a CONNECT, loop and get another request as well! */
    } while(req.open || (req.testno == DOCNUMBER_CONNECT));

    if(got_exit_signal)
      break;

    logmsg("====> Client disconnect");
    sclose(msgsock);
    msgsock = CURL_SOCKET_BAD;

    if(serverlogslocked) {
      serverlogslocked = 0;
      clear_advisor_read_lock(SERVERLOGS_LOCK);
    }

    if (req.testno == DOCNUMBER_QUIT)
      break;
  }

server_cleanup:

  if((msgsock != sock) && (msgsock != CURL_SOCKET_BAD))
    sclose(msgsock);

  if(sock != CURL_SOCKET_BAD)
    sclose(sock);

  if(got_exit_signal)
    logmsg("signalled to die");

  if(wrotepidfile)
    unlink(pidname);

  if(serverlogslocked) {
    serverlogslocked = 0;
    clear_advisor_read_lock(SERVERLOGS_LOCK);
  }

  restore_signal_handlers();

  if(got_exit_signal) {
    logmsg("========> %s rtspd (port: %d pid: %ld) exits with signal (%d)",
           ipv_inuse, (int)port, pid, exit_signal);
    /*
     * To properly set the return status of the process we
     * must raise the same signal SIGINT or SIGTERM that we
     * caught and let the old handler take care of it.
     */
    raise(exit_signal);
  }

  logmsg("========> rtspd quits");
  return 0;
}
Exemplo n.º 22
0
int
main(int argc, char *argv[])
{
    int retcode = EXIT_SUCCESS;
    prog_options_t my_opt;

    // read program options
    if (get_options(argc, argv, &my_opt) == 0) {
        print_usage(my_opt.progname);
        exit(EXIT_FAILURE);
    } /* end if */

    // set the time zone (TZ) to GMT in order to
    // ignore any other local time zone that would
    // interfere with correct time string parsing
    setenv("TZ", "GMT", 1);
    tzset();

    // do some checks and initialisations...
    open_logfile(&my_opt);
    check_root_dir(&my_opt);
    install_signal_handlers();
    init_logging_semaphore();

    // get root_dir to handle it later in child process
    char* root_dir = my_opt.root_dir;
    
    // start the server and create socket
    print_log("Starting server '%s'...\n", my_opt.progname);
    int accepting_socket = passive_tcp(my_opt.server_port, 5);
    if (accepting_socket < 0){
        err_print("Error when opening accepting socket!");
        exit(-1);
    }
    struct sockaddr_in from_client;
    
    int req_no = 0;
    server_running = true;
    while(server_running) {
        socklen_t from_client_len = sizeof(from_client);
        int listening_socket = accept(accepting_socket, (struct sockaddr *) &from_client, &from_client_len);
        
        if (listening_socket >= 0){ /* Accept was ok */
            ++req_no;
            pid_t pid = fork();
            if (pid == 0) 
            { /* Child Process */
                print_log("Process created to handle new request #%d\n", req_no);
                close(accepting_socket);            
                handle_client(listening_socket, root_dir);
                exit(0);
            } 
            else if (pid > 0) 
            { /* Parent Process */
                close(listening_socket);
            } 
            else 
            { /* Fork Failed */
                err_print("Could not fork for new request!");
                exit(-1);
            }
        } /*else {
            print_log("Accept failed!\n");
        }   */   
    } /* end while */

    printf("[%d] Good Bye...\n", getpid());
    exit(retcode);
} /* end of main */
Exemplo n.º 23
0
Arquivo: mce.c Projeto: ClementFan/mce
/**
 * Main
 *
 * @param argc Number of command line arguments
 * @param argv Array with command line arguments
 * @return 0 on success, non-zero on failure
 */
int main(int argc, char **argv)
{
	int optc;
	int opt_index;

	int verbosity = LL_DEFAULT;
	int logtype   = MCE_LOG_SYSLOG;

	gint status = EXIT_FAILURE;
	gboolean show_module_info = FALSE;
	gboolean daemonflag = FALSE;
	gboolean systembus = TRUE;
	gboolean debugmode = FALSE;

	const char optline[] = "dsTSMDqvhVt:";

	struct option const options[] = {
		{ "daemonflag",       no_argument,       0, 'd' },
		{ "force-syslog",     no_argument,       0, 's' },
		{ "force-stderr",     no_argument,       0, 'T' },
		{ "session",          no_argument,       0, 'S' },
		{ "show-module-info", no_argument,       0, 'M' },
		{ "debug-mode",       no_argument,       0, 'D' },
		{ "quiet",            no_argument,       0, 'q' },
		{ "verbose",          no_argument,       0, 'v' },
		{ "help",             no_argument,       0, 'h' },
		{ "version",          no_argument,       0, 'V' },
		{ "trace",            required_argument, 0, 't' },
		{ 0, 0, 0, 0 }
        };

	/* Initialise support for locales, and set the program-name */
	if (init_locales(PRG_NAME) != 0)
		goto EXIT;

	/* Parse the command-line options */
	while ((optc = getopt_long(argc, argv, optline,
				   options, &opt_index)) != -1) {
		switch (optc) {
		case 'd':
			daemonflag = TRUE;
			break;

		case 's':
			logtype = MCE_LOG_SYSLOG;
			break;

		case 'T':
			logtype = MCE_LOG_STDERR;
			break;

		case 'S':
			systembus = FALSE;
			break;

		case 'M':
			show_module_info = TRUE;
			break;

		case 'D':
			debugmode = TRUE;
			break;

		case 'q':
			if (verbosity > LL_NONE)
				verbosity--;
			break;

		case 'v':
			if (verbosity < LL_DEBUG)
				verbosity++;
			break;

		case 'h':
			usage();
			exit(EXIT_SUCCESS);

		case 'V':
			version();
			exit(EXIT_SUCCESS);
		case 't':
			if( !mce_enable_trace(optarg) )
				exit(EXIT_FAILURE);
			break;
		default:
			usage();
			exit(EXIT_FAILURE);
		}
	}

	/* We don't take any non-flag arguments */
	if ((argc - optind) > 0) {
		fprintf(stderr,
			_("%s: Too many arguments\n"
			  "Try: `%s --help' for more information.\n"),
			progname, progname);
		exit(EXIT_FAILURE);
	}

	mce_log_open(PRG_NAME, LOG_DAEMON, logtype);
	mce_log_set_verbosity(verbosity);

#ifdef ENABLE_WAKELOCKS
	/* Since mce enables automatic suspend, we must try to
	 * disable it when mce process exits */
	atexit(mce_cleanup_wakelocks);
#endif

	/* Daemonize if requested */
	if (daemonflag == TRUE)
		daemonize();

	/* Initialise GType system */
	g_type_init();

	/* Register a mainloop */
	mainloop = g_main_loop_new(NULL, FALSE);

	/* Signal handlers can be installed once we have a mainloop */
	if( !mce_init_signal_pipe() ) {
		mce_log(LL_CRIT, "Failed to initialise signal pipe");
		exit(EXIT_FAILURE);
	}
	install_signal_handlers();

	/* Initialise subsystems */

	/* Get configuration options */
	if( !mce_conf_init() ) {
		mce_log(LL_CRIT,
			"Failed to initialise configuration options");
		exit(EXIT_FAILURE);
	}

	/* Initialise D-Bus */
	if (mce_dbus_init(systembus) == FALSE) {
		mce_log(LL_CRIT,
			"Failed to initialise D-Bus");
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	/* Initialise GConf
	 * pre-requisite: g_type_init()
	 */
	if (mce_gconf_init() == FALSE) {
		mce_log(LL_CRIT,
			"Cannot connect to default GConf engine");
		mce_log_close();
		exit(EXIT_FAILURE);
	}

	/* Setup all datapipes */
	setup_datapipe(&system_state_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(MCE_STATE_UNDEF));
	setup_datapipe(&master_radio_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&call_state_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(CALL_STATE_NONE));
	setup_datapipe(&call_type_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(NORMAL_CALL));
	setup_datapipe(&alarm_ui_state_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(MCE_ALARM_UI_INVALID_INT32));
	setup_datapipe(&submode_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(MCE_NORMAL_SUBMODE));
	setup_datapipe(&display_state_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(MCE_DISPLAY_UNDEF));
	setup_datapipe(&display_brightness_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&led_brightness_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&led_pattern_activate_pipe, READ_ONLY, FREE_CACHE,
		       0, NULL);
	setup_datapipe(&led_pattern_deactivate_pipe, READ_ONLY, FREE_CACHE,
		       0, NULL);
	setup_datapipe(&key_backlight_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&keypress_pipe, READ_ONLY, FREE_CACHE,
		       sizeof (struct input_event), NULL);
	setup_datapipe(&touchscreen_pipe, READ_ONLY, FREE_CACHE,
		       sizeof (struct input_event), NULL);
	setup_datapipe(&device_inactive_pipe, READ_WRITE, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(FALSE));
	setup_datapipe(&lockkey_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&keyboard_slide_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&lid_cover_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&lens_cover_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&proximity_sensor_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&tk_lock_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(LOCK_UNDEF));
	setup_datapipe(&charger_state_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&battery_status_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(BATTERY_STATUS_UNDEF));
	setup_datapipe(&battery_level_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(100));
	setup_datapipe(&camera_button_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(CAMERA_BUTTON_UNDEF));
	setup_datapipe(&inactivity_timeout_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(DEFAULT_INACTIVITY_TIMEOUT));
	setup_datapipe(&audio_route_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(AUDIO_ROUTE_UNDEF));
	setup_datapipe(&usb_cable_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&jack_sense_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&power_saving_mode_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));
	setup_datapipe(&thermal_state_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(THERMAL_STATE_UNDEF));
	setup_datapipe(&heartbeat_pipe, READ_ONLY, DONT_FREE_CACHE,
		       0, GINT_TO_POINTER(0));

	/* Initialise mode management
	 * pre-requisite: mce_gconf_init()
	 * pre-requisite: mce_dbus_init()
	 */
	if (mce_mode_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise DSME
	 * pre-requisite: mce_gconf_init()
	 * pre-requisite: mce_dbus_init()
	 * pre-requisite: mce_mce_init()
	 */
	if (mce_dsme_init(debugmode) == FALSE) {
		if (debugmode == FALSE) {
			mce_log(LL_CRIT, "Cannot connect to DSME");
			goto EXIT;
		}
	}

	/* Initialise powerkey driver */
	if (mce_powerkey_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise /dev/input driver
	 * pre-requisite: g_type_init()
	 */
	if (mce_input_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise switch driver */
	if (mce_switches_init() == FALSE) {
		goto EXIT;
	}

	/* Initialise tklock driver */
	if (mce_tklock_init() == FALSE) {
		goto EXIT;
	}

	/* Load all modules */
	if (mce_modules_init() == FALSE) {
		goto EXIT;
	}

	if (show_module_info == TRUE) {
		mce_modules_dump_info();
		goto EXIT;
	}

	/* MCE startup succeeded */
	status = EXIT_SUCCESS;

	/* Run the main loop */
	g_main_loop_run(mainloop);

	/* If we get here, the main loop has terminated;
	 * either because we requested or because of an error
	 */
EXIT:
	/* Unload all modules */
	mce_modules_exit();

	/* Call the exit function for all components */
	mce_tklock_exit();
	mce_switches_exit();
	mce_input_exit();
	mce_powerkey_exit();
	mce_dsme_exit();
	mce_mode_exit();

	/* Free all datapipes */
	free_datapipe(&thermal_state_pipe);
	free_datapipe(&power_saving_mode_pipe);
	free_datapipe(&jack_sense_pipe);
	free_datapipe(&usb_cable_pipe);
	free_datapipe(&audio_route_pipe);
	free_datapipe(&inactivity_timeout_pipe);
	free_datapipe(&battery_level_pipe);
	free_datapipe(&battery_status_pipe);
	free_datapipe(&charger_state_pipe);
	free_datapipe(&tk_lock_pipe);
	free_datapipe(&proximity_sensor_pipe);
	free_datapipe(&lens_cover_pipe);
	free_datapipe(&lid_cover_pipe);
	free_datapipe(&keyboard_slide_pipe);
	free_datapipe(&lockkey_pipe);
	free_datapipe(&device_inactive_pipe);
	free_datapipe(&touchscreen_pipe);
	free_datapipe(&keypress_pipe);
	free_datapipe(&key_backlight_pipe);
	free_datapipe(&led_pattern_deactivate_pipe);
	free_datapipe(&led_pattern_activate_pipe);
	free_datapipe(&led_brightness_pipe);
	free_datapipe(&display_brightness_pipe);
	free_datapipe(&display_state_pipe);
	free_datapipe(&submode_pipe);
	free_datapipe(&alarm_ui_state_pipe);
	free_datapipe(&call_type_pipe);
	free_datapipe(&call_state_pipe);
	free_datapipe(&master_radio_pipe);
	free_datapipe(&system_state_pipe);
	free_datapipe(&heartbeat_pipe);

	/* Call the exit function for all subsystems */
	mce_gconf_exit();
	mce_dbus_exit();
	mce_conf_exit();

	/* If the mainloop is initialised, unreference it */
	if (mainloop != NULL) {
		g_main_loop_unref(mainloop);
		mainloop = 0;
	}

	/* Log a farewell message and close the log */
	mce_log(LL_INFO, "Exiting...");

	/* We do not need to explicitly close the log and doing so
	 * would not allow logging from atexit handlers */
	//mce_log_close();

	return status;
}
Exemplo n.º 24
0
int
main(int argc, char **argv)
{
	int e = 0;
	pid_t parent_pid = 0;

	stored_argc = argc;
	stored_argv = argv;

	/*
	 * Settings in order of preference:
	 *
	 * 1: Settings specified in command line options...
	 * 2: Settings specified in configuration file...
	 * 3: Default settings
	 *
	 * Because of this, and because one option (-c) specifies where
	 * the configuration file is, things are done in this order:
	 *
	 * 1. Read and set options.
	 * 2. Read configuration file; if option is read in configuration
	 *    file and not already set, then set it.
	 * 3. Having read configuration file, if parameter is not set,
	 *    set it to the default value.
	 *
	 * It is for this reason that the default values are **NOT** set
	 * in the variable declaration...
	 */

	/* Report that server is starting (report will be delayed) */
	report(RPT_NOTICE, "LCDd version %s starting", version);
	report(RPT_INFO, "Built on %s, protocol version %s, API version %s",
		build_date, protocol_version, api_version);

	clear_settings();

	/* Read command line*/
	CHAIN(e, process_command_line(argc, argv));

	/* Read config file
	 * If config file was not given on command line use default */
	if (strcmp(configfile, UNSET_STR) == 0)
		strncpy(configfile, DEFAULT_CONFIGFILE, sizeof(configfile));
	CHAIN(e, process_configfile(configfile));

	/* Set default values*/
	set_default_settings();

	/* Set reporting settings (will also flush delayed reports) */
	set_reporting("LCDd", report_level, report_dest);
	report(RPT_INFO, "Set report level to %d, output to %s", report_level,
			((report_dest == RPT_DEST_SYSLOG) ? "syslog" : "stderr"));
	CHAIN_END(e, "Critical error while processing settings, abort.");

	/* Now, go into daemon mode (if we should)...
	 * We wait for the child to report it is running OK. This mechanism
	 * is used because forking after starting the drivers causes the
	 * child to loose the (LPT) port access. */
	if (!foreground_mode) {
		report(RPT_INFO, "Server forking to background");
		CHAIN(e, parent_pid = daemonize());
	} else {
		output_GPL_notice();
		report(RPT_INFO, "Server running in foreground");
	}
	install_signal_handlers(!foreground_mode);
		/* Only catch SIGHUP if not in foreground mode */

	/* Startup the subparts of the server */
	CHAIN(e, sock_init(bind_addr, bind_port));
	CHAIN(e, screenlist_init());
	CHAIN(e, init_drivers());
	CHAIN(e, clients_init());
	CHAIN(e, input_init());
	CHAIN(e, menuscreens_init());
	CHAIN(e, server_screen_init());
	CHAIN_END(e, "Critical error while initializing, abort.");
	if (!foreground_mode) {
		/* Tell to parent that startup went OK. */
		wave_to_parent(parent_pid);
	}
	drop_privs(user); /* This can't be done before, because sending a
			signal to a process of a different user will fail */

	do_mainloop();
	/* This loop never stops; we'll get out only with a signal...*/

	return 0;
}
Exemplo n.º 25
0
mainwnd::mainwnd(perform *a_p):
    m_mainperf(a_p),
    m_modified(false),
    m_options(NULL)
{
    set_icon(Gdk::Pixbuf::create_from_xpm_data(seq24_32_xpm));


    /*sjh stuff...*/
    set_wsetlist_mode(m_mainperf->get_setlist_mode());
    /*............*/


    /* register for notification */
    m_mainperf->m_notify.push_back( this );

    /* main window */
    update_window_title();

#if GTK_MINOR_VERSION < 12
    m_tooltips = manage( new Tooltips() );
#endif
    m_main_wid = manage( new mainwid( m_mainperf ));
    m_main_time = manage( new maintime( ));

    m_menubar = manage(new MenuBar());

    m_menu_file = manage(new Menu());
    m_menubar->items().push_front(MenuElem("_File", *m_menu_file));

    m_menu_view = manage( new Menu());
    m_menubar->items().push_back(MenuElem("_View", *m_menu_view));

    m_menu_help = manage( new Menu());
    m_menubar->items().push_back(MenuElem("_Help", *m_menu_help));

    /* file menu items */
    m_menu_file->items().push_back(MenuElem("_New",
                Gtk::AccelKey("<control>N"),
                mem_fun(*this, &mainwnd::file_new)));
    m_menu_file->items().push_back(MenuElem("_Open...",
                Gtk::AccelKey("<control>O"),
                mem_fun(*this, &mainwnd::file_open)));
    m_menu_file->items().push_back(MenuElem("_Save",
                Gtk::AccelKey("<control>S"),
                mem_fun(*this, &mainwnd::file_save)));
    m_menu_file->items().push_back(MenuElem("Save _as...",
                mem_fun(*this, &mainwnd::file_save_as)));

    m_menu_file->items().push_back(MenuElem("Open _setlist...",
                mem_fun(*this, &mainwnd::file_open_setlist)));

    m_menu_file->items().push_back(SeparatorElem());
    m_menu_file->items().push_back(MenuElem("_Import...",
                mem_fun(*this, &mainwnd::file_import_dialog)));
    m_menu_file->items().push_back(MenuElem("O_ptions...",
                mem_fun(*this,&mainwnd::options_dialog)));
    m_menu_file->items().push_back(SeparatorElem());
    m_menu_file->items().push_back(MenuElem("E_xit",
                Gtk::AccelKey("<control>Q"),
                mem_fun(*this, &mainwnd::file_exit)));

    /* view menu items */
    m_menu_view->items().push_back(MenuElem("_Song Editor...",
                Gtk::AccelKey("<control>E"),
                mem_fun(*this, &mainwnd::open_performance_edit)));

    /* help menu items */
    m_menu_help->items().push_back(MenuElem("_About...",
                mem_fun(*this, &mainwnd::about_dialog)));

    /* top line items */
    HBox *tophbox = manage( new HBox( false, 0 ) );
    tophbox->pack_start(
    		*m_s24_pic,
    		// *manage(new Image(Gdk::Pixbuf::create_from_xpm_data(seq24_xpm))),
            false, false);

    // adjust placement...
    VBox *vbox_b = manage( new VBox() );
    HBox *hbox3 = manage( new HBox( false, 0 ) );
    vbox_b->pack_start( *hbox3, false, false );
    tophbox->pack_end( *vbox_b, false, false );
    hbox3->set_spacing( 10 );

    /* timeline */
    hbox3->pack_start( *m_main_time, false, false );

    /* group learn button */
    m_button_learn = manage( new Button( ));
    m_button_learn->set_focus_on_click( false );
    m_button_learn->set_flags( m_button_learn->get_flags() & ~Gtk::CAN_FOCUS );
    m_button_learn->set_image(*manage(new Image(
                    Gdk::Pixbuf::create_from_xpm_data( learn_xpm ))));
    m_button_learn->signal_clicked().connect(
            mem_fun(*this, &mainwnd::learn_toggle));
    add_tooltip( m_button_learn, "Mute Group Learn\n\n"
            "Click 'L' then press a mutegroup key to store the mute state of "
            "the sequences in that key.\n\n"
            "(see File/Options/Keyboard for available mutegroup keys "
            "and the corresponding hotkey for the 'L' button)" );
    hbox3->pack_end( *m_button_learn, false, false );

    /*this seems to be a dirty hack:*/
    Button w;
    hbox3->set_focus_child( w ); // clear the focus not to trigger L via keys


    /* bottom line items */
    HBox *bottomhbox = manage( new HBox(false, 10));

    /* container for start+stop buttons */
    HBox *startstophbox = manage(new HBox(false, 4));
    bottomhbox->pack_start(*startstophbox, Gtk::PACK_SHRINK);

    /* stop button */
    m_button_stop = manage( new Button());
    m_button_stop->add(*manage(new Image(
                    Gdk::Pixbuf::create_from_xpm_data( stop_xpm ))));
    m_button_stop->signal_clicked().connect(
            mem_fun(*this, &mainwnd::stop_playing));/*sjh - can't pass anything into the stop_playing function because of this. */
    add_tooltip( m_button_stop, "Stop playing MIDI sequence" );
    m_button_stop->set_can_focus(false);
    startstophbox->pack_start(*m_button_stop, Gtk::PACK_SHRINK);

    /* play button */
    m_button_play = manage(new Button() );
    m_button_play->add(*manage(new Image(
                    Gdk::Pixbuf::create_from_xpm_data( play2_xpm ))));
    m_button_play->signal_clicked().connect(
            mem_fun( *this, &mainwnd::start_playing));
    add_tooltip( m_button_play, "Play MIDI sequence" );
    startstophbox->pack_start(*m_button_play, Gtk::PACK_SHRINK);

    /* bpm spin button with label*/
    HBox *bpmhbox = manage(new HBox(false, 4));
    bottomhbox->pack_start(*bpmhbox, Gtk::PACK_SHRINK);

    m_adjust_bpm = manage(new Adjustment(m_mainperf->get_bpm(), 20, 500, 1));
    m_spinbutton_bpm = manage( new SpinButton( *m_adjust_bpm ));
    m_spinbutton_bpm->set_editable( false );
    m_adjust_bpm->signal_value_changed().connect(
            mem_fun(*this, &mainwnd::adj_callback_bpm));
    add_tooltip( m_spinbutton_bpm, "Adjust beats per minute (BPM) value");
    Label* bpmlabel = manage(new Label("_bpm", true));
    bpmlabel->set_mnemonic_widget(*m_spinbutton_bpm);
    bpmhbox->pack_start(*bpmlabel, Gtk::PACK_SHRINK);
    bpmhbox->pack_start(*m_spinbutton_bpm, Gtk::PACK_SHRINK);

    /* screen set name edit line */
    HBox *notebox = manage(new HBox(false, 4));
    bottomhbox->pack_start(*notebox, Gtk::PACK_EXPAND_WIDGET);

    m_entry_notes = manage( new Entry());
    m_entry_notes->signal_changed().connect(
            mem_fun(*this, &mainwnd::edit_callback_notepad));
    m_entry_notes->set_text(*m_mainperf->get_screen_set_notepad(
                m_mainperf->get_screenset()));
    add_tooltip( m_entry_notes, "Enter screen set name" );
    Label* notelabel = manage(new Label("_Name", true));
    notelabel->set_mnemonic_widget(*m_entry_notes);
    notebox->pack_start(*notelabel, Gtk::PACK_SHRINK);
    notebox->pack_start(*m_entry_notes, Gtk::PACK_EXPAND_WIDGET);

    /* sequence set spin button */
    HBox *sethbox = manage(new HBox(false, 4));
    bottomhbox->pack_start(*sethbox, Gtk::PACK_SHRINK);

    m_adjust_ss = manage( new Adjustment( 0, 0, c_max_sets - 1, 1 ));
    m_spinbutton_ss = manage( new SpinButton( *m_adjust_ss ));
    m_spinbutton_ss->set_editable( false );
    m_spinbutton_ss->set_wrap( true );
    m_adjust_ss->signal_value_changed().connect(
            mem_fun(*this, &mainwnd::adj_callback_ss ));
    add_tooltip( m_spinbutton_ss, "Select screen set" );
    Label* setlabel = manage(new Label("_Set", true));
    setlabel->set_mnemonic_widget(*m_spinbutton_ss);
    sethbox->pack_start(*setlabel, Gtk::PACK_SHRINK);
    sethbox->pack_start(*m_spinbutton_ss, Gtk::PACK_SHRINK);

    /* song edit button */
    m_button_songedit = manage( new Button( ));
    m_button_songedit->add( *manage( new Image(
                    Gdk::Pixbuf::create_from_xpm_data( perfedit_xpm  ))));
    m_button_songedit->signal_clicked().connect(
            mem_fun( *this, &mainwnd::open_performance_edit ));
    add_tooltip( m_button_songedit, "Show or hide song editor window" );
    bottomhbox->pack_end(*m_button_songedit, Gtk::PACK_SHRINK);


    /* vertical layout container for window content*/
    VBox *contentvbox = new VBox();
    contentvbox->set_spacing(10);
    contentvbox->set_border_width(10);
    contentvbox->pack_start(*tophbox, Gtk::PACK_SHRINK);
    contentvbox->pack_start(*m_main_wid, Gtk::PACK_SHRINK);
    contentvbox->pack_start(*bottomhbox, Gtk::PACK_SHRINK);


    /*main container for menu and window content */
    VBox *mainvbox = new VBox();

    mainvbox->pack_start(*m_menubar, false, false );
    mainvbox->pack_start( *contentvbox );

    /* add main layout box */
    this->add (*mainvbox);

    /* show everything */
    show_all();

    add_events( Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK );

    m_timeout_connect = Glib::signal_timeout().connect(
            mem_fun(*this, &mainwnd::timer_callback), 25);


    m_perf_edit = new perfedit( m_mainperf );
//    m_playlist_wnd = new playlist_wnd( m_mainperf);
    m_playplay = new playlist_player();

    m_sigpipe[0] = -1;
    m_sigpipe[1] = -1;
    install_signal_handlers();
}
Exemplo n.º 26
0
int main(int argc, char **argv)
{
  srvr_sockaddr_union_t me;
  struct tftphdr *tp;
  ssize_t n = 0;
  int arg = 1;
  unsigned short port = DEFAULT_PORT;
  curl_socket_t sock = CURL_SOCKET_BAD;
  int flag;
  int rc;
  int error;
  long pid;
  struct testcase test;
  int result = 0;

  memset(&test, 0, sizeof(test));

  while(argc>arg) {
    if(!strcmp("--version", argv[arg])) {
      printf("tftpd IPv4%s\n",
#ifdef ENABLE_IPV6
             "/IPv6"
#else
             ""
#endif
             );
      return 0;
    }
    else if(!strcmp("--pidfile", argv[arg])) {
      arg++;
      if(argc>arg)
        pidname = argv[arg++];
    }
    else if(!strcmp("--logfile", argv[arg])) {
      arg++;
      if(argc>arg)
        serverlogfile = argv[arg++];
    }
    else if(!strcmp("--ipv4", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv4";
      use_ipv6 = FALSE;
#endif
      arg++;
    }
    else if(!strcmp("--ipv6", argv[arg])) {
#ifdef ENABLE_IPV6
      ipv_inuse = "IPv6";
      use_ipv6 = TRUE;
#endif
      arg++;
    }
    else if(!strcmp("--port", argv[arg])) {
      arg++;
      if(argc>arg) {
        char *endptr;
        unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
        if((endptr != argv[arg] + strlen(argv[arg])) ||
           (ulnum < 1025UL) || (ulnum > 65535UL)) {
          fprintf(stderr, "tftpd: invalid --port argument (%s)\n",
                  argv[arg]);
          return 0;
        }
        port = curlx_ultous(ulnum);
        arg++;
      }
    }
    else if(!strcmp("--srcdir", argv[arg])) {
      arg++;
      if(argc>arg) {
        path = argv[arg];
        arg++;
      }
    }
    else {
      puts("Usage: tftpd [option]\n"
           " --version\n"
           " --logfile [file]\n"
           " --pidfile [file]\n"
           " --ipv4\n"
           " --ipv6\n"
           " --port [port]\n"
           " --srcdir [path]");
      return 0;
    }
  }

#ifdef WIN32
  win32_init();
  atexit(win32_cleanup);
#endif

  install_signal_handlers();

  pid = (long)getpid();

#ifdef ENABLE_IPV6
  if(!use_ipv6)
#endif
    sock = socket(AF_INET, SOCK_DGRAM, 0);
#ifdef ENABLE_IPV6
  else
    sock = socket(AF_INET6, SOCK_DGRAM, 0);
#endif

  if(CURL_SOCKET_BAD == sock) {
    error = SOCKERRNO;
    logmsg("Error creating socket: (%d) %s",
           error, strerror(error));
    result = 1;
    goto tftpd_cleanup;
  }

  flag = 1;
  if (0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
            (void *)&flag, sizeof(flag))) {
    error = SOCKERRNO;
    logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
           error, strerror(error));
    result = 1;
    goto tftpd_cleanup;
  }

#ifdef ENABLE_IPV6
  if(!use_ipv6) {
#endif
    memset(&me.sa4, 0, sizeof(me.sa4));
    me.sa4.sin_family = AF_INET;
    me.sa4.sin_addr.s_addr = INADDR_ANY;
    me.sa4.sin_port = htons(port);
    rc = bind(sock, &me.sa, sizeof(me.sa4));
#ifdef ENABLE_IPV6
  }
  else {
    memset(&me.sa6, 0, sizeof(me.sa6));
    me.sa6.sin6_family = AF_INET6;
    me.sa6.sin6_addr = in6addr_any;
    me.sa6.sin6_port = htons(port);
    rc = bind(sock, &me.sa, sizeof(me.sa6));
  }
#endif /* ENABLE_IPV6 */
  if(0 != rc) {
    error = SOCKERRNO;
    logmsg("Error binding socket on port %hu: (%d) %s",
           port, error, strerror(error));
    result = 1;
    goto tftpd_cleanup;
  }

  wrotepidfile = write_pidfile(pidname);
  if(!wrotepidfile) {
    result = 1;
    goto tftpd_cleanup;
  }

  logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);

  for (;;) {
    fromlen = sizeof(from);
#ifdef ENABLE_IPV6
    if(!use_ipv6)
#endif
      fromlen = sizeof(from.sa4);
#ifdef ENABLE_IPV6
    else
      fromlen = sizeof(from.sa6);
#endif
    n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
                          &from.sa, &fromlen);
    if(got_exit_signal)
      break;
    if (n < 0) {
      logmsg("recvfrom");
      result = 3;
      break;
    }

    set_advisor_read_lock(SERVERLOGS_LOCK);
    serverlogslocked = 1;

#ifdef ENABLE_IPV6
    if(!use_ipv6) {
#endif
      from.sa4.sin_family = AF_INET;
      peer = socket(AF_INET, SOCK_DGRAM, 0);
      if(CURL_SOCKET_BAD == peer) {
        logmsg("socket");
        result = 2;
        break;
      }
      if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
        logmsg("connect: fail");
        result = 1;
        break;
      }
#ifdef ENABLE_IPV6
    }
    else {
      from.sa6.sin6_family = AF_INET6;
      peer = socket(AF_INET6, SOCK_DGRAM, 0);
      if(CURL_SOCKET_BAD == peer) {
        logmsg("socket");
        result = 2;
        break;
      }
      if (connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
        logmsg("connect: fail");
        result = 1;
        break;
      }
    }
#endif

    maxtimeout = 5*TIMEOUT;

    tp = &buf.hdr;
    tp->th_opcode = ntohs(tp->th_opcode);
    if (tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
      memset(&test, 0, sizeof(test));
      if (do_tftp(&test, tp, n) < 0)
        break;
      if(test.buffer)
        free(test.buffer);
    }
    sclose(peer);
    peer = CURL_SOCKET_BAD;

    if(test.ofile > 0) {
      close(test.ofile);
      test.ofile = 0;
    }

    if(got_exit_signal)
      break;

    if(serverlogslocked) {
      serverlogslocked = 0;
      clear_advisor_read_lock(SERVERLOGS_LOCK);
    }

    logmsg("end of one transfer");

  }

tftpd_cleanup:

  if(test.ofile > 0)
    close(test.ofile);

  if((peer != sock) && (peer != CURL_SOCKET_BAD))
    sclose(peer);

  if(sock != CURL_SOCKET_BAD)
    sclose(sock);

  if(got_exit_signal)
    logmsg("signalled to die");

  if(wrotepidfile)
    unlink(pidname);

  if(serverlogslocked) {
    serverlogslocked = 0;
    clear_advisor_read_lock(SERVERLOGS_LOCK);
  }

  restore_signal_handlers();

  if(got_exit_signal) {
    logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
           ipv_inuse, (int)port, pid, exit_signal);
    /*
     * To properly set the return status of the process we
     * must raise the same signal SIGINT or SIGTERM that we
     * caught and let the old handler take care of it.
     */
    raise(exit_signal);
  }

  logmsg("========> tftpd quits");
  return result;
}