Ejemplo n.º 1
0
Archivo: nope.c Proyecto: amtjre/nope.c
int main(void)
{
    default_port = DEFAULT_PORT;

    int listenfd;

    char *pPort = getenv("PORT");

    if (pPort != NULL)
        default_port = (u_short) strtol(pPort, (char **)NULL, 10);

    listenfd = open_listenfd(default_port);
    if (listenfd > 0) {
        dbgprintf("listen on port %d, fd is %d\n", default_port, listenfd);
    } else {
        perror("ERROR");
        exit(listenfd);
    }
    /*Ignore SIGPIPE signal, so if browser cancels the request, it won't kill the whole process. */
    signal(SIGPIPE, SIG_IGN);

#ifdef NOPE_THREADS
    struct rlimit limit;

    limit.rlim_cur = MAX_NO_FDS * 4;
    limit.rlim_max = MAX_NO_FDS * 4;

    setrlimit(RLIMIT_NOFILE, &limit);

    /* Get max number of files. */
    getrlimit(RLIMIT_NOFILE, &limit);

    dbgprintf("The soft limit is %llu\n", limit.rlim_cur);
    dbgprintf("The hard limit is %llu\n", limit.rlim_max);
    initialize_threads();
#endif

#ifdef NOPE_PROCESSES
    for (i = 0; i < NOPE_PROCESSES; i++) {
        int pid = fork();
        if (pid == 0) {         //  child
            select_loop(listenfd);
        } else if (pid > 0) {   //  parent
            dbgprintf("child pid is %d\n", pid);
        } else {
            perror("fork");
        }
    }
#else                           /* Non-blocking if single processes */
    if (FCNTL_NONBLOCK(listenfd) < 0)
        perror("fcntl");
#endif

    select_loop(listenfd);
    return 0;
}
Ejemplo n.º 2
0
int		svr_start(t_game *game)
{
  int		svr_sock;
  int		result;
  t_select	slt_par;

  svr_sock = socket(AF_INET, SOCK_STREAM, 0);
  if (svr_sock > 0)
    {
      signal(SIGINT, signal_handler);
      
      result = init_svr(svr_sock, &(game->server), &slt_par);
      if (result == EXIT_SUCCESS)
	result = select_loop(svr_sock, &slt_par, game);
      else
	fprintf(stderr, "init server error\n");
      if (close(svr_sock) < 0)
	{
	  fprintf(stderr, "close svr sock error\n");
	  return (EXIT_FAILURE);
	}
      return (result);
    }
  fprintf(stderr, "socket creation error\n");
  return (EXIT_FAILURE);
}
Ejemplo n.º 3
0
static void main_event_loop(void) 
{
	void (*select_loop)(void ) = chessd_function("select_loop");

	while (1) {
		select_loop();

		/* check the reload flag */
		if (chessd_reload_flag) {
			void (*reload_close)(void ) = chessd_function("reload_close");
			void (*reload_open)(void );

			void (*db_disconnect)(void ) = chessd_function("db_disconnect");
			db_disconnect();

			chessd_reload_flag = 0;

			fprintf(stderr, "CHESSD: Reloading server code!\n");

			/* free up local vars */
			reload_close();

			/* close the handle to the shared lib */
			dlclose(chessd_so_handle);
			chessd_so_handle = NULL;

			/* re-initialise local variables */
			reload_open = chessd_function("reload_open");
			reload_open();
			select_loop = chessd_function("select_loop");
			void (*db_connect)(void ) = chessd_function("db_connect");
			db_connect();
		}
	}
}
Ejemplo n.º 4
0
void shell(SSH_SESSION *session){
    CHANNEL *channel;
    struct termios terminal_local;
    int interactive=isatty(0);
    channel = channel_new(session);
    if(interactive){
        tcgetattr(0,&terminal_local);
        memcpy(&terminal,&terminal_local,sizeof(struct termios));
    }
    if(channel_open_session(channel)){
        printf("error opening channel : %s\n",ssh_get_error(session));
        return;
    }
    chan=channel;
    if(interactive){
        channel_request_pty(channel);
        sizechanged();
    }
    if(channel_request_shell(channel)){
        printf("Requesting shell : %s\n",ssh_get_error(session));
        return;
    }
    if(interactive){
        cfmakeraw(&terminal_local);
        tcsetattr(0,TCSANOW,&terminal_local);
        setsignal();
    }
    signal(SIGTERM,do_cleanup);
    select_loop(session,channel);
}
Ejemplo n.º 5
0
int
main (const int argc, const char **argv)
{
	int i;
	struct chan *local;
	struct chan *remote;

	struct addrinfo local_hints;
	struct addrinfo remote_hints;

	if (argc != 5) {
		print_usage (stderr, argv[0]);
		exit (EXIT_FAILURE);
	}

	local_chan = new_listening_chan (argv[1], argv[2], &local_hints);
	if (local_chan == NULL) {
		perror ("[server] error");
		exit (EXIT_FAILURE);
	}

	remote_chan = new_connecting_chan (argv[3], argv[4], &remote_hints);
	if (local_chan == NULL) {
		perror ("[client] error");
		exit (EXIT_FAILURE);
	}

	select_loop (local, remote);

	free_chan (local_chan);
	free_chan (remote_chan);

	return 0;
}
Ejemplo n.º 6
0
void LogAnalyzer::run_live_analysis()
{
    reader = new MAVLink_Reader(config());

    _client = new Telem_Forwarder_Client(_client_recv_buf, sizeof(_client_recv_buf));
    _client->configure(config());

    writer = new MAVLink_Writer(config());
    if (writer == NULL) {
        la_log(LOG_ERR, "Failed to create writer from (%s)\n", config_filename);
        exit(1);
    }

    Heart *heart= new Heart(writer);
    if (heart != NULL) {
        reader->add_message_handler(heart, "Heart");
    } else {
        la_log(LOG_INFO, "Failed to create heart");
    }

    create_vehicle_from_commandline_arguments();
    if (_vehicle == NULL) {
        _vehicle = new AnalyzerVehicle::Base();
    }

    Analyze *analyze = create_analyze();

    Analyzing_MAVLink_Message_Handler *handler = new Analyzing_MAVLink_Message_Handler(analyze, _vehicle);
    reader->add_message_handler(handler, "Analyze");

    select_loop();

    _vehicle = NULL; // leak this memory
}
Ejemplo n.º 7
0
static void forwarding(ssh_session session){
    ssh_channel channel;
    int r;
    channel = ssh_channel_new(session);
    r = ssh_channel_open_forward(channel, desthost, atoi(port), "localhost", 22);
    if(r<0) {
        printf("error forwarding port : %s\n",ssh_get_error(session));
        return;
    }
    select_loop(session,channel);
}
Ejemplo n.º 8
0
void batch_shell(SSH_SESSION *session){
    CHANNEL *channel;
    char buffer[1024];
    int i,s=0;
    for(i=0;i<MAXCMD && cmds[i];++i)
        s+=snprintf(buffer+s,sizeof(buffer)-s,"%s ",cmds[i]);
    channel=channel_new(session);
    channel_open_session(channel);
    if(channel_request_exec(channel,buffer)){
        printf("error executing \"%s\" : %s\n",buffer,ssh_get_error(session));
        return;
    }
    select_loop(session,channel);
}
void DataFlash_Logger_Program::run()
{
    init_config();

    if (! debug_mode) {
        la_log_syslog_open();
    }

    la_log(LOG_INFO, "dataflash_logger starting: built " __DATE__ " " __TIME__);
    signal(SIGHUP, ::sighup_handler);

    reader = new MAVLink_Reader(config());
    if (reader == NULL) {
        la_log(LOG_ERR, "Failed to create reader from (%s)\n", config_filename);
        exit(1);
    }

    if (serial_port) {
        client = new Telem_Serial(_client_recv_buf, sizeof(_client_recv_buf));
    } else {
        client = new Telem_Forwarder_Client(_client_recv_buf, sizeof(_client_recv_buf));
    }
    client->configure(config());
    client->init();

    _writer = new MAVLink_Writer(config());
    if (_writer == NULL) {
        la_log(LOG_ERR, "Failed to create writer from (%s)\n", config_filename);
        exit(1);
    }
    _writer->add_client(client);

    // instantiate message handlers:
    DataFlash_Logger *dataflash_logger = new DataFlash_Logger(_writer);
    if (dataflash_logger != NULL) {
        reader->add_message_handler(dataflash_logger, "DataFlash_Logger");
    } else {
        la_log(LOG_INFO, "Failed to create dataflash logger");
    }

    Heart *heart= new Heart(_writer);
    if (heart != NULL) {
        reader->add_message_handler(heart, "Heart");
    } else {
        la_log(LOG_INFO, "Failed to create heart");
    }

    return select_loop();
}
Ejemplo n.º 10
0
Archivo: client.c Proyecto: jpmuga/bird
int
main(int argc, char **argv)
{
#ifdef HAVE_LIBDMALLOC
  if (!getenv("DMALLOC_OPTIONS"))
    dmalloc_debug(0x2f03d00);
#endif

  interactive = isatty(0);
  parse_args(argc, argv);
  cmd_build_tree();
  server_connect();
  select_loop();
  return 0;
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
	int opt;
	char *domname = NULL;
	int s;
	int just_exec = 0;
	int connect_existing = 0;
	char *local_cmdline = NULL;
	while ((opt = getopt(argc, argv, "d:l:ec")) != -1) {
		switch (opt) {
		case 'd':
			domname = strdup(optarg);
			break;
		case 'l':
			local_cmdline = strdup(optarg);
			break;
		case 'e':
			just_exec = 1;
			break;
		case 'c':
			connect_existing = 1;
			break;
		default:
			usage(argv[0]);
		}
	}
	if (optind >= argc || !domname)
		usage(argv[0]);

	s = connect_unix_socket(domname);
	setenv("QREXEC_REMOTE_DOMAIN", domname, 1);
	prepare_local_fds(local_cmdline);

	if (just_exec)
		send_cmdline(s, MSG_CLIENT_TO_SERVER_JUST_EXEC,
			     argv[optind]);
	else {
		int cmd;
		if (connect_existing)
			cmd = MSG_CLIENT_TO_SERVER_CONNECT_EXISTING;
		else
			cmd = MSG_CLIENT_TO_SERVER_EXEC_CMDLINE;
		send_cmdline(s, cmd, argv[optind]);
		select_loop(s);
	}
	return 0;
}
Ejemplo n.º 12
0
void display_loop(void)
{
  switch(DisplayMode) {
  case DisplayReport:
  case DisplayTXT:
  case DisplayXML:
  case DisplayCSV:
  case DisplaySplit:            /* BL */
  case DisplayCurses:
  case DisplayRaw:
    select_loop();
    break;
  case DisplayGTK:
    gtk_loop();
    break;
  }
}
Ejemplo n.º 13
0
static void batch_shell(ssh_session session){
    ssh_channel channel;
    char buffer[1024];
    int i,s=0;
    for(i=0;i<MAXCMD && cmds[i];++i) {
        s+=snprintf(buffer+s,sizeof(buffer)-s,"%s ",cmds[i]);
		free(cmds[i]);
		cmds[i] = NULL;
	}
    channel=ssh_channel_new(session);
    ssh_channel_open_session(channel);
    if(ssh_channel_request_exec(channel,buffer)){
        printf("error executing \"%s\" : %s\n",buffer,ssh_get_error(session));
        return;
    }
    select_loop(session,channel);
}
Ejemplo n.º 14
0
int main(int argc, char **argv) {
  netsnmp_session *session = NULL;
  netsnmp_transport *transport = NULL;
  char *listening_address = "udp:5200";
  int local = 1;
  char *default_domain = "udp";
  program_name = basename(argv[0]);
  printf("%s: main\n", program_name);
  init_usm();
  netsnmp_udp_ctor();
  init_snmpv3(NULL);
  setup_engineID(NULL, NULL);
  usm_parse_create_usmUser("createUser", "-e 0x8000000001020304 traptest SHA mypassword AES");
  transport = netsnmp_tdomain_transport(listening_address, local, default_domain);
  if (transport == NULL) {
    printf("%s: failed to open server: %s\n", argv[0], strerror(errno));
    exit(EXIT_FAILURE);
  }
  session = snmptrapd_add_session(transport);
  select_loop();
  snmp_close(session);
  exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
void *network_thread_start(void *data)
{
  printf("Starting network thread\n");

  shared_threads_t *shared = (shared_threads_t *) data;

  int32_t sockfd;

  /* Establish the connection with the C&C server */
  if ((sockfd = connect_to_server(shared->ip_address, shared->tcp_port)) > 0) {
    /* Infinite loop */
    select_loop(sockfd, shared);
  }
  else {
    shared->running = false;
  }
  
  /* Wakeup the worker thread that is still sleeping... */
  pthread_cond_signal(&(shared->input_fifo->cond));
  
  close(sockfd);
  return (NULL);
}
Ejemplo n.º 16
0
/*
 * GetIdleSlot
 *		Return a connection slot that is ready to execute a command.
 *
 * We return the first slot we find that is marked isFree, if one is;
 * otherwise, we loop on select() until one socket becomes available.  When
 * this happens, we read the whole set and mark as free all sockets that become
 * available.
 *
 * Process the slot list, if any free slot is available then return the slotid
 * else perform the select on all the socket's and wait until at least one slot
 * becomes available.
 *
 * If an error occurs, NULL is returned.
 */
static ParallelSlot *
GetIdleSlot(ParallelSlot slots[], int numslots, const char *dbname,
			const char *progname)
{
	int			i;
	int			firstFree = -1;
	fd_set		slotset;
	pgsocket	maxFd;

	for (i = 0; i < numslots; i++)
		if ((slots + i)->isFree)
			return slots + i;

	FD_ZERO(&slotset);

	maxFd = slots->sock;
	for (i = 0; i < numslots; i++)
	{
		FD_SET((slots + i)->sock, &slotset);
		if ((slots + i)->sock > maxFd)
			maxFd = (slots + i)->sock;
	}

	/*
	 * No free slot found, so wait until one of the connections has finished
	 * its task and return the available slot.
	 */
	for (firstFree = -1; firstFree < 0;)
	{
		bool		aborting;

		SetCancelConn(slots->connection);
		i = select_loop(maxFd, &slotset, &aborting);
		ResetCancelConn();

		if (aborting)
		{
			/*
			 * We set the cancel-receiving connection to the one in the zeroth
			 * slot above, so fetch the error from there.
			 */
			GetQueryResult(slots->connection, dbname, progname);
			return NULL;
		}
		Assert(i != 0);

		for (i = 0; i < numslots; i++)
		{
			if (!FD_ISSET((slots + i)->sock, &slotset))
				continue;

			PQconsumeInput((slots + i)->connection);
			if (PQisBusy((slots + i)->connection))
				continue;

			(slots + i)->isFree = true;

			if (!GetQueryResult((slots + i)->connection, dbname, progname))
				return NULL;

			if (firstFree < 0)
				firstFree = i;
		}
	}

	return slots + firstFree;
}
Ejemplo n.º 17
0
int main(int argc, char **argv)
{
    int c;                      /* command line arg */
    int server_s;                   /* boa socket */

    /* set umask to u+rw, u-x, go-rwx */
    c = umask(~0600);
    if (c == -1) {
        perror("umask");
        exit(1);
    }

    devnullfd = open("/dev/null", 0);

    /* make STDIN and STDOUT point to /dev/null */
    if (devnullfd == -1) {
        DIE("can't open /dev/null");
    }

    if (dup2(devnullfd, STDIN_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDIN_FILENO");
    }

    if (dup2(devnullfd, STDOUT_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDOUT_FILENO");
    }

    /* but first, update timestamp, because log_error_time uses it */
    (void) time(&current_time);

    while ((c = getopt(argc, argv, "c:r:d")) != -1) {
        switch (c) {
        case 'c':
            if (server_root)
                free(server_root);
            server_root = strdup(optarg);
            if (!server_root) {
                perror("strdup (for server_root)");
                exit(1);
            }
            break;
        case 'r':
            if (chdir(optarg) == -1) {
                log_error_time();
                perror("chdir (to chroot)");
                exit(1);
            }
            if (chroot(optarg) == -1) {
                log_error_time();
                perror("chroot");
                exit(1);
            }
            if (chdir("/") == -1) {
                log_error_time();
                perror("chdir (after chroot)");
                exit(1);
            }
            break;
        case 'd':
            do_fork = 0;
            break;
        default:
            fprintf(stderr, "Usage: %s [-c serverroot] [-r chroot] [-d]\n", argv[0]);
            exit(1);
        }
    }

    /* fix it first, see this file */
    fixup_server_root();
    /* parse configuration files, see config.c */
    read_config_files();
    /* log function, see log.c */
    open_logs();
    /* create http server socket, see this file */
    server_s = create_server_socket();
    /* init signal for later use, see signals.c */
    init_signals();
    /* give privs if we can, see this file */
    drop_privs();
    /* setup envrionment varables, see cgi.c */
    create_common_env();
    /* escape handle, see escape.c */
    build_needs_escape();

    /* max connections parse from config files,see config.c & y.tab.c for more detail */
    if (max_connections < 1) {
        struct rlimit rl;

        /* has not been set explicitly */
	/* getrlimit is system call, see man getrlimit for more detail */
        c = getrlimit(RLIMIT_NOFILE, &rl);
        if (c < 0) {
            perror("getrlimit");
            exit(1);
        }
	/* set to max allowed by HOST os. */
        max_connections = rl.rlim_cur;
    }

    /* background ourself */
    if (do_fork) {
        switch(fork()) {
        case -1:
            /* error */
            perror("fork");
            exit(1);
            break;
        case 0:
            /* child, success */
	    /* so,we run in child */
            break;
        default:
            /* parent, success */
	    /* exit in parent */
            exit(0);
            break;
        }
    }

    /* main loop */
    timestamp();

    status.requests = 0;
    status.errors = 0;

    start_time = current_time;

    /*start socket and process request, see select.c*/
    select_loop(server_s);
    return 0;
}
Ejemplo n.º 18
0
/*
 * GetIdleSlot
 *		Return a connection slot that is ready to execute a command.
 *
 * We return the first slot we find that is marked isFree, if one is;
 * otherwise, we loop on select() until one socket becomes available.  When
 * this happens, we read the whole set and mark as free all sockets that become
 * available.
 *
 * If an error occurs, NULL is returned.
 */
static ParallelSlot *
GetIdleSlot(ParallelSlot slots[], int numslots,
			const char *progname)
{
	int			i;
	int			firstFree = -1;

	/* Any connection already known free? */
	for (i = 0; i < numslots; i++)
	{
		if (slots[i].isFree)
			return slots + i;
	}

	/*
	 * No free slot found, so wait until one of the connections has finished
	 * its task and return the available slot.
	 */
	while (firstFree < 0)
	{
		fd_set		slotset;
		int			maxFd = 0;
		bool		aborting;

		/* We must reconstruct the fd_set for each call to select_loop */
		FD_ZERO(&slotset);

		for (i = 0; i < numslots; i++)
		{
			int			sock = PQsocket(slots[i].connection);

			/*
			 * We don't really expect any connections to lose their sockets
			 * after startup, but just in case, cope by ignoring them.
			 */
			if (sock < 0)
				continue;

			FD_SET(sock, &slotset);
			if (sock > maxFd)
				maxFd = sock;
		}

		SetCancelConn(slots->connection);
		i = select_loop(maxFd, &slotset, &aborting);
		ResetCancelConn();

		if (aborting)
		{
			/*
			 * We set the cancel-receiving connection to the one in the zeroth
			 * slot above, so fetch the error from there.
			 */
			GetQueryResult(slots->connection, progname);
			return NULL;
		}
		Assert(i != 0);

		for (i = 0; i < numslots; i++)
		{
			int			sock = PQsocket(slots[i].connection);

			if (sock >= 0 && FD_ISSET(sock, &slotset))
			{
				/* select() says input is available, so consume it */
				PQconsumeInput(slots[i].connection);
			}

			/* Collect result(s) as long as any are available */
			while (!PQisBusy(slots[i].connection))
			{
				PGresult   *result = PQgetResult(slots[i].connection);

				if (result != NULL)
				{
					/* Check and discard the command result */
					if (!ProcessQueryResult(slots[i].connection, result,
											progname))
						return NULL;
				}
				else
				{
					/* This connection has become idle */
					slots[i].isFree = true;
					if (firstFree < 0)
						firstFree = i;
					break;
				}
			}
		}
	}

	return slots + firstFree;
}
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
	char buffer[256];
	int s, addrlen = sizeof(struct sockaddr_in);
	struct sockaddr_in addr;
	struct hostent *hp;
	struct servent *sp;
	int verbose = 1;

	paclen_in = 1024;
	paclen_out = 1024;

	while ((s = getopt(argc, argv, "ci:o:q")) != -1) {
		switch (s) {
		case 'c':
			init_compress();
			compression = 1;
			break;
		case 'i':
			paclen_in = atoi(optarg);
			break;
		case 'o':
			paclen_out = atoi(optarg);
			break;
		case 'q':
			verbose = 0;
			break;
		case ':':
		case '?':
			err("ERROR: invalid option usage\n");
			return 1;
		}
	}

	if (paclen_in < 1 || paclen_out < 1) {
		err("ERROR: invalid paclen\n");
		return 1;
	}

	/*
	 * Arguments should be "tcp_call remaddr remport"
	 */
	if ((argc - optind) != 2) {
		strcpy(buffer, "ERROR: invalid number of parameters\n");
		err(buffer);
	}

	/*
	 * Open the socket into the kernel.
	 */
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		sprintf(buffer, "ERROR: can't open socket: %s\n", strerror(errno));
		err(buffer);
	}

	/*
	 * Resolve the hostname.
	 */
	hp = gethostbyname(argv[optind]);
	if (hp == NULL) {
		err("ERROR: Unknown host\n");
	}
	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;

	/*
	 * And the service name.
	 */
	if ((sp = getservbyname(argv[optind+1], "tcp")) != NULL)
		addr.sin_port = sp->s_port;
	else
		addr.sin_port = htons(atoi(argv[optind+1]));

	if (addr.sin_port == 0) {
		err("ERROR: Unknown service\n");
	}

	if (verbose) {
		sprintf(buffer, "*** Connecting to %s ...\n", hp->h_name);
		user_write(STDOUT_FILENO, buffer, strlen(buffer));
	}

	/*
	 * If no response in 30 seconds, go away.
	 */
	alarm(30);

	signal(SIGALRM, alarm_handler);

	/*
	 * Lets try and connect to the far end.
	 */
	if (connect(s, (struct sockaddr *)&addr, addrlen) != 0) {
		sprintf(buffer, "ERROR: can't connect: %s\n", strerror(errno));
		err(buffer);
	}

	/*
	 * We got there.
	 */
	alarm(0);

	if (verbose) {
		strcpy(buffer, "*** Connected\n");
		user_write(STDOUT_FILENO, buffer, strlen(buffer));
	}

	select_loop(s);

	if (verbose) {
		strcpy(buffer, "\n*** Disconnected\n");
		user_write(STDOUT_FILENO, buffer, strlen(buffer));
	}

	end_compress();

	return 0;
}
Ejemplo n.º 20
0
/*
 * loop_config - configure the loop filter
 *
 * LOCKCLOCK: The LOOP_DRIFTINIT and LOOP_DRIFTCOMP cases are no-ops.
 */
void
loop_config(
	int	item,
	double	freq
	)
{
	int	i;
	double	ftemp;

#ifdef DEBUG
	if (debug > 1)
		printf("loop_config: item %d freq %f\n", item, freq);
#endif
	switch (item) {

	/*
	 * We first assume the kernel supports the ntp_adjtime()
	 * syscall. If that syscall works, initialize the kernel time
	 * variables. Otherwise, continue leaving no harm behind.
	 */
	case LOOP_DRIFTINIT:
#ifndef LOCKCLOCK
#ifdef KERNEL_PLL
		if (mode_ntpdate)
			break;

		start_kern_loop();
#endif /* KERNEL_PLL */

		/*
		 * Initialize frequency if given; otherwise, begin frequency
		 * calibration phase.
		 */
		ftemp = init_drift_comp / 1e6;
		if (ftemp > NTP_MAXFREQ)
			ftemp = NTP_MAXFREQ;
		else if (ftemp < -NTP_MAXFREQ)
			ftemp = -NTP_MAXFREQ;
		set_freq(ftemp);
		if (freq_set)
			rstclock(EVNT_FSET, 0);
		else
			rstclock(EVNT_NSET, 0);
		loop_started = TRUE;
#endif /* LOCKCLOCK */
		break;

	case LOOP_KERN_CLEAR:
#if 0		/* XXX: needs more review, and how can we get here? */
#ifndef LOCKCLOCK
# ifdef KERNEL_PLL
		if (pll_control && kern_enable) {
			memset((char *)&ntv, 0, sizeof(ntv));
			ntv.modes = MOD_STATUS;
			ntv.status = STA_UNSYNC;
			ntp_adjtime(&ntv);
			sync_status("kernel time sync disabled",
				pll_status,
				ntv.status);
		   }
# endif /* KERNEL_PLL */
#endif /* LOCKCLOCK */
#endif
		break;

	/*
	 * Tinker command variables for Ulrich Windl. Very dangerous.
	 */
	case LOOP_ALLAN:	/* Allan intercept (log2) (allan) */
		allan_xpt = (u_char)freq;
		break;

	case LOOP_CODEC:	/* audio codec frequency (codec) */
		clock_codec = freq / 1e6;
		break;

	case LOOP_PHI:		/* dispersion threshold (dispersion) */
		clock_phi = freq / 1e6;
		break;

	case LOOP_FREQ:		/* initial frequency (freq) */
		init_drift_comp = freq;
		freq_set++;
		break;

	case LOOP_HUFFPUFF:	/* huff-n'-puff length (huffpuff) */
		if (freq < HUFFPUFF)
			freq = HUFFPUFF;
		sys_hufflen = (int)(freq / HUFFPUFF);
		sys_huffpuff = emalloc(sizeof(sys_huffpuff[0]) *
		    sys_hufflen);
		for (i = 0; i < sys_hufflen; i++)
			sys_huffpuff[i] = 1e9;
		sys_mindly = 1e9;
		break;

	case LOOP_PANIC:	/* panic threshold (panic) */
		clock_panic = freq;
		break;

	case LOOP_MAX:		/* step threshold (step) */
		clock_max_fwd = clock_max_back = freq;
		if (freq == 0 || freq > 0.5)
			select_loop(FALSE);
		break;

	case LOOP_MAX_BACK:	/* step threshold (step) */
		clock_max_back = freq;
		/*
		 * Leave using the kernel discipline code unless both
		 * limits are massive.  This assumes the reason to stop
		 * using it is that it's pointless, not that it goes wrong.
		 */
		if (  (clock_max_back == 0 || clock_max_back > 0.5)
		   || (clock_max_fwd  == 0 || clock_max_fwd  > 0.5))
			select_loop(FALSE);
		break;

	case LOOP_MAX_FWD:	/* step threshold (step) */
		clock_max_fwd = freq;
		if (  (clock_max_back == 0 || clock_max_back > 0.5)
		   || (clock_max_fwd  == 0 || clock_max_fwd  > 0.5))
			select_loop(FALSE);
		break;

	case LOOP_MINSTEP:	/* stepout threshold (stepout) */
		if (freq < CLOCK_MINSTEP)
			clock_minstep = CLOCK_MINSTEP;
		else
			clock_minstep = freq;
		break;

	case LOOP_TICK:		/* tick increment (tick) */
		set_sys_tick_precision(freq);
		break;

	case LOOP_LEAP:		/* not used, fall through */
	default:
		msyslog(LOG_NOTICE,
		    "loop_config: unsupported option %d", item);
	}
}
Ejemplo n.º 21
0
int main(int argc, char **argv)
{
    int c;                      
    int server_s;                   

    
    c = umask(~0600);
    if (c == -1) {
        perror("umask");
        exit(1);
    }

    devnullfd = open("/dev/null", 0);

    
    if (devnullfd == -1) {
        DIE("can't open /dev/null");
    }

    if (dup2(devnullfd, STDIN_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDIN_FILENO");
    }

    if (dup2(devnullfd, STDOUT_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDOUT_FILENO");
    }

    
    (void) time(&current_time);

    while ((c = getopt(argc, argv, "c:r:d")) != -1) {
        switch (c) {
        case 'c':
            if (server_root)
                free(server_root);
            server_root = strdup(optarg);
            if (!server_root) {
                perror("strdup (for server_root)");
                exit(1);
            }
            break;
        case 'r':
            if (chdir(optarg) == -1) {
                log_error_time();
                perror("chdir (to chroot)");
                exit(1);
            }
            if (chroot(optarg) == -1) {
                log_error_time();
                perror("chroot");
                exit(1);
            }
            if (chdir("/") == -1) {
                log_error_time();
                perror("chdir (after chroot)");
                exit(1);
            }
            break;
        case 'd':
            do_fork = 0;
            break;
        default:
            fprintf(stderr, "Usage: %s [-c serverroot] [-r chroot] [-d]\n", argv[0]);
            exit(1);
        }
    }

    fixup_server_root();
    read_config_files();
    open_logs();
    server_s = create_server_socket();
    boa_event_base = create_event_base(server_s);
    init_signals();
    drop_privs();
    create_common_env();
    build_needs_escape();

    if (max_connections < 1) {
        struct rlimit rl;

        
        c = getrlimit(RLIMIT_NOFILE, &rl);
        if (c < 0) {
            perror("getrlimit");
            exit(1);
        }
        max_connections = rl.rlim_cur;
    }

    
    if (do_fork) {
        switch(fork()) {
        case -1:
            
            perror("fork");
            exit(1);
            break;
        case 0:
            
            break;
        default:
            
            exit(0);
            break;
        }
    }

    
    timestamp();

    status.requests = 0;
    status.errors = 0;

    start_time = current_time;
    select_loop(server_s);
    return 0;
}
Ejemplo n.º 22
0
int main(int argc, char **argv)
{
    int c;                      /* command line arg */
    int server_s;                   /* boa socket */

    /* set umask to u+rw, u-x, go-rwx */
    c = umask(~0600);
    if (c == -1) {
        perror("umask");
        exit(1);
    }

    devnullfd = open("/dev/null", 0);

    /* make STDIN and STDOUT point to /dev/null */
    if (devnullfd == -1) {
        DIE("can't open /dev/null");
    }
#if 0
    if (dup2(devnullfd, STDIN_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDIN_FILENO");
    }

    if (dup2(devnullfd, STDOUT_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDOUT_FILENO");
    }
#endif

    /* but first, update timestamp, because log_error_time uses it */
    (void) time(&current_time);

    while ((c = getopt(argc, argv, "c:r:d")) != -1) {
        switch (c) {
        case 'c':
            if (server_root)
                free(server_root);
            server_root = strdup(optarg);
            if (!server_root) {
                perror("strdup (for server_root)");
                exit(1);
            }
            break;
        case 'r':
            if (chdir(optarg) == -1) {
                log_error_time();
                perror("chdir (to chroot)");
                exit(1);
            }
            if (chroot(optarg) == -1) {
                log_error_time();
                perror("chroot");
                exit(1);
            }
            if (chdir("/") == -1) {
                log_error_time();
                perror("chdir (after chroot)");
                exit(1);
            }
            break;
        case 'd':
            do_fork = 1;
            break;
        default:
            fprintf(stderr, "Usage: %s [-c serverroot] [-r chroot] [-d] [-b] [-q bitrate]\n", argv[0]);
            exit(1);
        }
    }

#ifdef DAVINCI_IPCAM
	if(ApproDrvInit(BOA_MSG_TYPE) < 0){
		exit(1);
	}
	//printf("func_get_mem Begin\n");
    if (func_get_mem(NULL)) {
        ApproDrvExit();
        exit(1);
    }
	//printf("SysDrvInit Begin\n");

	if(SysDrvInit(SYS_BOA_MSG) < 0){
        ApproDrvExit();
        exit(1);
	}
	//printf("InitFileMsgDrv Begin\n");

    if (InitFileMsgDrv(FILE_MSG_KEY, FILE_BOA_MSG) < 0) {
	ApproDrvExit();
	SysDrvExit();
	exit(1);
    }
	//printf("hash_table_init Begin\n");

    if (hash_table_init() < 0) {
        exit(1);
    }
	//printf("arg_hash_table_init Begin\n");

    if(arg_hash_table_init() < 0) {
        exit(1);
    }
	//printf("uri_hash_table_init Begin\n");

    if(uri_hash_table_init() < 0) {
        exit(1);
    }
	
#endif

#ifdef PSIA_MEDIA
	//printf("psia_uri_hash_table_init Begin\n");

    if(psia_uri_hash_table_init() < 0) {
        exit(1);
    }
#endif
	//printf("fixup_server_root Begin\n");

    fixup_server_root();
	printf("read_config_files Begin\n");
    read_config_files();
#ifdef DAVINCI_IPCAM
    {
    //printf("ControlSystemData Begin\n");
        unsigned short value;
		#if 1
        if (ControlSystemData(SFIELD_GET_HTTPPORT, (void *)&value, sizeof(value)) >= 0)
            server_port = value;
		#endif
		
		dbg("server_port=%d\n", server_port);
    }
#endif
    open_logs();
    server_s = create_server_socket();
    init_signals();
    drop_privs();
    create_common_env();
    build_needs_escape();
	

    if (max_connections < 1) {
        struct rlimit rl;

        /* has not been set explicitly */
        c = getrlimit(RLIMIT_NOFILE, &rl);
        if (c < 0) {
            perror("getrlimit");
            exit(1);
        }
        max_connections = rl.rlim_cur;
    }
	

    /* background ourself */
    if (do_fork) {
        switch(fork()) {
        case -1:
            /* error */
            perror("fork");
            exit(1);
            break;
        case 0:
            /* child, success */
            break;
        default:
            /* parent, success */
            exit(0);
            break;
        }
    }
	

	/* Ask system server to start upnp */
	//system("/opt/dvr/boot_proc 2\n");//add by sxh upnp

    /* main loop */
    timestamp();

    status.requests = 0;
    status.errors = 0;

    start_time = current_time;
    select_loop(server_s);
    return 0;
}
Ejemplo n.º 23
0
int
main( int argc, char * argv[]) 
{
 	struct sockaddr_in  	server;
	int 			port;
	int 			dtch=1;
	int			one=1,i;
	struct rlimit 		l;
	int 			needed=0;
	char			* as_user=USER;
	struct sigaction 	act,oact;
	in_addr_t 		bound = INADDR_ANY;
	const char 		* erm;

	errorout = stderr;

	port = PORT;

	for( i=1; i<argc; i++) {
		if ((!strcmp(argv[i],"-p")) && (i+1<argc)) {
			port=atoi(argv[++i]);
			if (port<=1) {
				fprintf(stderr,"Aborted: You really want a port number >1.\n");
				exit(1);
				};
		} else
		if ((!strcmp(argv[i],"-b")) && (i+1<argc)) {
			char * iface = argv[++i];
			bound = inet_addr(iface);  /* First treat it as an UP address */
			if (bound == INADDR_NONE) {
				/* Not a valid IP address - try to look it up */
				struct hostent * hp;
				if((hp = gethostbyname(iface))==NULL) {     
					perror("Address to listen on not found");
					exit(1);
                        	};
                		bound = *(u_long *) hp->h_addr;
			}
		} else
		if ((!strcmp(argv[i],"-d")) && (i+1<argc)) {
			my_dir = argv[++i];
			} else
		if ((!strcmp(argv[i],"-u")) && (i+1<argc)) {
			as_user= argv[++i];
		} else
		if (!strcmp(argv[i],"-U")) {
			as_user= NULL;
		} else
		if ((!strcmp(argv[i],"-C")) && (i+1<argc)) {
			conf_file = argv[++i];
			if ((erm=parse_config(conf_file))) {
                                fprintf(stderr,"Aborted: %s\n",erm);
                                exit(1);
                        }; 
			printf("Config file parsed OK\n");
			exit(0);
		} else
		if ((!strcmp(argv[i],"-c")) && (i+1<argc)) {
			conf_file = argv[++i];
		} else
		if ((!strcmp(argv[i],"-P")) && (i+1<argc)) {
			pid_file= argv[++i];
		} else
		if ((!strcmp(argv[i],"-n")) && (i+1<argc)) { 
			max_processes = atoi( argv[ ++i ] );
			if ((max_processes < 1) || (max_processes > MAX_CHILD)) {
				fprintf(stderr,"Aborted: Max Number of child processes must be between 1 and %d\n",MAX_CHILD);
				exit(1);
				};
		} else
		if ((!strcmp(argv[i],"-m")) && (i+1<argc)) { 
			max_dbms = atoi( argv[ ++i ] );
			if ((max_dbms < 1) || (max_dbms > MAX_DBMS)) {
				fprintf(stderr,"Aborted: Max Number of DB's must be between 1 and %d\n",MAX_DBMS);
				exit(1);
				};
		} else
		if ((!strcmp(argv[i],"-C")) && (i+1<argc)) { 
			max_clients = atoi( argv[ ++i ] );
			if ((max_clients < 1) || (max_clients> MAX_CLIENT)) {
				fprintf(stderr,"Aborted: Max Number of children must be between 1 and %d\n",MAX_CLIENT);
				exit(1);
				};
		} else
		if (!strcmp(argv[i],"-x")) {
			verbose++; debug++; 
			if (debug>2) dtch = 0;
		} else
		if (!strcmp(argv[i],"-D")) {
			dtch = 0;
		} else
		if (!strcmp(argv[i],"-t")) {
			trace_on= 1;
		} else
		if (!strcmp(argv[i],"-v")) {
			printf("%s\n",get_full());
			printf("Max clients:	%d\n",MAX_CLIENT);
			printf("Max DBs:	%d\n",MAX_DBMS);
			printf("Max Children:	%d\n",MAX_CHILD);
			printf("Max Payload:	%d bytes\n",MAX_PAYLOAD);
			printf("Default dir:	%s\n",DIR_PREFIX);
			printf("Default config:	%s\n",CONF_FILE);
			exit(0);
		} else
		if (!strcmp(argv[i],"-X")) {
			verbose=debug=100; dtch = 0; sysloglog = 0; stderrlog = 1;
	   } else
		if ((!strcmp(argv[i],"-e")) && (i+1<argc)) {
	      stderrlog = 1;
		   if ((errorout = fopen(argv[++i],"a")) == NULL) {
				fprintf(stderr,"Aborted. Cannot open logfile %s for writing: %s\n",
						argv[i],strerror(errno));
				exit(1);
		   };
		} else
		if (!strcmp(argv[i],"-E")) {
	      stderrlog = 1;
		} else { 	
			fprintf(stderr,"Syntax: %s [-U | -u <userid>] [-E] [-P <pid-file>] [-d <directory_prefix>] [-b <ip to bind to>] [-p <port>] [-x] [-n <max children>] [-m <max databases>] [-C <max clients>] <-c conffile>\n",argv[0]);
			exit(1);
			};
		};
	if ((erm=parse_config(conf_file))) {
               	fprintf(stderr,"Aborted: %s\n",erm);
        	exit(1);
        }

	if (HARD_MAX_CLIENTS < max_clients +3) {
		fprintf(stderr,"Aborted: Max number of clients larger than compiled hard max(%d)\n",HARD_MAX_CLIENTS);
		exit(1);
		};

	needed=MAX(max_processes, max_clients/max_processes+max_dbms/max_processes) + 5;

	if (FD_SETSIZE < needed ) {
		fprintf(stderr,"Aborted: Number of select()-able file descriptors too low (FD_SETSIZE)\n");
		exit(1);
		};

     	if (getrlimit(RLIMIT_NOFILE,&l)==-1) 
		barf("Could not obtain limit of files open\n");

	if (l.rlim_cur < needed ) {
		fprintf(stderr,"Aborted: Resource limit imposes on number of open files too limiting\n");
		exit(1);
		};

#ifndef RDFSTORE_PLATFORM_SOLARIS
     	if (getrlimit(RLIMIT_NPROC,&l)==-1) 
		barf("Could not obtain limit on children\n");

	if (l.rlim_cur < 2+max_processes) {
		fprintf(stderr,"Aborted: Resource limit imposes on number of children too limiting\n");
		exit(1);
		};
#endif

	if (sysloglog)
		openlog("dbms",LOG_LOCAL4, LOG_PID | LOG_CONS);

	if ( (sockfd = socket( AF_INET, SOCK_STREAM, 0))<0 ) 
		barf("Cannot open socket");

   	if( (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char *)&one,sizeof(one))) <0)
		barf("Could not set REUSEADDR option");

       	if( (setsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,(const void *)&one,sizeof(one))) <0) 
      		barf("Could not distable Nagle algoritm");

{
	int sendbuf = 32 * 1024;
	int recvbuf = 32 * 1024;

       	if( (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,(const void *)&sendbuf,sizeof(sendbuf))) <0) 
      		barf("Could not set sendbuffer size");

       	if( (setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,(const void *)&recvbuf,sizeof(sendbuf))) <0) 
      		barf("Could not set sendbuffer size");
}
	if ( (i=fcntl(sockfd, F_GETFL, 0)<0) || (fcntl(sockfd, F_SETFL,i | O_NONBLOCK)<0) )
		barf("Could not make socket non blocking");

	bzero( (char *) &server,sizeof(server) );
	server.sin_family	= AF_INET;
	server.sin_addr.s_addr	= bound;		/* Already in network order. */
	server.sin_port		= htons( port );

	if ( (bind( sockfd, ( struct sockaddr *) &server, sizeof (server)))<0 )
		barf("Cannot bind server to (lcoal) address.");

	/* Allow for a que.. */
	if ( listen(sockfd,MAX_QUEUE)<0 ) 
		barf("Could not start to listen to my port");

	/* fork and detach if ness. 
	 */
	if (dtch) {
#ifdef FORKING
		pid_t   pid;
/*
		fclose(stdin); 
		if (!trace_on) fclose(stdout); 
*/
        	if ( (pid = fork()) < 0) {
                	perror("Could not fork");
			exit(1);
			}
        	else if (pid != 0) {
			FILE * fd;
			if (!(fd=fopen(pid_file,"w"))) {
				fprintf(stderr,"Warning: Could not write pid file %s:%s",pid_file,strerror(errno));
				exit(1);
				};
			fprintf(fd,"%d\n", (int)pid);
			fclose(fd);	
                	exit(0);
			};
 
#else
		fprintf(stderr,"No forking compiled in, no detach\n");
#endif

	        /* become session leader 
		 */
       		if ((mum_pgid = setsid())<0)
			barf("Could not become session leader");
		};

	/* XXX security hole.. yes I know... 
	 */
	if (as_user != NULL) {
		struct passwd * p = getpwnam( as_user );
		uid_t uid;

		uid = (p == NULL) ? atoi( as_user ) : p->pw_uid;

		if ( !uid || setuid(uid) ) {
			perror("Cannot setuid");
			exit(0);
			};
	};

#if 0
        chdir(my_dir);          /* change working directory */
//	chroot(my_dir);		/* for sanities sake */
        umask(0);               /* clear our file mode creation mask */
#endif

	mum_pid = 0;

	FD_ZERO(&allrset);
	FD_ZERO(&allwset);
	FD_ZERO(&alleset);

	FD_SET(sockfd,&allrset);
	FD_SET(sockfd,&alleset);

	maxfd=sockfd;
	client_list=NULL;

	dbms_log(L_INFORM,"Waiting for connections");

	signal(SIGHUP,dumpie);
	signal(SIGUSR1,loglevel);
	signal(SIGUSR2,loglevel);
	signal(SIGINT,cleandown);
	signal(SIGQUIT,cleandown);
	signal(SIGKILL,cleandown);
	signal(SIGTERM,cleandown);
#ifdef FORKING
	signal(SIGCHLD,childied); 
#endif
	mum = NULL;

	trace("Tracing started\n");

	/* for now, SA_RESTART any interupted PIPE calls
	 */
	act.sa_handler = SIG_IGN;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_RESTART;
	sigaction(SIGPIPE,&act,&oact);

	init_cmd_table();

	select_loop(); 
		/* get down to handling.. (as the mother) */

	return 0; /* keep the compiler happy.. */
	}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
    int c;                      /* command line arg */
    int server_s;                   /* boa socket */

    /* set umask to u+rw, u-x, go-rwx */
    c = umask(~0600);
    if (c == -1) {
        perror("umask");
        exit(1);
    }

    devnullfd = open("/dev/null", 0);

    /* make STDIN and STDOUT point to /dev/null */
    if (devnullfd == -1) {
        DIE("can't open /dev/null");
    }

    if (dup2(devnullfd, STDIN_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDIN_FILENO");
    }

    if (dup2(devnullfd, STDOUT_FILENO) == -1) {
        DIE("can't dup2 /dev/null to STDOUT_FILENO");
    }

    /* but first, update timestamp, because log_error_time uses it */
    (void) time(&current_time);

    while ((c = getopt(argc, argv, "c:r:d")) != -1) {
        switch (c) {
        case 'c':
            if (server_root)
                free(server_root);
            server_root = strdup(optarg);
            if (!server_root) {
                perror("strdup (for server_root)");
                exit(1);
            }
            break;
        case 'r':
            if (chdir(optarg) == -1) {
                log_error_time();
                perror("chdir (to chroot)");
                exit(1);
            }
            if (chroot(optarg) == -1) {
                log_error_time();
                perror("chroot");
                exit(1);
            }
            if (chdir("/") == -1) {
                log_error_time();
                perror("chdir (after chroot)");
                exit(1);
            }
            break;
        case 'd':
            do_fork = 0;
            break;
        default:
            fprintf(stderr, "Usage: %s [-c serverroot] [-r chroot] [-d]\n", argv[0]);
            exit(1);
        }
    }

    fixup_server_root();
    read_config_files();
    open_logs();
    server_s = create_server_socket();
    init_signals();
    drop_privs();
    create_common_env();
    build_needs_escape();

    if (max_connections < 1) {
        struct rlimit rl;

        /* has not been set explicitly */
        c = getrlimit(RLIMIT_NOFILE, &rl);
        if (c < 0) {
            perror("getrlimit");
            exit(1);
        }
        max_connections = rl.rlim_cur;
    }

    /* background ourself */
    if (do_fork) {
        switch(fork()) {
        case -1:
            /* error */
            perror("fork");
            exit(1);
            break;
        case 0:
            /* child, success */
            break;
        default:
            /* parent, success */
            exit(0);
            break;
        }
    }

    /* main loop */
    timestamp();

    status.requests = 0;
    status.errors = 0;

    start_time = current_time;
    select_loop(server_s);
    return 0;
}
Ejemplo n.º 25
0
int main(int argc, char **argv)
{
    int opt;
    char *domname = NULL;
    libvchan_t *data_vchan = NULL;
    int data_port;
    int data_domain;
    int msg_type;
    int s;
    int just_exec = 0;
    int connect_existing = 0;
    char *local_cmdline = NULL;
    char *remote_cmdline = NULL;
    char *request_id;
    char *src_domain_name = NULL;
    int src_domain_id = 0; /* if not -c given, the process is run in dom0 */
    struct service_params svc_params;
    while ((opt = getopt(argc, argv, "d:l:ec:tT")) != -1) {
        switch (opt) {
            case 'd':
                domname = strdup(optarg);
                break;
            case 'l':
                local_cmdline = strdup(optarg);
                break;
            case 'e':
                just_exec = 1;
                break;
            case 'c':
                parse_connect(optarg, &request_id, &src_domain_name, &src_domain_id);
                connect_existing = 1;
                is_service = 1;
                break;
            case 't':
                replace_esc_stdout = 1;
                break;
            case 'T':
                replace_esc_stderr = 1;
                break;
            default:
                usage(argv[0]);
        }
    }
    if (optind >= argc || !domname)
        usage(argv[0]);
    remote_cmdline = argv[optind];

    register_exec_func(&do_exec);

    if (just_exec + connect_existing + (local_cmdline != 0) > 1) {
        fprintf(stderr, "ERROR: only one of -e, -l, -c can be specified\n");
        usage(argv[0]);
    }

    if (strcmp(domname, "dom0") == 0 && !connect_existing) {
        fprintf(stderr, "ERROR: when target domain is 'dom0', -c must be specified\n");
        usage(argv[0]);
    }

    if (strcmp(domname, "dom0") == 0) {
        if (connect_existing) {
            msg_type = MSG_SERVICE_CONNECT;
            strncpy(svc_params.ident, request_id, sizeof(svc_params.ident));
        } else if (just_exec)
            msg_type = MSG_JUST_EXEC;
        else
            msg_type = MSG_EXEC_CMDLINE;
        assert(src_domain_name);
        setenv("QREXEC_REMOTE_DOMAIN", src_domain_name, 1);
        s = connect_unix_socket(src_domain_name);
        negotiate_connection_params(s,
                0, /* dom0 */
                msg_type,
                connect_existing ? (void*)&svc_params : (void*)remote_cmdline,
                connect_existing ? sizeof(svc_params) : strlen(remote_cmdline) + 1,
                &data_domain,
                &data_port);

        prepare_local_fds(remote_cmdline);
        if (connect_existing)
            data_vchan = libvchan_client_init(data_domain, data_port);
        else {
            data_vchan = libvchan_server_init(data_domain, data_port,
                    VCHAN_BUFFER_SIZE, VCHAN_BUFFER_SIZE);
            while (data_vchan && libvchan_is_open(data_vchan) == VCHAN_WAITING)
                libvchan_wait(data_vchan);
        }
        if (!data_vchan || !libvchan_is_open(data_vchan)) {
            fprintf(stderr, "Failed to open data vchan connection\n");
            do_exit(1);
        }
        if (handle_agent_handshake(data_vchan, connect_existing) < 0)
            do_exit(1);
        select_loop(data_vchan);
    } else {
        if (just_exec)
            msg_type = MSG_JUST_EXEC;
        else
            msg_type = MSG_EXEC_CMDLINE;
        s = connect_unix_socket(domname);
        negotiate_connection_params(s,
                src_domain_id,
                msg_type,
                remote_cmdline,
                strlen(remote_cmdline) + 1,
                &data_domain,
                &data_port);
        close(s);
        setenv("QREXEC_REMOTE_DOMAIN", domname, 1);
        prepare_local_fds(local_cmdline);
        if (connect_existing) {
            s = connect_unix_socket(src_domain_name);
            send_service_connect(s, request_id, data_domain, data_port);
            close(s);
        } else {
            data_vchan = libvchan_server_init(data_domain, data_port,
                    VCHAN_BUFFER_SIZE, VCHAN_BUFFER_SIZE);
            if (!data_vchan) {
                fprintf(stderr, "Failed to start data vchan server\n");
                do_exit(1);
            }
            while (libvchan_is_open(data_vchan) == VCHAN_WAITING)
                libvchan_wait(data_vchan);
            if (!libvchan_is_open(data_vchan)) {
                fprintf(stderr, "Failed to open data vchan connection\n");
                do_exit(1);
            }
            if (handle_agent_handshake(data_vchan, 0) < 0)
                do_exit(1);
            select_loop(data_vchan);
        }
    }
    return 0;
}