void PluginManager::start(){
  Logger* log = Logger::getLogger();

  std::string list = Settings::getSettings()->get("autoload_plugins");
  size_t pos_c = 0;
  size_t pos_e;
  if(list.length() > 0){
    while(pos_c != list.npos){
      pos_e = list.find(",", pos_c);
      load(list.substr(pos_c, pos_e));
      pos_c = pos_e;
    }
  }else{
    log->info("No automatically loaded plugins were defined in the "
        "configuation, add \"autoload_plugins = <comma list of plugins>\" to conf "
        "to have them loaded.");
  }

  /* Initalise the ltdl module. */
  LTDL_SET_PRELOADED_SYMBOLS();
  if(lt_dlinit() != 0){
    // FIXME: Should raise an error here.!
    log->error("Failed to load initalise the loader %s", lt_dlerror());
	stop();
  }

  /* Need to load ourselves before we can load other modules. */
  lt_dlhandle nlib = lt_dlopen(NULL);
  if(nlib == NULL){
    log->error("Failed to load ourselves because %s.", lt_dlerror());
	stop();
  }

}
示例#2
0
int main(void)
{
  JavaVMInitArgs vmargs;
  JavaVM *vm;
  void *env;
  JavaVMOption myoptions[1];

  /* set up libtool/libltdl dlopen emulation */
  LTDL_SET_PRELOADED_SYMBOLS();
  
  myoptions[0].optionString = concatString("-Xbootclasspath:", getenv("BOOTCLASSPATH"));

  vmargs.version = JNI_VERSION_1_2;
  
  if (JNI_GetDefaultJavaVMInitArgs (&vmargs) < 0)
    {
      fprintf(stderr, " Cannot retrieve default arguments\n");
      return 1;
    }

  vmargs.nOptions = 1;
  vmargs.options = myoptions;

  if (JNI_CreateJavaVM (&vm, &env, &vmargs) < 0)
    {
      fprintf(stderr, " Cannot create the Java VM\n");
      return 1;
    }

  (*vm)->DestroyJavaVM(vm);

  return 0;
}
示例#3
0
/*-------------------------------------------------------------------*/
int main(int ac,char *av[])
{
    DROP_PRIVILEGES(CAP_SYS_NICE);
    SET_THREAD_NAME("bootstrap");

#if defined( OPTION_DYNAMIC_LOAD ) && defined( HDL_USE_LIBTOOL )
    LTDL_SET_PRELOADED_SYMBOLS();
#endif
    exit(impl(ac,av));
}
示例#4
0
int nv_plugins_init() {
	int ret = 0;

	/* init the plugin system */
	LTDL_SET_PRELOADED_SYMBOLS();
	ret = lt_dlinit();
	if (ret) {
		nv_log(NVLOG_ERROR, "lt_dlinit(): %s", lt_dlerror());
		return -1;
	}
	return ret;
}
int
main(int argc, char *argv[])
{
    int					rc = 0;
    int					test_num = 0;
    int					not_ok = 0;

    LTDL_SET_PRELOADED_SYMBOLS();
    if(argc < 2)
    {
	fprintf(stderr, "Usage: %s resource-manager-contact [test number]\n",
		argv[0]);
	exit(1);
    }
    resource_manager_contact = argv[1];

    if(argc > 2)
    {
	test_num = atoi(argv[2]);
    }
    rc = globus_module_activate(GLOBUS_COMMON_MODULE);
    if(rc)
    {
	not_ok |= rc;
	goto end;
    }

    if(test_num == 0 || test_num == 1)
    {
	rc = test1();
	printf("%sok\n", rc ? "not " : "");
	not_ok |= rc;
    }

    if(test_num == 0 || test_num == 2)
    {
	rc = test2();
	printf("%sok\n", rc ? "not " : "");
	not_ok |= rc;
    }

    if(test_num == 0 || test_num == 3)
    {
	rc = test3();
	printf("%sok\n", rc ? "not " : "");
	not_ok |= rc;
    }


    globus_module_deactivate_all();
end:
    return not_ok;
}
/*
 * Function:	main
 *
 * Description:	
 *		
 * Parameters:	
 *
 * Returns:	
 */
int
main(int argc, char **argv)
{
    int					rc;
    
    LTDL_SET_PRELOADED_SYMBOLS();

    globus_module_activate(GLOBUS_COMMON_MODULE);
    globus_module_activate(GLOBUS_IO_MODULE);

#if 1
    test1();				/* connect, read, write, read */
    test2();				/* connect, read, writev, read */
    test3();				/* failed connect */
#endif
    test4(atoi(argv[1]));		/* connect to secure server*/
    globus_module_deactivate(GLOBUS_IO_MODULE);
    globus_module_deactivate(GLOBUS_COMMON_MODULE);
    return 0;
}
int main(int argc, char *argv[])
{
    int i;
    int failed;
    test_case_t tests[] =
    {
        TEST_CASE(test_stdio_update),
        {NULL, NULL}
    };

    LTDL_SET_PRELOADED_SYMBOLS();
    printf("1..%d\n", (int) (sizeof(tests)/sizeof(tests[0]) - 1));
    contact_string = getenv("CONTACT_STRING");
    if (argc == 2)
    {
        contact_string = argv[1];
    }
    if (contact_string == NULL)
    {
        fprintf(stderr, "Usage: %s CONTACT-STRING\n", argv[0]);
        exit(1);
    }

    globus_module_activate(GLOBUS_GRAM_CLIENT_MODULE);
    globus_module_activate(GLOBUS_GASS_TRANSFER_MODULE);

    for (i = 0, failed = 0; tests[i].test_name != NULL; i++)
    {
        int rc = tests[i].test_case();

        if (rc != 0)
        {
            printf("not ");
            failed++;
        }
        printf("ok  %s\n", tests[i].test_name);
    }
    globus_module_deactivate_all();

    return failed;
}
int main(int argc,
	 char *argv[])
{
    globus_ftp_client_handle_t			handle;
    globus_ftp_client_operationattr_t		attr;
    globus_byte_t				buffer[1024];
    globus_size_t				buffer_length = sizeof(buffer);
    globus_result_t				result;
    char *					src;
    char *					dst;
    globus_ftp_client_handleattr_t		handle_attr;

    LTDL_SET_PRELOADED_SYMBOLS();
    globus_module_activate(GLOBUS_FTP_CLIENT_MODULE);

    globus_ftp_client_handleattr_init(&handle_attr);
    globus_ftp_client_operationattr_init(&attr);

    test_parse_args(argc, 
		    argv,
		    &handle_attr,
		    &attr,
		    &src,
		    &dst);

    globus_mutex_init(&lock, GLOBUS_NULL);
    globus_cond_init(&cond, GLOBUS_NULL);

    globus_ftp_client_handle_init(&handle,  &handle_attr);

    done = GLOBUS_FALSE;
    result = globus_ftp_client_get(&handle,
				   src,
				   &attr,
				   GLOBUS_NULL,
				   done_cb,
				   0);
    globus_module_deactivate_all();

    return done;
}
int main(int argc, char *argv[])
{
    int rc;

    LTDL_SET_PRELOADED_SYMBOLS();
    rc = globus_module_activate(GLOBUS_GRAM_CLIENT_MODULE);
    if(rc != GLOBUS_SUCCESS)
    {
	fprintf(stderr, "Error activating GRAM Client\n");

	goto error_exit;
    }
    if(argc < 2)
    {
	rc = -1;

	fprintf(stderr, "Usage: %s rm_contact\n", argv[0]);

	goto deactivate_exit;
    }
    rc = globus_gram_client_ping(argv[1]);
    if(rc == GLOBUS_SUCCESS)
    {
	printf("Success pinging %s\n", argv[1]);
    }
    else
    {
	printf("Failed pinging %s because %s\n",
		argv[1],
		globus_gram_client_error_string(rc));
    }

  deactivate_exit:
    globus_module_deactivate_all();
  error_exit:
    return rc;
}
示例#10
0
/* Uses dlpreloading to discover plugins that
 * were statically linked at compile time */
int
loadPlugins_static ()
{
    if(LTDL_SET_PRELOADED_SYMBOLS() != 0)
        return -1;
    
    lt_dlsymlist sym;
    int i = 1;
    char* dot;
    int nameLen;
    char pluginName[64];
    char nameComp[128];
    
    while (1) {
        sym = lt_preloaded_symbols[i];
        if (sym.name && !sym.address)
        {
            dot = strrchr (sym.name, '.');
            nameLen = dot - sym.name;
            memset (pluginName, '\0', 64);
            memcpy (pluginName, sym.name, nameLen);
            memset (nameComp, '\0', 128);
            memcpy (nameComp, sym.name, nameLen);
            snprintf (nameComp+nameLen, 128-nameLen, "_LTX_getPluginHead");
        }
        else if (sym.name && sym.address)
        {
            if (strncmp (nameComp, sym.name, 128) == 0)
                checkAddPlugin_static (pluginName, sym.address);
        }
        else
            break;
        ++i;
    }
    
    return 0;
}
int
main(
    int                                 argc,
    char **                             argv)
{
    globus_result_t                     result;
    int                                 rc;
    globus_byte_t                       buffer[GF_DYN_PACKET_LEN];
    uint32_t                            tmp32;
    char *                              be_cs;
    char *                              reg_cs;
    globus_size_t                       nbytes;

    LTDL_SET_PRELOADED_SYMBOLS();
    rc = globus_module_activate(GLOBUS_XIO_MODULE);
    if(rc != 0)
    {
        goto error_activate;
    }

    result = gfs_l_dynclient_master_options(argc, argv);
    if(result != GLOBUS_SUCCESS)
    {
        goto error_opts;
    }
    if(argc < 3)
    {
        fprintf(stderr, "%s [options] <backend contact string>"
            " <frontend contact string>\n", argv[0]);
        fprintf(stderr, "Use -help for more information\n");
        exit(0);
    }

    be_cs = argv[argc - 2];
    reg_cs = argv[argc - 1];

    result = gfs_l_dynclient_xio_setup();
    if(result != GLOBUS_SUCCESS)
    {
        goto error_xio;
    }

    memset(buffer, '\0', GF_DYN_PACKET_LEN);
    buffer[GF_VERSION_NDX] = GF_VERSION;
    buffer[GF_MSG_TYPE_NDX] = GFS_GFORK_MSG_TYPE_DYNBE;

    tmp32 = htonl(g_at_once);
    memcpy(&buffer[GF_DYN_AT_ONCE_NDX], &tmp32, sizeof(uint32_t));

    tmp32 = htonl(g_total_cons);
    memcpy(&buffer[GF_DYN_TOTAL_NDX], &tmp32, sizeof(uint32_t));

    tmp32 = htonl(1);
    memcpy(&buffer[GF_DYN_ENTRY_COUNT_NDX], &tmp32, sizeof(uint32_t));

    strncpy((char *) &buffer[GF_DYN_CS_NDX], be_cs, GF_DYN_CS_LEN);

    result = globus_xio_open(g_xio_handle, reg_cs, NULL);
    if(result != GLOBUS_SUCCESS)
    {
        goto error_open;
    }
    result = globus_xio_write(
        g_xio_handle, buffer, 
        GF_DYN_PACKET_LEN, GF_DYN_PACKET_LEN, &nbytes, NULL);
    if(result != GLOBUS_SUCCESS)
    {
        goto error_write;
    }
    /* read reply */
    result = globus_xio_read(
        g_xio_handle, buffer,
        GF_DYN_PACKET_LEN, GF_DYN_PACKET_LEN, &nbytes, NULL);
    if(result != GLOBUS_SUCCESS)
    {
        gfs_l_dynclient_log(GLOBUS_SUCCESS, 0,
            "Read failed\n");
        goto error_read;
    }
    result = globus_xio_close(g_xio_handle, NULL);
    if(result != GLOBUS_SUCCESS)
    {
        gfs_l_dynclient_log(GLOBUS_SUCCESS, 0,
            "Close failed\n");
        goto error_close;
    }

    gfs_l_dynclient_log(GLOBUS_SUCCESS, 1,
        "proper net commication with %s\n",
        reg_cs);

    if(buffer[GF_MSG_TYPE_NDX] == GFS_GFORK_MSG_TYPE_ACK)
    {
        gfs_l_dynclient_log(GLOBUS_SUCCESS, 0,
            "SUCCESS: registered %s to %s",
            be_cs, reg_cs);
        rc = 0;
    }
    else
    {
        gfs_l_dynclient_log(GLOBUS_SUCCESS, 0,
            "ERROR: %s rejected registration of %s",
            reg_cs, be_cs);
        rc = 1;
    }

    return rc;

error_close:
error_read:
error_write:
error_open:
error_xio:
error_opts:
error_activate:
    gfs_l_dynclient_log(result, 0, "");

    return 2;
}
/*
 * MAIN
 */
int
main(int argc, char* argv[])
{
	int farg;
	const char* cp;
	void* env;

#if defined(MAIN_MD)
	MAIN_MD;
#endif

#if defined(HAVE_LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
	setlocale(LC_CTYPE, "");
#endif
#if defined(HAVE_GETTEXT)
	bindtextdomain(PACKAGE, KAFFE_LOCALEDIR);
	textdomain(PACKAGE);
#endif

	vmargs.version = JNI_VERSION_1_1;

#if defined(KAFFE_PROFILER)
	profFlag = 0;
#endif

	JNI_GetDefaultJavaVMInitArgs(&vmargs);

	/* set up libtool/libltdl dlopen emulation */
	LTDL_SET_PRELOADED_SYMBOLS();

#if defined(KAFFE_VMDEBUG)
	cp = getenv("KAFFE_VMDEBUG");
	if (cp != 0)
		dbgSetMaskStr(cp);
#endif

	cp = getenv(BOOTCLASSPATH);
	vmargs.bootClasspath = cp;

	cp = getenv(CLASSPATH1);
	if (cp == 0) {
		cp = getenv(CLASSPATH2);
#if defined(DEFAULT_CLASSPATH)
		if (cp == 0) {
			cp = DEFAULT_CLASSPATH;
		}
#endif
	}
	vmargs.classpath = (cp == NULL? NULL :strdup(cp));

        cp = getenv(LIBRARYPATH1);
	if (cp == 0) {
		cp = getenv(LIBRARYPATH2);
	}
        vmargs.libraryhome = cp;

        cp = getenv(KAFFEHOME);
        if (cp == 0) {
#if defined(DEFAULT_KAFFEHOME)
                cp = DEFAULT_KAFFEHOME;
#endif
        }
        vmargs.classhome = cp;

	/* Process program options */
	farg = options(argv, argc);
	argc = argc - farg;

#if defined(KAFFE_XPROFILER)
	if( xProfFlag )
	{
		if( !enableXCallGraph() && !enableXProfiling() )
		{
			fprintf(stderr, 
				"Unable to initialize cross "
				"language profiling\n");
			xProfFlag = 0;
		}
	}
#endif

	/* Get the class name to start with */
	if (argv[farg] == 0) {
		usage();
		exit(EXIT_FAILURE);
	}

	if (strcmp(argv[farg] + strlen(argv[farg]) - strlen(".class"),
		   ".class") == 0) {
		fprintf(stderr,
			"Please do not specify the .class extension\n");
		exit(EXIT_FAILURE);
	}

	/* Initialise */
	if (JNI_CreateJavaVM(&global_vm, 
			     &env, 
			     &vmargs) 
	    < 0)
	  {
	    fprintf(stderr, "Cannot create the Java VM\n");
	    exit(EXIT_FAILURE);
	  }

	return main2(env, argv, farg, argc);
}
示例#13
0
int main(int ac,char **av)
{
    /*****************************************/
    /* COMMANDHANDLER is the function type   */
    /* of the engine's panel command handler */
    /* this MUST be resolved at run time     */
    /* since some HDL module might have      */
    /* redirected the initial engine function*/
    /*****************************************/

    COMMANDHANDLER  ch;
    char *str,*bfr;

#if defined( OPTION_DYNAMIC_LOAD ) && defined( HDL_USE_LIBTOOL )
    /* LTDL Preloaded symbols for HDL using libtool */
    LTDL_SET_PRELOADED_SYMBOLS();
#endif

    /******************************************/
    /* Register the 'mywrite' function as the */
    /* log callback routine                   */
    /******************************************/
    registerLogCallback(mywrite);

    /******************************************/
    /* Initialize the HERCULE Engine          */
    /******************************************/
    impl(ac,av);

    /******************************************/
    /* Get the command handler function       */
    /* This MUST be done after IML            */
    /******************************************/
    ch=getCommandHandler();

    /******************************************/
    /* Read STDIN and pass to Command Handler */
    /******************************************/
    bfr=(char *)malloc(1024);
    while
    (
#ifdef _MSVC_
        !hLogCallbackThread ||
        WaitForSingleObject(hLogCallbackThread,0)
            != WAIT_OBJECT_0
#else
        1
#endif
    )
    {
#ifdef _MSVC_
        if (!kbhit()) Sleep(50); else
#endif
        if ((str=fgets(bfr,1024,stdin)))
        {
            str[strlen(str)-1]=0;
            ch(str);
        }
    }
#ifdef _MSVC_
    CloseHandle(hLogCallbackThread);
#endif
    return 0;
}
int
main()
{
    gss_cred_id_t                       credential;
    int                                 listen_fd;
    int                                 accept_fd;
    struct sockaddr_in                  address = {0};
    globus_sockaddr_t                   connect_address;
    globus_socklen_t                    connect_address_len = sizeof(connect_address);
    struct thread_arg *                 arg = NULL;
    globus_thread_t                     thread_handle;
    int                                 i;
    int                                 ret;
    int                                 error;

    LTDL_SET_PRELOADED_SYMBOLS();

    globus_thread_set_model(THREAD_MODEL);

    globus_module_activate(GLOBUS_COMMON_MODULE);
    globus_module_activate(GLOBUS_GSI_GSSAPI_MODULE);

    printf("1..%d\n", NUM_CLIENTS);
    /* initialize global mutex */
    globus_mutex_init(&mutex, NULL);

    /* and the condition variable */

    globus_cond_init(&done, NULL);
    
    /* setup listener */
    address.sin_family = AF_INET;
    address.sin_port = 0;
    address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);

    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_fd == 0)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    ret = bind(listen_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
    if (ret != 0)
    {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    ret = getsockname(listen_fd, (struct sockaddr *) &connect_address, &connect_address_len);
    if (ret != 0)
    {
        perror("getsockname");
        exit(EXIT_FAILURE);
    }

    ret = listen(listen_fd, -1);
    if (ret != 0)
    {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    /* acquire credentials */
    credential = globus_gsi_gssapi_test_acquire_credential();

    if(credential == GSS_C_NO_CREDENTIAL)
    {
	fprintf(stderr,"Unable to aquire credential\n");
	exit(-1);
    }

    /* start the clients here */
    for(i=0;i<NUM_CLIENTS;i++)
    {
	arg = malloc(sizeof(struct thread_arg));

	arg->address = &connect_address;
	arg->len = connect_address_len;

	arg->credential = credential;
	
        globus_mutex_lock(&mutex);
        {
            client_thread_count++;
        }
        globus_mutex_unlock(&mutex);

	globus_thread_create(&thread_handle,NULL,client_func,(void *) arg);
    }
    
    /* accept connections */

    globus_mutex_lock(&mutex);
    while (client_thread_count > 0)
    {
        while (pending_connects > 0)
	{
            accept_fd = accept(listen_fd,NULL,0);

            if(accept_fd < 0)
            {
                perror("accept");
                abort();
            }
	
            arg = malloc(sizeof(struct thread_arg));

            arg->fd = accept_fd;
            arg->credential = credential;

            server_thread_count++;
            pending_connects--;
            globus_thread_create(&thread_handle,NULL,server_func,(void *) arg);
        }
        globus_cond_wait(&done, &mutex);
    }

    /* wait for last thread to terminate */
    while (server_thread_count > 0)
    {
        globus_cond_wait(&done, &mutex);
    }
    globus_mutex_unlock(&mutex);


    /* destroy global mutex */

    globus_mutex_destroy(&mutex);

    /* and the condition variable */

    globus_cond_destroy(&done);
    
    /* close the listener */

    close(listen_fd);
    
    /* release credentials */

    globus_gsi_gssapi_test_release_credential(&credential); 

    globus_module_deactivate_all();

    exit(client_failed);
}
int main(int argc,
	 char *argv[])
{
    globus_ftp_client_handle_t			handle;
    globus_ftp_client_operationattr_t		attr;
    globus_byte_t				buffer[SIZE];
    globus_size_t				buffer_length = sizeof(buffer);
    globus_result_t				result;
    char *					src;
    char *					dst;
    globus_ftp_client_handleattr_t		handle_attr;
    globus_ftp_control_layout_t			layout;
    globus_ftp_control_parallelism_t		parallelism;
    int						i;
    globus_ftp_client_restart_marker_t		restart;

    LTDL_SET_PRELOADED_SYMBOLS();
    globus_module_activate(GLOBUS_FTP_CLIENT_MODULE);
    globus_ftp_client_handleattr_init(&handle_attr);
    globus_ftp_client_operationattr_init(&attr);

    layout.mode = GLOBUS_FTP_CONTROL_STRIPING_NONE;
    parallelism.mode = GLOBUS_FTP_CONTROL_PARALLELISM_NONE;

    globus_ftp_client_restart_marker_init(&restart);

    /* Parse local arguments */
    for(i = 1; i < argc; i++)
    {
	if(strcmp(argv[i], "-S") == 0 && i < argc)
	{
	    layout.mode =
		GLOBUS_FTP_CONTROL_STRIPING_BLOCKED_ROUND_ROBIN;
	    layout.round_robin.block_size = 15;

	    test_remove_arg(&argc, argv, &i, 0);
	}
	else if(strcmp(argv[i], "-P") == 0 && i + 1 < argc)
	{
	    parallelism.mode = GLOBUS_FTP_CONTROL_PARALLELISM_FIXED;
	    parallelism.fixed.size = atoi(argv[i+1]);

	    test_remove_arg(&argc, argv, &i, 1);
	}
	else if(strcmp(argv[i], "-R") == 0 && i+1 < argc)
	{
	    char * p;
	    globus_off_t offset, end;
	    int bytes;

	    p = argv[i+1];
	    while((*p) && (sscanf(p,
				  "%"GLOBUS_OFF_T_FORMAT
				  "-%"GLOBUS_OFF_T_FORMAT"%n",
				  &offset,
				  &end,
				  &bytes) >= 2))
	    {
		globus_ftp_client_restart_marker_insert_range(
		    &restart,
		    offset, end);
		p += bytes;
		if(*p && *p == ',') p++;
	    }
	    test_remove_arg(&argc, argv, &i, 1);
	}
    }
    test_parse_args(argc, 
		    argv,
                    &handle_attr,
                    &attr,
		    &src,
		    &dst);

    globus_mutex_init(&lock, GLOBUS_NULL);
    globus_cond_init(&cond, GLOBUS_NULL);

    globus_ftp_client_operationattr_set_mode(
        &attr,
        GLOBUS_FTP_CONTROL_MODE_EXTENDED_BLOCK);
    globus_ftp_client_operationattr_set_layout(&attr,
	                                       &layout);
    globus_ftp_client_operationattr_set_parallelism(&attr,
					            &parallelism);

    globus_ftp_client_handle_init(&handle,  &handle_attr);

    done = GLOBUS_FALSE;
    result = globus_ftp_client_get(&handle,
				   src,
				   &attr,
				   &restart,
				   done_cb,
				   0);
    if(result != GLOBUS_SUCCESS)
    {
	fprintf(stderr, "%s", globus_object_printable_to_string(globus_error_get(result)));
	done = GLOBUS_TRUE;
	error = GLOBUS_TRUE;
    }
    else
    {
	globus_ftp_client_register_read(
	    &handle,
	    buffer,
	    buffer_length,
	    data_cb,
	    0);
    }
    globus_mutex_lock(&lock);
    while(!done)
    {
	globus_cond_wait(&cond, &lock);
    }
    globus_mutex_unlock(&lock);

    globus_ftp_client_handle_destroy(&handle);

    globus_module_deactivate_all();

    if(test_abort_count && error)
    {
	return 0;
    }
    return error;
}
示例#16
0
/*
 * rig_load_backend
 * Dynamically load a rig backend through dlopen mechanism
 */
int HAMLIB_API rig_load_backend(const char *be_name)
{
# define PREFIX "hamlib-"

	lt_dlhandle be_handle;
	backend_init_t be_init;
	int status;
	char libname[PATH_MAX];
	char probefname[MAXFUNCNAMELEN];
	int i;

	/*
	 * lt_dlinit may be called several times
	 *
	 * FIXME: make static build seamless
	 */
#if 0
	LTDL_SET_PRELOADED_SYMBOLS();
#endif

	status = lt_dlinit();
	if (status) {
    		rig_debug(RIG_DEBUG_ERR, "rig_backend_load: lt_dlinit for %s "
							"failed: %s\n", be_name, lt_dlerror());
    		return -RIG_EINTERNAL;
	}

	lt_dladdsearchdir(HAMLIB_MODULE_DIR);

	rig_debug(RIG_DEBUG_VERBOSE, "rig: loading backend %s\n",be_name);

	/*
	 * add hamlib directory here
	 */
	snprintf (libname, sizeof (libname), PREFIX"%s", be_name);

	be_handle = lt_dlopenext (libname);

	/*
	 * external module not found? try dlopenself for backends
	 * compiled in static
	 */
	if (!be_handle || rig_check_backend_version(be_handle, be_name, &be_init) != RIG_OK) {
		rig_debug(RIG_DEBUG_VERBOSE, "rig:  lt_dlopen(\"%s\") failed (%s), "
						"trying static symbols...\n",
						libname, lt_dlerror());
		be_handle = lt_dlopen (NULL);
		if (!be_handle || rig_check_backend_version(be_handle, be_name, &be_init) != RIG_OK) {
			rig_debug(RIG_DEBUG_ERR, "rig:  lt_dlopen(\"%s\") failed (%s)\n",
						libname, lt_dlerror());
			return -RIG_EINVAL;
		}
	}


	/*
	 * register probe function if present
	 * NOTE: rig_load_backend might have been called upon a backend
	 * 	not in riglist.h! In this case, do nothing.
	 */
	for (i=0; i<RIG_BACKEND_MAX && rig_backend_list[i].be_name; i++) {
		if (!strncmp(be_name, rig_backend_list[i].be_name, 64)) {
    			snprintf(probefname, MAXFUNCNAMELEN, "probeallrigs%d_%s", ABI_VERSION, be_name);
    			rig_backend_list[i].be_probe_all =
				(rig_model_t (*)(hamlib_port_t*, rig_probe_func_t, rig_ptr_t))
						lt_dlsym (be_handle, probefname);
				break;
		}
	}

	status = (*be_init)(be_handle);

 	return status;
}
示例#17
0
int main(int argc, char *argv[]) {
    pa_core *c = NULL;
    pa_strbuf *buf = NULL;
    pa_daemon_conf *conf = NULL;
    pa_mainloop *mainloop = NULL;
    char *s;
    char *configured_address;
    int r = 0, retval = 1, d = 0;
    bool valid_pid_file = false;
    bool ltdl_init = false;
    int passed_fd = -1;
    const char *e;
#ifdef HAVE_FORK
    int daemon_pipe[2] = { -1, -1 };
    int daemon_pipe2[2] = { -1, -1 };
#endif
    int autospawn_fd = -1;
    bool autospawn_locked = false;
#ifdef HAVE_DBUS
    pa_dbusobj_server_lookup *server_lookup = NULL; /* /org/pulseaudio/server_lookup */
    pa_dbus_connection *lookup_service_bus = NULL; /* Always the user bus. */
    pa_dbus_connection *server_bus = NULL; /* The bus where we reserve org.pulseaudio.Server, either the user or the system bus. */
    bool start_server;
#endif

    pa_log_set_ident("pulseaudio");
    pa_log_set_level(PA_LOG_NOTICE);
    pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);

#if defined(__linux__) && defined(__OPTIMIZE__)
    /*
       Disable lazy relocations to make usage of external libraries
       more deterministic for our RT threads. We abuse __OPTIMIZE__ as
       a check whether we are a debug build or not. This all is
       admittedly a bit snake-oilish.
    */

    if (!getenv("LD_BIND_NOW")) {
        char *rp;
        char *canonical_rp;

        /* We have to execute ourselves, because the libc caches the
         * value of $LD_BIND_NOW on initialization. */

        pa_set_env("LD_BIND_NOW", "1");

        if ((canonical_rp = pa_realpath(PA_BINARY))) {

            if ((rp = pa_readlink("/proc/self/exe"))) {

                if (pa_streq(rp, canonical_rp))
                    pa_assert_se(execv(rp, argv) == 0);
                else
                    pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);

                pa_xfree(rp);

            } else
                pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");

            pa_xfree(canonical_rp);

        } else
            pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
    }
#endif

    if ((e = getenv("PULSE_PASSED_FD"))) {
        passed_fd = atoi(e);

        if (passed_fd <= 2)
            passed_fd = -1;
    }

    /* We might be autospawned, in which case have no idea in which
     * context we have been started. Let's cleanup our execution
     * context as good as possible */

    pa_reset_personality();
    pa_drop_root();
    pa_close_all(passed_fd, -1);
    pa_reset_sigs(-1);
    pa_unblock_sigs(-1);
    pa_reset_priority();

    setlocale(LC_ALL, "");
    pa_init_i18n();

    conf = pa_daemon_conf_new();

    if (pa_daemon_conf_load(conf, NULL) < 0)
        goto finish;

    if (pa_daemon_conf_env(conf) < 0)
        goto finish;

    if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
        pa_log(_("Failed to parse command line."));
        goto finish;
    }

    if (conf->log_target)
        pa_log_set_target(conf->log_target);
    else {
        pa_log_target target = { .type = PA_LOG_STDERR, .file = NULL };
        pa_log_set_target(&target);
    }

    pa_log_set_level(conf->log_level);
    if (conf->log_meta)
        pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
    if (conf->log_time)
        pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
    pa_log_set_show_backtrace(conf->log_backtrace);

#ifdef HAVE_DBUS
    /* conf->system_instance and conf->local_server_type control almost the
     * same thing; make them agree about what is requested. */
    switch (conf->local_server_type) {
        case PA_SERVER_TYPE_UNSET:
            conf->local_server_type = conf->system_instance ? PA_SERVER_TYPE_SYSTEM : PA_SERVER_TYPE_USER;
            break;
        case PA_SERVER_TYPE_USER:
        case PA_SERVER_TYPE_NONE:
            conf->system_instance = false;
            break;
        case PA_SERVER_TYPE_SYSTEM:
            conf->system_instance = true;
            break;
        default:
            pa_assert_not_reached();
    }

    start_server = conf->local_server_type == PA_SERVER_TYPE_USER || (getuid() == 0 && conf->local_server_type == PA_SERVER_TYPE_SYSTEM);

    if (!start_server && conf->local_server_type == PA_SERVER_TYPE_SYSTEM) {
        pa_log_notice(_("System mode refused for non-root user. Only starting the D-Bus server lookup service."));
        conf->system_instance = false;
    }
#endif

    LTDL_SET_PRELOADED_SYMBOLS();
    pa_ltdl_init();
    ltdl_init = true;

    if (conf->dl_search_path)
        lt_dlsetsearchpath(conf->dl_search_path);

#ifdef OS_IS_WIN32
    {
        WSADATA data;
        WSAStartup(MAKEWORD(2, 0), &data);
    }
#endif

    pa_random_seed();

    switch (conf->cmd) {
        case PA_CMD_DUMP_MODULES:
            pa_dump_modules(conf, argc-d, argv+d);
            retval = 0;
            goto finish;

        case PA_CMD_DUMP_CONF: {

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            s = pa_daemon_conf_dump(conf);
            fputs(s, stdout);
            pa_xfree(s);
            retval = 0;
            goto finish;
        }

        case PA_CMD_DUMP_RESAMPLE_METHODS: {
            int i;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            for (i = 0; i < PA_RESAMPLER_MAX; i++)
                if (pa_resample_method_supported(i))
                    printf("%s\n", pa_resample_method_to_string(i));

            retval = 0;
            goto finish;
        }

        case PA_CMD_HELP :
            pa_cmdline_help(argv[0]);
            retval = 0;
            goto finish;

        case PA_CMD_VERSION :

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
            retval = 0;
            goto finish;

        case PA_CMD_CHECK: {
            pid_t pid;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
                pa_log_info(_("Daemon not running"));
            else {
                pa_log_info(_("Daemon running as PID %u"), pid);
                retval = 0;
            }

            goto finish;

        }
        case PA_CMD_KILL:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
                pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
            else
                retval = 0;

            goto finish;

        case PA_CMD_CLEANUP_SHM:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_shm_cleanup() >= 0)
                retval = 0;

            goto finish;

        default:
            pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
    }

    if (d < argc) {
        pa_log("Too many arguments.\n");
        goto finish;
    }

#ifdef HAVE_GETUID
    if (getuid() == 0 && !conf->system_instance)
        pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
#ifndef HAVE_DBUS /* A similar, only a notice worthy check was done earlier, if D-Bus is enabled. */
    else if (getuid() != 0 && conf->system_instance) {
        pa_log(_("Root privileges required."));
        goto finish;
    }
#endif
#endif  /* HAVE_GETUID */

    if (conf->cmd == PA_CMD_START && conf->system_instance) {
        pa_log(_("--start not supported for system instances."));
        goto finish;
    }

    if (conf->cmd == PA_CMD_START && (configured_address = check_configured_address())) {
        /* There is an server address in our config, but where did it come from?
         * By default a standard X11 login will load module-x11-publish which will
         * inject PULSE_SERVER X11 property. If the PA daemon crashes, we will end
         * up hitting this code path. So we have to check to see if our configured_address
         * is the same as the value that would go into this property so that we can
         * recover (i.e. autospawn) from a crash.
         */
        char *ufn;
        bool start_anyway = false;

        if ((ufn = pa_runtime_path(PA_NATIVE_DEFAULT_UNIX_SOCKET))) {
            char *id;

            if ((id = pa_machine_id())) {
                pa_strlist *server_list;
                char formatted_ufn[256];

                pa_snprintf(formatted_ufn, sizeof(formatted_ufn), "{%s}unix:%s", id, ufn);
                pa_xfree(id);

                if ((server_list = pa_strlist_parse(configured_address))) {
                    char *u = NULL;

                    /* We only need to check the first server */
                    server_list = pa_strlist_pop(server_list, &u);
                    pa_strlist_free(server_list);

                    start_anyway = (u && pa_streq(formatted_ufn, u));
                    pa_xfree(u);
                }
            }
            pa_xfree(ufn);
        }

        if (!start_anyway) {
            pa_log_notice(_("User-configured server at %s, refusing to start/autospawn."), configured_address);
            pa_xfree(configured_address);
            retval = 0;
            goto finish;
        }

        pa_log_notice(_("User-configured server at %s, which appears to be local. Probing deeper."), configured_address);
        pa_xfree(configured_address);
    }

    if (conf->system_instance && !conf->disallow_exit)
        pa_log_warn(_("Running in system mode, but --disallow-exit not set!"));

    if (conf->system_instance && !conf->disallow_module_loading)
        pa_log_warn(_("Running in system mode, but --disallow-module-loading not set!"));

    if (conf->system_instance && !conf->disable_shm) {
        pa_log_notice(_("Running in system mode, forcibly disabling SHM mode!"));
        conf->disable_shm = true;
    }

    if (conf->system_instance && conf->exit_idle_time >= 0) {
        pa_log_notice(_("Running in system mode, forcibly disabling exit idle time!"));
        conf->exit_idle_time = -1;
    }

    if (conf->cmd == PA_CMD_START) {
        /* If we shall start PA only when it is not running yet, we
         * first take the autospawn lock to make things
         * synchronous. */

        if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
            pa_log("Failed to initialize autospawn lock");
            goto finish;
        }

        if ((pa_autospawn_lock_acquire(true) < 0)) {
            pa_log("Failed to acquire autospawn lock");
            goto finish;
        }

        autospawn_locked = true;
    }

    if (conf->daemonize) {
#ifdef HAVE_FORK
        pid_t child;
#endif

        if (pa_stdio_acquire() < 0) {
            pa_log(_("Failed to acquire stdio."));
            goto finish;
        }

#ifdef HAVE_FORK
        if (pipe(daemon_pipe) < 0) {
            pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if ((child = fork()) < 0) {
            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
            pa_close_pipe(daemon_pipe);
            goto finish;
        }

        if (child != 0) {
            ssize_t n;
            /* Father */

            pa_assert_se(pa_close(daemon_pipe[1]) == 0);
            daemon_pipe[1] = -1;

            if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {

                if (n < 0)
                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));

                retval = 1;
            }

            if (retval)
                pa_log(_("Daemon startup failed."));
            else
                pa_log_info(_("Daemon startup successful."));

            goto finish;
        }

        if (autospawn_fd >= 0) {
            /* The lock file is unlocked from the parent, so we need
             * to close it in the child */

            pa_autospawn_lock_release();
            pa_autospawn_lock_done(true);

            autospawn_locked = false;
            autospawn_fd = -1;
        }

        pa_assert_se(pa_close(daemon_pipe[0]) == 0);
        daemon_pipe[0] = -1;
#endif

        if (!conf->log_target) {
#ifdef HAVE_JOURNAL
            pa_log_target target = { .type = PA_LOG_JOURNAL, .file = NULL };
#else
            pa_log_target target = { .type = PA_LOG_SYSLOG, .file = NULL };
#endif
            pa_log_set_target(&target);
        }
示例#18
0
文件: main.c 项目: genesi/pulseaudio
int main(int argc, char *argv[]) {
    pa_core *c = NULL;
    pa_strbuf *buf = NULL;
    pa_daemon_conf *conf = NULL;
    pa_mainloop *mainloop = NULL;
    char *s;
    char *configured_address;
    int r = 0, retval = 1, d = 0;
    pa_bool_t valid_pid_file = FALSE;
    pa_bool_t ltdl_init = FALSE;
    int passed_fd = -1;
    const char *e;
#ifdef HAVE_FORK
    int daemon_pipe[2] = { -1, -1 };
    int daemon_pipe2[2] = { -1, -1 };
#endif
#ifdef OS_IS_WIN32
    pa_time_event *win32_timer;
    struct timeval win32_tv;
#endif
    int autospawn_fd = -1;
    pa_bool_t autospawn_locked = FALSE;
#ifdef HAVE_DBUS
    pa_dbusobj_server_lookup *server_lookup = NULL; /* /org/pulseaudio/server_lookup */
    pa_dbus_connection *lookup_service_bus = NULL; /* Always the user bus. */
    pa_dbus_connection *server_bus = NULL; /* The bus where we reserve org.pulseaudio.Server, either the user or the system bus. */
    pa_bool_t start_server;
#endif

    pa_log_set_ident("pulseaudio");
    pa_log_set_level(PA_LOG_NOTICE);
    pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);

#if defined(__linux__) && defined(__OPTIMIZE__)
    /*
       Disable lazy relocations to make usage of external libraries
       more deterministic for our RT threads. We abuse __OPTIMIZE__ as
       a check whether we are a debug build or not. This all is
       admittedly a bit snake-oilish.
    */

    if (!getenv("LD_BIND_NOW")) {
        char *rp;
        char *canonical_rp;

        /* We have to execute ourselves, because the libc caches the
         * value of $LD_BIND_NOW on initialization. */

        pa_set_env("LD_BIND_NOW", "1");

        if ((canonical_rp = pa_realpath(PA_BINARY))) {

            if ((rp = pa_readlink("/proc/self/exe"))) {

                if (pa_streq(rp, canonical_rp))
                    pa_assert_se(execv(rp, argv) == 0);
                else
                    pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);

                pa_xfree(rp);

            } else
                pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");

            pa_xfree(canonical_rp);

        } else
            pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
    }
#endif

    if ((e = getenv("PULSE_PASSED_FD"))) {
        passed_fd = atoi(e);

        if (passed_fd <= 2)
            passed_fd = -1;
    }

    /* We might be autospawned, in which case have no idea in which
     * context we have been started. Let's cleanup our execution
     * context as good as possible */

    pa_reset_personality();
    pa_drop_root();
    pa_close_all(passed_fd, -1);
    pa_reset_sigs(-1);
    pa_unblock_sigs(-1);
    pa_reset_priority();

    setlocale(LC_ALL, "");
    pa_init_i18n();

    conf = pa_daemon_conf_new();

    if (pa_daemon_conf_load(conf, NULL) < 0)
        goto finish;

    if (pa_daemon_conf_env(conf) < 0)
        goto finish;

    if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
        pa_log(_("Failed to parse command line."));
        goto finish;
    }

    pa_log_set_level(conf->log_level);
    pa_log_set_target(conf->auto_log_target ? PA_LOG_STDERR : conf->log_target);
    if (conf->log_meta)
        pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
    if (conf->log_time)
        pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
    pa_log_set_show_backtrace(conf->log_backtrace);

#ifdef HAVE_DBUS
    /* conf->system_instance and conf->local_server_type control almost the
     * same thing; make them agree about what is requested. */
    switch (conf->local_server_type) {
        case PA_SERVER_TYPE_UNSET:
            conf->local_server_type = conf->system_instance ? PA_SERVER_TYPE_SYSTEM : PA_SERVER_TYPE_USER;
            break;
        case PA_SERVER_TYPE_USER:
        case PA_SERVER_TYPE_NONE:
            conf->system_instance = FALSE;
            break;
        case PA_SERVER_TYPE_SYSTEM:
            conf->system_instance = TRUE;
            break;
        default:
            pa_assert_not_reached();
    }

    start_server = conf->local_server_type == PA_SERVER_TYPE_USER || (getuid() == 0 && conf->local_server_type == PA_SERVER_TYPE_SYSTEM);

    if (!start_server && conf->local_server_type == PA_SERVER_TYPE_SYSTEM) {
        pa_log_notice(_("System mode refused for non-root user. Only starting the D-Bus server lookup service."));
        conf->system_instance = FALSE;
    }
#endif

    LTDL_SET_PRELOADED_SYMBOLS();
    pa_ltdl_init();
    ltdl_init = TRUE;

    if (conf->dl_search_path)
        lt_dlsetsearchpath(conf->dl_search_path);

#ifdef OS_IS_WIN32
    {
        WSADATA data;
        WSAStartup(MAKEWORD(2, 0), &data);
    }
#endif

    pa_random_seed();

    switch (conf->cmd) {
        case PA_CMD_DUMP_MODULES:
            pa_dump_modules(conf, argc-d, argv+d);
            retval = 0;
            goto finish;

        case PA_CMD_DUMP_CONF: {

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            s = pa_daemon_conf_dump(conf);
            fputs(s, stdout);
            pa_xfree(s);
            retval = 0;
            goto finish;
        }

        case PA_CMD_DUMP_RESAMPLE_METHODS: {
            int i;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            for (i = 0; i < PA_RESAMPLER_MAX; i++)
                if (pa_resample_method_supported(i))
                    printf("%s\n", pa_resample_method_to_string(i));

            retval = 0;
            goto finish;
        }

        case PA_CMD_HELP :
            pa_cmdline_help(argv[0]);
            retval = 0;
            goto finish;

        case PA_CMD_VERSION :

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
            retval = 0;
            goto finish;

        case PA_CMD_CHECK: {
            pid_t pid;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
                pa_log_info(_("Daemon not running"));
            else {
                pa_log_info(_("Daemon running as PID %u"), pid);
                retval = 0;
            }

            goto finish;

        }
        case PA_CMD_KILL:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
                pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
            else
                retval = 0;

            goto finish;

        case PA_CMD_CLEANUP_SHM:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_shm_cleanup() >= 0)
                retval = 0;

            goto finish;

        default:
            pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
    }

    if (d < argc) {
        pa_log("Too many arguments.\n");
        goto finish;
    }

#ifdef HAVE_GETUID
    if (getuid() == 0 && !conf->system_instance)
        pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
#ifndef HAVE_DBUS /* A similar, only a notice worthy check was done earlier, if D-Bus is enabled. */
    else if (getuid() != 0 && conf->system_instance) {
        pa_log(_("Root privileges required."));
        goto finish;
    }
#endif
#endif  /* HAVE_GETUID */

    if (conf->cmd == PA_CMD_START && conf->system_instance) {
        pa_log(_("--start not supported for system instances."));
        goto finish;
    }

    if (conf->cmd == PA_CMD_START && (configured_address = check_configured_address())) {
        /* There is an server address in our config, but where did it come from?
         * By default a standard X11 login will load module-x11-publish which will
         * inject PULSE_SERVER X11 property. If the PA daemon crashes, we will end
         * up hitting this code path. So we have to check to see if our configured_address
         * is the same as the value that would go into this property so that we can
         * recover (i.e. autospawn) from a crash.
         */
        char *ufn;
        pa_bool_t start_anyway = FALSE;

        if ((ufn = pa_runtime_path(PA_NATIVE_DEFAULT_UNIX_SOCKET))) {
            char *id;

            if ((id = pa_machine_id())) {
                pa_strlist *server_list;
                char formatted_ufn[256];

                pa_snprintf(formatted_ufn, sizeof(formatted_ufn), "{%s}unix:%s", id, ufn);
                pa_xfree(id);

                if ((server_list = pa_strlist_parse(configured_address))) {
                    char *u = NULL;

                    /* We only need to check the first server */
                    server_list = pa_strlist_pop(server_list, &u);
                    pa_strlist_free(server_list);

                    start_anyway = (u && pa_streq(formatted_ufn, u));
                    pa_xfree(u);
                }
            }
            pa_xfree(ufn);
        }

        if (!start_anyway) {
            pa_log_notice(_("User-configured server at %s, refusing to start/autospawn."), configured_address);
            pa_xfree(configured_address);
            retval = 0;
            goto finish;
        }

        pa_log_notice(_("User-configured server at %s, which appears to be local. Probing deeper."), configured_address);
        pa_xfree(configured_address);
    }

    if (conf->system_instance && !conf->disallow_exit)
        pa_log_warn(_("Running in system mode, but --disallow-exit not set!"));

    if (conf->system_instance && !conf->disallow_module_loading)
        pa_log_warn(_("Running in system mode, but --disallow-module-loading not set!"));

    if (conf->system_instance && !conf->disable_shm) {
        pa_log_notice(_("Running in system mode, forcibly disabling SHM mode!"));
        conf->disable_shm = TRUE;
    }

    if (conf->system_instance && conf->exit_idle_time >= 0) {
        pa_log_notice(_("Running in system mode, forcibly disabling exit idle time!"));
        conf->exit_idle_time = -1;
    }

    if (conf->cmd == PA_CMD_START) {
        /* If we shall start PA only when it is not running yet, we
         * first take the autospawn lock to make things
         * synchronous. */

        if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
            pa_log("Failed to initialize autospawn lock");
            goto finish;
        }

        if ((pa_autospawn_lock_acquire(TRUE) < 0)) {
            pa_log("Failed to acquire autospawn lock");
            goto finish;
        }

        autospawn_locked = TRUE;
    }

    if (conf->daemonize) {
#ifdef HAVE_FORK
        pid_t child;
#endif

        if (pa_stdio_acquire() < 0) {
            pa_log(_("Failed to acquire stdio."));
            goto finish;
        }

#ifdef HAVE_FORK
        if (pipe(daemon_pipe) < 0) {
            pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if ((child = fork()) < 0) {
            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
            pa_close_pipe(daemon_pipe);
            goto finish;
        }

        if (child != 0) {
            ssize_t n;
            /* Father */

            pa_assert_se(pa_close(daemon_pipe[1]) == 0);
            daemon_pipe[1] = -1;

            if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {

                if (n < 0)
                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));

                retval = 1;
            }

            if (retval)
                pa_log(_("Daemon startup failed."));
            else
                pa_log_info(_("Daemon startup successful."));

            goto finish;
        }

        if (autospawn_fd >= 0) {
            /* The lock file is unlocked from the parent, so we need
             * to close it in the child */

            pa_autospawn_lock_release();
            pa_autospawn_lock_done(TRUE);

            autospawn_locked = FALSE;
            autospawn_fd = -1;
        }

        pa_assert_se(pa_close(daemon_pipe[0]) == 0);
        daemon_pipe[0] = -1;
#endif

        if (conf->auto_log_target)
            pa_log_set_target(PA_LOG_SYSLOG);

#ifdef HAVE_SETSID
        if (setsid() < 0) {
            pa_log(_("setsid() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }
#endif

#ifdef HAVE_FORK
        /* We now are a session and process group leader. Let's fork
         * again and let the father die, so that we'll become a
         * process that can never acquire a TTY again, in a session and
         * process group without leader */

        if (pipe(daemon_pipe2) < 0) {
            pa_log(_("pipe() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if ((child = fork()) < 0) {
            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
            pa_close_pipe(daemon_pipe2);
            goto finish;
        }

        if (child != 0) {
            ssize_t n;
            /* Father */

            pa_assert_se(pa_close(daemon_pipe2[1]) == 0);
            daemon_pipe2[1] = -1;

            if ((n = pa_loop_read(daemon_pipe2[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {

                if (n < 0)
                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));

                retval = 1;
            }

            /* We now have to take care of signalling the first fork with
             * the return value we've received from this fork... */
            pa_assert(daemon_pipe[1] >= 0);

            pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
            pa_close(daemon_pipe[1]);
            daemon_pipe[1] = -1;

            goto finish;
        }

        pa_assert_se(pa_close(daemon_pipe2[0]) == 0);
        daemon_pipe2[0] = -1;

        /* We no longer need the (first) daemon_pipe as it's handled in our child above */
        pa_close_pipe(daemon_pipe);
#endif

#ifdef SIGTTOU
        signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
        signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
        signal(SIGTSTP, SIG_IGN);
#endif

        pa_nullify_stdfds();
    }

    pa_set_env_and_record("PULSE_INTERNAL", "1");
    pa_assert_se(chdir("/") == 0);
    umask(0022);

#ifdef HAVE_SYS_RESOURCE_H
    set_all_rlimits(conf);
#endif
    pa_rtclock_hrtimer_enable();

    pa_raise_priority(conf->nice_level);

    if (conf->system_instance)
        if (change_user() < 0)
            goto finish;

    pa_set_env_and_record("PULSE_SYSTEM", conf->system_instance ? "1" : "0");

    pa_log_info(_("This is PulseAudio %s"), PACKAGE_VERSION);
    pa_log_debug(_("Compilation host: %s"), CANONICAL_HOST);
    pa_log_debug(_("Compilation CFLAGS: %s"), PA_CFLAGS);

    s = pa_uname_string();
    pa_log_debug(_("Running on host: %s"), s);
    pa_xfree(s);

    pa_log_debug(_("Found %u CPUs."), pa_ncpus());

    pa_log_info(_("Page size is %lu bytes"), (unsigned long) PA_PAGE_SIZE);

#ifdef HAVE_VALGRIND_MEMCHECK_H
    pa_log_debug(_("Compiled with Valgrind support: yes"));
#else
    pa_log_debug(_("Compiled with Valgrind support: no"));
#endif

    pa_log_debug(_("Running in valgrind mode: %s"), pa_yes_no(pa_in_valgrind()));

    pa_log_debug(_("Running in VM: %s"), pa_yes_no(pa_running_in_vm()));

#ifdef __OPTIMIZE__
    pa_log_debug(_("Optimized build: yes"));
#else
    pa_log_debug(_("Optimized build: no"));
#endif

#ifdef NDEBUG
    pa_log_debug(_("NDEBUG defined, all asserts disabled."));
#elif defined(FASTPATH)
    pa_log_debug(_("FASTPATH defined, only fast path asserts disabled."));
#else
    pa_log_debug(_("All asserts enabled."));
#endif

    if (!(s = pa_machine_id())) {
        pa_log(_("Failed to get machine ID"));
        goto finish;
    }
    pa_log_info(_("Machine ID is %s."), s);
    pa_xfree(s);

    if ((s = pa_session_id())) {
        pa_log_info(_("Session ID is %s."), s);
        pa_xfree(s);
    }

    if (!(s = pa_get_runtime_dir()))
        goto finish;
    pa_log_info(_("Using runtime directory %s."), s);
    pa_xfree(s);

    if (!(s = pa_get_state_dir()))
        goto finish;
    pa_log_info(_("Using state directory %s."), s);
    pa_xfree(s);

    pa_log_info(_("Using modules directory %s."), conf->dl_search_path);

    pa_log_info(_("Running in system mode: %s"), pa_yes_no(pa_in_system_mode()));

    if (pa_in_system_mode())
        pa_log_warn(_("OK, so you are running PA in system mode. Please note that you most likely shouldn't be doing that.\n"
                      "If you do it nonetheless then it's your own fault if things don't work as expected.\n"
                      "Please read http://pulseaudio.org/wiki/WhatIsWrongWithSystemMode for an explanation why system mode is usually a bad idea."));

    if (conf->use_pid_file) {
        int z;

        if ((z = pa_pid_file_create("pulseaudio")) != 0) {

            if (conf->cmd == PA_CMD_START && z > 0) {
                /* If we are already running and with are run in
                 * --start mode, then let's return this as success. */

                retval = 0;
                goto finish;
            }

            pa_log(_("pa_pid_file_create() failed."));
            goto finish;
        }

        valid_pid_file = TRUE;
    }

    pa_disable_sigpipe();

    if (pa_rtclock_hrtimer())
        pa_log_info(_("Fresh high-resolution timers available! Bon appetit!"));
    else
        pa_log_info(_("Dude, your kernel stinks! The chef's recommendation today is Linux with high-resolution timers enabled!"));

    if (conf->lock_memory) {
#ifdef HAVE_SYS_MMAN_H
        if (mlockall(MCL_FUTURE) < 0)
            pa_log_warn("mlockall() failed: %s", pa_cstrerror(errno));
        else
            pa_log_info("Successfully locked process into memory.");
#else
        pa_log_warn("Memory locking requested but not supported on platform.");
#endif
    }

    pa_memtrap_install();

    pa_assert_se(mainloop = pa_mainloop_new());

    if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm, conf->shm_size))) {
        pa_log(_("pa_core_new() failed."));
        goto finish;
    }

    c->default_sample_spec = conf->default_sample_spec;
    c->alternate_sample_rate = conf->alternate_sample_rate;
    c->default_channel_map = conf->default_channel_map;
    c->default_n_fragments = conf->default_n_fragments;
    c->default_fragment_size_msec = conf->default_fragment_size_msec;
    c->deferred_volume_safety_margin_usec = conf->deferred_volume_safety_margin_usec;
    c->deferred_volume_extra_delay_usec = conf->deferred_volume_extra_delay_usec;
    c->exit_idle_time = conf->exit_idle_time;
    c->scache_idle_time = conf->scache_idle_time;
    c->resample_method = conf->resample_method;
    c->realtime_priority = conf->realtime_priority;
    c->realtime_scheduling = !!conf->realtime_scheduling;
    c->disable_remixing = !!conf->disable_remixing;
    c->disable_lfe_remixing = !!conf->disable_lfe_remixing;
    c->deferred_volume = !!conf->deferred_volume;
    c->running_as_daemon = !!conf->daemonize;
    c->disallow_exit = conf->disallow_exit;
    c->flat_volumes = conf->flat_volumes;
#ifdef HAVE_DBUS
    c->server_type = conf->local_server_type;
#endif

    c->cpu_info.cpu_type = PA_CPU_UNDEFINED;
    if (!getenv("PULSE_NO_SIMD")) {
        if (pa_cpu_init_x86(&(c->cpu_info.flags.x86)))
            c->cpu_info.cpu_type = PA_CPU_X86;
        if (pa_cpu_init_arm(&(c->cpu_info.flags.arm)))
            c->cpu_info.cpu_type = PA_CPU_ARM;
	pa_cpu_init_orc(c->cpu_info);
    }

    pa_assert_se(pa_signal_init(pa_mainloop_get_api(mainloop)) == 0);
    pa_signal_new(SIGINT, signal_callback, c);
    pa_signal_new(SIGTERM, signal_callback, c);
#ifdef SIGUSR1
    pa_signal_new(SIGUSR1, signal_callback, c);
#endif
#ifdef SIGUSR2
    pa_signal_new(SIGUSR2, signal_callback, c);
#endif
#ifdef SIGHUP
    pa_signal_new(SIGHUP, signal_callback, c);
#endif

#ifdef OS_IS_WIN32
    win32_timer = pa_mainloop_get_api(mainloop)->time_new(pa_mainloop_get_api(mainloop), pa_gettimeofday(&win32_tv), message_cb, NULL);
#endif

    if (!conf->no_cpu_limit)
        pa_assert_se(pa_cpu_limit_init(pa_mainloop_get_api(mainloop)) == 0);

    buf = pa_strbuf_new();

#ifdef HAVE_DBUS
    pa_assert_se(dbus_threads_init_default());

    if (start_server) {
#endif
        if (conf->load_default_script_file) {
            FILE *f;

            if ((f = pa_daemon_conf_open_default_script_file(conf))) {
                r = pa_cli_command_execute_file_stream(c, f, buf, &conf->fail);
                fclose(f);
            }
        }

        if (r >= 0)
            r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);

        pa_log_error("%s", s = pa_strbuf_tostring_free(buf));
        pa_xfree(s);

        if (r < 0 && conf->fail) {
            pa_log(_("Failed to initialize daemon."));
            goto finish;
        }

        if (!c->modules || pa_idxset_size(c->modules) == 0) {
            pa_log(_("Daemon startup without any loaded modules, refusing to work."));
            goto finish;
        }
#ifdef HAVE_DBUS
    } else {
        /* When we just provide the D-Bus server lookup service, we don't want
         * any modules to be loaded. We haven't loaded any so far, so one might
         * think there's no way to contact the server, but receiving certain
         * signals could still cause modules to load. */
        conf->disallow_module_loading = TRUE;
    }
#endif

    /* We completed the initial module loading, so let's disable it
     * from now on, if requested */
    c->disallow_module_loading = !!conf->disallow_module_loading;

#ifdef HAVE_DBUS
    if (!conf->system_instance) {
        if ((server_lookup = pa_dbusobj_server_lookup_new(c))) {
            if (!(lookup_service_bus = register_dbus_name(c, DBUS_BUS_SESSION, "org.PulseAudio1")))
                goto finish;
        }
    }

    if (start_server)
        server_bus = register_dbus_name(c, conf->system_instance ? DBUS_BUS_SYSTEM : DBUS_BUS_SESSION, "org.pulseaudio.Server");
#endif

#ifdef HAVE_FORK
    if (daemon_pipe2[1] >= 0) {
        int ok = 0;
        pa_loop_write(daemon_pipe2[1], &ok, sizeof(ok), NULL);
        pa_close(daemon_pipe2[1]);
        daemon_pipe2[1] = -1;
    }
#endif

    pa_log_info(_("Daemon startup complete."));

    retval = 0;
    if (pa_mainloop_run(mainloop, &retval) < 0)
        goto finish;

    pa_log_info(_("Daemon shutdown initiated."));

finish:
#ifdef HAVE_DBUS
    if (server_bus)
        pa_dbus_connection_unref(server_bus);
    if (lookup_service_bus)
        pa_dbus_connection_unref(lookup_service_bus);
    if (server_lookup)
        pa_dbusobj_server_lookup_free(server_lookup);
#endif

    if (autospawn_fd >= 0) {
        if (autospawn_locked)
            pa_autospawn_lock_release();

        pa_autospawn_lock_done(FALSE);
    }

#ifdef OS_IS_WIN32
    if (mainloop && win32_timer)
        pa_mainloop_get_api(mainloop)->time_free(win32_timer);
#endif

    if (c) {
        /* Ensure all the modules/samples are unloaded when the core is still ref'ed,
         * as unlink callback hooks in modules may need the core to be ref'ed */
        pa_module_unload_all(c);
        pa_scache_free_all(c);

        pa_core_unref(c);
        pa_log_info(_("Daemon terminated."));
    }

    if (!conf->no_cpu_limit)
        pa_cpu_limit_done();

    pa_signal_done();

#ifdef HAVE_FORK
    /* If we have daemon_pipe[1] still open, this means we've failed after
     * the first fork, but before the second. Therefore just write to it. */
    if (daemon_pipe[1] >= 0)
        pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);
    else if (daemon_pipe2[1] >= 0)
        pa_loop_write(daemon_pipe2[1], &retval, sizeof(retval), NULL);

    pa_close_pipe(daemon_pipe2);
    pa_close_pipe(daemon_pipe);
#endif

    if (mainloop)
        pa_mainloop_free(mainloop);

    if (conf)
        pa_daemon_conf_free(conf);

    if (valid_pid_file)
        pa_pid_file_remove();

    /* This has no real purpose except making things valgrind-clean */
    pa_unset_env_recorded();

#ifdef OS_IS_WIN32
    WSACleanup();
#endif

    if (ltdl_init)
        pa_ltdl_done();

#ifdef HAVE_DBUS
    dbus_shutdown();
#endif

    return retval;
}
int main(int argc, char **argv)
{
    globus_ftp_client_handle_t			handle;
    globus_ftp_client_operationattr_t		attr;
    globus_byte_t *				buffer;
    globus_result_t				result;
    globus_ftp_client_handleattr_t		handle_attr;
    char *					src;
    char *					dst;
    int						i;
    globus_size_t				parallelism_level = 1;
    globus_ftp_control_parallelism_t		parallelism;
    globus_ftp_control_layout_t			layout;

    LTDL_SET_PRELOADED_SYMBOLS();
    globus_module_activate(GLOBUS_FTP_CLIENT_MODULE);
    globus_ftp_client_handleattr_init(&handle_attr);
    globus_ftp_client_operationattr_init(&attr);

    /* Parse local arguments */
    for(i = 1; i < argc; i++)
    {
	if(strcmp(argv[i], "-P") == 0 && i + 1 < argc)
	{
	    parallelism_level = atoi(argv[i+1]);

	    test_remove_arg(&argc, argv, &i, 1);
	}
    }
    test_parse_args(argc,
		    argv,
		    &handle_attr,
		    &attr,
		    &src,
		    &dst);
    if(parallelism_level < 1) 
    {
	parallelism_level = 1;
    }
    parallelism.mode = GLOBUS_FTP_CONTROL_PARALLELISM_FIXED;
    parallelism.fixed.size = parallelism_level;
    layout.mode = GLOBUS_FTP_CONTROL_STRIPING_BLOCKED_ROUND_ROBIN;
    layout.round_robin.block_size = 64*1024;

    globus_mutex_init(&lock, GLOBUS_NULL);
    globus_cond_init(&cond, GLOBUS_NULL);

    globus_ftp_client_operationattr_set_mode(
        &attr,
        GLOBUS_FTP_CONTROL_MODE_EXTENDED_BLOCK);
    globus_ftp_client_operationattr_set_parallelism(&attr,
					            &parallelism);

    globus_ftp_client_operationattr_set_layout(&attr,
				               &layout);

    globus_ftp_client_handle_init(&handle,  &handle_attr);

    done = GLOBUS_FALSE;
    result = globus_ftp_client_put(&handle,
				   dst,
				   &attr,
				   GLOBUS_NULL,
				   done_cb,
				   0);
    globus_mutex_lock(&lock);
    if(result != GLOBUS_SUCCESS)
    {
	globus_object_t * err;
	err = globus_error_get(result);
	fprintf(stderr, "%s", globus_object_printable_to_string(err));
	done = GLOBUS_TRUE;
    }
    else
    {
	int rc=1;
	int i;

	for(i = 0; i < parallelism_level && rc != 0; i++)
	{
	    buffer = malloc(MYSIZE);

	    rc = read(0, buffer, MYSIZE);
	    globus_ftp_client_register_write(
		&handle,
		buffer,
		rc,
		global_offset,
		rc == 0,
		data_cb,
		0);
	    global_offset += rc;
	}
    }
    while(!done)
    {
	globus_cond_wait(&cond, &lock);
    }
    globus_mutex_unlock(&lock);

    globus_ftp_client_handle_destroy(&handle);
    globus_module_deactivate_all();
    
    if(test_abort_count && error)
    {
	return 0;
    }
    return error;
}
示例#20
0
/*
 *	Parse the module config sections, and load
 *	and call each module's init() function.
 *
 *	Libtool makes your life a LOT easier, especially with libltdl.
 *	see: http://www.gnu.org/software/libtool/
 */
int setup_modules(void)
{
	int comp;
	CONF_SECTION *cs;

	/*
	 *  FIXME: This should be pulled from somewhere else.
	 */
	const char *filename="radiusd.conf";

	/*
	 *	No current list of modules: Go initialize libltdl.
	 */
	if (!module_list) {
		/*
		 *	Set the default list of preloaded symbols.
		 *	This is used to initialize libltdl's list of
		 *	preloaded modules. 
		 *
		 *	i.e. Static modules.
		 */
		LTDL_SET_PRELOADED_SYMBOLS();

		if (lt_dlinit() != 0) {
			radlog(L_ERR|L_CONS, "Failed to initialize libraries: %s\n",
					lt_dlerror());
			exit(1); /* FIXME */
			
		}

		/*
		 *	Set the search path to ONLY our library directory.
		 *	This prevents the modules from being found from
		 *	any location on the disk.
		 */
		lt_dlsetsearchpath(radlib_dir);
		
		DEBUG2("Module: Library search path is %s",
				lt_dlgetsearchpath());

		/*
		 *	Initialize the components.
		 */
		for (comp = 0; comp < RLM_COMPONENT_COUNT; comp++) {
			components[comp] = NULL;
		}

	} else {
		detach_modules();
	}

	/*
	 *	Create any DICT_VALUE's for the types.  See
	 *	'doc/configurable_failover' for examples of 'authtype'
	 *	used to create new Auth-Type values.  In order to
	 *	let the user create new names, we've got to look for
	 *	those names, and create DICT_VALUE's for them.
	 */
	for (comp = 0; section_type_value[comp].section != NULL; comp++) {
		const char	*name2;
		DICT_ATTR	*dattr;
		DICT_VALUE	*dval;
		CONF_SECTION	*sub, *next;
		CONF_PAIR	*cp;

		/*
		 *  Big-time YUCK
		 */
		static int my_value = 32767;

		cs = cf_section_find(section_type_value[comp].section);

		if (!cs) continue;

		sub = NULL;
		do {
			/*
			 *	See if there's a sub-section by that
			 *	name.
			 */
			next = cf_subsection_find_next(cs, sub,
						      section_type_value[comp].typename);

			/*
			 *	Allow some old names, too.
			 */
			if (!next && (comp <= 4)) {
				
				next = cf_subsection_find_next(cs, sub,
							       old_section_type_value[comp].typename);
			}
			sub = next;

			/*
			 *	If so, look for it to define a new
			 *	value.
			 */
			name2 = cf_section_name2(sub);
			if (!name2) continue;


			/*
			 *	If the value already exists, don't
			 *	create it again.
			 */
			dval = dict_valbyname(section_type_value[comp].attr,
					      name2);
			if (dval) continue;

			/*
       			 *	Find the attribute for the value.
			 */
			dattr = dict_attrbyvalue(section_type_value[comp].attr);
			if (!dattr) continue;

			/*
			 *	Finally, create the new attribute.
			 */
			if (dict_addvalue(name2, dattr->name, my_value++) < 0) {
				radlog(L_ERR, "%s", librad_errstr);
				exit(1);
			}
		} while (sub != NULL);

		/*
		 *	Loop over the non-sub-sections, too.
		 */
		cp = NULL;
		do {
			/*
			 *	See if there's a conf-pair by that
			 *	name.
			 */
			cp = cf_pair_find_next(cs, cp, NULL);
			if (!cp) break;


			/*
			 *	If the value already exists, don't
			 *	create it again.
			 */
			name2 = cf_pair_attr(cp);
			dval = dict_valbyname(section_type_value[comp].attr,
					      name2);
			if (dval) continue;

			/*
       			 *	Find the attribute for the value.
			 */
			dattr = dict_attrbyvalue(section_type_value[comp].attr);
			if (!dattr) continue;

			/*
			 *	Finally, create the new attribute.
			 */
			if (dict_addvalue(name2, dattr->name, my_value++) < 0) {
				radlog(L_ERR, "%s", librad_errstr);
				exit(1);
			}
		} while (cp != NULL);
	} /* over the sections which can have redundent sub-sections */
int
main(
    int					argc,
    char *				argv[])
{
    globus_io_handle_t			listener;
    globus_io_handle_t			server_handle;
    globus_io_handle_t			client_handle;
    globus_io_attr_t			attr;
    unsigned short			port = 0;
    globus_result_t			result;
    globus_io_secure_authorization_data_t
					auth_data;
    globus_l_io_authorization_test_monitor_t
					monitor;
    char				greeting[] = "Hello, my friend.";
    char 				reply_buffer[256];
    globus_size_t			written;
    globus_size_t			read_amt;

    LTDL_SET_PRELOADED_SYMBOLS();

    globus_module_activate(GLOBUS_COMMON_MODULE);
    globus_module_activate(GLOBUS_IO_MODULE);

    /* Initialize monitor */
    globus_mutex_init(&monitor.mutex, GLOBUS_NULL);
    globus_cond_init(&monitor.cond, GLOBUS_NULL);
    monitor.connected = GLOBUS_FALSE;

    /* Prepare attributes */
    globus_io_secure_authorization_data_initialize(&auth_data);
    globus_io_tcpattr_init(&attr);
    globus_io_attr_set_secure_authentication_mode(
	    &attr,
	    GLOBUS_IO_SECURE_AUTHENTICATION_MODE_GSSAPI,
	    GSS_C_NO_CREDENTIAL);


    if(argc >= 2)
    {
	if(! strcasecmp(argv[1], "self"))
	{
	    globus_io_attr_set_secure_authorization_mode(
		    &attr,
		    GLOBUS_IO_SECURE_AUTHORIZATION_MODE_SELF,
		    &auth_data);
	}
	else if(argc > 2 && ! strcasecmp(argv[1], "identity") )
	{
	    globus_io_secure_authorization_data_set_identity(&auth_data,
		                                             argv[2]);
	    globus_io_attr_set_secure_authorization_mode(
		    &attr,
		    GLOBUS_IO_SECURE_AUTHORIZATION_MODE_IDENTITY,
		    &auth_data);
	}
	else if(! strcasecmp(argv[1], "callback"))
	{
	    globus_io_secure_authorization_data_set_callback(
		    &auth_data,
		    globus_l_io_authorization_test_callback,
		    GLOBUS_NULL);

	    globus_io_attr_set_secure_authorization_mode(
		    &attr,
		    GLOBUS_IO_SECURE_AUTHORIZATION_MODE_CALLBACK,
		    &auth_data);
	}
	else if(! strcasecmp(argv[1], "-callback"))
	{
	    globus_io_secure_authorization_data_set_callback(
		    &auth_data,
		    globus_l_io_authorization_test_callback,
		    (void *) 0x1);

	    globus_io_attr_set_secure_authorization_mode(
		    &attr,
		    GLOBUS_IO_SECURE_AUTHORIZATION_MODE_CALLBACK,
		    &auth_data);
	}
	else
	{
	    goto no_authorization_mode;
	}
    }
    else
    {
	goto no_authorization_mode;
    }

    result = globus_io_tcp_create_listener(
	    &port,
	    -1,
	    &attr,
	    &listener);

    if(result != GLOBUS_SUCCESS)
    {
        char *msg = globus_error_print_friendly(globus_error_peek(result));
	globus_libc_fprintf(stderr, "# Could not create listener: %s\n", msg);
        free(msg);

	goto error_exit;
    }

    result = globus_io_tcp_register_connect(
	    "localhost",
	    port,
	    &attr,
	    globus_l_io_authorization_test_connect_callback,
	    &monitor,
	    &client_handle);

    if(result != GLOBUS_SUCCESS)
    {
	globus_libc_printf("# Could not register connect\n");
	goto error_exit;
    }

    result = globus_io_tcp_listen(&listener);
    if(result != GLOBUS_SUCCESS)
    {
	globus_libc_printf("# Could not listen for connections\n");
	goto error_exit;
    }
    result = globus_io_tcp_accept(&listener,
	                          &attr,
			          &server_handle);
    if(result != GLOBUS_SUCCESS)
    {
	if(strcasecmp(argv[1], "-callback") == 0)
	{
	    globus_module_deactivate_all();
	    exit(0);
	}
	else
	{
	    globus_libc_printf("# Could not accept connection\n");
	    goto error_exit;
	}
    }

    globus_mutex_lock(&monitor.mutex);
    while(! monitor.connected)
    {
	globus_cond_wait(&monitor.cond, &monitor.mutex);
    }

    result = globus_io_close(&listener);
    if(result != GLOBUS_SUCCESS)
    {
	globus_libc_printf("# Could not close listener\n");
	goto error_exit;
    }

    result = globus_io_write(&server_handle,
			     greeting,
		             sizeof(greeting),
		             &written);
    if(result != GLOBUS_SUCCESS)
    {
	globus_libc_printf("# Could not write greeting\n");
	goto error_exit;
    }
    result = globus_io_close(&server_handle);
    if(result != GLOBUS_SUCCESS)
    {
	globus_libc_printf("# Could not close server\n");
	goto error_exit;
    }
    result = globus_io_read(&client_handle,
	                    reply_buffer,
		            sizeof(reply_buffer),
		            sizeof(reply_buffer),
		            &read_amt);
    if(result != GLOBUS_SUCCESS)
    {
	globus_object_t * err;

	err = globus_error_get(result);

	if(! globus_io_eof(err))
	{
	    globus_libc_printf("# Could not read greeting\n");
	    goto error_exit;
	}
    }
    result = globus_io_close(&client_handle);
    if(result != GLOBUS_SUCCESS)
    {
	globus_libc_printf("# Could not close client\n");
	goto error_exit;
    }

    if(!memcmp(greeting, reply_buffer, sizeof(greeting)) == 0)
    {
	result = GLOBUS_FAILURE;
        goto error_exit;
    }

    globus_module_deactivate_all();
    exit(0);


no_authorization_mode:
    globus_libc_printf(
    "Usage: %s AUTHORIZATION\n"
    "      AUTHORIZATION is one of\n"
    "      self                 use Globus I/O's self-authorization mode\n"
    "      identity \"subject\"   use Globus I/O's subject-based authorization\n"
    "      callback             use Globus I/O's callback authorization\n"
    "      -callback            use Globus I/O's callback authorization with\n"
    "                           a failure callback\n",
    argv[0]);

error_exit:
    globus_module_deactivate_all();
    exit(1);
}
int main(
    int                                 argc,
    char *                              argv[])
{
    int					rc;
    char *				server_callback_contact;
    globus_byte_t *			msg;
    globus_size_t			msgsize;
    monitor_t 				monitor;

    LTDL_SET_PRELOADED_SYMBOLS();
    printf("1..1\n");
    rc = globus_module_activate(GLOBUS_GRAM_PROTOCOL_MODULE);
    if(rc != GLOBUS_SUCCESS)
    {
	return rc;
    }

    globus_mutex_init(&monitor.mutex, GLOBUS_NULL);
    globus_mutex_lock(&monitor.mutex);
    globus_cond_init(&monitor.cond, GLOBUS_NULL);
    monitor.done = GLOBUS_FALSE;
    monitor.status_request[0] = "status";
    monitor.status_request[1] = NULL;
    monitor.job_status[1] = GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE;
    monitor.failure_code[1] = 0;
    monitor.job_failure_code[1] = 0;
    monitor.error = 0;

    rc = globus_gram_protocol_allow_attach(
	    &server_callback_contact,
	    server_callback,
	    &monitor);

    if(rc != GLOBUS_SUCCESS)
    {
	goto unlock_error;
    }

    rc = globus_gram_protocol_pack_status_request(
	    monitor.status_request[0],
	    &msg,
	    &msgsize);

    if(rc != GLOBUS_SUCCESS)
    {
	goto disallow_error;
    }

    if (argc > 1 && !strcmp(argv[1], "invalid_host"))
    {
        globus_free(server_callback_contact);
        server_callback_contact = globus_libc_strdup(
                "https://bogushost.globus.org:7777/7777");
    }

    rc = globus_gram_protocol_post(server_callback_contact,
	                           GLOBUS_NULL,
				   GLOBUS_NULL,
				   msg,
				   msgsize,
				   client_callback,
				   &monitor);
    if(rc != GLOBUS_SUCCESS)
    {
	goto free_msg_error;
    }

    while(!monitor.done)
    {
	globus_cond_wait(&monitor.cond, &monitor.mutex);
    }

    globus_libc_free(msg);
    globus_mutex_unlock(&monitor.mutex);
    globus_mutex_destroy(&monitor.mutex);
    globus_cond_destroy(&monitor.cond);

    if(monitor.job_status[0] != monitor.job_status[1] ||
       monitor.failure_code[0] != monitor.failure_code[1] ||
       monitor.job_failure_code[0] != monitor.job_failure_code[1] ||
       strcmp(monitor.status_request[0], monitor.status_request[1]) != 0)
    {
        printf("not ");
        rc = EXIT_FAILURE;
    }
    globus_libc_free(monitor.status_request[1]);
    globus_gram_protocol_callback_disallow(server_callback_contact);
    globus_module_deactivate(GLOBUS_GRAM_PROTOCOL_MODULE);

    printf("ok - io-test\n");

    return rc;

free_msg_error:
    globus_libc_free(msg);
disallow_error:
    globus_gram_protocol_callback_disallow(server_callback_contact);
unlock_error:
    globus_mutex_unlock(&monitor.mutex);
    globus_mutex_destroy(&monitor.mutex);
    globus_cond_destroy(&monitor.cond);
    globus_module_deactivate(GLOBUS_GRAM_PROTOCOL_MODULE);
error_out:
    printf("not ok - io-test %d\n", rc);
    return rc;
}
int main(int argc,
	 char *argv[])
{
    globus_ftp_client_handle_t			handle;
    globus_ftp_client_operationattr_t 		attr;
    globus_ftp_client_handleattr_t		handle_attr;
    globus_byte_t				buffer[SIZE];
    globus_size_t				buffer_length = sizeof(buffer);
    globus_result_t				result;
    globus_off_t				size;
    char *					src;
    char *					dst;

    LTDL_SET_PRELOADED_SYMBOLS();
    globus_module_activate(GLOBUS_FTP_CLIENT_MODULE);
    globus_ftp_client_handleattr_init(&handle_attr);
    globus_ftp_client_operationattr_init(&attr);
    
    test_parse_args(argc, 
		    argv,
		    &handle_attr,
		    &attr,
		    &src,
		    &dst);

    globus_mutex_init(&lock, GLOBUS_NULL);
    globus_cond_init(&cond, GLOBUS_NULL);

    globus_ftp_client_handle_init(&handle, &handle_attr);

    done = GLOBUS_FALSE;
    result = globus_ftp_client_size(&handle,
				   src,
				   &attr,
				   &size,
				   done_cb,
				   0);
    if(result != GLOBUS_SUCCESS)
    {
	fprintf(stderr, "%s", globus_object_printable_to_string(globus_error_get(result)));
	error = GLOBUS_TRUE;
	done = GLOBUS_TRUE;
    }
    globus_mutex_lock(&lock);
    while(!done)
    {
	globus_cond_wait(&cond, &lock);
    }
    globus_mutex_unlock(&lock);

    globus_ftp_client_handle_destroy(&handle);

    globus_module_deactivate_all();

    if(test_abort_count && error)
    {
	return 0;
    }
    if(error == GLOBUS_SUCCESS)
    {
	printf("%"GLOBUS_OFF_T_FORMAT"\n", size);
    }
    return error;
}
int main(int argc, char **argv)
{
    globus_ftp_client_handle_t			handle;
    globus_ftp_client_operationattr_t		attr;
    globus_result_t				result;
    globus_ftp_client_handleattr_t		handle_attr;
    char *					src;
    char *					dst;

    LTDL_SET_PRELOADED_SYMBOLS();
    globus_module_activate(GLOBUS_FTP_CLIENT_MODULE);
    globus_ftp_client_handleattr_init(&handle_attr);
    globus_mutex_init(&lock, GLOBUS_NULL);
    globus_cond_init(&cond, GLOBUS_NULL);

    globus_ftp_client_operationattr_init(&attr);

    test_parse_args(argc,
		    argv,
		    &handle_attr,
		    &attr,
		    &src,
		    &dst);

    globus_ftp_client_handle_init(&handle,  &handle_attr);

    done = GLOBUS_FALSE;
    result = globus_ftp_client_third_party_transfer(&handle,
						    src,
						    &attr,
						    dst,
						    &attr,
						    GLOBUS_NULL,
						    done_cb,
						    0);
    if(result != GLOBUS_SUCCESS)
    {
	globus_object_t * err;
	char * tmpstr;
	err = globus_error_get(result);
	tmpstr = globus_object_printable_to_string(err);
	fprintf(stderr, "Error: %s", tmpstr);
	globus_object_free(err);
	globus_libc_free(tmpstr);
	error = GLOBUS_TRUE;
	done = GLOBUS_TRUE;
    }
    globus_mutex_lock(&lock);
    while(!done)
    {
	globus_cond_wait(&cond, &lock);
    }
    globus_mutex_unlock(&lock);

    globus_ftp_client_handle_destroy(&handle);
    globus_module_deactivate_all();

    if(test_abort_count && error)
    {
	return 0;
    }
    return error;
}
int main(int argc, char *argv[])
{
    char *                              callback_contact;
    char *                              job_contact;
    char *                              rm_contact;
    monitor_t                           monitor;
    int                                 rc = 0;

    LTDL_SET_PRELOADED_SYMBOLS();

    printf("1..1\n");
    rm_contact = getenv("CONTACT_STRING");

    if (argc == 2)
    {
        rm_contact = argv[1];
    }

    if (rm_contact == NULL)
    {
        fprintf(stderr, "Usage: %s resource-manager-contact\n", argv[0]);
        exit(1);
    }

    rc = globus_module_activate(GLOBUS_COMMON_MODULE);
    if(rc)
    {
        goto end;
    }
    rc = globus_module_activate(GLOBUS_GRAM_CLIENT_MODULE);
    if(rc)
    {
        goto disable_modules;
    }

    globus_mutex_init(&monitor.mutex ,GLOBUS_NULL);
    globus_cond_init(&monitor.cond, GLOBUS_NULL);
    monitor.state = GLOBUS_GRAM_PROTOCOL_JOB_STATE_PENDING;

    rc = globus_gram_client_callback_allow(gram_state_callback,
                                           &monitor,
                                           &callback_contact);
    if(rc != GLOBUS_SUCCESS)
    {
        fprintf(stderr,
                "Error creating callback contact %s.\n",
                globus_gram_client_error_string(rc));

        goto error_exit;
    }

    globus_mutex_lock(&monitor.mutex);
    rc = globus_gram_client_job_request(
            rm_contact,
            "&(executable=/bin/sleep)(arguments=300)",
            GLOBUS_GRAM_PROTOCOL_JOB_STATE_ALL,
            callback_contact,
            &job_contact);

    if(rc != GLOBUS_SUCCESS)
    {
        fprintf(stderr,
                "Error submitting job request %s.\n",
                globus_gram_client_error_string(rc));

        goto destroy_callback_contact;
    }

    while(monitor.state != GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE &&
          monitor.state != GLOBUS_GRAM_PROTOCOL_JOB_STATE_FAILED &&
          monitor.state != GLOBUS_GRAM_PROTOCOL_JOB_STATE_DONE)
    {
        globus_cond_wait(&monitor.cond, &monitor.mutex);
    }

    if(monitor.state == GLOBUS_GRAM_PROTOCOL_JOB_STATE_ACTIVE)
    {
        rc = globus_gram_client_job_cancel(job_contact);
        if(rc != GLOBUS_SUCCESS)
        {
            fprintf(stderr,
                    "Error cancelling job %s.\n",
                    globus_gram_client_error_string(rc));

            goto destroy_callback_contact;
        }
    }

    while(monitor.state != GLOBUS_GRAM_PROTOCOL_JOB_STATE_DONE &&
          monitor.state != GLOBUS_GRAM_PROTOCOL_JOB_STATE_FAILED)
    {
        globus_cond_wait(&monitor.cond, &monitor.mutex);
    }
    rc = monitor.errorcode;
    if(rc == GLOBUS_GRAM_PROTOCOL_ERROR_USER_CANCELLED)
    {
        rc = GLOBUS_SUCCESS;
    }
destroy_callback_contact:
    globus_mutex_unlock(&monitor.mutex);
    globus_gram_client_callback_disallow(callback_contact);
    free(callback_contact);
    free(job_contact);
error_exit:
    globus_mutex_destroy(&monitor.mutex);
    globus_cond_destroy(&monitor.cond);
disable_modules:
    globus_module_deactivate_all();
end:
    printf("%s - cancel-test\n", rc == 0 ? "ok" : "not ok");
    return rc;
}
示例#26
0
int main(int argc, char *argv[])
{
	char *cmd_buf;
	int ret;
	int ret_init;
	size_t n;
	char *configfilename;
	configfile_t *configfile;
	otts_synth_plugin_t *synth;
	char *status_info = NULL;

	g_thread_init(NULL);
	init_logging();
	open_log("stderr", 3);

	synth = synth_plugin_get();

	/* Initialize ltdl's list of preloaded audio backends. */
	LTDL_SET_PRELOADED_SYMBOLS();
	module_num_dc_options = 0;
	module_audio_id = 0;

	if (argc >= 2) {
		configfilename = g_strdup(argv[1]);
	} else {
		configfilename = NULL;
	}

	ret = synth->load();
	if (ret == -1)
		synth->close(1);

	if (configfilename != NULL) {
		/* Add the LAST option */
		module_dc_options = module_add_config_option(module_dc_options,
							     &module_num_dc_options,
							     "", 0, NULL, NULL,
							     0);

		configfile =
		    dotconf_create(configfilename, module_dc_options, 0,
				   CASE_INSENSITIVE);
		if (configfile) {
			if (dotconf_command_loop(configfile) == 0) {
				log_msg(OTTS_LOG_CRIT,
					"Error reading config file\n");
				synth->close(1);
			}
			dotconf_cleanup(configfile);
			log_msg(OTTS_LOG_NOTICE,
				"Configuration (pre) has been read from \"%s\"\n",
				configfilename);

			g_free(configfilename);
		} else {
			log_msg(OTTS_LOG_ERR,
				"Can't read specified config file!\n");
		}
	} else {
		log_msg(OTTS_LOG_WARN,
			"No config file specified, using defaults...\n");
	}

	ret_init = synth->init(&status_info);

	if (status_info == NULL) {
		status_info = g_strdup("unknown, was not set by module");
	}

	cmd_buf = NULL;
	n = 0;
	ret = otts_getline(&cmd_buf, &n, stdin);
	if (ret == -1) {
		log_msg(OTTS_LOG_CRIT,
			"Broken pipe when reading INIT, exiting... \n");
		synth->close(2);
	}

	if (!strcmp(cmd_buf, "INIT\n")) {
		if (ret_init != 0) {
			printf("399-%s\n", status_info);
			ret = printf("%s\n", "399 ERR CANT INIT MODULE");
			g_free(status_info);
			return -1;
		}

		printf("299-%s\n", status_info);
		ret = printf("%s\n", "299 OK LOADED SUCCESSFULLY");

		if (ret < 0) {
			log_msg(OTTS_LOG_CRIT, "Broken pipe, exiting...\n");
			synth->close(2);
		}
		fflush(stdout);
	} else {
		log_msg(OTTS_LOG_ERR,
			"ERROR: Wrong communication from module client: didn't call INIT\n");
		synth->close(3);
	}

	g_free(status_info);
	xfree(cmd_buf);

	while (1) {
		cmd_buf = NULL;
		n = 0;
		ret = otts_getline(&cmd_buf, &n, stdin);
		if (ret == -1) {
			log_msg(OTTS_LOG_CRIT, "Broken pipe, exiting... \n");
			synth->close(2);
		}

		log_msg(OTTS_LOG_INFO, "CMD: <%s>", cmd_buf);

		dispatch_cmd(synth, cmd_buf);

		xfree(cmd_buf);
	}
}
int main(int argc, char **argv)
{
    globus_ftp_client_handle_t			handle;
    globus_ftp_client_operationattr_t		attr;
    globus_result_t				result;
    int						i;
    globus_ftp_client_handleattr_t		handle_attr;
    char *					src;
    char *					dst;

    LTDL_SET_PRELOADED_SYMBOLS();
    globus_module_activate(GLOBUS_FTP_CLIENT_MODULE);

    globus_ftp_client_handleattr_init(&handle_attr);
    globus_ftp_client_operationattr_init(&attr);

    globus_mutex_init(&lock, GLOBUS_NULL);
    globus_cond_init(&cond, GLOBUS_NULL);


    test_parse_args(argc,
		    argv,
		    &handle_attr,
		    &attr,
		    &src,
		    &dst);

    globus_ftp_client_handle_init(&handle,  &handle_attr);
    globus_ftp_client_handle_cache_url_state(&handle,
	                                     src);
    globus_ftp_client_handle_cache_url_state(&handle,
	                                     dst);
    for (i = 0; i < 2; i++)
    {
	done = GLOBUS_FALSE;
	result = globus_ftp_client_third_party_transfer(&handle,
							src,
				                        &attr,
							dst,
				                        &attr,
							GLOBUS_NULL,
				                        done_cb,
				                        0);
	if(result != GLOBUS_SUCCESS)
	{
	    done = GLOBUS_TRUE;
	}

	globus_mutex_lock(&lock);
	while(!done)
	{
	    globus_cond_wait(&cond, &lock);
	}
	globus_mutex_unlock(&lock);
    }

    globus_ftp_client_handle_destroy(&handle);
    globus_module_deactivate_all();

    if(test_abort_count && error)
    {
	return 0;
    }

    return error;
}
示例#28
0
文件: main.c 项目: jctemkin/xen-audio
int main(int argc, char *argv[]) {
    pa_core *c = NULL;
    pa_strbuf *buf = NULL;
    pa_daemon_conf *conf = NULL;
    pa_mainloop *mainloop = NULL;
    char *s;
    int r = 0, retval = 1, d = 0;
    pa_bool_t valid_pid_file = FALSE;
    pa_bool_t ltdl_init = FALSE;
    int passed_fd = -1;
    const char *e;
#ifdef HAVE_FORK
    int daemon_pipe[2] = { -1, -1 };
#endif
#ifdef OS_IS_WIN32
    pa_time_event *win32_timer;
    struct timeval win32_tv;
#endif
    int autospawn_fd = -1;
    pa_bool_t autospawn_locked = FALSE;
#ifdef HAVE_DBUS
    pa_dbus_connection *dbus = NULL;
#endif

    pa_log_set_ident("pulseaudio");
    pa_log_set_level(PA_LOG_NOTICE);
    pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);

#if defined(__linux__) && defined(__OPTIMIZE__)
    /*
       Disable lazy relocations to make usage of external libraries
       more deterministic for our RT threads. We abuse __OPTIMIZE__ as
       a check whether we are a debug build or not. This all is
       admittedly a bit snake-oilish.
    */

    if (!getenv("LD_BIND_NOW")) {
        char *rp;
        char *canonical_rp;

        /* We have to execute ourselves, because the libc caches the
         * value of $LD_BIND_NOW on initialization. */

        pa_set_env("LD_BIND_NOW", "1");

        if ((canonical_rp = pa_realpath(PA_BINARY))) {

            if ((rp = pa_readlink("/proc/self/exe"))) {

                if (pa_streq(rp, canonical_rp))
                    pa_assert_se(execv(rp, argv) == 0);
                else
                    pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);

                pa_xfree(rp);

            } else
                pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");

            pa_xfree(canonical_rp);

        } else
            pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
    }
#endif

    if ((e = getenv("PULSE_PASSED_FD"))) {
        passed_fd = atoi(e);

        if (passed_fd <= 2)
            passed_fd = -1;
    }

    /* We might be autospawned, in which case have no idea in which
     * context we have been started. Let's cleanup our execution
     * context as good as possible */

    pa_reset_personality();
    pa_drop_root();
    pa_close_all(passed_fd, -1);
    pa_reset_sigs(-1);
    pa_unblock_sigs(-1);
    pa_reset_priority();

    setlocale(LC_ALL, "");
    pa_init_i18n();

    conf = pa_daemon_conf_new();

    if (pa_daemon_conf_load(conf, NULL) < 0)
        goto finish;

    if (pa_daemon_conf_env(conf) < 0)
        goto finish;

    if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
        pa_log(_("Failed to parse command line."));
        goto finish;
    }

    pa_log_set_level(conf->log_level);
    pa_log_set_target(conf->auto_log_target ? PA_LOG_STDERR : conf->log_target);
    if (conf->log_meta)
        pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
    if (conf->log_time)
        pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
    pa_log_set_show_backtrace(conf->log_backtrace);

    LTDL_SET_PRELOADED_SYMBOLS();
    pa_ltdl_init();
    ltdl_init = TRUE;

    if (conf->dl_search_path)
        lt_dlsetsearchpath(conf->dl_search_path);

#ifdef OS_IS_WIN32
    {
        WSADATA data;
        WSAStartup(MAKEWORD(2, 0), &data);
    }
#endif

    pa_random_seed();

    switch (conf->cmd) {
        case PA_CMD_DUMP_MODULES:
            pa_dump_modules(conf, argc-d, argv+d);
            retval = 0;
            goto finish;

        case PA_CMD_DUMP_CONF: {

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            s = pa_daemon_conf_dump(conf);
            fputs(s, stdout);
            pa_xfree(s);
            retval = 0;
            goto finish;
        }

        case PA_CMD_DUMP_RESAMPLE_METHODS: {
            int i;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            for (i = 0; i < PA_RESAMPLER_MAX; i++)
                if (pa_resample_method_supported(i))
                    printf("%s\n", pa_resample_method_to_string(i));

            retval = 0;
            goto finish;
        }

        case PA_CMD_HELP :
            pa_cmdline_help(argv[0]);
            retval = 0;
            goto finish;

        case PA_CMD_VERSION :

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
            retval = 0;
            goto finish;

        case PA_CMD_CHECK: {
            pid_t pid;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
                pa_log_info(_("Daemon not running"));
            else {
                pa_log_info(_("Daemon running as PID %u"), pid);
                retval = 0;
            }

            goto finish;

        }
        case PA_CMD_KILL:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
                pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
            else
                retval = 0;

            goto finish;

        case PA_CMD_CLEANUP_SHM:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_shm_cleanup() >= 0)
                retval = 0;

            goto finish;

        default:
            pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
    }

    if (d < argc) {
        pa_log("Too many arguments.\n");
        goto finish;
    }

    if (getuid() == 0 && !conf->system_instance)
        pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
    else if (getuid() != 0 && conf->system_instance) {
        pa_log(_("Root privileges required."));
        goto finish;
    }

    if (conf->cmd == PA_CMD_START && conf->system_instance) {
        pa_log(_("--start not supported for system instances."));
        goto finish;
    }

    if (conf->system_instance && !conf->disallow_exit)
        pa_log_warn(_("Running in system mode, but --disallow-exit not set!"));

    if (conf->system_instance && !conf->disallow_module_loading)
        pa_log_warn(_("Running in system mode, but --disallow-module-loading not set!"));

    if (conf->system_instance && !conf->disable_shm) {
        pa_log_notice(_("Running in system mode, forcibly disabling SHM mode!"));
        conf->disable_shm = TRUE;
    }

    if (conf->system_instance && conf->exit_idle_time >= 0) {
        pa_log_notice(_("Running in system mode, forcibly disabling exit idle time!"));
        conf->exit_idle_time = -1;
    }

    if (conf->cmd == PA_CMD_START) {
        /* If we shall start PA only when it is not running yet, we
         * first take the autospawn lock to make things
         * synchronous. */

        if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
            pa_log("Failed to initialize autospawn lock");
            goto finish;
        }

        if ((pa_autospawn_lock_acquire(TRUE) < 0)) {
            pa_log("Failed to acquire autospawn lock");
            goto finish;
        }

        autospawn_locked = TRUE;
    }

    if (conf->daemonize) {
        pid_t child;
        int tty_fd;

        if (pa_stdio_acquire() < 0) {
            pa_log(_("Failed to acquire stdio."));
            goto finish;
        }

#ifdef HAVE_FORK
        if (pipe(daemon_pipe) < 0) {
            pa_log(_("pipe failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if ((child = fork()) < 0) {
            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if (child != 0) {
            ssize_t n;
            /* Father */

            pa_assert_se(pa_close(daemon_pipe[1]) == 0);
            daemon_pipe[1] = -1;

            if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {

                if (n < 0)
                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));

                retval = 1;
            }

            if (retval)
                pa_log(_("Daemon startup failed."));
            else
                pa_log_info(_("Daemon startup successful."));

            goto finish;
        }

        if (autospawn_fd >= 0) {
            /* The lock file is unlocked from the parent, so we need
             * to close it in the child */

            pa_autospawn_lock_release();
            pa_autospawn_lock_done(TRUE);

            autospawn_locked = FALSE;
            autospawn_fd = -1;
        }

        pa_assert_se(pa_close(daemon_pipe[0]) == 0);
        daemon_pipe[0] = -1;
#endif

        if (conf->auto_log_target)
            pa_log_set_target(PA_LOG_SYSLOG);

#ifdef HAVE_SETSID
        setsid();
#endif
#ifdef HAVE_SETPGID
        setpgid(0,0);
#endif

#ifndef OS_IS_WIN32
        pa_close(0);
        pa_close(1);
        pa_close(2);

        pa_assert_se(open("/dev/null", O_RDONLY) == 0);
        pa_assert_se(open("/dev/null", O_WRONLY) == 1);
        pa_assert_se(open("/dev/null", O_WRONLY) == 2);
#else
        FreeConsole();
#endif

#ifdef SIGTTOU
        signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
        signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
        signal(SIGTSTP, SIG_IGN);
#endif

#ifdef TIOCNOTTY
        if ((tty_fd = open("/dev/tty", O_RDWR)) >= 0) {
            ioctl(tty_fd, TIOCNOTTY, (char*) 0);
            pa_assert_se(pa_close(tty_fd) == 0);
        }
#endif
    }

    pa_set_env_and_record("PULSE_INTERNAL", "1");
    pa_assert_se(chdir("/") == 0);
    umask(0022);

#ifdef HAVE_SYS_RESOURCE_H
    set_all_rlimits(conf);
#endif
    pa_rtclock_hrtimer_enable();

    pa_raise_priority(conf->nice_level);

    if (conf->system_instance)
        if (change_user() < 0)
            goto finish;

    pa_set_env_and_record("PULSE_SYSTEM", conf->system_instance ? "1" : "0");

    pa_log_info(_("This is PulseAudio %s"), PACKAGE_VERSION);
    pa_log_debug(_("Compilation host: %s"), CANONICAL_HOST);
    pa_log_debug(_("Compilation CFLAGS: %s"), PA_CFLAGS);

    s = pa_uname_string();
    pa_log_debug(_("Running on host: %s"), s);
    pa_xfree(s);

    pa_log_debug(_("Found %u CPUs."), pa_ncpus());

    pa_log_info(_("Page size is %lu bytes"), (unsigned long) PA_PAGE_SIZE);

#ifdef HAVE_VALGRIND_MEMCHECK_H
    pa_log_debug(_("Compiled with Valgrind support: yes"));
#else
    pa_log_debug(_("Compiled with Valgrind support: no"));
#endif

    pa_log_debug(_("Running in valgrind mode: %s"), pa_yes_no(pa_in_valgrind()));

    pa_log_debug(_("Running in VM: %s"), pa_yes_no(pa_running_in_vm()));

#ifdef __OPTIMIZE__
    pa_log_debug(_("Optimized build: yes"));
#else
    pa_log_debug(_("Optimized build: no"));
#endif

#ifdef NDEBUG
    pa_log_debug(_("NDEBUG defined, all asserts disabled."));
#elif defined(FASTPATH)
    pa_log_debug(_("FASTPATH defined, only fast path asserts disabled."));
#else
    pa_log_debug(_("All asserts enabled."));
#endif

    if (!(s = pa_machine_id())) {
        pa_log(_("Failed to get machine ID"));
        goto finish;
    }
    pa_log_info(_("Machine ID is %s."), s);
    pa_xfree(s);

    if ((s = pa_session_id())) {
        pa_log_info(_("Session ID is %s."), s);
        pa_xfree(s);
    }

    if (!(s = pa_get_runtime_dir()))
        goto finish;
    pa_log_info(_("Using runtime directory %s."), s);
    pa_xfree(s);

    if (!(s = pa_get_state_dir()))
        goto finish;
    pa_log_info(_("Using state directory %s."), s);
    pa_xfree(s);

    pa_log_info(_("Using modules directory %s."), conf->dl_search_path);

    pa_log_info(_("Running in system mode: %s"), pa_yes_no(pa_in_system_mode()));

    if (pa_in_system_mode())
        pa_log_warn(_("OK, so you are running PA in system mode. Please note that you most likely shouldn't be doing that.\n"
                      "If you do it nonetheless then it's your own fault if things don't work as expected.\n"
                      "Please read http://pulseaudio.org/wiki/WhatIsWrongWithSystemMode for an explanation why system mode is usually a bad idea."));

    if (conf->use_pid_file) {
        int z;

        if ((z = pa_pid_file_create("pulseaudio")) != 0) {

            if (conf->cmd == PA_CMD_START && z > 0) {
                /* If we are already running and with are run in
                 * --start mode, then let's return this as success. */

                retval = 0;
                goto finish;
            }

            pa_log(_("pa_pid_file_create() failed."));
            goto finish;
        }

        valid_pid_file = TRUE;
    }

    pa_disable_sigpipe();

    if (pa_rtclock_hrtimer())
        pa_log_info(_("Fresh high-resolution timers available! Bon appetit!"));
    else
        pa_log_info(_("Dude, your kernel stinks! The chef's recommendation today is Linux with high-resolution timers enabled!"));

    if (conf->lock_memory) {
#ifdef HAVE_SYS_MMAN_H
        if (mlockall(MCL_FUTURE) < 0)
            pa_log_warn("mlockall() failed: %s", pa_cstrerror(errno));
        else
            pa_log_info("Sucessfully locked process into memory.");
#else
        pa_log_warn("Memory locking requested but not supported on platform.");
#endif
    }

    pa_memtrap_install();

    if (!getenv("PULSE_NO_SIMD")) {
        pa_cpu_init_x86();
        pa_cpu_init_arm();
    }

    pa_assert_se(mainloop = pa_mainloop_new());

    if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm, conf->shm_size))) {
        pa_log(_("pa_core_new() failed."));
        goto finish;
    }

    c->default_sample_spec = conf->default_sample_spec;
    c->default_channel_map = conf->default_channel_map;
    c->default_n_fragments = conf->default_n_fragments;
    c->default_fragment_size_msec = conf->default_fragment_size_msec;
    c->exit_idle_time = conf->exit_idle_time;
    c->scache_idle_time = conf->scache_idle_time;
    c->resample_method = conf->resample_method;
    c->realtime_priority = conf->realtime_priority;
    c->realtime_scheduling = !!conf->realtime_scheduling;
    c->disable_remixing = !!conf->disable_remixing;
    c->disable_lfe_remixing = !!conf->disable_lfe_remixing;
    c->running_as_daemon = !!conf->daemonize;
    c->disallow_exit = conf->disallow_exit;
    c->flat_volumes = conf->flat_volumes;

    pa_assert_se(pa_signal_init(pa_mainloop_get_api(mainloop)) == 0);
    pa_signal_new(SIGINT, signal_callback, c);
    pa_signal_new(SIGTERM, signal_callback, c);
#ifdef SIGUSR1
    pa_signal_new(SIGUSR1, signal_callback, c);
#endif
#ifdef SIGUSR2
    pa_signal_new(SIGUSR2, signal_callback, c);
#endif
#ifdef SIGHUP
    pa_signal_new(SIGHUP, signal_callback, c);
#endif

#ifdef OS_IS_WIN32
    win32_timer = pa_mainloop_get_api(mainloop)->rtclock_time_new(pa_mainloop_get_api(mainloop), pa_gettimeofday(&win32_tv), message_cb, NULL);
#endif

    if (!conf->no_cpu_limit)
        pa_assert_se(pa_cpu_limit_init(pa_mainloop_get_api(mainloop)) == 0);

    buf = pa_strbuf_new();
    if (conf->load_default_script_file) {
        FILE *f;

        if ((f = pa_daemon_conf_open_default_script_file(conf))) {
            r = pa_cli_command_execute_file_stream(c, f, buf, &conf->fail);
            fclose(f);
        }
    }

    if (r >= 0)
        r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);

    pa_log_error("%s", s = pa_strbuf_tostring_free(buf));
    pa_xfree(s);

    /* We completed the initial module loading, so let's disable it
     * from now on, if requested */
    c->disallow_module_loading = !!conf->disallow_module_loading;

    if (r < 0 && conf->fail) {
        pa_log(_("Failed to initialize daemon."));
        goto finish;
    }

    if (!c->modules || pa_idxset_size(c->modules) == 0) {
        pa_log(_("Daemon startup without any loaded modules, refusing to work."));
        goto finish;
    }

#ifdef HAVE_FORK
    if (daemon_pipe[1] >= 0) {
        int ok = 0;
        pa_loop_write(daemon_pipe[1], &ok, sizeof(ok), NULL);
        pa_close(daemon_pipe[1]);
        daemon_pipe[1] = -1;
    }
#endif

#ifdef HAVE_DBUS
    dbus = register_dbus(c);
#endif

    pa_log_info(_("Daemon startup complete."));

    retval = 0;
    if (pa_mainloop_run(mainloop, &retval) < 0)
        goto finish;

    pa_log_info(_("Daemon shutdown initiated."));

finish:
#ifdef HAVE_DBUS
    if (dbus)
        pa_dbus_connection_unref(dbus);
#endif

    if (autospawn_fd >= 0) {
        if (autospawn_locked)
            pa_autospawn_lock_release();

        pa_autospawn_lock_done(FALSE);
    }

#ifdef OS_IS_WIN32
    if (win32_timer)
        pa_mainloop_get_api(mainloop)->time_free(win32_timer);
#endif

    if (c) {
        pa_core_unref(c);
        pa_log_info(_("Daemon terminated."));
    }

    if (!conf->no_cpu_limit)
        pa_cpu_limit_done();

    pa_signal_done();

#ifdef HAVE_FORK
    if (daemon_pipe[1] >= 0)
        pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);

    pa_close_pipe(daemon_pipe);
#endif

    if (mainloop)
        pa_mainloop_free(mainloop);

    if (conf)
        pa_daemon_conf_free(conf);

    if (valid_pid_file)
        pa_pid_file_remove();

    /* This has no real purpose except making things valgrind-clean */
    pa_unset_env_recorded();

#ifdef OS_IS_WIN32
    WSACleanup();
#endif

    if (ltdl_init)
        pa_ltdl_done();

#ifdef HAVE_DBUS
    dbus_shutdown();
#endif

    return retval;
}