Example #1
0
static void
pid_file_clean (const char *pid_file)
{
	char    *pid_file_worker;
	cuint_t  len;

	if (pid_file == NULL)
		return;

	/* Clean main choerkee pid file
	 */
	remove_pid_file (pid_file);

	/* Clean also "worker" pid file
	 */
	len = strlen (pid_file);
	pid_file_worker = (char *) malloc (len + 8);
	if (unlikely (pid_file_worker == NULL)) {
		return;
	}

	memcpy (pid_file_worker, pid_file, len);
	memcpy (pid_file_worker + len, ".worker\0", 8);

	remove_pid_file (pid_file_worker);

	free (pid_file_worker);
}
Example #2
0
void initialize_panel (int sig) {
	(void) sig;
	bindToGalax();

	if (!ts) {
		fprintf(stderr, "error: ts_open\n");
		remove_pid_file();

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

		close (fd_uinput);
		exit(-1);
	}

	if (ts_config(ts)) {
		fprintf(stderr, "error: ts_config\n");
		remove_pid_file();

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

		close (fd_uinput);
		exit(-1);
	}
}
Example #3
0
void signal_handler(int sig) {

    (void) sig;
    set_keyboard_brightness_value(0);
    remove_pid_file();
    printf("Killed!\n");
    exit(1);
}
Example #4
0
void handle_falling_child()
{
  struct plugins_list_entry *list = NULL;
  int j, ret;

  /* we first scan failed_plugins[] array for plugins failed during the
     startup phase: when we are building plugins_list, we cannot arbitrarily 
     delete nodes (plugins) from it */ 
  for (j = 0; j < MAX_N_PLUGINS; j++) {
    if (failed_plugins[j]) { 
      list = search_plugin_by_pid(failed_plugins[j]);
      if (list) {
        Log(LOG_WARNING, "WARN: connection lost to '%s-%s'; closing connection.\n", list->name, list->type.string);
        close(list->pipe[1]);
        delete_pipe_channel(list->pipe[1]);
        ret = delete_plugin_by_id(list->id);
        if (!ret) {
          Log(LOG_WARNING, "WARN: no more plugins active. Shutting down.\n");
	  if (config.pidfile) remove_pid_file(config.pidfile);
          exit(1);
        }
      }
      failed_plugins[j] = 0;
    }
    else break;
  } 

  j = waitpid(-1, 0, WNOHANG);
  list = search_plugin_by_pid(j);
  if (list) {
    Log(LOG_WARNING, "WARN: connection lost to '%s-%s'; closing connection.\n", list->name, list->type.string);
    close(list->pipe[1]);
    delete_pipe_channel(list->pipe[1]);
    ret = delete_plugin_by_id(list->id);
    if (!ret) {
      Log(LOG_WARNING, "WARN: no more plugins active. Shutting down.\n");
      if (config.pidfile) remove_pid_file(config.pidfile);
      exit(1);
    }
  }

  signal(SIGCHLD, handle_falling_child);
}
Example #5
0
void signal_handler (int sig) {
	(void) sig;
	remove_pid_file();

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

	close (fd_uinput);
	exit(1);
}
Example #6
0
/**
 * Teardown the gui.
 */
static void teardown ( int pfd )
{
    // Cleanup font setup.
    textbox_cleanup ( );

    // Release the window.
    release_keyboard ( );

    // Cleanup view
    rofi_view_cleanup ();
    // Cleanup pid file.
    remove_pid_file ( pfd );
}
Example #7
0
File: helper.c Project: alepez/rofi
int create_pid_file ( const char *pidfile )
{
    if ( pidfile == NULL ) {
        return -1;
    }

    int fd = g_open ( pidfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR );
    if ( fd < 0 ) {
        fprintf ( stderr, "Failed to create pid file." );
        return -1;
    }
    // Set it to close the File Descriptor on exit.
    int flags = fcntl ( fd, F_GETFD, NULL );
    flags = flags | FD_CLOEXEC;
    if ( fcntl ( fd, F_SETFD, flags, NULL ) < 0 ) {
        fprintf ( stderr, "Failed to set CLOEXEC on pidfile." );
        remove_pid_file ( fd );
        return -1;
    }
    // Try to get exclusive write lock on FD
    int retv = flock ( fd, LOCK_EX | LOCK_NB );
    if ( retv != 0 ) {
        fprintf ( stderr, "Failed to set lock on pidfile: Rofi already running?\n" );
        fprintf ( stderr, "Got error: %d %s\n", retv, strerror ( errno ) );
        remove_pid_file ( fd );
        return -1;
    }
    if ( ftruncate ( fd, (off_t) 0 ) == 0 ) {
        // Write pid, not needed, but for completeness sake.
        char    buffer[64];
        int     length = snprintf ( buffer, 64, "%i", getpid () );
        ssize_t l      = 0;
        while ( l < length ) {
            l += write ( fd, &buffer[l], length - l );
        }
    }
    return fd;
}
Example #8
0
File: main.c Project: niklask/echod
/*
	* Handle options to control the daemon
	*/
void daemon_manager(const char *bin, const char *cmd)
{
				pid_t pid;
				char *str;

				str = str_tolower(cmd);

				if (strcmp(str, "start") == 0) {
								if (load_pid_file() > 0) {
												printf("Daemon is already running\n");
												exit(EXIT_FAILURE);
								}

								pid = create_daemon(bin);
								/* If the returned pid is < 0, there was a problem with the
											fork and we exit with a failure */
								if (pid < 0) {
												free(str);
												exit(EXIT_FAILURE);
								}
								/* If the returned pid > 0 it is the pid of the child and we are
											the parent. Save the pid to the pid file and exit with success */
								if (pid > 0) {
												save_pid_file(pid);
												free(str);
												exit(EXIT_SUCCESS);
								}

								/* If this point is reached, the fork was successfull and we
											are the child process. Continue as daemon from here on. */

				} else if (strcmp(str, "stop") == 0) {
								pid = load_pid_file();
								if (pid <= 0) {
												printf("No pid file, cannot stop\n");
												exit(EXIT_FAILURE);
								}
								/* Send a SIGTERM signal to the daemon */
								kill(pid, SIGTERM);

								remove_pid_file();

								exit(EXIT_SUCCESS);

				} else if (strcmp(str, "restart") == 0 ) {
								/* Leave empty for now */
				}

				free(str);
}
Example #9
0
static void stop_gstreamill (gint number)
{
    /* run in SINGLE_JOB_MODE? just exit */
    if (gstreamill->mode == SINGLE_JOB_MODE) {
        g_printf ("Interrupt signal received\n");
        exit (0);
    }

    /* run in background, stop gstreamill and remove pid file. */
    gstreamill_stop (gstreamill);
    if (number == SIGTERM) {
        remove_pid_file ();
    }
}
Example #10
0
static void stop_gstreamill (gint number)
{
        /* run in foreground? just exit */
        if (!gstreamill->daemon) {
                g_printf ("Interrupt signal received\n");
                exit (0);
        }

        /* run in background, stop gstreamill and remove pid file. */
        gstreamill_stop (gstreamill);
        if (number == SIGTERM) {
                remove_pid_file ();
        }
}
Example #11
0
void av_shutdown(int rc) { 
    pid_t pid; 
    
    pid = check_pid_file(); 
    if (!pid) 
        remove_pid_file(); 
    notice("shutdown"); 
    shutdownlog(); 
    free( drweb_id );
    if ( connect_to != NULL ) 
        free( connect_to );
    if ( bind_to != NULL ) 
        free( bind_to );
    exit(rc);
}
Example #12
0
void my_sigint_handler(int signum)
{
  struct plugins_list_entry *list = plugins_list;

  if (config.syslog) closelog();

  /* We are about to exit, but it may take a while - because of the
     wait() call. Let's release collector's socket to improve turn-
     around times when restarting the daemon */
  if (config.acct_type == ACCT_NF || config.acct_type == ACCT_SF) close(config.sock);

#if defined (IRIX) || (SOLARIS)
  signal(SIGCHLD, SIG_IGN);
#else
  signal(SIGCHLD, ignore_falling_child);
#endif

  signal(SIGINT, SIG_IGN);
  signal(SIGTERM, SIG_IGN);

  fill_pipe_buffer();
  sleep(2); /* XXX: we should really choose an adaptive value here. It should be
	            closely bound to, say, biggest plugin_buffer_size value */ 

  while (list) {
    if (memcmp(list->type.string, "core", sizeof("core"))) kill(list->pid, SIGINT);
    list = list->next;
  }

  wait(NULL);

  Log(LOG_INFO, "INFO ( %s/%s ): OK, Exiting ...\n", config.name, config.type);

  if (config.acct_type == ACCT_PM && !config.uacctd_group /* XXX */) {
    if (config.dev) {
      if (pcap_stats(glob_pcapt, &ps) < 0) printf("\npcap_stats: %s\n", pcap_geterr(glob_pcapt));
      printf("\n");
      printf("%u packets received by filter\n", ps.ps_recv);
      printf("%u packets dropped by kernel\n", ps.ps_drop);
    }
  }

  if (config.pidfile) remove_pid_file(config.pidfile);
  exit(0);
}
Example #13
0
void
sigusr_handler(int signum)
{
  if (signum==SIGUSR1) {
    if (!starttime) {
      grab_isp_info(0);
      if (current_isp>=num_isps)
	current_isp=0;
      DrawISPName();
      RedrawWindow();
    } else {
      got_sched=1;
      warn_pref();
    }
  }
  else {
    remove_pid_file();
    exit(0);
  }
}
Example #14
0
File: main.c Project: l3ib/fsniper
/* handler for any quit signal.  cleans up memory and exits gracefully. */
void handle_quit_signal(int signum) 
{
    if (verbose) log_write("Received signal %d, exiting.\n", signum);

    /* kill anything in our process group, including all handler childs */
    killpg(getpid(), SIGTERM);
	
    /* free things */
    free_all_globals();

    /* shut down log */
    log_close();

    remove_pid_file(get_pid_filename());

    /* return an error if there was one */
    if (signum < 0)
	exit(signum);

    exit(0); 
} 
Example #15
0
int main ( int argc, char ** argv )
{
    cmd_set_arguments ( argc, argv );

    if ( setlocale ( LC_ALL, "" ) == NULL ) {
        fprintf ( stderr, "Failed to set locale.\n" );
        return EXIT_FAILURE;
    }

    /**
     * Char function
     */

    TASSERT ( helper_parse_char ( "\\n" ) == '\n' );
    TASSERT ( helper_parse_char ( "\\a" ) == '\a' );
    TASSERT ( helper_parse_char ( "\\b" ) == '\b' );
    TASSERT ( helper_parse_char ( "\\t" ) == '\t' );
    TASSERT ( helper_parse_char ( "\\v" ) == '\v' );
    TASSERT ( helper_parse_char ( "\\f" ) == '\f' );
    TASSERT ( helper_parse_char ( "\\r" ) == '\r' );
    TASSERT ( helper_parse_char ( "\\\\" ) == '\\' );
    TASSERT ( helper_parse_char ( "\\0" ) == 0 );
    TASSERT ( helper_parse_char ( "\\x77" ) == 'w' );
    TASSERT ( helper_parse_char ( "\\x0A" ) == '\n' );

    /**
     * tokenize
     */

    TASSERT ( levenshtein ( "aap", g_utf8_strlen ( "aap", -1), "aap", g_utf8_strlen ( "aap", -1) ) == 0 );
    TASSERT ( levenshtein ( "aap", g_utf8_strlen ( "aap", -1), "aap ", g_utf8_strlen ( "aap ", -1) ) == 1 );
    TASSERT ( levenshtein ( "aap ", g_utf8_strlen ( "aap ", -1), "aap", g_utf8_strlen ( "aap", -1) ) == 1 );
    TASSERTE ( levenshtein ( "aap", g_utf8_strlen ( "aap", -1), "aap noot", g_utf8_strlen ( "aap noot", -1) ), 5 );
    TASSERTE ( levenshtein ( "aap", g_utf8_strlen ( "aap", -1), "noot aap", g_utf8_strlen ( "noot aap", -1) ), 5 );
    TASSERTE ( levenshtein ( "aap", g_utf8_strlen ( "aap", -1), "noot aap mies", g_utf8_strlen ( "noot aap mies", -1) ), 10 );
    TASSERTE ( levenshtein ( "noot aap mies", g_utf8_strlen ( "noot aap mies", -1), "aap", g_utf8_strlen ( "aap", -1) ), 10 );
    TASSERTE ( levenshtein ( "otp", g_utf8_strlen ( "otp", -1), "noot aap", g_utf8_strlen ( "noot aap", -1) ), 5 );
    /**
     * Quick converision check.
     */
    {
        char *str = rofi_latin_to_utf8_strdup ( "\xA1\xB5", 2 );
        TASSERT ( g_utf8_collate ( str, "¡µ" ) == 0 );
        g_free ( str );
    }

    {
        char *str = rofi_force_utf8 ( "Valid utf8", 10 );
        TASSERT ( g_utf8_collate ( str, "Valid utf8" ) == 0 );
        g_free ( str );
        char in[] = "Valid utf8 until \xc3\x28 we continue here";
        TASSERT ( g_utf8_validate ( in, -1, NULL ) == FALSE );
        str = rofi_force_utf8 ( in, strlen ( in ) );
        TASSERT ( g_utf8_validate ( str, -1, NULL ) == TRUE );
        TASSERT ( g_utf8_collate ( str, "Valid utf8 until �( we continue here" ) == 0 );
        g_free ( str );
    }
    // Pid test.
    // Tests basic functionality of writing it, locking, seeing if I can write same again
    // And close/reopen it again.
    {
        const char *path = "/tmp/rofi-test.pid";
        TASSERT ( create_pid_file ( NULL ) == -1 );
        int        fd = create_pid_file ( path );
        TASSERT ( fd >= 0 );
        int        fd2 = create_pid_file ( path );
        TASSERT ( fd2 < 0 );

        remove_pid_file ( fd );
        fd = create_pid_file ( path );
        TASSERT ( fd >= 0 );
        remove_pid_file ( fd );
    }
}
Example #16
0
int main(int argc, char **argv)
{
  long cache_hits, cache_misses;

  /* Parse command line, exit on error */
  parse_args(argc, argv);

  if (!opt_no_banner) {
    fprintf(stderr,
"VNC Reflector %s.  Copyright (C) 2001-2003 HorizonLive.com, Inc.\n\n"
"HorizonLive provides e-Learning and collaborative synchronous presentation\n"
"solutions in a totally Web-based environment.  For more information about\n"
"HorizonLive, please see our website at http://www.horizonlive.com/\n\n",
            VERSION);
  }


   log_write(LL_MSG, "log_open");
  if (!log_open(opt_log_filename, opt_file_loglevel,
                (opt_foreground) ? opt_stderr_loglevel : -1)) {
    fprintf(stderr, "%s: error opening log file (ignoring this error)\n",
            argv[0]);
  }
  log_write(LL_MSG, "Starting VNC Reflector %s", VERSION);

  /* Fork the process to the background if necessary */
  if (!opt_foreground) {
    if (!opt_no_banner) {
      fprintf(stderr, "Starting in the background, "
              "see the log file for errors and other messages.\n");
    }

    if (getpid() != 1) {
      signal(SIGTTIN, SIG_IGN);
      signal(SIGTTOU, SIG_IGN);
      signal(SIGTSTP, SIG_IGN);
      if (fork ())
        return 0;
      setsid();
    }
    close(0);
    close(1);
    close(2);
    log_write(LL_INFO, "Switched to the background mode");
  }
  log_write(LL_MSG, "init_screen_info()");
  /* Initialization */
  if (init_screen_info()) {
    log_write(LL_MSG, "read_password_file()");
    read_password_file();
    set_host_encodings(opt_request_tight, opt_tight_level);
    set_client_passwords(opt_client_password, opt_client_ro_password);
    fbs_set_prefix(opt_fbs_prefix, opt_join_sessions);

    set_active_file(opt_active_filename);
    set_actions_file(opt_actions_filename);
    log_write(LL_INFO, "---------- haciendo bind -----------");
    aio_init();
    if (opt_bind_ip != NULL) {
      if (aio_set_bind_address(opt_bind_ip)) {
        log_write(LL_INFO, "Would bind listening sockets to address %s",
                  opt_bind_ip);
      } else {
        log_write(LL_WARN, "Illegal address to bind listening sockets to: %s",
                  opt_bind_ip);
      }
    }
    
    log_write(LL_INFO, "----------main.c-----------");
    /* Main work */
    if (connect_to_host(opt_host_info_file, opt_cl_listen_port)) {
      if (write_pid_file()) {
        set_control_signals();
        aio_mainloop();
        remove_pid_file();
      }
    }

    /* Cleanup */
    if (g_framebuffer != NULL) {
      log_write(LL_DETAIL, "Freeing framebuffer and associated structures");
      free(g_framebuffer);
      free_enc_cache();
    }
    if (g_screen_info.name != NULL)
      free(g_screen_info.name);

    get_hextile_caching_stats(&cache_hits, &cache_misses);
    if (cache_hits + cache_misses != 0) {
      log_write(LL_INFO, "Hextile BGR233 caching efficiency: %d%%",
                (int)((cache_hits * 100 + (cache_hits + cache_misses) / 2)
                      / (cache_hits + cache_misses)));
    }
  }

  log_write(LL_MSG, "Terminating");

  /* Close logs */
  if (!log_close() && opt_foreground) {
    fprintf(stderr, "%s: error closing log file (ignoring this error)\n",
            argv[0]);
  }

  /* Done */
  exit(1);
}
Example #17
0
int run_network(void*(*func)(void*)){
    struct sockaddr_in sockserv,sockclient;
    int clientfd;
    int socketfd;
    socklen_t clientsocklen;
    pthread_t children[NUMTHREADS];
    struct threadData data[NUMTHREADS];
    int i,j;
    stop = 0;
    #ifdef DETACHED_THREADS
    pthread_attr_t attr;
    #endif
    fd_set rfds;
    struct timeval tv;
    int retval;
    int sec;
    int usec;
    int port;

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

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

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

    clientsocklen = sizeof socketfd;

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                g_main_loop_run (loop);

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

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

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

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

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

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

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

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

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

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

        loop = g_main_loop_new (NULL, FALSE);

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

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

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

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

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

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

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

        g_main_loop_run (loop);

        return 0;
}
Example #19
0
int main(int argc, char **argv) {
	char buffer[MAX_INPUT_BUFFER];
	int result;
	uid_t uid = -1;
	gid_t gid = -1;


	/* process command-line arguments */
	result = process_arguments(argc, argv);

	if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE) {

		if (result != OK)
			printf("Incorrect command line arguments supplied\n");
		printf("\n");
		printf("NSCA - Nagios Service Check Acceptor for Icinga\n");
		printf("Copyright (c) 2010-2012 Icinga Development Team and Community Contributors (http://www.icinga.org)\n");
		printf("Copyright (c) 2009-2012 Nagios Core Development Team and Community Contributors\n");
		printf("Copyright (c) 2000-2009 Ethan Galstad\n");
		printf("Version: %s\n", PROGRAM_VERSION);
		printf("Last Modified: %s\n", MODIFICATION_DATE);
		printf("License: GPL v2\n");
		printf("Encryption Routines: ");
#ifdef HAVE_LIBMCRYPT
		printf("AVAILABLE");
#else
		printf("NOT AVAILABLE");
#endif
		printf("\n");
#ifdef HAVE_LIBWRAP
		printf("TCP Wrappers Available\n");
#endif
		printf("\n");
	}

	if (result != OK || show_help == TRUE) {
		printf("Usage: %s -c <config_file> [mode]\n", argv[0]);
		printf("\n");
		printf("Options:\n");
		printf(" <config_file> = Name of config file to use\n");
		printf(" [mode]        = Determines how NSCA should run. Valid modes:\n");
		printf("   --inetd     = Run as a service under inetd or xinetd\n");
		printf("   --daemon    = Run as a standalone multi-process daemon\n");
		printf("   --single    = Run as a standalone single-process daemon (default)\n");
		printf("\n");
		printf("Notes:\n");
		printf("This program is designed to accept passive check results from\n");
		printf("remote hosts that use the send_nsca utility.  Can run as a service\n");
		printf("under inetd or xinetd (read the docs for info on this), or as a\n");
		printf("standalone daemon.\n");
		printf("\n");
	}

	if (show_license == TRUE)
		display_license();

	if (result != OK || show_help == TRUE || show_license == TRUE || show_version == TRUE)
		do_exit(STATE_UNKNOWN);


	/* open a connection to the syslog facility */
	/* facility may be overridden later */
	get_log_facility(NSCA_LOG_FACILITY);
	openlog("nsca", LOG_PID | LOG_NDELAY, log_facility);

	/* make sure the config file uses an absolute path */
	if (config_file[0] != '/') {

		/* save the name of the config file */
		strncpy(buffer, config_file, sizeof(buffer));
		buffer[sizeof(buffer) - 1] = '\0';

		/* get absolute path of current working directory */
		strcpy(config_file, "");
		getcwd(config_file, sizeof(config_file));

		/* append a forward slash */
		strncat(config_file, "/", sizeof(config_file) - 2);
		config_file[sizeof(config_file) - 1] = '\0';

		/* append the config file to the path */
		strncat(config_file, buffer, sizeof(config_file) - strlen(config_file) - 1);
		config_file[sizeof(config_file) - 1] = '\0';
	}

	/* read the config file */
	result = read_config_file(config_file);

	/* exit if there are errors... */
	if (result == ERROR)
		do_exit(STATE_CRITICAL);

	/* generate the CRC 32 table */
	generate_crc32_table();


	/* how should we handle client connections? */
	switch (mode) {

	case INETD:
		/* chroot if configured */
		do_chroot();

		/* if we're running under inetd, handle one connection and get out */
		handle_connection(0, NULL);
		break;

	case MULTI_PROCESS_DAEMON:

		/* older style, mult-process daemon */
		/* execution cascades below... */
		install_child_handler();

		/*     |
		       |
		       |     */
	case SINGLE_PROCESS_DAEMON:
		/*     |
		       |
		       V     */

		/* daemonize and start listening for requests... */
		if (fork() == 0) {

			/* we're a daemon - set up a new process group */
			setsid();

			/* handle signals */
			signal(SIGQUIT, sighandler);
			signal(SIGTERM, sighandler);
			signal(SIGHUP, sighandler);
			
			signal(SIGPIPE, SIG_IGN);

			/* close standard file descriptors */
			close(0);
			close(1);
			close(2);

			/* redirect standard descriptors to /dev/null */
			open("/dev/null", O_RDONLY);
			open("/dev/null", O_WRONLY);
			open("/dev/null", O_WRONLY);

			/* get group information before chrooting */
			get_user_info(nsca_user, &uid);
			get_group_info(nsca_group, &gid);

			/* write pid file */
			if (write_pid_file(uid, gid) == ERROR)
				return STATE_CRITICAL;

			/* chroot if configured */
			do_chroot();

			/* drop privileges */
			if (drop_privileges(nsca_user, uid, gid) == ERROR)
				do_exit(STATE_CRITICAL);

			do {

				/* reset flags */
				sigrestart = FALSE;
				sigshutdown = FALSE;

				/* wait for connections */
				wait_for_connections();

				if (sigrestart == TRUE) {

					/* free memory */
					free_memory();

					/* re-read the config file */
					result = read_config_file(config_file);

					/* exit if there are errors... */
					if (result == ERROR) {
						syslog(LOG_ERR, "Config file '%s' contained errors, bailing out...", config_file);
						break;
					}
				}

			} while (sigrestart == TRUE && sigshutdown == FALSE);

			/* remove pid file */
			remove_pid_file();

			syslog(LOG_NOTICE, "Daemon shutdown\n");
		}
		break;

	default:
		break;
	}

	/* we are now running in daemon mode, or the connection handed over by inetd has been completed, so the parent process exits */
	do_exit(STATE_OK);

	/* keep the compilers happy... */
	return STATE_OK;
}
Example #20
0
int32_t
main(int32_t argc, char *argv[])
{
	struct bthid_server	 srv;
	struct sigaction	 sa;
	char const		*pid_file = BTHIDD_PIDFILE;
	char			*ep;
	int32_t			 opt, detach, tval;

	memset(&srv, 0, sizeof(srv));
	memset(&srv.bdaddr, 0, sizeof(srv.bdaddr));
	detach = 1;
	tval = 10; /* sec */

	while ((opt = getopt(argc, argv, "a:c:dH:hp:t:")) != -1) {
		switch (opt) {
		case 'a': /* BDADDR */
			if (!bt_aton(optarg, &srv.bdaddr)) {
				struct hostent  *he;

				if ((he = bt_gethostbyname(optarg)) == NULL)
					errx(1, "%s: %s", optarg, hstrerror(h_errno));

				memcpy(&srv.bdaddr, he->h_addr, sizeof(srv.bdaddr));
			}
			break;
			
		case 'c': /* config file */
			config_file = optarg;
			break;

		case 'd': /* do not detach */
			detach = 0;
			break;

		case 'H': /* hids file */
			hids_file = optarg;
			break;

		case 'p': /* pid file */
			pid_file = optarg;
			break;

		case 't': /* rescan interval */
			tval = strtol(optarg, (char **) &ep, 10);
			if (*ep != '\0' || tval <= 0)
				usage();
			break;

		case 'h':
		default:
			usage();
			/* NOT REACHED */
		}
	}

	openlog(BTHIDD_IDENT, LOG_PID|LOG_PERROR|LOG_NDELAY, LOG_USER);

	/* Become daemon if required */
	if (detach && daemon(0, 0) < 0) {
		syslog(LOG_CRIT, "Could not become daemon. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	/* Install signal handler */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sighandler;

	if (sigaction(SIGTERM, &sa, NULL) < 0 ||
	    sigaction(SIGHUP, &sa, NULL) < 0 ||
	    sigaction(SIGINT, &sa, NULL) < 0) {
		syslog(LOG_CRIT, "Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	sa.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &sa, NULL) < 0) {
		syslog(LOG_CRIT, "Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT;
	if (sigaction(SIGCHLD, &sa, NULL) < 0) {
		syslog(LOG_CRIT, "Could not install signal handlers. %s (%d)",
			strerror(errno), errno);
		exit(1);
	}

	if (read_config_file() < 0 || read_hids_file() < 0 ||
	    server_init(&srv) < 0 || write_pid_file(pid_file) < 0)
		exit(1);

	for (done = 0; !done; ) {
		if (elapsed(tval))
			client_rescan(&srv);

		if (server_do(&srv) < 0)
			break;
	}

	server_shutdown(&srv);
	remove_pid_file(pid_file);
	clean_config();
	closelog();

	return (0);
}
Example #21
0
int main(int argc, char **argv){
	int result=OK;
	int x;
	char buffer[MAX_INPUT_BUFFER];
	char *env_string=NULL;
#ifdef HAVE_SSL
	DH *dh;
	char seedfile[FILENAME_MAX];
	int i,c;
#endif

	/* set some environment variables */
	asprintf(&env_string,"NRPE_MULTILINESUPPORT=1");
	putenv(env_string);
	asprintf(&env_string,"NRPE_PROGRAMVERSION=%s",PROGRAM_VERSION);
	putenv(env_string);

	/* process command-line args */
	result=process_arguments(argc,argv);

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE){

		printf("\n");
		printf("NRPE - Nagios Remote Plugin Executor\n");
		printf("Copyright (c) 1999-2008 Ethan Galstad ([email protected])\n");
		printf("Version: %s\n",PROGRAM_VERSION);
		printf("Last Modified: %s\n",MODIFICATION_DATE);
		printf("License: GPL v2 with exemptions (-l for more info)\n");
#ifdef HAVE_SSL
		printf("SSL/TLS Available: Anonymous DH Mode, OpenSSL 0.9.6 or higher required\n");
#endif
#ifdef HAVE_LIBWRAP
		printf("TCP Wrappers Available\n");
#endif
		printf("\n");
#ifdef ENABLE_COMMAND_ARGUMENTS
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - COMMAND ARGUMENTS ARE SUPPORTED! **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
#ifndef HAVE_LIBWRAP
		printf("***************************************************************\n");
		printf("** POSSIBLE SECURITY RISK - TCP WRAPPERS ARE NOT AVAILABLE!  **\n");
		printf("**      Read the NRPE SECURITY file for more information     **\n");
		printf("***************************************************************\n");
		printf("\n");
#endif
	        }

	if(show_license==TRUE)
		display_license();

	else if(result!=OK || show_help==TRUE){

		printf("Usage: nrpe [-n] -c <config_file> <mode>\n");
		printf("\n");
		printf("Options:\n");
		printf(" -n            = Do not use SSL\n");
		printf(" <config_file> = Name of config file to use\n");
		printf(" <mode>        = One of the following two operating modes:\n");  
		printf("   -i          =    Run as a service under inetd or xinetd\n");
		printf("   -d          =    Run as a standalone daemon\n");
		printf("\n");
		printf("Notes:\n");
		printf("This program is designed to process requests from the check_nrpe\n");
		printf("plugin on the host(s) running Nagios.  It can run as a service\n");
		printf("under inetd or xinetd (read the docs for info on this), or as a\n");
		printf("standalone daemon. Once a request is received from an authorized\n");
		printf("host, NRPE will execute the command/plugin (as defined in the\n");
		printf("config file) and return the plugin output and return code to the\n");
		printf("check_nrpe plugin.\n");
		printf("\n");
		}

        if(result!=OK || show_help==TRUE || show_license==TRUE || show_version==TRUE)
		exit(STATE_UNKNOWN);


	/* open a connection to the syslog facility */
	/* facility name may be overridden later */
	get_log_facility(NRPE_LOG_FACILITY);
        openlog("nrpe",LOG_PID,log_facility); 

	/* make sure the config file uses an absolute path */
	if(config_file[0]!='/'){

		/* save the name of the config file */
		strncpy(buffer,config_file,sizeof(buffer));
		buffer[sizeof(buffer)-1]='\x0';

		/* get absolute path of current working directory */
		strcpy(config_file,"");
		getcwd(config_file,sizeof(config_file));

		/* append a forward slash */
		strncat(config_file,"/",sizeof(config_file)-2);
		config_file[sizeof(config_file)-1]='\x0';

		/* append the config file to the path */
		strncat(config_file,buffer,sizeof(config_file)-strlen(config_file)-1);
		config_file[sizeof(config_file)-1]='\x0';
	        }

	/* read the config file */
	result=read_config_file(config_file);	

	/* exit if there are errors... */
	if(result==ERROR){
		syslog(LOG_ERR,"Config file '%s' contained errors, aborting...",config_file);
		return STATE_CRITICAL;
		}

        /* generate the CRC 32 table */
        generate_crc32_table();

	/* initialize macros */
	for(x=0;x<MAX_COMMAND_ARGUMENTS;x++)
		macro_argv[x]=NULL;

#ifdef HAVE_SSL
	/* initialize SSL */
	if(use_ssl==TRUE){
		SSL_library_init();
		SSLeay_add_ssl_algorithms();
		meth=SSLv23_server_method();
		SSL_load_error_strings();

		/* use week random seed if necessary */
		if(allow_weak_random_seed && (RAND_status()==0)){

			if(RAND_file_name(seedfile,sizeof(seedfile)-1))
				if(RAND_load_file(seedfile,-1))
					RAND_write_file(seedfile);

			if(RAND_status()==0){
				syslog(LOG_ERR,"Warning: SSL/TLS uses a weak random seed which is highly discouraged");
				srand(time(NULL));
				for(i=0;i<500 && RAND_status()==0;i++){
					for(c=0;c<sizeof(seedfile);c+=sizeof(int)){
						*((int *)(seedfile+c))=rand();
					        }
					RAND_seed(seedfile,sizeof(seedfile));
					}
				}
			}

		if((ctx=SSL_CTX_new(meth))==NULL){
			syslog(LOG_ERR,"Error: could not create SSL context.\n");
			exit(STATE_CRITICAL);
		        }

		/* ADDED 01/19/2004 */
		/* use only TLSv1 protocol */
		SSL_CTX_set_options(ctx,SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);

		/* use anonymous DH ciphers */
		SSL_CTX_set_cipher_list(ctx,"ADH");
		dh=get_dh512();
		SSL_CTX_set_tmp_dh(ctx,dh);
		DH_free(dh);
		if(debug==TRUE)
			syslog(LOG_INFO,"INFO: SSL/TLS initialized. All network traffic will be encrypted.");
	        }
	else{
		if(debug==TRUE)
			syslog(LOG_INFO,"INFO: SSL/TLS NOT initialized. Network encryption DISABLED.");
	        }
#endif

	/* if we're running under inetd... */
	if(use_inetd==TRUE){

		/* make sure we're not root */
		check_privileges();

		/* redirect STDERR to /dev/null */
		close(2);
		open("/dev/null",O_WRONLY);

		/* handle the connection */
		handle_connection(0);
	        }

	/* else daemonize and start listening for requests... */
	else if(fork()==0){
		
		/* we're a daemon - set up a new process group */
		setsid();

		/* close standard file descriptors */
		close(0);
		close(1);
		close(2);

		/* redirect standard descriptors to /dev/null */
		open("/dev/null",O_RDONLY);
		open("/dev/null",O_WRONLY);
		open("/dev/null",O_WRONLY);

		chdir("/");
		/*umask(0);*/

		/* handle signals */
		signal(SIGQUIT,sighandler);
		signal(SIGTERM,sighandler);
		signal(SIGHUP,sighandler);

		/* log info to syslog facility */
		syslog(LOG_NOTICE,"Starting up daemon");

		/* write pid file */
		if(write_pid_file()==ERROR)
			return STATE_CRITICAL;
		
		/* drop privileges */
		drop_privileges(nrpe_user,nrpe_group);

		/* make sure we're not root */
		check_privileges();

		do{

			/* reset flags */
			sigrestart=FALSE;
			sigshutdown=FALSE;

			/* wait for connections */
			wait_for_connections();

			/* free all memory we allocated */
			free_memory();

			if(sigrestart==TRUE){

				/* read the config file */
				result=read_config_file(config_file);	

				/* exit if there are errors... */
				if(result==ERROR){
					syslog(LOG_ERR,"Config file '%s' contained errors, bailing out...",config_file);
					return STATE_CRITICAL;
				        }
			        }
	
		        }while(sigrestart==TRUE && sigshutdown==FALSE);

		/* remove pid file */
		remove_pid_file();

		syslog(LOG_NOTICE,"Daemon shutdown\n");
	        }

#ifdef HAVE_SSL
	if(use_ssl==TRUE)
		SSL_CTX_free(ctx);
#endif

	/* We are now running in daemon mode, or the connection handed over by inetd has
	   been completed, so the parent process exits */
        return STATE_OK;
	}
Example #22
0
int main(int argc, char **argv)
#endif
{
  long cache_hits, cache_misses;

#if CHROMIUM
  char *argv[] = { "vncreflector" };
  (void) parse_args;
  (void) report_usage;
  /*opt_log_filename = "reflector.log";*/
  opt_log_filename = NULL;
  opt_no_banner = 1;
  opt_foreground = 1;
  opt_stderr_loglevel = 5;
#else
  /* Parse command line, exit on error */
  parse_args(argc, argv);
#endif


  if (!opt_no_banner) {
    fprintf(stderr,
"VNC Reflector %s.  Copyright (C) 2001-2003 HorizonLive.com, Inc.\n\n"
"HorizonLive provides e-Learning and collaborative synchronous presentation\n"
"solutions in a totally Web-based environment.  For more information about\n"
"HorizonLive, please see our website at http://www.horizonlive.com/\n\n",
            VERSION);
  }

  if (!log_open(opt_log_filename, opt_file_loglevel,
                (opt_foreground) ? opt_stderr_loglevel : -1)) {
    fprintf(stderr, "%s: error opening log file (ignoring this error)\n",
            argv[0]);
  }

  log_write(LL_MSG, "Starting VNC Reflector %s", VERSION);

  /* Fork the process to the background if necessary */
  if (!opt_foreground) {
    if (!opt_no_banner) {
      fprintf(stderr, "Starting in the background, "
              "see the log file for errors and other messages.\n");
    }

    if (getpid() != 1) {
      signal(SIGTTIN, SIG_IGN);
      signal(SIGTTOU, SIG_IGN);
      signal(SIGTSTP, SIG_IGN);
      if (fork ())
        return 0;
      setsid();
    }
    close(0);
    close(1);
    close(2);
    log_write(LL_INFO, "Switched to the background mode");
  }

  /* Initialization */
  if (init_screen_info()) {
    read_password_file();
    set_host_encodings(opt_request_tight, opt_tight_level);
    set_client_passwords(opt_client_password, opt_client_ro_password);
    fbs_set_prefix(opt_fbs_prefix, opt_join_sessions);

    set_active_file(opt_active_filename);
    set_actions_file(opt_actions_filename);

    aio_init();
    if (opt_bind_ip != NULL) {
      if (aio_set_bind_address(opt_bind_ip)) {
        log_write(LL_INFO, "Would bind listening sockets to address %s",
                  opt_bind_ip);
      } else {
        log_write(LL_WARN, "Illegal address to bind listening sockets to: %s",
                  opt_bind_ip);
      }
    }

    /* Main work */
    if (vnc_spu.server_port == -1)
    {
      /* Try a series of port numbers until we find one that's free
       * for us.  Then, signal our parent thread that the port number
       * is available.
       */
      int i;
      for (i = 0; i < NUM_SERVER_PORTS; i++) {
        int p = FIRST_SERVER_PORT + i;
	if (wait_for_client(p)) {
	  /* OK, we've got our port number now.  So signal parent thread. */
	  crLockMutex(&vnc_spu.lock);
	  vnc_spu.server_port = p;
	  opt_cl_listen_port = vnc_spu.server_port;
	  crSignalCondition(&vnc_spu.cond);
	  crUnlockMutex(&vnc_spu.lock);

	  if (write_pid_file()) {
	    /*set_control_signals()*/
	    aio_mainloop();
	    remove_pid_file();
	  }
	  break;
	}
      }
      if (i == NUM_SERVER_PORTS) {
	log_write(LL_ERROR, "Unable to find a free port in the range"
		  " %d through %d",
		  FIRST_SERVER_PORT, FIRST_SERVER_PORT + NUM_SERVER_PORTS - 1);
	exit(1);
      }
    }
    else {
      /* user-configured port number */
      opt_cl_listen_port = vnc_spu.server_port;
      if (wait_for_client(opt_cl_listen_port)) {
	if (write_pid_file()) {
	  /*set_control_signals()*/
	  aio_mainloop();
	  remove_pid_file();
	}
      }
    }

    /* Cleanup */
    if (g_framebuffer != NULL) {
      log_write(LL_DETAIL, "Freeing framebuffer and associated structures");
      free(g_framebuffer);
      free_enc_cache();
    }
    if (g_screen_info.name != NULL)
      free(g_screen_info.name);

    get_hextile_caching_stats(&cache_hits, &cache_misses);
    if (cache_hits + cache_misses != 0) {
      log_write(LL_INFO, "Hextile BGR233 caching efficiency: %d%%",
                (int)((cache_hits * 100 + (cache_hits + cache_misses) / 2)
                      / (cache_hits + cache_misses)));
    }
  }

  log_write(LL_MSG, "Terminating");

  /* Close logs */
  if (!log_close() && opt_foreground) {
    fprintf(stderr, "%s: error closing log file (ignoring this error)\n",
            argv[0]);
  }

  /* Done */
  exit(1);
}
Example #23
0
int create_pid_file (void) {
	int fd;
	char *pidfile;
	char buf[100];
	ssize_t cnt;
	char* procpid = malloc( sizeof(buf) + 15 );

	pidfile = default_pid_file();

	if (file_exists(pidfile)) {

		// check if /proc/{pid}/cmdline exists and contains opengalax
		// if it does, means opengalax is already running, so we exit cowardly
		// if it does not contain opengalax, then we remove the old pid file and continue

		fd = open(pidfile, O_RDONLY);
		if (fd < 0) {
			fprintf (stderr,"Could not open pid file: %s\n", pidfile);
			return 0;
		}
		cnt=read(fd, buf, sizeof(buf)-1);
		buf[cnt]='\0';
		
		close(fd);

		strcpy(procpid, "");
		strcat(procpid, "/proc/");
		strcat(procpid, buf);
		strcat(procpid, "/cmdline");

		if (file_exists(procpid)) {
			fd = open(procpid, O_RDONLY);
			if (fd < 0) {
				fprintf (stderr,"Could not open file: %s\n", procpid);
				return 0;
			}

			cnt=read(fd, buf, sizeof(buf)-1);
			buf[cnt]='\0';
			
			close(fd);

			if (strstr(buf,"opengalax") != NULL) {
				fprintf (stderr,"Refusing to start as another instance is already running\n");
				return 0;
			} else {
				if (!remove_pid_file()) 
					return 0;
			}
		}
	}

	fd = open(pidfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if (fd < 0 ) {
		fprintf(stderr,"Could not write pid file: %s\n", pidfile);
		return 0;
	}

	sprintf( buf, "%d", getpid() );
	if (write(fd, buf, strlen(buf)) < 1) {
		perror("Something wrong happening while writing pid file");
		close(fd);
		return 0;
	}
	close(fd);

	free(procpid);

	return 1;
}