Exemple #1
0
int main(int argc,char **argv) {
	char *wrkdir;
	int ch;
	int32_t nicelevel;
	struct rlimit rls;

  exiting = 0;
	strerr_init();
  set_signal_handlers();

	if (initialize()) {
		if (getrlimit(RLIMIT_NOFILE,&rls)==0) {
			syslog(LOG_NOTICE,"open files limit: %lu",(unsigned long)(rls.rlim_cur));
		}

		if (initialize_late()) {
			mainloop();
			ch=0;
		} else {
			ch=1;
		}
	} else {
		fprintf(stderr,"error occured during initialization - exiting\n");
		ch=1;
	}
	destruct();
	free_all_registered_entries();
	strerr_term();

	return ch;
}
Exemple #2
0
int main(
    int argc,
    char *argv[]
)   {
    int index = 1;
    if (argc < 2) {
        sharedq_help(argc, argv, index);
        return 0;
    }

    while (index < argc) {
        if (argv[index][0] != '-') {
            break;
        }
        index++;
    }

    if (argc == index) {
        sharedq_help(argc, argv, index);
        return 0;
    }

    int rc = sem_init(&adds, 0, 0);
    if (rc < 0) {
        printf("unable to initialize add semapahore\n");
        return 0;
    }

    rc = sem_init(&events, 0, 1);
    if (rc < 0) {
        printf("unable to initialize event semapahore\n");
        return 0;
    }

    rc = sem_init(&calls, 0, 0);
    if (rc < 0) {
        printf("unable to initialize call semapahore\n");
        return 0;
    }

    set_signal_handlers();

    int length = strlen(argv[index]);
    int i;
    for (i = 0; i < CODE_MAX; i++) {
        if ((length == strlen(cmd_str[i])) && (memcmp(argv[index],
                cmd_str[i],
                length) == 0)) {
            (*cmds[i])(argc, argv, index);
            break;
        }
    }

    if (i == CODE_MAX) {
        sharedq_help(argc, argv, index);
    }
    return 0;
}
Exemple #3
0
int main(int argc, char **argv) {

  set_signal_handlers();

  /* Create mmap space */
  dlmmap_init();

  mqdl_server();

  return(0);
}
Exemple #4
0
int main(int argc, char** argv)
{
    struct sockaddr_in server;
    struct sockaddr_in client;
    char buffer[BUFSIZE];
    socklen_t len_client;
    int transfered = 0;
    char* msg;
    pthread_t thread_tweet_fetcher;

    if (argc < 2) {
        printf("USAGE: %s [port]\n", argv[0]);
        return 0;
    }

    atexit(at_exit);
    set_signal_handlers();

    T = twitter_new();
    printf("Reading tweets...\n");
    fetch_tweets(T, 15);

    pthread_create(&thread_tweet_fetcher, NULL, thread_fetch_tweets, NULL);

    printf("Opening server...\n");
    sock = udp_create_socket(&server, sizeof(server), htonl(INADDR_ANY), atoi(argv[1]), 0);
    if (sock < 0)
        error_and_exit("cannot create socket", __FILE__, __LINE__);

    if (bind(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
        error_and_exit("Cannot bind to socket", __FILE__, __LINE__);

    len_client = sizeof(client);
    for (;;) {
        transfered = udp_receive(sock, buffer, BUFSIZE, &client, len_client);
        switch (transfered) {
            case -1: 
                error_and_exit("Failed to receive message", __FILE__, __LINE__);
            case 0:
                error_and_exit("Client has shut down...", __FILE__, __LINE__);
        }

        msg = get_tweet(T);
        transfered = udp_send(sock, msg, &client, sizeof(client));
        free(msg);

        if (!transfered)
            error_and_exit("Sending has failed!", __FILE__, __LINE__);
    }

    close(sock);
    return 0;
}
Exemple #5
0
void Replay::setup()
{
    ::printf("Starting\n");

    uint8_t argc;
    char * const *argv;

    hal.util->commandline_arguments(argc, argv);

    _parse_command_line(argc, argv);

    if (!check_generate) {
        logreader.set_save_chek_messages(true);
    }

    set_signal_handlers();

    hal.console->printf("Processing log %s\n", filename);

    // remember filename for reporting
    log_filename = filename;

    if (!find_log_info(log_info)) {
        printf("Update to get log information\n");
        exit(1);
    }

    hal.console->printf("Using an update rate of %u Hz\n", log_info.update_rate);

    if (!logreader.open_log(filename)) {
        perror(filename);
        exit(1);
    }

    _vehicle.setup();

    inhibit_gyro_cal();

    if (log_info.update_rate == 400) {
        // assume copter for 400Hz
        _vehicle.ahrs.set_vehicle_class(AHRS_VEHICLE_COPTER);
        _vehicle.ahrs.set_fly_forward(false);
    } else if (log_info.update_rate == 50) {
        // assume copter for 400Hz
        _vehicle.ahrs.set_vehicle_class(AHRS_VEHICLE_FIXED_WING);
        _vehicle.ahrs.set_fly_forward(true);
    }
    
    set_ins_update_rate(log_info.update_rate);
}
Exemple #6
0
int fuse_serve_init(int argc, char ** argv)
{
	int r;

	root_cfs = NULL;
	serving = 0;

	if ((r = fstitchd_register_shutdown_module(fuse_serve_shutdown, NULL, SHUTDOWN_PREMODULES)) < 0)
	{
		fprintf(stderr, "%s(): fstitchd_register_shutdown_module() = %d\n", __FUNCTION__, r);
		return r;
	}

	if ((r = pipe(shutdown_pipe)) < 0)
	{
		perror("fuse_serve_init(): pipe:");
		return -1;
	}

	if ((r = fuse_serve_mount_init(argc, argv, &serve_oper, sizeof(serve_oper))) < 0)
	{
		fprintf(stderr, "%s(): fuse_serve_mount_init() = %d\n", __FUNCTION__, r);
		goto error_pipe;
	}
	remove_activity = r;

	channel_buf_len = fuse_serve_mount_chan_bufsize();
	if (!(channel_buf = (char *) malloc(channel_buf_len)))
	{
		fprintf(stderr, "%s(): malloc(%u) failed to allocate read buffer\n", __FUNCTION__, (unsigned) channel_buf_len);
		goto error_buf_len;
	}

	if ((r = set_signal_handlers()) < 0)
		goto error_buf_malloc;

	return 0;

  error_buf_malloc:
	free(channel_buf);
	channel_buf = NULL;
  error_buf_len:
	channel_buf_len = 0;
  error_pipe:
	close(shutdown_pipe[1]);
	close(shutdown_pipe[0]);
	shutdown_pipe[1] = shutdown_pipe[0] = -1;
	return r;
}
Exemple #7
0
int main(int argc, char *argv[])
{
    int argctr;
    int flags;
    struct fuse *fuse;

    if(argc < 2) {
        fprintf(stderr,
                "usage: %s unmount_cmd [options] \n"
                "Options:\n"
                "    -d      enable debug output\n"
                "    -s      disable multithreaded operation\n",
                argv[0]);
        exit(1);
    }

    argctr = 1;
    unmount_cmd = argv[argctr++];

    set_signal_handlers();
    atexit(cleanup);

    flags = FUSE_MULTITHREAD;
    for(; argctr < argc && argv[argctr][0] == '-'; argctr ++) {
        switch(argv[argctr][1]) {
        case 'd':
            flags |= FUSE_DEBUG;
            break;

        case 's':
            flags &= ~FUSE_MULTITHREAD;
            break;

        default:
            fprintf(stderr, "invalid option: %s\n", argv[argctr]);
            exit(1);
        }
    }
    if(argctr != argc) {
        fprintf(stderr, "missing or surplus argument\n");
        exit(1);
    }

    fuse = fuse_new(0, flags);
    fuse_set_operations(fuse, &xmp_oper);
    fuse_loop(fuse);

    return 0;
}
Exemple #8
0
int
main (int argc, char **argv)
{
    int c;
    char *config_dir = DEFAULT_CONFIG_DIR;
    char *seafile_dir = NULL;
    char *logfile = NULL;
    const char *debug_str = NULL;
    int daemon_mode = 1;
    int is_master = 0;
    CcnetClient *client;
    char *ccnet_debug_level_str = "info";
    char *seafile_debug_level_str = "debug";
    int cloud_mode = 0;

    while ((c = getopt_long (argc, argv, short_options, 
                             long_options, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            exit (1);
            break;
        case 'v':
            exit (1);
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'f':
            daemon_mode = 0;
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'D':
            debug_str = optarg;
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            seafile_debug_level_str = optarg;
            break;
        case 'm':
            is_master = 1;
        case 'P':
            pidfile = optarg;
            break;
        case 'C':
            cloud_mode = 1;
            break;
        default:
            usage ();
            exit (1);
        }
    }

    argc -= optind;
    argv += optind;

#ifndef WIN32
    if (daemon_mode)
        daemon (1, 0);
#endif

    g_type_init ();
#if !GLIB_CHECK_VERSION(2,32,0)
    g_thread_init (NULL);
#endif

    if (!debug_str)
        debug_str = g_getenv("SEAFILE_DEBUG");
    seafile_debug_set_flags_string (debug_str);

    client = ccnet_init (config_dir);
    if (!client)
        exit (1);

    register_processors (client);

    start_rpc_service (client, cloud_mode);

    create_sync_rpc_clients (config_dir);
    create_async_rpc_clients (client);

    if (seafile_dir == NULL)
        seafile_dir = g_build_filename (config_dir, "seafile", NULL);
    if (logfile == NULL)
        logfile = g_build_filename (seafile_dir, "seafile.log", NULL);

    seaf = seafile_session_new (seafile_dir, client);
    if (!seaf) {
        fprintf (stderr, "Failed to create seafile session.\n");
        exit (1);
    }
    seaf->is_master = is_master;
    seaf->ccnetrpc_client = ccnetrpc_client;
    seaf->async_ccnetrpc_client = async_ccnetrpc_client;
    seaf->ccnetrpc_client_t = ccnetrpc_client_t;
    seaf->async_ccnetrpc_client_t = async_ccnetrpc_client_t;
    seaf->client_pool = ccnet_client_pool_new (config_dir);
    seaf->cloud_mode = cloud_mode;

    load_history_config ();

    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          seafile_debug_level_str) < 0) {
        fprintf (stderr, "Failed to init log.\n");
        exit (1);
    }

    g_free (seafile_dir);
    g_free (logfile);

    set_signal_handlers (seaf);

    /* init seaf */
    if (seafile_session_init (seaf) < 0)
        exit (1);

    if (seafile_session_start (seaf) < 0)
        exit (1);

    if (pidfile) {
        if (write_pidfile (pidfile) < 0) {
            ccnet_message ("Failed to write pidfile\n");
            return -1;
        }
    }
    atexit (on_seaf_server_exit);

    ccnet_main (client);

    return 0;
}
Exemple #9
0
int
main (int argc, char **argv)
{
    int c;
    char *config_dir = DEFAULT_CONFIG_DIR;
    char *seafile_dir = NULL;
    char *worktree_dir = NULL;
    char *logfile = NULL;
    const char *debug_str = NULL;
    int daemon_mode = 0;
    CcnetClient *client;
    char *ccnet_debug_level_str = "info";
    char *seafile_debug_level_str = "debug";

#ifdef WIN32
    LoadLibraryA ("exchndl.dll");

    argv = get_argv_utf8 (&argc);
#endif

    while ((c = getopt_long (argc, argv, short_options, 
                             long_options, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            usage();
            exit (1);
            break;
        case 'v':
            exit (1);
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'b':
            daemon_mode = 1;
            break;
        case 'D':
            debug_str = optarg;
            break;
        case 'w':
            worktree_dir = g_strdup(optarg);
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            seafile_debug_level_str = optarg;
            break;
        default:
            usage ();
            exit (1);
        }
    }

    argc -= optind;
    argv += optind;

#ifndef WIN32
    if (daemon_mode) {
#ifndef __APPLE__
        daemon (1, 0);
#else   /* __APPLE */
        /* daemon is deprecated under APPLE
         * use fork() instead
         * */
        switch (fork ()) {
          case -1:
              seaf_warning ("Failed to daemonize");
              exit (-1);
              break;
          case 0:
              /* all good*/
              break;
          default:
              /* kill origin process */
              exit (0);
        }
#endif  /* __APPLE */
    }
#endif /* !WIN32 */

    cdc_init ();

#if !GLIB_CHECK_VERSION(2, 35, 0)
    g_type_init();
#endif
#if !GLIB_CHECK_VERSION(2, 31, 0)
    g_thread_init(NULL);
#endif

    if (!debug_str)
        debug_str = g_getenv("SEAFILE_DEBUG");
    seafile_debug_set_flags_string (debug_str);

    if (logfile == NULL)
        logfile = g_build_filename (config_dir, "logs", "seafile.log", NULL);
    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          seafile_debug_level_str) < 0) {
        seaf_warning ("Failed to init log.\n");
        exit (1);
    }

    if (!bind_ccnet_service (config_dir)) {
        seaf_warning ("Failed to bind ccnet service\n");
        exit (1);
    }

    /* init ccnet */
    client = ccnet_init (config_dir);
    if (!client)
        exit (1);

    start_rpc_service (client);

    create_sync_rpc_clients (config_dir);
    appletrpc_client = ccnet_create_async_rpc_client (client, NULL, 
                                                      "applet-rpcserver");

    /* init seafile */
    if (seafile_dir == NULL)
        seafile_dir = g_build_filename (config_dir, "seafile-data", NULL);
    if (worktree_dir == NULL)
        worktree_dir = g_build_filename (g_get_home_dir(), "seafile", NULL);

    seaf = seafile_session_new (seafile_dir, worktree_dir, client);
    if (!seaf) {
        seaf_warning ("Failed to create seafile session.\n");
        exit (1);
    }
    seaf->ccnetrpc_client = ccnetrpc_client;
    seaf->appletrpc_client = appletrpc_client;

    seaf_message ("starting seafile client "SEAFILE_CLIENT_VERSION"\n");
#if defined(SEAFILE_SOURCE_COMMIT_ID)
    seaf_message ("seafile source code version "SEAFILE_SOURCE_COMMIT_ID"\n");
#endif

    g_free (seafile_dir);
    g_free (worktree_dir);
    g_free (logfile);

    set_signal_handlers (seaf);

    seafile_session_prepare (seaf);
    seafile_session_start (seaf);

    seafile_session_config_set_string (seaf, "wktree", seaf->worktree_dir);
    ccnet_main (client);

    return 0;
}
Exemple #10
0
int
main(int argc, char *argv[], char *envp[])
{
	int c;
	int show_version = 0;
	const char *cmdopts = OPTION_COMMANDS;
	char SoftBotRoot[MAX_PATH_LEN], *tmp;

	// set gSoftBotRoot
	if ( realpath(argv[0], SoftBotRoot) ) {
		tmp = strstr( SoftBotRoot, "/bin/softbotd" );
		if ( tmp ) {
			*tmp = '\0';

			strcpy( gSoftBotRoot, SoftBotRoot );
		}
	}
	info("server has started in [%s].", gSoftBotRoot );


#ifdef AIX5
	{ char *env = getenv("EXTSHM");
	  if (!env || strcmp(env, "ON")) {
		/* we need EXTSHM=ON in our environment to make the shmat and mmaps work */
		setenv("EXTSHM", "ON", 1);
		fprintf(stderr, "re-executing self with EXTSHM=ON exported to fix AIX shmat problem.\n");
		execv(argv[0], argv);
		fprintf(stderr, "re-execution failed - terminating.\n");
		exit(1);
	  }
	}
#endif

	init_setproctitle(argc, argv, envp);
	set_static_modules(server_static_modules);

	/* getopt stuff */
	opterr = 0;
	while ( (c = 
#ifdef HAVE_GETOPT_LONG
		getopt_long(argc, argv, cmdopts, opts, NULL)
#elif HAVE_GETOPT
		getopt(argc, argv, cmdopts)
#else
#	error at least one of getopt, getopt_long must exist.
#endif /* HAVE_GETOPT_LONG */
		) != -1 )
	{
		int i = 0;

		switch ( c ) {
			case 'n':
				nodaemon++;
				set_screen_log();
				break;
			case 'p':
				clc_listen_port++;
				if (strcmp(optarg,"show")==0) { /* show using ports info */
					clc_listen_port++; 
					nodaemon++;
					log_setlevelstr("error");
					clc_log_level++;
					break;
				}

				i=atoi(optarg);
				if (i<1024) gSoftBotListenPort += i;
				else gSoftBotListenPort = i;

				info("Setting gSoftBotListenPort to %d",gSoftBotListenPort);

				break;
			case 'g':
				if ( !optarg ) {
					error("Fatal: -g requires error log level argument.");
					exit(1);
				}

				if (log_setlevelstr(optarg) == SUCCESS) {
					clc_log_level++;
				} else {
					error("Invalid log level.");
					info("  arg for -d is like following");
					for (i=0; gLogLevelStr[i]; i++) {
						info("    %s",gLogLevelStr[i]);
					}
					exit(1);
				}
				break;
			case 'm':
				if ( !optarg ) {
					error("Fatal: -m requires module name.");
					exit(1);
				}

				strncpy(debug_module, optarg, MAX_MODULE_NAME);
				debug_module[MAX_MODULE_NAME-1] = '\0';

				/* nodaemon is on by default when debugging a module */
				nodaemon++;
				set_screen_log();
				debug("debugging module[%s]", debug_module);
				break;
			case 'u':
				if (unittest==0) {
					info("When doing unittest,");
					info("always check that modules to be tested are loaded");
				}
				nodaemon++;
				set_screen_log();
				unittest++;
				break;
			case 'k':
				/* refer to hook.c, hook.h, modules.c */
				debug_module_hooks++;
				break;
			case 'l':
				list_static_modules(stdout);
				exit(0);
				break;
			case 'c':
				if ( !optarg ) {
					error("Fatal: -c requires configuration path");
					exit(1);
				}
				strncpy(mConfigFile, optarg, MAX_PATH_LEN);
				mConfigFile[MAX_PATH_LEN-1] = '\0';
				debug("configuration file path set to %s",mConfigFile);
				break;
			case 't':
				check_config_syntax = 1;

				clc_log_level++;
				gLogLevel = LEVEL_INFO;

				set_screen_log(); // syntax checking 시 error를 화면으로..
				printf("Checking syntax of configuration file\n");
				fflush(stdout);
				break;
			case 'r':
				if ( !optarg ) {
					error("Fatal: -r requires server root path");
					exit(1);
				}
				strncpy(gSoftBotRoot, optarg, MAX_PATH_LEN);
				gSoftBotRoot[MAX_PATH_LEN-1] = '\0';
				clc_server_root++;
				debug("gSoftBotRoot is set to %s by -r option.",gSoftBotRoot);
				break;
			case 'v':
				show_version++;
				break;
			case 'h':
				show_usage(0);
			case '?':
				error("Unknown option: %c", (char)optopt);
				show_usage(1);
		} /* switch ( c ) */
	} 
	/* end of getopt stuff */

	if ( show_version ) show_version_and_exit();


	/* initializing */

	/* we're only doing a syntax check of the configuration file.
	 */
	if ( check_config_syntax ) {
		int ret=FAIL;
		// TODO: is this enough? -aragorn
		debug("checking syntax");
		debug("configuration file:%s",mConfigFile);
		load_static_modules();
		ret = read_config(mConfigFile, NULL);

		printf("Syntax check completed.\n");
		printf("Configuration module returned %d\n",ret);
		exit(0);
	}

	/* setuid, setgid stuff */

	/* signal handler stuff */
	set_signal_handlers();
	/* resource limits */

	if ( nodaemon == 0 ) detach();

/*  RESTART:*/

	/* set pid */
	gRootPid = getpid();

	server_main();
	/* if ( restart ) goto RESTART; */

	return 0;
}
Exemple #11
0
int main(int argc,char **argv) {
	char *logappname;
//	char *lockfname;
	char *wrkdir;
	char *cfgfile;
	char *appname;
	int ch;
	uint8_t runmode;
	int rundaemon,logundefined;
	int lockmemory;
	int32_t nicelevel;
	uint32_t locktimeout;
	int fd;
	uint8_t movewarning;
	struct rlimit rls;

	strerr_init();
	mycrc32_init();

	movewarning = 0;
	cfgfile=strdup(ETC_PATH "/mfs/" STR(APPNAME) ".cfg");
	passert(cfgfile);
	if ((fd = open(cfgfile,O_RDONLY))<0 && errno==ENOENT) {
		free(cfgfile);
		cfgfile=strdup(ETC_PATH "/" STR(APPNAME) ".cfg");
		passert(cfgfile);
		if ((fd = open(cfgfile,O_RDONLY))>=0) {
			movewarning = 1;
		}
	}
	if (fd>=0) {
		close(fd);
	}
	locktimeout = 1800;
	rundaemon = 1;
	runmode = RM_RESTART;
	logundefined = 0;
	lockmemory = 0;
	appname = argv[0];

	while ((ch = getopt(argc, argv, "uvdfsc:t:h?")) != -1) {
		switch(ch) {
			case 'v':
				printf("version: %u.%u.%u\n",VERSMAJ,VERSMID,VERSMIN);
				return 0;
			case 'd':
				rundaemon=0;
				break;
			case 'f':
				runmode=RM_START;
				break;
			case 's':
				runmode=RM_STOP;
				break;
			case 't':
				locktimeout=strtoul(optarg,NULL,10);
				break;
			case 'c':
				free(cfgfile);
				cfgfile = strdup(optarg);
				passert(cfgfile);
				movewarning = 0;
				break;
			case 'u':
				logundefined=1;
				break;
			default:
				usage(appname);
				return 1;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc==1) {
		if (strcasecmp(argv[0],"start")==0) {
			runmode = RM_START;
		} else if (strcasecmp(argv[0],"stop")==0) {
			runmode = RM_STOP;
		} else if (strcasecmp(argv[0],"restart")==0) {
			runmode = RM_RESTART;
		} else if (strcasecmp(argv[0],"reload")==0) {
			runmode = RM_RELOAD;
		} else if (strcasecmp(argv[0],"test")==0) {
			runmode = RM_TEST;
		} else if (strcasecmp(argv[0],"kill")==0) {
			runmode = RM_KILL;
		} else {
			usage(appname);
			return 1;
		}
	} else if (argc!=0) {
		usage(appname);
		return 1;
	}

	if (movewarning) {
		mfs_syslog(LOG_WARNING,"default sysconf path has changed - please move " STR(APPNAME) ".cfg from "ETC_PATH"/ to "ETC_PATH"/mfs/");
	}

	if ((runmode==RM_START || runmode==RM_RESTART) && rundaemon) {
		makedaemon();
	} else {
		if (runmode==RM_START || runmode==RM_RESTART) {
			set_signal_handlers(0);
		}
	}

	if (cfg_load(cfgfile,logundefined)==0) {
		fprintf(stderr,"can't load config file: %s - using defaults\n",cfgfile);
	}
	free(cfgfile);

	logappname = cfg_getstr("SYSLOG_IDENT",STR(APPNAME));

	if (rundaemon) {
		if (logappname[0]) {
			openlog(logappname, LOG_PID | LOG_NDELAY , LOG_DAEMON);
		} else {
			openlog(STR(APPNAME), LOG_PID | LOG_NDELAY , LOG_DAEMON);
		}
	} else {
#if defined(LOG_PERROR)
		if (logappname[0]) {
			openlog(logappname, LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_USER);
		} else {
			openlog(STR(APPNAME), LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_USER);
		}
#else
		if (logappname[0]) {
			openlog(logappname, LOG_PID | LOG_NDELAY, LOG_USER);
		} else {
			openlog(STR(APPNAME), LOG_PID | LOG_NDELAY, LOG_USER);
		}
#endif
	}

	if (runmode==RM_START || runmode==RM_RESTART) {
		rls.rlim_cur = MFSMAXFILES;
		rls.rlim_max = MFSMAXFILES;
		if (setrlimit(RLIMIT_NOFILE,&rls)<0) {
			syslog(LOG_NOTICE,"can't change open files limit to %u",MFSMAXFILES);
		}

		lockmemory = cfg_getnum("LOCK_MEMORY",0);
#ifdef MFS_USE_MEMLOCK
		if (lockmemory) {
			rls.rlim_cur = RLIM_INFINITY;
			rls.rlim_max = RLIM_INFINITY;
			setrlimit(RLIMIT_MEMLOCK,&rls);
		}
#endif
		nicelevel = cfg_getint32("NICE_LEVEL",-19);
		setpriority(PRIO_PROCESS,getpid(),nicelevel);
	}

	changeugid();

	wrkdir = cfg_getstr("DATA_PATH",DATA_PATH);
	if (runmode==RM_START || runmode==RM_RESTART) {
		fprintf(stderr,"working directory: %s\n",wrkdir);
	}

	if (chdir(wrkdir)<0) {
		mfs_arg_syslog(LOG_ERR,"can't set working directory to %s",wrkdir);
		if (rundaemon) {
			fputc(0,stderr);
			close_msg_channel();
		}
		closelog();
		free(logappname);
		return 1;
	}
	free(wrkdir);

	umask(cfg_getuint32("FILE_UMASK",027)&077);

	/* for upgrading from previous versions of MFS */
	if (check_old_locks(runmode,locktimeout)<0) {
		if (rundaemon) {
			fputc(0,stderr);
			close_msg_channel();
		}
		closelog();
		free(logappname);
		wdunlock();
		return 1;
	}

	if (wdlock(runmode,locktimeout)<0) {
		if (rundaemon) {
			fputc(0,stderr);
			close_msg_channel();
		}
		closelog();
		free(logappname);
		wdunlock();
		return 1;
	}

	remove_old_wdlock();

	if (runmode==RM_STOP || runmode==RM_KILL || runmode==RM_RELOAD || runmode==RM_TEST) {
		if (rundaemon) {
			close_msg_channel();
		}
		closelog();
		free(logappname);
		wdunlock();
		return 0;
	}

#ifdef MFS_USE_MEMLOCK
	if (lockmemory) {
		if (getrlimit(RLIMIT_MEMLOCK,&rls)<0) {
			mfs_errlog(LOG_WARNING,"error getting memory lock limits");
		} else {
			if (rls.rlim_cur!=RLIM_INFINITY && rls.rlim_max==RLIM_INFINITY) {
				rls.rlim_cur = RLIM_INFINITY;
				rls.rlim_max = RLIM_INFINITY;
				if (setrlimit(RLIMIT_MEMLOCK,&rls)<0) {
					mfs_errlog(LOG_WARNING,"error setting memory lock limit to unlimited");
				}
			}
			if (getrlimit(RLIMIT_MEMLOCK,&rls)<0) {
				mfs_errlog(LOG_WARNING,"error getting memory lock limits");
			} else {
				if (rls.rlim_cur!=RLIM_INFINITY) {
					mfs_errlog(LOG_WARNING,"can't set memory lock limit to unlimited");
				} else {
					if (mlockall(MCL_CURRENT|MCL_FUTURE)<0) {
						mfs_errlog(LOG_WARNING,"memory lock error");
					} else {
						mfs_syslog(LOG_NOTICE,"process memory was successfully locked in RAM");
					}
			}	}
		}
	}
#else
	if (lockmemory) {
		mfs_syslog(LOG_WARNING,"memory lock not supported !!!");
	}
#endif
	fprintf(stderr,"initializing %s modules ...\n",logappname);

	if (initialize()) {
		if (getrlimit(RLIMIT_NOFILE,&rls)==0) {
			syslog(LOG_NOTICE,"open files limit: %lu",(unsigned long)(rls.rlim_cur));
		}
		fprintf(stderr,"%s daemon initialized properly\n",logappname);
		if (rundaemon) {
			close_msg_channel();
		}
		if (initialize_late()) {
			mainloop();
			ch=0;
		} else {
			ch=1;
		}
	} else {
		fprintf(stderr,"error occured during initialization - exiting\n");
		if (rundaemon) {
			fputc(0,stderr);
			close_msg_channel();
		}
		ch=1;
	}
	destruct();
	free_all_registered_entries();
	signal_cleanup();
	cfg_term();
	strerr_term();
	closelog();
	free(logappname);
	wdunlock();
	return ch;
}
Exemple #12
0
void makedaemon() {
	int f;
	uint8_t pipebuff[1000];
	ssize_t r;
	size_t happy;
	int piped[2];

	fflush(stdout);
	fflush(stderr);
	if (pipe(piped)<0) {
		fprintf(stderr,"pipe error\n");
		exit(1);
	}
	f = fork();
	if (f<0) {
		syslog(LOG_ERR,"first fork error: %s",strerr(errno));
		exit(1);
	}
	if (f>0) {
		wait(&f);	// just get child status - prevents child from being zombie during initialization stage
		if (f) {
			fprintf(stderr,"Child status: %d\n",f);
			exit(1);
		}
		close(piped[1]);
//		printf("Starting daemon ...\n");
		while ((r=read(piped[0],pipebuff,1000))) {
			if (r>0) {
				if (pipebuff[r-1]==0) {	// zero as a last char in the pipe means error
					if (r>1) {
						happy = fwrite(pipebuff,1,r-1,stderr);
						(void)happy;
					}
					exit(1);
				}
				happy = fwrite(pipebuff,1,r,stderr);
				(void)happy;
			} else {
				fprintf(stderr,"Error reading pipe: %s\n",strerr(errno));
				exit(1);
			}
		}
		exit(0);
	}
	setsid();
	setpgid(0,getpid());
	f = fork();
	if (f<0) {
		syslog(LOG_ERR,"second fork error: %s",strerr(errno));
		if (write(piped[1],"fork error\n",11)!=11) {
			syslog(LOG_ERR,"pipe write error: %s",strerr(errno));
		}
		close(piped[1]);
		exit(1);
	}
	if (f>0) {
		exit(0);
	}
	set_signal_handlers(1);

	close(STDIN_FILENO);
	sassert(open("/dev/null", O_RDWR, 0)==STDIN_FILENO);
	close(STDOUT_FILENO);
	sassert(dup(STDIN_FILENO)==STDOUT_FILENO);
	close(STDERR_FILENO);
	sassert(dup(piped[1])==STDERR_FILENO);
	close(piped[1]);
//	setvbuf(stderr,(char *)NULL,_IOLBF,0);
}
Exemple #13
0
int main(int argc, char** argv)
{
    struct sockaddr_in server;
    int chan;
    PaStream *stream;
    PaStreamParameters output_parameters;
    PaError err;

    voice = NULL;
    srand(time(NULL));
    atexit(at_exit);
    set_signal_handlers();
    init();

    if (argc != 4)
        return usage(argv[0]);

    set_output_parameters(&output_parameters, atoi(argv[3]));

    /* connect to server */
    sock = udp_create_socket(&server, sizeof(server), inet_addr(argv[1]), atoi(argv[2]), WAIT_FOR_RECEIVE);
    if (sock < 0)
        error_and_exit("Cannot create socket", __FILE__, __LINE__);
    
    /* create speech thingies */
    si.w          = malloc(sizeof(cst_wave) * si.channel_count);
    si.pos        = malloc(sizeof(long) * si.channel_count);
    si.done       = malloc(sizeof(int) * si.channel_count);
    si.cur_delay  = malloc(sizeof(double) * si.channel_count);
    si.rate_delay = malloc(sizeof(double) * si.channel_count);
    for (chan = 0; chan < si.channel_count; ++chan) {
        si.w[chan] = NULL;
        next_tweet(&server, chan);
    }

    err = Pa_OpenStream(&stream, NULL, &output_parameters,
            44100., 0, paNoFlag, say_text_callback, &si);
    if (paNoError != err) {
        fprintf(stderr, "Cannot open stream: %s\n", Pa_GetErrorText(err));
        exit(-1);
    }
/*        Pa_OpenDefaultStream(&stream, 0, si.channel_count, paInt16,
            si.w->sample_rate, 0, say_text_callback, &si); */
    err = Pa_StartStream(stream);
    if (paNoError != err) {
        fprintf(stderr, "Cannot start stream: %s\n", Pa_GetErrorText(err));
        exit(-1);
    }
    
    while (1)
    {
        usleep(100);
        for (chan = 0; chan < si.channel_count; ++chan) 
        {
            if (si.done[chan])
                next_tweet(&server, chan);
        }
    }
    //Pa_StopStream(stream);

    return 0;
}
Exemple #14
0
int main( int argc, char **argv ) {
    /* Options with their defaults */
    unsigned short opt_buffer = DEFAULT_BUFFER;
    unsigned short opt_daemon = 0;
    unsigned short opt_debug = 0;
    char *opt_filename = NULL;
    unsigned short opt_port = DEFAULT_PORT;
    unsigned short opt_reply = 0;
    int option;
    /* Program logic */
    unsigned short debug_counter = DEFAULT_LOOPS;
    int client_length;
    int recv_bytes;
    int status;
    static char tcp_options_text[MAX_TCPOPT];
    /* Our process ID and Session ID */
    pid_t pid, sid;

    /* We won't run as root */
   /* if ( geteuid() == 0 ) {
        fprintf(stderr,"This program is not intended to run as superuser.\n");
        fprintf(stderr,"Please use a non-privileged user instead.\n");
        exit(EXIT_FAILURE);
    }*

    /* Parse options */
    while ( (option = getopt(argc, argv, "b:dD:f:hrp:")) != -1 ) {
        switch ( option ) {
            case 'b':
                opt_buffer = (unsigned short)( strtoul( optarg, NULL, 10 ) );
                if ( opt_buffer < MIN_BUFFER ) {
                    opt_buffer = MIN_BUFFER;
                }
                break;
            case 'd':
                opt_daemon = 1;
                break;
            case 'D':
                opt_debug = (unsigned short)( strtoul( optarg, NULL, 10 ) );
                break;
            case 'f':
                opt_filename = optarg;
                break;
            case 'h':
                puts("Welcome to tcpsnoop!\\"
                     "Usage: tcpsnoop [-d] [-D debuglevel] [-f filename] [-h] [-p tcpport] [-b buffersize]");
                exit(EXIT_SUCCESS);
                break;
            case 'p':
                opt_port = (unsigned short)( strtoul( optarg, NULL, 10 ) );
                if ( opt_port < 1024 ) {
                    fprintf(stderr,"We can't bind to port %u! It is privileged.\n",opt_port);
                    exit(EXIT_FAILURE);
                }
                break;
            case 'r':
                opt_reply = 1;
                break;
        }
    }
    if ( opt_filename == NULL ) {
        opt_filename = (char *)default_filename;
    }
    /* Check for debug level. */
    if ( opt_debug > 0 ) {
        printf("Welcome to debug level %d!\n\\"
               "Will listen on port %u and write to file %s.\n\\"
               "Will allocate %u bytes for TCP buffer\n",
                opt_debug,opt_port,opt_filename,opt_buffer);
        /* We don't allow daemon mode when debug mode is active, no 
         * matter whether the daemon option is present or not.
         * */
        opt_daemon = 0;
    }
    if ( opt_daemon != 0 ) {
        syslog( LOG_DAEMON | LOG_INFO, "Starting daemon mode.");
    }

    /* Check if we should go into daemon mode */
    if ( opt_daemon != 0 ) {
        /* Fork and get a PID. */
        pid = fork();
        /* Check if forking was successful */
        if ( pid < 0 ) {
            fprintf(stderr,"fork() failed!\n");
            exit(EXIT_FAILURE);
        }
        if ( pid > 0 ) {
            syslog( LOG_DAEMON | LOG_INFO, "Got PID %u.", pid );
            exit(EXIT_SUCCESS);
        }
    }

    /* Set umask */
    umask(022);

    /* Here we open logs and files we probably need */
    /*
     *
     */
    openlog( SYSLOG_IDENTITY, LOG_PID, LOG_DAEMON );
    statistics = fopen( opt_filename, "a+" );
    if ( statistics == NULL ) {
        if ( opt_debug > 0 ) {
            fprintf(stderr,"Could not open statistics file: %s\n",strerror(errno));
        }
        else {
            syslog( LOG_DAEMON | LOG_CRIT, "Could not open statistics file: %s", strerror(errno) );
            exit(EXIT_FAILURE);
        }
    }

    /* Create a new SID for the child process */
    if ( opt_daemon != 0 ) {
        sid = setsid();
        if (sid < 0) {
            /* Could not aquire new SID. */
            syslog( LOG_DAEMON | LOG_CRIT, "%s", "Could not aquire new SID." );
            exit(EXIT_FAILURE);
        }
        /* Close standard file descriptors since daemons don't do standard
         * I/O. They need to use log files or syslog instead
         */
        fclose(stdout);
        fclose(stdin);
        fclose(stderr);
        set_signal_handlers();
    }

    /* Prepare TCP socket. */
    tcp_socket = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP );
    if ( tcp_socket == -1 ) {
        /* Could not open socket. */
        if ( opt_debug > 0 ) {
            fprintf(stderr,"Could not open TCP socket: %s\n",strerror(errno));
        }
        else {
            syslog( LOG_DAEMON | LOG_CRIT, "Could not open TCP socket: %s", strerror(errno) );
        }
        exit(EXIT_FAILURE);
    }
    else {
        /* Bind to any address on local machine */
        server_address.sin_family = AF_INET;
        server_address.sin_addr.s_addr = inet_addr("10.0.1.2");
        server_address.sin_port = htons(opt_port);
        memset((void *)&(server_address.sin_zero), '\0', 8);
        status = bind( tcp_socket, (struct sockaddr *)&server_address, sizeof(server_address) );
        if ( status == 0 ) {
            /* We can now listen for incoming connections. We only allow a backlog of one
             * connection
             */
            status = listen( tcp_socket, 1 );
            if ( status != 0 ) {
                /* Cannot listen on socket. */
                if ( opt_debug > 0 ) {
                    fprintf(stderr,"Cannot listen on socket: %s\n",strerror(errno));
                }
                else {
                    syslog( LOG_DAEMON | LOG_CRIT, "Cannot listen on socket: %s", strerror(errno) );
                }
                exit(EXIT_FAILURE);
            }
        }
        else {
            /* Cannot bind to socket. */
            if ( opt_debug > 0 ) {
                fprintf(stderr,"Cannot bind to socket: %s\n",strerror(errno));
            }
            else {
                syslog( LOG_DAEMON | LOG_CRIT, "Cannot bind to socket: %s", strerror(errno) );
            }
            exit(EXIT_FAILURE);
        }
    }
    
    /* Allocate Buffer for TCP stream data.
     * (We store it temporarily only since we act as an TCP sink.)
     */
    tcp_buffer = malloc(opt_buffer);
    if ( tcp_buffer == NULL ) {
        if ( opt_debug > 0 ) {
            fprintf(stderr,"Can't allocate buffer for TCP temporary memory.\n");
        }
        else {
            syslog( LOG_DAEMON | LOG_CRIT, "Can't allocate buffer for TCP temporary memory.\n" );
        }
        exit(EXIT_FAILURE);
    }

    /* Our main loop where we wait for (a) TCP connection(s). */
    if ( opt_debug > 0 ) {
        puts("Entering main loop.");
    }
    while ( debug_counter > 0 ) {
        client_length = sizeof(client_address);
        tcp_work_socket = accept( tcp_socket, (struct sockaddr *)&client_address, (socklen_t *)&client_length );
        /* Get time for counting milliseconds. */
        get_now( &time_start, opt_debug );
        /* As soon as we got a connection, we deal with the incoming data by using
         * a second socket. We only read as much as opt_buffer bytes.
         */
        if ( (recv_bytes = recv( tcp_work_socket, tcp_buffer, opt_buffer, 0 ) ) > 0 ) {
            /* Fill tcp_info structure with data to get the TCP options and the client's
             * name.
             */
            tcp_info_length = sizeof(tcp_info);
            if ( getsockopt( tcp_work_socket, SOL_IP, TCP_INFO, (void *)&tcp_info, (socklen_t *)&tcp_info_length ) == 0 ) {
                memset((void *)tcp_options_text, 0, MAX_TCPOPT);
                decode_tcp_options(tcp_options_text,tcp_info.tcpi_options);
                if ( opt_debug > 0 ) {
                    printf("Got a new connection from client %s.\n",inet_ntoa(client_address.sin_addr));
                }
                else {
                    syslog( LOG_DAEMON | LOG_INFO, "Received connection from client at address %s.",
                           inet_ntoa(client_address.sin_addr));
                }
                /* Write some statistics and start of connection to log file. */
                fprintf(statistics,"# Received connection from %s (AdvMSS %u, PMTU %u, options (%0.X): %s)\n",
                        inet_ntoa(client_address.sin_addr),
                        tcp_info.tcpi_advmss,
                        tcp_info.tcpi_pmtu,
                        tcp_info.tcpi_options,
                        tcp_options_text
                       );
            }
        }
        while ( (recv_bytes = recv( tcp_work_socket, tcp_buffer, opt_buffer, 0 ) ) > 0 ) {
            if ( opt_debug > 0 ) {
                printf("\nReceived %d bytes on socket.\n",recv_bytes);
            }
            /* Measure time in order to create time intervals. */
            get_now( &time_now, opt_debug );
            /* Fill tcp_info structure with data */
            tcp_info_length = sizeof(tcp_info);
            if ( getsockopt( tcp_work_socket, SOL_TCP, TCP_INFO, (void *)&tcp_info, (socklen_t *)&tcp_info_length ) == 0 ) {
                if ( opt_debug > 0 ) {
                    printf("snd_cwnd: %u\nsnd_ssthresh: %u\nrcv_ssthresh: %u\nrtt: %u\nrtt_var: %u\n",
                           tcp_info.tcpi_snd_cwnd,
                           tcp_info.tcpi_snd_ssthresh,
                           tcp_info.tcpi_rcv_ssthresh,
                           tcp_info.tcpi_rtt,
                           tcp_info.tcpi_rttvar
                          );
                }
                fprintf(statistics,"%.6f %u %u %u %u %u %u %u %u %u %u %u %u\n",
                        time_to_seconds( &time_start, &time_now ),
                        tcp_info.tcpi_last_data_sent,
                        tcp_info.tcpi_last_data_recv,
                        tcp_info.tcpi_snd_cwnd,
                        tcp_info.tcpi_snd_ssthresh,
                        tcp_info.tcpi_rcv_ssthresh,
                        tcp_info.tcpi_rtt,
                        tcp_info.tcpi_rttvar,
                        tcp_info.tcpi_unacked,
                        tcp_info.tcpi_sacked,
                        tcp_info.tcpi_lost,
                        tcp_info.tcpi_retrans,
                        tcp_info.tcpi_fackets
                       );
                if ( fflush(statistics) != 0 ) {
                    if ( opt_debug > 0 ) {
                        fprintf(stderr, "Cannot flush buffers: %s\n", strerror(errno) );
                    }
                    else {
                        syslog( LOG_DAEMON | LOG_CRIT, "Cannot flush buffers: %s", strerror(errno) );
                    }
                }
                /* Send reply text via TCP connection */
                if ( opt_reply != 0 ) {
                    reply_size = snprintf( reply_string, REPLY_MAXLENGTH, "rcv_ssthresh %u\n", tcp_info.tcpi_rcv_ssthresh );
                    if ( reply_size > 0 ) {
                        if ( send( tcp_work_socket, (void *)reply_string, reply_size, MSG_DONTWAIT ) == -1 ) {
                            if ( opt_debug > 0 ) {
                                fprintf(stderr, "Reply size %u didn't match: %s\n", reply_size, strerror(errno) );
                            }
                            else {
                                syslog( LOG_DAEMON | LOG_ERR, "Reply size %u didn't match: %s", reply_size, strerror(errno) );
                            }
                        }
                    }
                }
            }
        }
        close(tcp_work_socket);
        fprintf(statistics,"# Closed connection from %s.\n",inet_ntoa(client_address.sin_addr));
        if ( fflush(statistics) != 0 ) {
            if ( opt_debug > 0 ) {
                fprintf(stderr, "Cannot flush buffers: %s\n", strerror(errno) );
            }
            else {
                syslog( LOG_DAEMON | LOG_CRIT, "Cannot flush buffers: %s", strerror(errno) );
            }
        }
        if ( opt_debug > 0 ) {
            debug_counter--;
            printf("Closed connection. Decrementing debug counter to %u.\n\n",debug_counter);
        }
        else {
            syslog( LOG_DAEMON | LOG_INFO, "Closed connection from %s",
                   inet_ntoa(client_address.sin_addr));
        }
        sleep(DEFAULT_SLEEP);
    }

    /* That's a happy ending. */
    exit(EXIT_SUCCESS);
}
Exemple #15
0
int
main (int argc, char **argv)
{
    int c;
    char *config_dir = DEFAULT_CONFIG_DIR;
    char *seafile_dir = NULL;
    char *central_config_dir = NULL;
    char *logfile = NULL;
    const char *debug_str = NULL;
    int daemon_mode = 1;
    int is_master = 0;
    CcnetClient *client;
    char *ccnet_debug_level_str = "info";
    char *seafile_debug_level_str = "debug";
    int cloud_mode = 0;

#ifdef WIN32
    argv = get_argv_utf8 (&argc);
#endif

    while ((c = getopt_long (argc, argv, short_options, 
                             long_options, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            exit (1);
            break;
        case 'v':
            exit (1);
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'F':
            central_config_dir = g_strdup(optarg);
            break;
        case 'f':
            daemon_mode = 0;
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'D':
            debug_str = optarg;
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            seafile_debug_level_str = optarg;
            break;
        case 'm':
            is_master = 1;
            break;
        case 'P':
            pidfile = optarg;
            break;
        case 'C':
            cloud_mode = 1;
            break;
        default:
            usage ();
            exit (1);
        }
    }

    argc -= optind;
    argv += optind;

#ifndef WIN32
    if (daemon_mode) {
#ifndef __APPLE__
        daemon (1, 0);
#else   /* __APPLE */
        /* daemon is deprecated under APPLE
         * use fork() instead
         * */
        switch (fork ()) {
          case -1:
              seaf_warning ("Failed to daemonize");
              exit (-1);
              break;
          case 0:
              /* all good*/
              break;
          default:
              /* kill origin process */
              exit (0);
        }
#endif  /* __APPLE */
    }
#endif /* !WIN32 */

    cdc_init ();

#if !GLIB_CHECK_VERSION(2, 35, 0)
    g_type_init();
#endif
#if !GLIB_CHECK_VERSION(2,32,0)
    g_thread_init (NULL);
#endif

    if (!debug_str)
        debug_str = g_getenv("SEAFILE_DEBUG");
    seafile_debug_set_flags_string (debug_str);

    if (seafile_dir == NULL)
        seafile_dir = g_build_filename (config_dir, "seafile", NULL);
    if (logfile == NULL)
        logfile = g_build_filename (seafile_dir, "seafile.log", NULL);

    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          seafile_debug_level_str) < 0) {
        seaf_warning ("Failed to init log.\n");
        exit (1);
    }

    client = ccnet_init (central_config_dir, config_dir);
    if (!client)
        exit (1);

    register_processors (client);

    start_rpc_service (client, cloud_mode);

    create_sync_rpc_clients (central_config_dir, config_dir);
    create_async_rpc_clients (client);

    seaf = seafile_session_new (central_config_dir, seafile_dir, client);
    if (!seaf) {
        seaf_warning ("Failed to create seafile session.\n");
        exit (1);
    }
    seaf->is_master = is_master;
    seaf->ccnetrpc_client = ccnetrpc_client;
    seaf->async_ccnetrpc_client = async_ccnetrpc_client;
    seaf->ccnetrpc_client_t = ccnetrpc_client_t;
    seaf->async_ccnetrpc_client_t = async_ccnetrpc_client_t;
    seaf->client_pool = ccnet_client_pool_new (central_config_dir, config_dir);
    seaf->cloud_mode = cloud_mode;

    load_history_config ();

    g_free (seafile_dir);
    g_free (logfile);

    set_signal_handlers (seaf);

    /* init seaf */
    if (seafile_session_init (seaf) < 0)
        exit (1);

    if (seafile_session_start (seaf) < 0)
        exit (1);

    if (pidfile) {
        if (write_pidfile (pidfile) < 0) {
            ccnet_message ("Failed to write pidfile\n");
            return -1;
        }
    }
    atexit (on_seaf_server_exit);

    /* Create a system default repo to contain the tutorial file. */
    schedule_create_system_default_repo (seaf);

    ccnet_main (client);

    return 0;
}
Exemple #16
0
int main(int argc, char *argv[])
{
	if(argc <= 2) {
		QString arg = "-h";
		if(argc > 1)
			arg = argv[1];
		if(arg == QStringLiteral("-h") || arg == QStringLiteral("--help")) {
			std::cout << argv[0] << " FUSE_options --dbfs DBFS_options" << std::endl;
			std::cout << "FUSE_options" << std::endl;
			std::cout << "\tuse -h --dbfs switch to print FUSE options" << std::endl;
			std::cout << "DBFS_options" << std::endl;
			std::cout << "\t--dbfs\t" << "DBFS options separator, all options prior this will be ignored by DBFS" << std::endl;
			std::cout << "\t--host <host>\t" << "Database host" << std::endl;
			std::cout << "\t--port <port>\t" << "Database port" << std::endl;
			std::cout << "\t -u" << std::endl;
			std::cout << "\t--user <user>\t" << "Database user" << std::endl;
			std::cout << "\t -p" << std::endl;
			std::cout << "\t--password [<password>]\t" << "Database user password, use -p without password for interactive input." << std::endl;
			std::cout << "\t--database <database>\t" << "Database name" << std::endl;
			std::cout << "\t--db-schema\t" << "Database schema name" << std::endl;
			std::cout << "\t--table-name\t" << "DBFS table name, default is 'dbfs'" << std::endl;
			std::cout << "\t--create\t" << "Create DBFS tables" << std::endl;
			exit(0);
		}
	}

	int dbfs_switch_index;
	for(dbfs_switch_index = 1; dbfs_switch_index < argc; dbfs_switch_index++)
		if(argv[dbfs_switch_index] == QLatin1String("--dbfs")) {
			break;
		}

	QScopedPointer<qf::core::LogDevice> file_log_device(qf::core::FileLogDevice::install());
	file_log_device->setDomainTresholds(argc - dbfs_switch_index, argv + dbfs_switch_index);
	file_log_device->setPrettyDomain(true);

	QString o_database;
	QString o_user;
	QString o_password;
	QString o_host;
	int o_port = 0;
	QString o_db_schema;
	QString o_table_name;
	bool o_create_db = false;
	bool o_ask_passwd = false;

	for(int i=dbfs_switch_index + 1; i<argc; i++) {
		QString arg = argv[i];
		if(arg == QStringLiteral("--host")) {
			if(i<argc-1) {
				i++;
				o_host = argv[i];
			}
		}
		else if(arg == QStringLiteral("--port")) {
			if(i<argc-1) {
				i++;
				o_port = QString(argv[i]).toInt();
			}
		}
		else if(arg == QStringLiteral("-u") || arg == QStringLiteral("--user")) {
			if(i<argc-1) {
				i++;
				o_user = argv[i];
			}
		}
		else if(arg == QStringLiteral("-p") || arg == QStringLiteral("--password")) {
			if(i<argc-1) {
				QString p = argv[i+1];
				if(p.startsWith('-')) {
					o_ask_passwd = true;
				}
				else {
					o_password = p;
					i++;
				}
			}
			else {
				o_ask_passwd = true;
			}
		}
		else if(arg == QStringLiteral("--database")) {
			if(i<argc-1) {
				i++;
				o_database = argv[i];
			}
		}
		else if(arg == QStringLiteral("--db-schema")) {
			if(i<argc-1) {
				i++;
				o_db_schema = argv[i];
			}
		}
		else if(arg == QStringLiteral("--table-name")) {
			if(i<argc-1) {
				i++;
				o_table_name = argv[i];
			}
		}
		else if(arg == QStringLiteral("--create")) {
			o_create_db = true;
		}
	}

	if(o_ask_passwd) {
		char pwd[256];
		std::cout << "Please, enter your password: "******"Empty database name.";
		exit(1);
	}

	qfs::DbFsDriver *dbfs_drv = nullptr;
	qf::core::sql::Connection db_connection;
	if(dbfs_switch_index < (argc - 1)) {
		db_connection = QSqlDatabase::addDatabase("QPSQL");
		db_connection.setHostName(o_host);
		if(o_port > 0)
			db_connection.setPort(o_port);
		db_connection.setDatabaseName(o_database);
		db_connection.setUserName(o_user);
		db_connection.setPassword(o_password);
		//qfInfo() << o_host << o_port << o_user << o_database;
		bool ok = db_connection.open();
		if(!ok) {
			qfError() << db_connection.lastError().text();
			exit(1);
		}
		if(!o_db_schema.isEmpty()) {
			if(!db_connection.setCurrentSchema(o_db_schema)) {
				qfError() << "Error setting db schema to:" << o_db_schema;
				exit(1);
			}
		}
		dbfs_drv = new qfs::DbFsDriver();
		dbfs_drv->setConnectionName(db_connection.connectionName());

		if(!o_table_name.isEmpty()) {
			dbfs_drv->setTableName(o_table_name);
		}
		if(o_create_db) {
			if(!dbfs_drv->createDbFs()) {
				qfError() << "Error creating dbfs table" << dbfs_drv->tableName();
			}
			exit(1);
		}

		qfsqldbfs_setdriver(dbfs_drv);
	}

	int fuse_argc = dbfs_switch_index;

	/// FUSE variables
	struct fuse_args fuse_arguments = FUSE_ARGS_INIT(fuse_argc, argv);
	struct fuse_chan *fuse_channel = NULL;
	struct fuse *fuse_handle = NULL;
	char *mount_point = nullptr;

	if (fuse_parse_cmdline(&fuse_arguments, &mount_point, NULL, NULL) == -1) {
		qfError() << "fuse_parse_cmdline() - Error parsing fuse command line arguments!";
		exit(1);
	}

	/// Tell FUSE where the local mountpoint is
	fuse_channel = fuse_mount(mount_point, &fuse_arguments);
	if (fuse_channel == NULL){
		qfError()<<"fuse_mount() failed";
		exit(1);
	}

	// Tell FUSE about implementations of FS operations
	struct fuse_operations fuse_ops;
	memset(&fuse_ops, 0, sizeof(fuse_ops));
	fuse_ops.getattr = qfsqldbfs_getattr;
	fuse_ops.readdir = qfsqldbfs_readdir;
	fuse_ops.open = qfsqldbfs_open;
	fuse_ops.read = qfsqldbfs_read;
	fuse_ops.write = qfsqldbfs_write;
	fuse_ops.fsync = qfsqldbfs_fsync;
	fuse_ops.flush = qfsqldbfs_flush;
	fuse_ops.release = qfsqldbfs_release;
	fuse_ops.mknod = qfsqldbfs_mknod;
	fuse_ops.mkdir = qfsqldbfs_mkdir;
	fuse_ops.unlink = qfsqldbfs_unlink;
	fuse_ops.rmdir = qfsqldbfs_rmdir;
	fuse_ops.utime = qfsqldbfs_utime;
	fuse_ops.truncate = qfsqldbfs_truncate;
	fuse_ops.ftruncate = qfsqldbfs_ftruncate;
	fuse_ops.chmod = qfsqldbfs_chmod;
	fuse_ops.chown = qfsqldbfs_chown;
	fuse_ops.create = qfsqldbfs_create;
	fuse_ops.rename = qfsqldbfs_rename;

	fuse_handle = fuse_new(fuse_channel, &fuse_arguments, &fuse_ops, sizeof(fuse_ops), NULL);
	if (fuse_handle == NULL){
		qfError()<<"fuse_new() failed";
		exit(1);
	}

	if(dbfs_drv) {
#ifdef USE_QT_EVENT_LOOP
		qfInfo() << "Using Qt event loop with FUSE in separated thread";
		TheApp *app = new TheApp(argc, argv);
		s_fuseThread = new FuseThread(fuse_handle, fuse_channel, QString::fromUtf8(mount_point));
		dbfs_drv->moveToThread(s_fuseThread);
		QObject::connect(s_fuseThread, &QThread::finished, app, &TheApp::onFuseThreadFinished, Qt::QueuedConnection);
		s_fuseThread->start();

		set_signal_handlers();

		{
			/// setup SQL notify
			QSqlDatabase notify_db = QSqlDatabase::addDatabase("QPSQL", "DBFS_Notify");
			notify_db.setHostName(db_connection.hostName());
			notify_db.setPort(db_connection.port());
			notify_db.setUserName(db_connection.userName());
			notify_db.setPassword(db_connection.password());
			notify_db.setDatabaseName(db_connection.databaseName());
			bool ok = notify_db.open();
			if(!ok) {
				qfError() << "Error connect DBFS notify connection" << notify_db.lastError().text();
			}
			else {
				QSqlDriver *drv = notify_db.driver();
				//qRegisterMetaType<QSqlDriver::NotificationSource>("QSqlDriver::NotificationSource");
				QObject::connect(drv, SIGNAL(notification(QString,QSqlDriver::NotificationSource,QVariant)), dbfs_drv, SLOT(onSqlNotify(QString,QSqlDriver::NotificationSource,QVariant)), Qt::DirectConnection);
				//QObject::connect(drv, SIGNAL(notification(QString,QSqlDriver::NotificationSource,QVariant)), app, SLOT(onSqlNotify(QString,QSqlDriver::NotificationSource,QVariant)));
				drv->subscribeToNotification(qfs::DbFsDriver::CHANNEL_INVALIDATE_DBFS_DRIVER_CACHE);
				qfInfo() << drv << "subscribedToNotifications:" << drv->subscribedToNotifications().join(", ");
			}
		}

		app->exec();

		qfInfo() << "Waiting for FUSE thread to join ...";
		s_fuseThread->wait();
#else
		qfInfo() << "Using FUSE event loop";
		fuse_loop(fuse_handle);
		qfInfo() << "FUSE has quit its event loop";
#endif

		qfsqldbfs_setdriver(nullptr);
		QF_SAFE_DELETE(dbfs_drv);
#ifdef USE_QT_EVENT_LOOP
		QF_SAFE_DELETE(s_fuseThread);
		QF_SAFE_DELETE(app);
#endif
	}
	else {
		// used just to print FUSE help
		fuse_loop(fuse_handle);
	}

	qfInfo() << "bye";
	return 0;
}
int main (int argc, char **argv)
{
    if (argc <= 1) {
        usage ();
        exit (1);
    }

    char *config_dir = DEFAULT_CONFIG_DIR;
    char *central_config_dir = NULL;
    char *seafile_dir = NULL;
    char *logdir = NULL;
    char *ccnet_debug_level_str = "info";
    char *seafile_debug_level_str = "debug";
    int daemon_mode = 1;
    gboolean test_conf = FALSE;

    int c;
    while ((c = getopt_long (argc, argv, short_opts,
                             long_opts, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            usage ();
            exit(1);
            break;
        case 'v':
            fprintf (stderr, "seafile-controller version 1.0\n");
            break;
        case 't':
            test_conf = TRUE;
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'F':
            central_config_dir = g_strdup(optarg);
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'f':
            daemon_mode = 0;
            break;
        case 'L':
            logdir = g_strdup(optarg);
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            seafile_debug_level_str = optarg;
            break;
        case 'P':
            controller_pidfile = optarg;
            break;
        default:
            usage ();
            exit (1);
        }
    }

#if !GLIB_CHECK_VERSION(2, 35, 0)
    g_type_init();
#endif
#if !GLIB_CHECK_VERSION(2,32,0)
    g_thread_init (NULL);
#endif

    if (!seafile_dir) {
        fprintf (stderr, "<seafile_dir> must be specified with --seafile-dir\n");
        exit(1);
    }

    if (!central_config_dir) {
        fprintf (stderr, "<central_config_dir> must be specified with --central-config-dir\n");
        exit(1);
    }

    central_config_dir = ccnet_expand_path (central_config_dir);
    config_dir = ccnet_expand_path (config_dir);
    seafile_dir = ccnet_expand_path (seafile_dir);

    if (test_conf) {
        test_config (central_config_dir, config_dir, seafile_dir);
    }

    ctl = g_new0 (SeafileController, 1);
    if (seaf_controller_init (ctl, central_config_dir, config_dir, seafile_dir, logdir) < 0) {
        controller_exit(1);
    }

    char *logfile = g_build_filename (ctl->logdir, "controller.log", NULL);
    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          seafile_debug_level_str) < 0) {
        seaf_warning ("Failed to init log.\n");
        controller_exit (1);
    }

    if (init_syslog_config () < 0) {
        controller_exit (1);
    }

    set_signal_handlers ();

    if (seaf_controller_start () < 0)
        controller_exit (1);

#ifndef WIN32
    if (daemon_mode) {
#ifndef __APPLE__
        daemon (1, 0);
#else   /* __APPLE */
        /* daemon is deprecated under APPLE
         * use fork() instead
         * */
        switch (fork ()) {
          case -1:
              seaf_warning ("Failed to daemonize");
              exit (-1);
              break;
          case 0:
              /* all good*/
              break;
          default:
              /* kill origin process */
              exit (0);
        }
#endif  /* __APPLE */
    }
#endif /* !WIN32 */

    if (controller_pidfile == NULL) {
        controller_pidfile = g_strdup(g_getenv ("SEAFILE_PIDFILE"));
    }

    if (controller_pidfile != NULL) {
        if (write_controller_pidfile () < 0) {
            seaf_warning ("Failed to write pidfile %s\n", controller_pidfile);
            return -1;
        }
    }

    run_controller_loop ();

    return 0;
}
Exemple #18
0
int main (int argc,char *argv[]) {
    int force = 0;
    pid_t consistency_pid;
    pid_t listener_pid;

    slave_get_options(&argc,&argv,&force,&sdb);

    logtool = DRQ_LOG_TOOL_SLAVE;

    // Set some standard defaults based on DRQUEUE_ROOT (must be already set!)
    set_default_env();

    // Config files overrides environment
    // Read the config file after reading the arguments, as those may change
    // the path to the config file
    if (sdb.conf[0]) {
        config_parse(sdb.conf);
    } else {
        config_parse_tool("slave");
    }

    if (!common_environment_check()) {
        log_auto (L_ERROR,"Error checking the environment: %s",drerrno_str());
        exit (1);
    }


    set_signal_handlers ();

    //system ("env | grep DRQUEUE");
    sdb.shmid = get_shared_memory_slave (force);
    sdb.comp = attach_shared_memory_slave (sdb.shmid);
    sdb.semid = get_semaphores_slave ();
    log_auto (L_INFO,"Starting...");

    computer_init (sdb.comp);
    sdb.comp->used = 1;
    get_hwinfo (&sdb.comp->hwinfo);
    computer_limits_cpu_init (sdb.comp); // computer_init_limits depends on the hardware information
    slave_set_limits (&sdb);	       // Override defaults
    logger_computer = sdb.comp;

    report_hwinfo (&sdb.comp->hwinfo);
    fprintf (stderr,"Working silently...");

    register_slave (sdb.comp);
    // Before sending the limits we have to set the pools
    computer_pool_set_from_environment (&sdb.comp->limits);
    computer_pool_list (&sdb.comp->limits);
    update_computer_limits(&sdb.comp->limits); /* Does not need to be locked because at this point */
    /* because there is only one process running. The rest of the time */
    /* either we call it locked or we make a copy of the limits while locked */
    /* and then we send that copy */

    if (pipe(phantom) != 0) {
        fprintf (stderr,"Phantom pipe could not be created\n");
        exit (1);
    }

    if ((listener_pid = fork()) == 0) {
        /* Create the listening process */
        log_auto (L_INFO,"Listener process starting...");
        set_signal_handlers_child_listening ();
        slave_listening_process (&sdb);
        log_auto (L_INFO,"Listener process exiting...");
        exit (0);
    } else if (listener_pid == -1) {
        drerrno_system = errno;
        log_auto (L_ERROR,"Could not create the listener process. (%s)", strerror(drerrno_system));
        slave_exit(SIGINT);
    }

    if ((consistency_pid = fork()) == 0) {
        // Create the consistency checks process
        // Signal are treated the same way as the listening process
        log_auto (L_INFO,"Consistency process starting...");
        set_signal_handlers_child_listening ();
        slave_consistency_process (&sdb);
        log_auto (L_INFO,"Consistency process exiting...");
        exit (0);
    } else if (consistency_pid == -1) {
        drerrno_system = errno;
        log_auto (L_ERROR,"Could not create the listener process. (%s)", strerror(drerrno_system));
        slave_exit(SIGINT);
    }

    while (1) {
        get_computer_status (&sdb.comp->status,sdb.semid);

        computer_autoenable_check (&sdb); /* Check if it's time for autoenable */

        while (computer_available(sdb.comp)) {
            uint16_t itask;
            if (request_job_available(&sdb,&itask)) {
                launch_task(&sdb,itask);
                update_computer_status (&sdb);
            } else {
                // computer not available
                break;   // break the while loop
            }
        } /* WARNING could be in this loop forever if no care is taken !! */

        update_computer_status (&sdb); /* sends the computer status to the master */
        /* Does not need to be locked because we lock inside it */

        FD_ZERO(&read_set);
        FD_SET(phantom[0],&read_set);
        timeout.tv_sec = SLAVEDELAY;
        timeout.tv_usec = 0;
        rs = select (phantom[0]+1,&read_set,NULL,NULL,&timeout);
        switch (rs) {
        case -1:
            /* Error in select */
            log_auto(L_ERROR,"Select call failed");
        case 0:
            log_auto(L_DEBUG,"Slave loop (select call timeout)");
            break;
        default:
            if (FD_ISSET(phantom[0],&read_set)) {
                log_auto(L_DEBUG,"Select call, notification came. Available for reading.");
                read(phantom[0],buffer,BUFFERLEN);
            } else {
                log_auto(L_WARNING,"Select call, report this message, please. It should never happen.");
            }
        }
    }

    exit (0);
}
Exemple #19
0
int main (int argc, char **argv)
{
    if (argc <= 1) {
        usage ();
        exit (1);
    }
    
    char *bin_dir = NULL;
    char *config_dir = DEFAULT_CONFIG_DIR;
    char *seafile_dir = NULL;
    char *logfile = NULL;
    char *ccnet_debug_level_str = "info";
    char *seafile_debug_level_str = "debug";
    int daemon_mode = 1;
    gboolean cloud_mode = FALSE;

    int c;
    while ((c = getopt_long (argc, argv, short_opts,
                             long_opts, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            usage ();
            exit(1);
            break;
        case 'v':
            fprintf (stderr, "seafile-controller version 1.0\n");
            break;
        case 'b':
            bin_dir = optarg;
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'f':
            daemon_mode = 0;
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'C':
            cloud_mode = TRUE;
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            seafile_debug_level_str = optarg;
            break;
        default:
            usage ();
            exit (1);
        }
    }

    if (daemon_mode)
        daemon (1, 0);

    g_type_init ();
#if !GLIB_CHECK_VERSION(2,32,0)
    g_thread_init (NULL);
#endif

    if (!seafile_dir) {
        seaf_warning ("<seafile_dir> must be specified with --seafile-dir\n");
        controller_exit(1);
    }

    if (bin_dir)
        bin_dir = ccnet_expand_path(bin_dir);

    config_dir = ccnet_expand_path (config_dir);
    seafile_dir = ccnet_expand_path(seafile_dir);

    ctl = g_new0 (SeafileController, 1);
    if (seaf_controller_init (ctl, bin_dir, config_dir, seafile_dir, cloud_mode) < 0) {
        controller_exit(1);
    }

    if (!logfile) {
        logfile = g_build_filename (seafile_dir, "controller.log", NULL);
    }

    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          seafile_debug_level_str) < 0) {
        seaf_warning ("Failed to init log.\n");
        controller_exit (1);
    }

    set_signal_handlers ();

    if (ctl->bin_dir) 
        set_path_env (ctl->bin_dir);

    if (seaf_controller_start (ctl) < 0)
        controller_exit (1);

    run_controller_loop ();

    return 0;
}
Exemple #20
0
ad_comm::ad_comm(int _argc,char * _argv[])
{
    if (option_match(_argc,_argv,"-version") > -1
            || option_match(_argc,_argv,"--version") > -1)
    {
        void banner(const adstring& program_name);
        banner(_argv[0]);

        exit(0);
    }

    ad_comm::argc=_argc;
    ad_comm::argv=_argv;
    if (option_match(_argc,_argv,"-time")>-1)
    {
        time_flag=1;
    }
    else
    {
        time_flag=0;
    }
    if (time_flag)
    {
        if (!ptm)
        {
            ptm=new adtimer();
        }
        if (!ptm1)
        {
            ptm1=new adtimer();
        }
    }
    no_atlas_flag=0;
    if (option_match(_argc,_argv,"-noatlas")>-1) no_atlas_flag=1;

#if defined(USE_ADPVM)
    int pvm_flag=0;
    if (option_match(_argc,_argv,"-slave")>-1)  pvm_flag=2;
    if (option_match(_argc,_argv,"-master")>-1) pvm_flag=1;

    if (pvm_flag)
        pvm_manager = new adpvm_manager(pvm_flag);
    else
        pvm_manager = NULL;

    if (pvm_manager)
    {
        if (pvm_manager->mode==2)  //slave
        {
            int on=0;
            int nopt=0;
            if ( (on=option_match(_argc,_argv,"-slave",nopt))>-1)
            {
                if (nopt ==1)
                {
                    pvm_manager->slave_number=atoi(ad_comm::argv[on+1]);
                }
                else
                {
                    cerr << "Wrong number of options to -slave -- must be 1"
                         " you have " << nopt << endl;
                    ad_exit(1);
                }
            }
            if ( (on=option_match(_argc,_argv,"-slavedir",nopt))>-1)
            {
                if (nopt ==1)
                {
                    ad_chdir(_argv[on+1]);
                }
                else
                {
                    cerr << "Wrong number of options to -slavedir -- must be 1"
                         " you have " << nopt << endl;
                }
            }
        }
    }
#endif

    /*
      if (option_match(_argc,_argv,"-gui")>-1)
      {
        void vm_initialize(void);
        vm_initialize();
      }
    */
    set_signal_handlers();
    adprogram_name=_argv[0];
    //int len=strlen(_argv[0]);
    //for (int i=1;i<=len;i++) adprogram_name[i]=tolower(adprogram_name[i]);
#if defined(_MSC_VER)
    strip_full_path(adprogram_name);
#endif
    adstring workdir;
    ad_getcd(workdir);
    if (_argc>1)
    {
        if (option_match(_argc,_argv,"-?")>-1
                || option_match(_argc,_argv,"-help")>-1
                || option_match(_argc,_argv,"--help")>-1)
        {
            // remove path (if user runs -help)
            for (size_t i = adprogram_name.size(); i >= 1; i--)
            {
#ifdef _WIN32
                if (adprogram_name(i) == '\\')
#else
                if (adprogram_name(i) == '/')
#endif
                {
                    adprogram_name=adprogram_name(i+1,adprogram_name.size());
                    break;
                }
            }

            //(*ad_printf)(" %s", (char*)admb_banner);
            (*ad_printf)( "Usage: %s [options]\n\n",(char*)(adprogram_name));

            (*ad_printf)( "Options:\n");
            (*ad_printf)( " -ainp FILE      change default ascii input parameter "
                          "filename to FILE\n");
            (*ad_printf)( " -binp FILE      change default binary input parameter "
                          "filename to FILE\n");
            (*ad_printf)( " -est            only do the parameter estimation\n");
            (*ad_printf)( " -noest          do not do the parameter estimation "
                          "(optimization) \n");
            (*ad_printf)( " -ind FILE       change default input data filename to "
                          "FILE\n");
            (*ad_printf)( " -lmn N          use limited memory quasi newton -- keep "
                          "N steps\n");
            (*ad_printf)( " -lmn2 N         use other limited memory quasi newton -- "
                          "keep N steps\n");
            (*ad_printf)( " -ilmn N         use other limited memory quasi newton "
                          "for random effects models - keep N steps\n");
            (*ad_printf)( " -dd N           check derivatives after N function "
                          "evaluations\n");
            (*ad_printf)( " -lprof          perform profile likelihood "
                          "calculations\n");
            (*ad_printf)( " -maxph N        increase the maximum phase number to "
                          "N\n");
            (*ad_printf)( " -mcdiag         use diagonal covariance matrix for mcmc "
                          "with diagonal values 1\n");
            (*ad_printf)( " -mcmc [N]       perform markov chain monte carlo with N "
                          "simulations\n");
            (*ad_printf)( " -mcmult N       multiplier N for mcmc default\n");
            (*ad_printf)( " -mcr            resume previous mcmc\n");
            (*ad_printf)( " -mcrb  N        reduce amount of correlation in the "
                          "covariance matrix 1<=N<=9\n");
            (*ad_printf)( " -mcnoscale      don't rescale step size for mcmc "
                          "depending on acceptance rate\n");
            (*ad_printf)( " -nosdmcmc       turn off mcmc histogram calcs to make "
                          "mcsave run faster\n");
            (*ad_printf)( " -mcprobe N      use probing strategy for mcmc with "
                          "factor N\n");
            (*ad_printf)( " -mcgrope N      Deprecated, same as -mcprobe\n");
            (*ad_printf)( " -mcseed N       seed for random number generator for "
                          "markov chain monte carlo\n");
            (*ad_printf)( " -mcscale N      rescale step size for first N "
                          "evaluations\n");
            (*ad_printf)( " -mcsave N       save the parameters for every Nth "
                          "simulation\n");
            (*ad_printf)( " -mceval         go through the saved mcmc values from a "
                          "previous mcsave\n");
            (*ad_printf)( " -mcu            use uniformaly distributed steps for "
                          "mcmc instead of random normal\n");
            (*ad_printf)( " -crit N1,N2,... set gradient magnitude convergence "
                          "criterion to N\n");
            (*ad_printf)( " -iprint N       print out function minimizer report "
                          "every N iterations\n");
            (*ad_printf)( " -maxfn N1,N2,.. set maximum number opf function eval's "
                          "to N\n");
            (*ad_printf)( " -rs             if function minimizer can't make "
                          "progress rescale and try again\n");
            //(*ad_printf)( " -sp             for DLL running from splus write to "
            //"command window\n");
            (*ad_printf)( " -nox            suppress vector and gradient values in "
                          "minimizer screen report\n");
            (*ad_printf)( " -phase N        start minimization in phase N\n");
            (*ad_printf)( " -simplex        use simplex for minimization -- "
                          "deprecated, use -neldmead\n");
            (*ad_printf)( " -neldmead       use Nelder-Mead simplex algorithm for "
                          "minimization\n");
            (*ad_printf)( " -nohess         don't do hessian or delta method for std "
                          "dev\n");
            (*ad_printf)( " -eigvec         calculate eigenvectors of the Hessian\n");
            (*ad_printf)( " -sdonly         do delta method for std dev estimates "
                          "without redoing hessian\n");
            (*ad_printf)( " -ams N          set arrmblsize to N "
                          "(ARRAY_MEMBLOCK_SIZE)\n");
            (*ad_printf)( " -cbs N          set CMPDIF_BUFFER_SIZE to N "
                          "(ARRAY_MEMBLOCK_SIZE)\n");
            (*ad_printf)( " -mno N          set the maximum number of independent "
                          "variables to N\n");
            (*ad_printf)( " -mdl N          set the maximum number of dvariables to "
                          "N\n");
            (*ad_printf)( " -gbs N          set GRADSTACK_BUFFER_SIZE to N "
                          "(ARRAY_MEMBLOCK_SIZE)\n");
#if defined(USE_ADPVM)
            (*ad_printf)( " -master         run as PVM master program\n");
            (*ad_printf)( " -slave          run as PVM slave program\n");
            (*ad_printf)( " -pvmtime        record timing information for PVM "
                          "performance analysis\n");
#endif
            (*ad_printf)( " -info           show how to cite ADMB, license, and "
                          "acknowledgements\n");
            (*ad_printf)( " -version        show version information\n");
            (*ad_printf)( " -help           show this message\n\n");
            //if (function_minimizer::random_effects_flag)
            //{
            (*ad_printf)( "Random effects options if applicable\n");
            (*ad_printf)( " -nr N           maximum number of Newton-Raphson "
                          "steps\n");
            (*ad_printf)( " -imaxfn N       maximum number of evals in quasi-Newton "
                          "inner optimization\n");
            (*ad_printf)( " -is N           set importance sampling size to N\n");
            (*ad_printf)( " -isf N          set importance sampling size funnel "
                          "blocks to N\n");
            (*ad_printf)( " -isdiag         print importance sampling diagnostics\n");
            (*ad_printf)( " -hybrid         do hybrid Monte Carlo version of MCMC\n");
            (*ad_printf)( " -hbf            set the hybrid bounded flag for bounded "
                          "parameters\n");
            (*ad_printf)( " -hyeps          mean step size for hybrid Monte Carlo\n");
            (*ad_printf)( " -hynstep        number of steps for hybrid Monte "
                          "Carlo\n");
            (*ad_printf)( " -noinit         do not initialize RE before inner "
                          "optimization\n");
            (*ad_printf)( " -ndi N          set maximum number of separable calls\n");
            (*ad_printf)( " -ndb N          set number of blocks for RE derivatives "
                          "(reduce temp file size)\n");
            (*ad_printf)( " -ddnr           use high precision Newton-Raphson, for "
                          "banded Hessian case only\n");
            (*ad_printf)( " -nrdbg          verbose reporting for debugging "
                          "newton-raphson\n");
#  if defined(__MINI_MAX__)
            (*ad_printf)( " -mm N           do minimax optimization\n");
#  endif
            (*ad_printf)( " -shess          use sparse Hessian structure inner "
                          "optimzation\n\n");

            (*ad_printf)("Read online documentation at http://admb-project.org\n");
            (*ad_printf)("Contact <*****@*****.**> for help.\n");
            //}
            ad_exit(0);
        }
        else if (option_match(_argc,_argv,"-info") > -1)
        {
            (*ad_printf)("ADMB Information\n");
            (*ad_printf)("================\n\n");

            (*ad_printf)("How to Cite ADMB\n");
            (*ad_printf)("----------------\n\n");

            (*ad_printf)("Fournier, D.A., H.J. Skaug, J. Ancheta, J. Ianelli, "
                         "A. Magnusson, M.N. Maunder,\n");
            (*ad_printf)("A. Nielsen, and J. Sibert. 2012. AD Model Builder: using "
                         "automatic\n");
            (*ad_printf)("differentiation for statistical inference of highly "
                         "parameterized complex\n");
            (*ad_printf)("nonlinear models. Optim. Methods Softw. 27:233-249.\n\n");

            //(*ad_printf)(" %s", (char*)admb_banner);
            (*ad_printf)("License\n");
            (*ad_printf)("-------\n\n");

            (*ad_printf)("Copyright (c) 2008-2013\n");
            (*ad_printf)("Regents of the University of California and ADMB "
                         "Foundation\n\n");
            (*ad_printf)("ADMB is free software and comes with ABSOLUTELY NO "
                         "WARRANTY.\n");
            (*ad_printf)("You are welcome to redistribute it under certain "
                         "conditions.\n\n");
            (*ad_printf)("AD Model Builder, or ADMB, was developed by David Fournier "
                         "of Otter Research\n");
            (*ad_printf)("Ltd, Sidney, BC, Canada. In 2007, scientists from the "
                         "University of Hawai'i at\n");
            (*ad_printf)("Manoa Pelagic Fisheries Research Program (John Sibert and "
                         "Anders Nielsen) and\n");
            (*ad_printf)("the Inter-American Tropical Tuna Commission (Mark "
                         "Maunder), in consultation with\n");
            (*ad_printf)("scientists from NOAA Fisheries (Richard Methot), created "
                         "the non-profit ADMB\n");
            (*ad_printf)("Foundation (admb-foundation.org) with the goal of "
                         "increasing the number of ADMB\n");
            (*ad_printf)("users by making the software free and open source. In "
                         "partnership with NOAA\n");
            (*ad_printf)("Fisheries and the National Center for Ecological Analysis "
                         "and Synthesis (NCEAS,\n");
            (*ad_printf)("www.nceas.ucsb.edu), the ADMB Foundation obtained funding "
                         "from the Gordon and\n");
            (*ad_printf)("Betty Moore Foundation (www.moore.org) to acquire the "
                         "copyright to the ADMB\n");
            (*ad_printf)("software suite, in order to make it broadly and freely "
                         "available to the research\n");
            (*ad_printf)("community. In 2008 the copyright was transferred from "
                         "Otter Research Ltd to the\n");
            (*ad_printf)("University of California. The binary files were released "
                         "in November 2008 and\n");
            (*ad_printf)("the source code was released in December 2009. More "
                         "information about the ADMB\n");
            (*ad_printf)("Project can be found at admb-project.org.\n\n");
            (*ad_printf)("ADMB was originally developed by David Fournier of Otter "
                         "Research Ltd.\n\n");
            (*ad_printf)("It is now maintained by the ADMB Core Team, whose members "
                         "are listed on\n");
            (*ad_printf)("http://admb-project.org/developers/core-team.\n");

            ad_exit(0);
        }
    }
    allocate();
}
Exemple #21
0
int
main (int argc, char **argv)
{
    int c;
    char *config_dir = DEFAULT_CONFIG_DIR;
    char *seafile_dir = NULL;
    char *worktree_dir = NULL;
    char *logfile = NULL;
    const char *debug_str = NULL;
    int daemon_mode = 0;
    CcnetClient *client;
    char *ccnet_debug_level_str = "info";
    char *seafile_debug_level_str = "debug";

#ifdef WIN32
    argv = get_argv_utf8 (&argc);
#endif

    while ((c = getopt_long (argc, argv, short_options, 
                             long_options, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            exit (1);
            break;
        case 'v':
            exit (1);
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'b':
            daemon_mode = 1;
            break;
        case 'D':
            debug_str = optarg;
            break;
        case 'w':
            worktree_dir = g_strdup(optarg);
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            seafile_debug_level_str = optarg;
            break;
        default:
            usage ();
            exit (1);
        }
    }

    argc -= optind;
    argv += optind;

#ifndef WIN32

#ifndef __APPLE__
    if (daemon_mode)
        daemon (1, 0);
#endif

#endif

    g_type_init ();
#if !GLIB_CHECK_VERSION(2,32,0)
    g_thread_init (NULL);
#endif
    if (!debug_str)
        debug_str = g_getenv("SEAFILE_DEBUG");
    seafile_debug_set_flags_string (debug_str);

    /* init ccnet */
    client = ccnet_init (config_dir);
    if (!client)
        exit (1);
    register_processors (client);
    start_rpc_service (client);
    create_sync_rpc_clients (config_dir);
    appletrpc_client = ccnet_create_async_rpc_client (client, NULL, 
                                                      "applet-rpcserver");

    /* init seafile */
    if (seafile_dir == NULL)
        seafile_dir = g_build_filename (config_dir, "seafile-data", NULL);
    if (worktree_dir == NULL)
        worktree_dir = g_build_filename (g_get_home_dir(), "seafile", NULL);
    if (logfile == NULL)
        logfile = g_build_filename (config_dir, "logs", "seafile.log", NULL);

    seaf = seafile_session_new (seafile_dir, worktree_dir, client);
    if (!seaf) {
        fprintf (stderr, "Failed to create seafile session.\n");
        exit (1);
    }
    seaf->ccnetrpc_client = ccnetrpc_client;
    seaf->appletrpc_client = appletrpc_client;

    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          seafile_debug_level_str) < 0) {
        fprintf (stderr, "Failed to init log.\n");
        exit (1);
    }

    g_free (seafile_dir);
    g_free (worktree_dir);
    g_free (logfile);

    set_signal_handlers (seaf);

    seafile_session_prepare (seaf);
    seafile_session_start (seaf);

    seafile_session_config_set_string (seaf, "wktree", seaf->worktree_dir);
    ccnet_main (client);

    return 0;
}
Exemple #22
0
int
main (int argc, char **argv)
{
    int c;
    char *config_dir = DEFAULT_CONFIG_DIR;
    char *seafile_dir = NULL;
    char *logfile = NULL;
    int daemon_mode = 1;
    CcnetClient *client;
    char *ccnet_debug_level_str = "info";
    char *monitor_debug_level_str = "debug";

#ifdef WIN32
    argv = get_argv_utf8 (&argc);
#endif

    while ((c = getopt_long (argc, argv, short_options,
                             long_options, NULL)) != EOF)
    {
        switch (c) {
        case 'h':
            exit (1);
            break;
        case 'v':
            exit (1);
            break;
        case 'c':
            config_dir = optarg;
            break;
        case 'd':
            seafile_dir = g_strdup(optarg);
            break;
        case 'f':
            daemon_mode = 0;
            break;
        case 'l':
            logfile = g_strdup(optarg);
            break;
        case 'g':
            ccnet_debug_level_str = optarg;
            break;
        case 'G':
            monitor_debug_level_str = optarg;
            break;
        case 'P':
            pidfile = optarg;
            break;
        default:
            usage ();
            exit (1);
        }
    }

    argc -= optind;
    argv += optind;

#ifndef WIN32
    if (daemon_mode)
        daemon (1, 0);
#endif
    g_type_init ();

    if (seafile_dir == NULL) {
        usage ();
        exit (1);
    }

    if (logfile == NULL)
        logfile = g_build_filename (seafile_dir, "monitor.log", NULL);

    if (seafile_log_init (logfile, ccnet_debug_level_str,
                          monitor_debug_level_str) < 0) {
        seaf_warning ("Failed to init log.\n");
        exit (1);
    }

    client = ccnet_init (config_dir);
    if (!client)
        exit (1);

    register_processors (client);

    start_rpc_service (client);

    seaf = seafile_session_new (seafile_dir, client);
    if (!seaf) {
        seaf_warning ("Failed to create seafile monitor.\n");
        exit (1);
    }

    if (seafile_session_init (seaf) < 0) {
        seaf_warning ("Failed to init seafile monitor.\n");
        exit (1);
    }

    g_free (seafile_dir);
    g_free (logfile);

    set_signal_handlers (seaf);

    seafile_session_start (seaf);

    if (pidfile) {
        if (write_pidfile (pidfile) < 0) {
            ccnet_message ("Failed to write pidfile\n");
            return -1;
        }
    }
    atexit (on_seaf_mon_exit);

    ccnet_main (client);

    return 0;
}
Exemple #23
0
int main(int argc, char *argv[])
{
	int c;

	/* Set up owlib */
	LibSetup(program_type_httpd);
	Setup_Systemd() ; // systemd?
	Setup_Launchd() ; // launchd?

	/* grab our executable name */
	ArgCopy( argc, argv ) ;

	while ((c = getopt_long(argc, argv, OWLIB_OPT, owopts_long, NULL)) != -1) {
		switch (c) {
		case 'V':
			fprintf(stderr, "%s version:\n\t" VERSION "\n", argv[0]);
			break;
		default:
			break;
		}
		if ( BAD( owopt(c, optarg) ) ) {
			ow_exit(0);			/* rest of message */
		}
	}

	/* non-option arguments */
	while (optind < argc) {
		ARG_Generic(argv[optind]);
		++optind;
	}

	switch (Globals.daemon_status) {
		case e_daemon_sd:
		case e_daemon_sd_done:
			// systemd done later
			break ;
		default:
			if (Outbound_Control.active == 0) {
				if (Globals.zero == zero_none) {
					LEVEL_DEFAULT("%s would be \"locked in\" so will quit.\nBonjour and Avahi not available.", argv[0]);
					ow_exit(1);
				} else {
					LEVEL_CONNECT("%s will use an ephemeral port", argv[0]) ;
				}
				ARG_Server(NULL);		// make an ephemeral assignment
			}
			break ;
	}

	/* become a daemon if not told otherwise */
	if ( BAD(EnterBackground()) ) {
		ow_exit(1);
	}

	/* Set up adapters and systemd */
	if ( BAD(LibStart(NULL)) ) {
		ow_exit(1);
	}

	set_exit_signal_handlers(exit_handler);
	set_signal_handlers(NULL);

	ServerProcess(Acceptor);

	LEVEL_DEBUG("ServerProcess done");
	ow_exit(0);
	LEVEL_DEBUG("owhttpd done");
	return 0;
}
Exemple #24
0
/*
 * main function
 */
int main(int argc, char *argv[])
{
    int sock = -1, ret;
    unsigned groups; 

    /* set option */
    ret = set_options(argc, argv);
    if(ret < 0)
        close_exit(sock, 0, ret);

    /* open log file */
    ret = open_log(log_file);
    if(ret < 0)
        close_exit(sock, 0, ret);

    /* open debug file */
    if(log_opts & L_DEBUG) {
        ret = open_dbg(dbg_file);
        if(ret < 0)
            close_exit(sock, 0, ret);
    }

    /* create lock file */
    ret = open_lock();
    if(ret < 0)
        close_exit(sock, 0, ret);

    /* set signal handlers */
    ret = set_signal_handlers();
    if(ret < 0)
        close_exit(sock, 0, ret);

    /* initizlize daemon */
    ret = init_daemon();
    if(ret < 0)
        close_exit(sock, 0, ret);

    rec_log("info: nield %s started(PID: %ld)", VERSION, (long)getpid());

    /* write pid to lock file */
    ret = write_lock();
    if(ret < 0)
        close_exit(sock, 0, ret);

    /* open netlink socket to create list */
    groups = 0;
    sock = open_netlink_socket(groups, NETLINK_ROUTE);
    if(sock < 0)
        close_exit(sock, 1, ret);

    /* request interface list */
    ret = send_request(sock, RTM_GETLINK, AF_UNSPEC);
    if(ret < 0)
        close_exit(sock, 1, ret);

    /* receive interface list */
    ret = recv_reply(sock, RTM_GETLINK);
    if(ret != 0)
        close_exit(sock, 1, ret);

    /* request bridge interface list */
    ret = send_request(sock, RTM_GETLINK, AF_BRIDGE);
    if(ret < 0)
        close_exit(sock, 1, ret);

    /* receive bridge interface list */
    ret = recv_reply(sock, RTM_GETLINK);
    if(ret != 0)
        close_exit(sock, 1, ret);

    /* request neighbor cache list */
    ret = send_request(sock, RTM_GETNEIGH, AF_UNSPEC);
    if(ret < 0)
        close_exit(sock, 1, ret);

    /* receive & create interface list */
    ret = recv_reply(sock, RTM_GETNEIGH);
    if(ret != 0)
        close_exit(sock, 1, ret);

    /* close socket */
    close(sock);

    /* set rtnetlink multicast groups */
    groups = set_rtnetlink_groups();
    sock = open_netlink_socket(groups, NETLINK_ROUTE);
    if(sock < 0)
        close_exit(sock, 1, ret);

    /* recevie events */
    ret = recv_events(sock);

    close_exit(sock, 1, ret);

    return(0);
}
Exemple #25
0
int
main (int argc, char *argv[])
{
  struct timespec ts[2];
  struct timespec *targ;
  struct timeval wt;
  int d;
  int rc;

  setprogname (argv[0]);

  /* 
   * make the file the right size by writing our time
   * there
   */
  mmcd_gettime (ts);
  ts[1]  = ts[0];

  if (argc != 2) 
    usage (argc, argv);

  mmap_file = argv[1];
  mmap_fd = open (mmap_file, O_RDWR|O_CREAT, 0644);

  if (mmap_fd < 0) {
    fprintf (stderr, "mmcd: %s: cannot open file for reading\n", argv[1]);
    exit (1);
  }
  if (write (mmap_fd, (char *)ts, sizeof (ts)) != sizeof (ts)) {
    fprintf (stderr, "mmcd: %s: short write\n", argv[1]);
    exit (1);
  }

  mmap_rgn_sz = sizeof (struct timespec )  * 2;
  mmap_rgn = mmap (NULL, mmap_rgn_sz, PROT_READ|PROT_WRITE, MAP_SHARED, mmap_fd, 0); 
  if (mmap_rgn == MAP_FAILED) {
    fprintf (stderr, "mmcd: mmap failed: %d\n", errno);
    exit (1);
  }

  fprintf (stderr, "%s: starting up; file=%s; pid=%d\n", 
	   progname, mmap_file, getpid ());

  set_signal_handlers ();
  
  targ = (struct timespec *) mmap_rgn;
  while (1) {
    
    wt.tv_sec = 0;
    wt.tv_usec = CLCKD_INTERVAL;

    mmcd_gettime (ts); 
    targ[0] = ts[0];
    targ[1] = ts[0];
      
    rc = select (0, NULL, NULL, NULL, &wt);
    if (rc < 0) {
      fprintf (stderr, "%s: select failed: %d\n", progname, errno);
      continue;
    } 

    mmcd_gettime (ts+1); 
    d = timespec_diff (ts[1], ts[0]);
    /*
     * long sleeps will hurt the accuracy of the clock; may as well
     * report them, although eventually it would be nice to do something
     * about them on the client side;
     *
     */
    if (d > 10 * CLCKD_INTERVAL)
      fprintf (stderr, "%s: %s: very long sleep: %d\n", progname, argv[0], d);
  }
  return 0;
}
Exemple #26
0
int main(int argc, char *argv[])
{
	int listenfd;
	int res = 0;
	int lfd;
	struct flock lock;
	char pids[10];

	parse_opts(argc, argv);

	argc -= optind;
	argv += optind;

	if (!foreground) {
		verbose += LL_WARNING;
		log_enable_syslog();
	} else {
		verbose += LL_NOTICE;
	}

	/* set log level to specified verbosity */
	log_level = verbose;

	usbmuxd_log(LL_NOTICE, "usbmuxd v%s starting up", PACKAGE_VERSION);
	should_exit = 0;
	should_discover = 0;

	set_signal_handlers();
	signal(SIGPIPE, SIG_IGN);

	res = lfd = open(lockfile, O_WRONLY|O_CREAT, 0644);
	if(res == -1) {
		usbmuxd_log(LL_FATAL, "Could not open lockfile");
		goto terminate;
	}
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	lock.l_pid = 0;
	fcntl(lfd, F_GETLK, &lock);
	close(lfd);
	if (lock.l_type != F_UNLCK) {
		if (opt_exit) {
			if (lock.l_pid && !kill(lock.l_pid, 0)) {
				usbmuxd_log(LL_NOTICE, "Sending signal %d to instance with pid %d", exit_signal, lock.l_pid);
				res = 0;
				if (kill(lock.l_pid, exit_signal) < 0) {
					usbmuxd_log(LL_FATAL, "Could not deliver signal %d to pid %d", exit_signal, lock.l_pid);
					res = -1;
				}
				goto terminate;
			} else {
				usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
				res = -1;
				goto terminate;
			}
		} else {
			if (!opt_disable_hotplug) {
				usbmuxd_log(LL_ERROR, "Another instance is already running (pid %d). exiting.", lock.l_pid);
				res = -1;
			} else {
				usbmuxd_log(LL_NOTICE, "Another instance is already running (pid %d). Telling it to check for devices.", lock.l_pid);
				if (lock.l_pid && !kill(lock.l_pid, 0)) {
					usbmuxd_log(LL_NOTICE, "Sending signal SIGUSR2 to instance with pid %d", lock.l_pid);
					res = 0;
					if (kill(lock.l_pid, SIGUSR2) < 0) {
						usbmuxd_log(LL_FATAL, "Could not deliver SIGUSR2 to pid %d", lock.l_pid);
						res = -1;
					}
				} else {
					usbmuxd_log(LL_ERROR, "Could not determine pid of the other running instance!");
					res = -1;
				}
			}
			goto terminate;
		}
	}
	unlink(lockfile);

	if (opt_exit) {
		usbmuxd_log(LL_NOTICE, "No running instance found, none killed. Exiting.");
		goto terminate;
	}

	if (!foreground) {
		if ((res = daemonize()) < 0) {
			fprintf(stderr, "usbmuxd: FATAL: Could not daemonize!\n");
			usbmuxd_log(LL_FATAL, "Could not daemonize!");
			goto terminate;
		}
	}

	// now open the lockfile and place the lock
	res = lfd = open(lockfile, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644);
	if(res < 0) {
		usbmuxd_log(LL_FATAL, "Could not open lockfile");
		goto terminate;
	}
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;
	if ((res = fcntl(lfd, F_SETLK, &lock)) < 0) {
		usbmuxd_log(LL_FATAL, "Lockfile locking failed!");
		goto terminate;
	}
	sprintf(pids, "%d", getpid());
	if ((size_t)(res = write(lfd, pids, strlen(pids))) != strlen(pids)) {
		usbmuxd_log(LL_FATAL, "Could not write pidfile!");
		if(res >= 0)
			res = -2;
		goto terminate;
	}

	// set number of file descriptors to higher value
	struct rlimit rlim;
	getrlimit(RLIMIT_NOFILE, &rlim);
	rlim.rlim_max = 65536;
	setrlimit(RLIMIT_NOFILE, (const struct rlimit*)&rlim);

	usbmuxd_log(LL_INFO, "Creating socket");
	res = listenfd = create_socket();
	if(listenfd < 0)
		goto terminate;

#ifdef HAVE_LIBIMOBILEDEVICE
	const char* userprefdir = config_get_config_dir();
	struct stat fst;
	memset(&fst, '\0', sizeof(struct stat));
	if (stat(userprefdir, &fst) < 0) {
		if (mkdir(userprefdir, 0775) < 0) {
			usbmuxd_log(LL_FATAL, "Failed to create required directory '%s': %s", userprefdir, strerror(errno));
			res = -1;
			goto terminate;
		}
		if (stat(userprefdir, &fst) < 0) {
			usbmuxd_log(LL_FATAL, "stat() failed after creating directory '%s': %s", userprefdir, strerror(errno));
			res = -1;
			goto terminate;
		}
	}

	// make sure permission bits are set correctly
	if (fst.st_mode != 02775) {
		if (chmod(userprefdir, 02775) < 0) {
			usbmuxd_log(LL_WARNING, "chmod(%s, 02775) failed: %s", userprefdir, strerror(errno));
		}
	}
#endif

	// drop elevated privileges
	if (drop_privileges && (getuid() == 0 || geteuid() == 0)) {
		struct passwd *pw;
		if (!drop_user) {
			usbmuxd_log(LL_FATAL, "No user to drop privileges to?");
			res = -1;
			goto terminate;
		}
		pw = getpwnam(drop_user);
		if (!pw) {
			usbmuxd_log(LL_FATAL, "Dropping privileges failed, check if user '%s' exists!", drop_user);
			res = -1;
			goto terminate;
		}
		if (pw->pw_uid == 0) {
			usbmuxd_log(LL_INFO, "Not dropping privileges to root");
		} else {
#ifdef HAVE_LIBIMOBILEDEVICE
			/* make sure the non-privileged user has proper access to the config directory */
			if ((fst.st_uid != pw->pw_uid) || (fst.st_gid != pw->pw_gid)) {
				if (chown(userprefdir, pw->pw_uid, pw->pw_gid) < 0) {
					usbmuxd_log(LL_WARNING, "chown(%s, %d, %d) failed: %s", userprefdir, pw->pw_uid, pw->pw_gid, strerror(errno));
				}
			}
#endif

			if ((res = initgroups(drop_user, pw->pw_gid)) < 0) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set supplementary groups)");
				goto terminate;
			}
			if ((res = setgid(pw->pw_gid)) < 0) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set group ID to %d)", pw->pw_gid);
				goto terminate;
			}
			if ((res = setuid(pw->pw_uid)) < 0) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges (cannot set user ID to %d)", pw->pw_uid);
				goto terminate;
			}

			// security check
			if (setuid(0) != -1) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
				res = -1;
				goto terminate;
			}
			if (getuid() != pw->pw_uid || getgid() != pw->pw_gid) {
				usbmuxd_log(LL_FATAL, "Failed to drop privileges properly!");
				res = -1;
				goto terminate;
			}
			usbmuxd_log(LL_NOTICE, "Successfully dropped privileges to '%s'", drop_user);
		}
	}

	client_init();
	device_init();
	usbmuxd_log(LL_INFO, "Initializing USB");
	if((res = usb_init()) < 0)
		goto terminate;

	usbmuxd_log(LL_INFO, "%d device%s detected", res, (res==1)?"":"s");

	usbmuxd_log(LL_NOTICE, "Initialization complete");

	if (report_to_parent)
		if((res = notify_parent(0)) < 0)
			goto terminate;

	if(opt_disable_hotplug) {
		usbmuxd_log(LL_NOTICE, "Automatic device discovery on hotplug disabled.");
		usb_autodiscover(0); // discovery to be triggered by new instance
	}
	if (opt_enable_exit) {
		usbmuxd_log(LL_NOTICE, "Enabled exit on SIGUSR1 if no devices are attached. Start a new instance with \"--exit\" to trigger.");
	}

	res = main_loop(listenfd);
	if(res < 0)
		usbmuxd_log(LL_FATAL, "main_loop failed");

	usbmuxd_log(LL_NOTICE, "usbmuxd shutting down");
	device_kill_connections();
	usb_shutdown();
	device_shutdown();
	client_shutdown();
	usbmuxd_log(LL_NOTICE, "Shutdown complete");

terminate:
	log_disable_syslog();

	if (res < 0)
		res = -res;
	else
		res = 0;
	if (report_to_parent)
		notify_parent(res);

	return res;
}
Exemple #27
0
int
qdpll_main (int argc, char **argv)
{
  QDPLLResult result = QDPLL_RESULT_UNKNOWN;
  QDPLLApp app;
  memset (&app, 0, sizeof (QDPLLApp));
  set_default_options (&app);

  qdpll = qdpll_create ();

  parse_cmd_line_options (&app, qdpll, argc, argv);
  check_options (&app);
  set_signal_handlers (&app);

  if (app.options.print_usage)
    {
      print_usage ();
      cleanup (qdpll, &app);
      return result;
    }
  if (app.options.print_version)
    {
      print_version ();
      cleanup (qdpll, &app);
      return result;
    }

  if (app.options.max_time)
    alarm (app.options.max_time);

  parse (&app, qdpll, app.options.in, app.options.trace);

  if (app.options.pretty_print)
    {
      /* Call 'qdpll_gc' to clean up the formula by removing variables
         which have no occurrences and removing empty quantifier
         blocks. */
      qdpll_gc (qdpll);
      qdpll_print (qdpll, stdout);
    }
  else if (app.options.deps_only)
    {
      qdpll_init_deps (qdpll);
      if (app.options.print_deps)
        print_deps (&app, qdpll);
      if (app.options.dump_dep_graph)
        qdpll_dump_dep_graph (qdpll);
    }
  else
    {
        result = qdpll_sat (qdpll);
#if (COMPUTE_STATS || COMPUTE_TIMES)
        qdpll_print_stats (qdpll);
#endif
    }

  if (app.options.trace == TRACE_QRP)
    fprintf (stdout, "r ");
  else if (app.options.trace == TRACE_BQRP)
    fprintf (stdout, "%cr ", 0);

  print_result_message (&app, qdpll, result, stdout);

  cleanup (qdpll, &app);

  return result;
}