Esempio n. 1
0
int main(void)
{
	struct data *d = malloc(sizeof(*d));
	struct addrinfo *addrinfo;
	struct io_listener *l;
	int fd, status;

	/* This is how many tests you plan to run */
	plan_tests(22);
	d->state = 0;
	fd = make_listen_fd(PORT, &addrinfo);
	ok1(fd >= 0);
	l = io_new_listener(fd, init_conn, d);
	ok1(l);
	fflush(stdout);
	if (!fork()) {
		io_close_listener(l);
		write_to_socket("hellothere", addrinfo);
		freeaddrinfo(addrinfo);
		free(d);
		exit(0);
	}
	ok1(io_loop() == d);
	ok1(d->state == 2);
	ok1(d->bytes > 0);
	ok1(d->bytes <= sizeof(d->buf));
	ok1(memcmp(d->buf, "hellothere", d->bytes) == 0);

	ok1(wait(&status));
	ok1(WIFEXITED(status));
	ok1(WEXITSTATUS(status) == 0);

	fflush(stdout);
	if (!fork()) {
		io_close_listener(l);
		write_to_socket("hi", addrinfo);
		freeaddrinfo(addrinfo);
		free(d);
		exit(0);
	}
	d->state = 0;
	ok1(io_loop() == d);
	ok1(d->state == 2);
	ok1(d->bytes > 0);
	ok1(d->bytes <= strlen("hi"));
	ok1(memcmp(d->buf, "hi", d->bytes) == 0);

	freeaddrinfo(addrinfo);
	free(d);
	io_close_listener(l);

	ok1(wait(&status));
	ok1(WIFEXITED(status));
	ok1(WEXITSTATUS(status) == 0);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 2
0
int main(void)
{
	struct data *d = malloc(sizeof(*d));
	struct addrinfo *addrinfo;
	struct io_listener *l;
	int fd, status;

	/* This is how many tests you plan to run */
	plan_tests(13);
	d->state = 0;
	fd = make_listen_fd(PORT, &addrinfo);
	ok1(fd >= 0);
	l = io_new_listener(fd, init_conn, d);
	ok1(l);
	fflush(stdout);
	if (!fork()) {
		int i;

		io_close_listener(l);
		fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
			    addrinfo->ai_protocol);
		if (fd < 0)
			exit(1);
		if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
			exit(2);
		signal(SIGPIPE, SIG_IGN);
		for (i = 0; i < strlen("hellothere"); i++) {
			if (write(fd, "hellothere" + i, 1) != 1)
				break;
		}
		close(fd);
		freeaddrinfo(addrinfo);
		free(d);
		exit(0);
	}
	freeaddrinfo(addrinfo);
	ok1(io_loop() == d);
	ok1(d->state == 1);
	io_close_listener(l);

	ok1(io_loop() == NULL);
	ok1(d->state == 3);
	ok1(memcmp(d->buf, "hellothere", sizeof(d->buf)) == 0);
	free(d);

	ok1(wait(&status));
	ok1(WIFEXITED(status));
	ok1(WEXITSTATUS(status) == 0);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 3
0
/*
 * Creates a fan-in funnel from num_writers socketpairs into a single
 * reader
 *
 *   writers
 *    \\|//
 *   reader
 */
static bool test_multi_write(const tal_t *ctx)
{
	struct write_state ws[num_writers];
	struct read_state sink;
	struct reader_state rs[num_writers];
	int fds[2];

	sink.pos = 0;
	sink.lock = io_lock_new(ctx);
	memset(&sink.reads, 0, sizeof(sink.reads));

	for (size_t i=0; i<num_writers; i++) {
		socketpair(AF_LOCAL, SOCK_STREAM, 0, fds);

		rs[i].read_state = &sink;
		rs[i].count = 0;
		rs[i].buf = -1;

		ws[i].id = (u8)(i+'a');
		ws[i].count = 0;

		rs[i].upstream = io_new_conn(ctx, fds[1], writer, &ws[i]);
		io_new_conn(ctx, fds[0], reader_locked, &rs[i]);
	}
	io_loop(NULL, NULL);

	/* Now check that we were serialized correctly, i.e., num_writers sets of num_writes identical numbers */
	for (size_t i=0; i<num_writers; i++) {
		for (size_t j=1; j<num_writes; j++)
			if (sink.reads[i*num_writes+j] != sink.reads[i*num_writes+j-1])
				return false;
	}

	return true;
}
Esempio n. 4
0
int
main(int argc, char *argv[])
{
	int max_fd = 0;
	int i, x;
#ifdef SERVLINK_DEBUG
	int GDBAttached = 0;

	while (!GDBAttached)
		sleep(1);
#endif

	/* Make sure we are running under ircd.. */
	
	if(argc != 4 || strcmp(argv[0], "-slink"))
		usage();	/* exits */


	for (i = 0; i < 3; i++)
	{
		fds[i].fd = atoi(argv[i + 1]);
		if(fds[i].fd < 0)
			exit(1);
	}

	for (i = 0; i < 3; i++)
	{		
		/* XXX: Hack alert...we need to do dup2() here for some dumb
		 * platforms (Solaris) that don't like select using fds > 255
		 */

		if(fds[i].fd >= 255)
		{
			for(x = 0; x < 255; x++)
			{
				if(x != fds[0].fd && x != fds[1].fd && x != fds[2].fd)
				{
					if(dup2(fds[i].fd, x) < 0)
						exit(1);
					close(fds[i].fd);
					fds[i].fd = x;
					break;
				}
			}
		}		
		fcntl(fds[i].fd, F_SETFL, O_NONBLOCK);
		if(fds[i].fd > max_fd)
			max_fd = fds[i].fd;
	}
	
	/* enter io loop */
	io_loop(max_fd + 1);

	/* NOTREACHED */
	return (0);
}				/* main() */
Esempio n. 5
0
void *
serve_client (void *data)
{
  struct thread_data *thread_data = data;
  int client_sock = thread_data->client_sock;
  int server_sock;
  FILE *protocol = thread_data->protocol_file;
  FILE *client;
  FILE *server;
  int err;

  client = NULL;
  server = NULL;

  /* Connect to server.  */
  err = connect_to_socket (opt.server_spec, &server_sock);
  if (err)
    goto out;

  /* Set IO mode to nonblicking.  */
  err = set_nonblock_flag (server_sock, 1);
  if (err)
    goto out;

  client = fdopen (client_sock, "r+");
  if (! client)
    {
      err = errno;
      goto out;
    }

  server = fdopen (server_sock, "r+");
  if (! server)
    {
      err = errno;
      goto out;
    }

  err = io_loop (client, server, protocol);

 out:

  if (client)
    fclose (client);
  else
    close (client_sock);

  if (server)
    fclose (server);
  else
    close (server_sock);

  free (data);

  return NULL;
}
Esempio n. 6
0
int main(void)
{
	struct packet *pkt = malloc(sizeof(*pkt));
	struct addrinfo *addrinfo;
	struct io_listener *l;
	int fd, status;

	/* This is how many tests you plan to run */
	plan_tests(13);
	pkt->state = 0;
	fd = make_listen_fd(PORT, &addrinfo);
	ok1(fd >= 0);
	l = io_new_listener(fd, init_conn, pkt);
	ok1(l);
	fflush(stdout);
	if (!fork()) {
		struct {
			size_t len;
			char data[8];
		} data;

		io_close_listener(l);
		fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
			    addrinfo->ai_protocol);
		if (fd < 0)
			exit(1);
		if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
			exit(2);
		signal(SIGPIPE, SIG_IGN);

		data.len = sizeof(data.data);
		memcpy(data.data, "hithere!", sizeof(data.data));
		if (write(fd, &data, sizeof(data)) != sizeof(data))
			exit(3);

		close(fd);
		freeaddrinfo(addrinfo);
		free(pkt);
		exit(0);
	}
	freeaddrinfo(addrinfo);
	ok1(io_loop() == pkt);
	ok1(pkt->state == 4);
	ok1(pkt->len == 8);
	ok1(memcmp(pkt->contents, "hithere!", 8) == 0);
	free(pkt->contents);
	free(pkt);
	io_close_listener(l);

	ok1(wait(&status));
	ok1(WIFEXITED(status));
	ok1(WEXITSTATUS(status) == 0);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
/********************************************************************
* FUNCTION main
*
* STDIN is input from the SSH client (sent to ncxserver)
* STDOUT is output to the SSH client (rcvd from ncxserver)
* 
* RETURNS:
*   0 if NO_ERR
*   1 if error connecting or logging into ncxserver
*********************************************************************/
int main (int argc, char **argv) 
{
    status_t  res;
    const char *msg;
    char logfile[40] = "/tmp/netconf-subsystem.log";

    errfile = fopen( logfile, "a" );

    configure_logging( argc, argv );

    res = init_subsys();
    if (res != NO_ERR) {
        msg = "init failed";
    }

    if (res == NO_ERR) {
        res = send_ncxconnect();
        if (res != NO_ERR) {
            msg = "connect failed";
        }
    }

    if (res == NO_ERR) {
        res = io_loop();
        if (res != NO_ERR) {
            msg = "IO error";
        }
    }

    if (res != NO_ERR) {
        SUBSYS_TRACE1( "ERROR: io_loop(): exited with error %s \n", msg );
    }


    fprintf(errfile,"%s\n", msg);
    fflush(errfile);
    fprintf(errfile,"SESSION TERMINATED with %s:%s\n",client_addr, port);
    fflush(errfile);

    cleanup_subsys();


    if (res != NO_ERR) {
        return 1;
    } else {
        return 0;
    }

} /* main */
int main(void)
{
	struct addrinfo *addrinfo = NULL;
	int fd, status;
	struct data d;

	/* This is how many tests you plan to run */
	plan_tests(8);
	fd = make_listen_fd(PORT, &addrinfo);
	ok1(fd >= 0);
	d.l = io_new_listener(NULL, fd, init_conn, &d);
	ok1(d.l);
	fflush(stdout);

	if (!fork()) {
		io_close_listener(d.l);
		fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
			    addrinfo->ai_protocol);
		if (fd < 0)
			exit(1);
		if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
			exit(2);
		signal(SIGPIPE, SIG_IGN);

		if (write(fd, "1hellothere", strlen("1hellothere")) != strlen("1hellothere"))
			exit(3);
		sleep(1);
		if (write(fd, "1helloagain", strlen("1helloagain")) != strlen("1helloagain"))
			exit(4);
		close(fd);
		freeaddrinfo(addrinfo);
		exit(0);
	}
	freeaddrinfo(addrinfo);

	d.pattern = tal_arrz(NULL, char, 1);
	ok1(io_loop(NULL, NULL) == NULL);
	/* No trace of writes */
	ok1(strcmp(d.pattern, "<1hellothere<1helloagain") == 0);
	tal_free(d.pattern);

	ok1(wait(&status));
	ok1(WIFEXITED(status));
	ok1(WEXITSTATUS(status) == 0);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 9
0
int main(void)
{
	int fds[2];

	plan_tests(8);

	pipe(fds);
	ok1(io_poll_override(mypoll) == poll);

	io_new_conn(NULL, fds[0], setup_conn, NULL);
	ok1(io_loop(NULL, NULL) == NULL);
	close(fds[1]);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 10
0
int main(void)
{
	int fds[2];
	struct io_conn *conn;

	plan_tests(3);

	ok1(pipe(fds) == 0);
	conn = io_new_conn(fds[0], io_idle());
	io_new_conn(fds[1], io_write("EASYTEST", 8, wake_it, conn));

	ok1(io_loop() == NULL);
	ok1(memcmp(inbuf, "EASYTEST", sizeof(inbuf)) == 0);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
  int max_fd = 0;
  int i;
#ifdef SERVLINK_DEBUG
  int GDBAttached = 0;

  while (!GDBAttached)
    sleep(1);
#endif

#ifdef HAVE_LIBCRYPTO
  /* load error strings */
  ERR_load_crypto_strings();
#endif

  /* Make sure we are running under hybrid.. */
  if (argc != 6 || strcmp(argv[0], "-slink"))
    usage(); /* exits */

  for (i = 0; i < 5; i++ )
  {
    fds[i].fd = dup(atoi(argv[i+1]));
    if (fds[i].fd < 0)
      exit(1);
    if (fds[i].fd > max_fd)
      max_fd = fds[i].fd;
  }

  for (i = 0; i < 5; i++ )
  {
    close(atoi(argv[i+1]));
  }

  /* set file descriptors to nonblocking mode */
  for (i = 0; i < 5; i++)
  {
    fcntl(fds[i].fd, F_SETFL, O_NONBLOCK);
  }

  /* enter io loop */
  io_loop(max_fd + 1);

  /* NOTREACHED */
  return(0);
} /* main() */
Esempio n. 12
0
static int handle_device(int dev_id)
{
  int r, i;
  struct usb_device *dev = g_devices[dev_id].usb_dev;
  usb_dev_handle *hdev = g_devices[dev_id].hdev;

  usb_detach_kernel_driver_np(hdev, 0);
  
  if( 0 != (r = usb_set_configuration(hdev, dev->config[0].bConfigurationValue)) )
  {
    printf("usb_set_configuration returns %d (%s)\n", r, usb_strerror());
    return -1;
  }

  if((r = usb_claim_interface(hdev, 0)) < 0)
  {
    printf("Interface cannot be claimed: %d\n", r);
    return r;
  }

  int nep = dev->config->interface->altsetting->bNumEndpoints;
  for(i=0; i<nep; i++)
  {
    int ep = dev->config->interface->altsetting->endpoint[i].bEndpointAddress;
    if(ep&(1<<7))
      g_devices[dev_id].epin = ep;
    else
      g_devices[dev_id].epout = ep;
  }

  // Set baudrate
  int baudrate = 250000;
  r = usb_control_msg(hdev, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, 
                      CP210X_IFC_ENABLE, UART_ENABLE, 0, NULL, 0, 500);
  r = usb_control_msg(hdev, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, 
                      CP210X_SET_BAUDRATE, 0, 0, (char *)&baudrate, sizeof(baudrate), 500);
  r = usb_control_msg(hdev, USB_TYPE_VENDOR | USB_RECIP_INTERFACE | USB_ENDPOINT_OUT, 
                      CP210X_IFC_ENABLE, UART_DISABLE, 0, NULL, 0, 500);
  
// read/write main loop
  io_loop(dev_id);
 
  usb_release_interface(hdev, 0);
  return 0;
}
Esempio n. 13
0
int main(void)
{
	int state = 0;
	struct addrinfo *addrinfo;
	struct io_listener *l;
	int fd;

	/* This is how many tests you plan to run */
	plan_tests(12);
	fd = make_listen_fd(PORT, &addrinfo);
	ok1(fd >= 0);
	l = io_new_listener(NULL, fd, init_conn, &state);
	ok1(l);
	fflush(stdout);
	if (!fork()) {
		io_close_listener(l);
		fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
			    addrinfo->ai_protocol);
		if (fd < 0)
			exit(1);
		if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
			exit(2);
		close(fd);
		fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
			    addrinfo->ai_protocol);
		if (fd < 0)
			exit(3);
		if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
			exit(4);
		close(fd);
		freeaddrinfo(addrinfo);
		exit(0);
	}
	freeaddrinfo(addrinfo);
	ok1(io_loop(NULL, NULL) == &state + 1);
	ok1(state == 4);
	io_close_listener(l);
	ok1(wait(&state));
	ok1(WIFEXITED(state));
	ok1(WEXITSTATUS(state) == 0);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 14
0
int main(void)
{
	struct data *d = malloc(sizeof(*d));
	struct addrinfo *addrinfo;
	struct io_listener *l;
	int fd, status;

	/* This is how many tests you plan to run */
	plan_tests(9);
	d->state = 0;
	d->bytes = 1024*1024;
	d->buf = malloc(d->bytes);
	memset(d->buf, 'a', d->bytes);
	fd = make_listen_fd(PORT, &addrinfo);
	ok1(fd >= 0);
	l = io_new_listener(fd, init_conn, d);
	ok1(l);
	fflush(stdout);
	if (!fork()) {
		io_close_listener(l);
		read_from_socket(d->bytes, addrinfo);
		freeaddrinfo(addrinfo);
		free(d->buf);
		free(d);
		exit(0);
	}
	ok1(io_loop() == d);
	ok1(d->state == 2);

	ok1(wait(&status));
	ok1(WIFEXITED(status));
	ok1(WEXITSTATUS(status) == 0);

	freeaddrinfo(addrinfo);
	free(d->buf);
	free(d);
	io_close_listener(l);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 15
0
/********************************************************************
* FUNCTION main
*
* STDIN is input from the SSH client (sent to ncxserver)
* STDOUT is output to the SSH client (rcvd from ncxserver)
*
* RETURNS:
*   0 if NO_ERR
*   1 if error connecting or logging into ncxserver
*********************************************************************/
int main (int argc, char **argv)
{
    status_t  res;
    const char *msg;

    configure_logging( argc, argv );

    res = init_subsys(argc, argv);
    if (res != NO_ERR) {
        msg = "init failed";
    }

    if (res == NO_ERR) {
        res = send_ncxconnect();
        if (res != NO_ERR) {
            msg = "connect failed";
        }
    }

    if (res == NO_ERR) {
        res = io_loop();
        if (res != NO_ERR) {
            msg = "IO error";
        }
    }

    if (res != NO_ERR) {
        SUBSYS_TRACE1( "ERROR: io_loop(): exited with error %s \n", msg );
    }

    cleanup_subsys();

    if (res != NO_ERR) {
        return 1;
    } else {
        return 0;
    }

} /* main */
Esempio n. 16
0
int main(void)
{
	int status;

	plan_tests(3);

	if (fork() == 0) {
		int fds[2];

		ok1(pipe(fds) == 0);
		io_new_conn(NULL, fds[0], setup_waiter, &status);
		io_loop(NULL, NULL);
		exit(1);
	}

	ok1(wait(&status) != -1);
	ok1(WIFSIGNALED(status));
	ok1(WTERMSIG(status) == SIGABRT);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 17
0
int main(void)
{
	struct io_listener *l;
	int fd;
	struct timers timers;
	struct timer timer, *expired;
	struct addrinfo *addrinfo;

	/* This is how many tests you plan to run */
	plan_tests(7);

	fake_time = time_now();

	timers_init(&timers, fake_time);
	timer_init(&timer);
	timer_add(&timers, &timer,
		  timeabs_add(fake_time, time_from_sec(1000)));

	fd = make_listen_fd(PORT, &addrinfo);
	freeaddrinfo(addrinfo);
	ok1(fd >= 0);
	l = io_new_listener(NULL, fd, init_conn, NULL);
	ok1(l);

	fake_time.ts.tv_sec += 1000;
	ok1(io_time_override(get_fake_time) == time_now);
	ok1(io_loop(&timers, &expired) == NULL);

	ok1(expired == &timer);
	ok1(!timers_expire(&timers, fake_time));
	ok1(io_time_override(time_now) == get_fake_time);
	io_close_listener(l);

	timers_cleanup(&timers);

	/* This exits depending on whether all tests passed */
	return exit_status();
}
Esempio n. 18
0
int main(int argc, const char **argv) {

  uint8_t mac[6];
  oob_nic *nic;
  oob_intf *intf;
  struct wedge_eeprom_st eeprom;
  int rc;
  int from_eeprom = 0;

  nic = oob_nic_open(0, 0x49);
  if (!nic) {
    return -1;
  }

  /* read EEPROM for the MAC */
  if (wedge_eeprom_parse(NULL, &eeprom) == 0) {
    if (eeprom.fbw_mac_size <= 0) {
      LOG_ERR(EFAULT, "Invalid extended MAC size: %d", eeprom.fbw_mac_size);
    } else {
      uint16_t carry;
      int pos;
      /* use the last MAC address from the extended MAC range */
      memcpy(mac, eeprom.fbw_mac_base, sizeof(mac));
      if (eeprom.fbw_mac_size > 128) {
        LOG_ERR(EFAULT, "Extended MAC size (%d) is too large.",
                eeprom.fbw_mac_size);
        carry = 127;
      } else {
        /*
         * hack around bug device which have the same MAC address on
         * left and right.
         */
        if (strncmp(eeprom.fbw_location, "LEFT", FBW_EEPROM_F_LOCATION) == 0) {
          carry = eeprom.fbw_mac_size - 2;
        } else {
          carry = eeprom.fbw_mac_size - 1;
        }
      }
      for (pos = sizeof(mac) - 1; pos >= 0 && carry; pos--) {
        uint16_t tmp = mac[pos] + carry;
        mac[pos] = tmp & 0xFF;
        carry = tmp >> 8;
      }
      from_eeprom = 1;
    }
  }

  if (!from_eeprom) {
    while (oob_nic_get_mac(nic, mac)) {
      usleep(1000);
    }
    /*
     * increase the last byte of the mac by 1 and turn on the
     * local administered bit to use it as the oob nic mac
     */
    mac[0] |= 0x2;
    mac[5]++;
  }

  LOG_INFO("Retrieve MAC %x:%x:%x:%x:%x:%x from %s",
           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5],
           (from_eeprom) ? "EEPROM" : "NIC");

  /* create the tap interface */
  intf = oob_intf_create("oob", mac);
  if (!intf) {
    return -1;
  }

  while (oob_nic_start(nic, mac)) {
    usleep(1000);
  }

  io_loop(nic, intf, mac);

  return 0;
}
Esempio n. 19
0
int main(int argc, char * argv[]) {
	init(argc, argv);
	io_loop();
	end(0);
	return 0;
}
Esempio n. 20
0
int
main(int argc, char *argv[])
{
	/* Check to see if the user is running us as root, which is a nono */
	if(geteuid() == 0)
	{
		fprintf(stderr, "Don't run ircd as root!!!\n");
		return -1;
	}

	/*
	 * save server boot time right away, so getrusage works correctly
	 */
	set_time();
	/*
	 * Setup corefile size immediately after boot -kre
	 */
	setup_corefile();

	/*
	 * set initialVMTop before we allocate any memory
	 */
	initialVMTop = get_vm_top();

	ServerRunning = 0;
	/* It ain't random, but it ought to be a little harder to guess */
	srand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));
	memset(&me, 0, sizeof(me));
	memset(&meLocalUser, 0, sizeof(meLocalUser));
	me.localClient = &meLocalUser;

	/* Make sure all lists are zeroed */
	memset(&unknown_list, 0, sizeof(unknown_list));
	memset(&lclient_list, 0, sizeof(lclient_list));
	memset(&serv_list, 0, sizeof(serv_list));
	memset(&global_serv_list, 0, sizeof(global_serv_list));
	memset(&oper_list, 0, sizeof(oper_list));

	dlinkAddTail(&me, &me.node, &global_client_list);

	memset((void *) &Count, 0, sizeof(Count));
	memset((void *) &ServerInfo, 0, sizeof(ServerInfo));
	memset((void *) &AdminInfo, 0, sizeof(AdminInfo));

	/* Initialise the channel capability usage counts... */
	init_chcap_usage_counts();

	ConfigFileEntry.dpath = DPATH;
	ConfigFileEntry.configfile = CPATH;	/* Server configuration file */
	ConfigFileEntry.klinefile = KPATH;	/* Server kline file */
	ConfigFileEntry.dlinefile = DLPATH;	/* dline file */
	ConfigFileEntry.xlinefile = XPATH;
	ConfigFileEntry.resvfile = RESVPATH;
	ConfigFileEntry.connect_timeout = 30;	/* Default to 30 */
	myargv = argv;
	umask(077);		/* better safe than sorry --SRB */

	parseargs(&argc, &argv, myopts);

	if(printVersion)
	{
		printf("ircd: version %s\n", ircd_version);
		exit(EXIT_SUCCESS);
	}

	if(chdir(ConfigFileEntry.dpath))
	{
		fprintf(stderr, "Unable to chdir to %s: %s\n", ConfigFileEntry.dpath, strerror(errno));
		exit(EXIT_FAILURE);
	}

	setup_signals();

#ifdef __CYGWIN__
	server_state_foreground = 1;
#endif

	if (testing_conf)
		server_state_foreground = 1;

	/* We need this to initialise the fd array before anything else */
	fdlist_init();
	if(!server_state_foreground)
	{
		comm_close_all();
	}


	/* Check if there is pidfile and daemon already running */
	if(!testing_conf)
	{
		check_pidfile(pidFileName);

		if(!server_state_foreground)
			make_daemon();
		else
			print_startup(getpid());
	}

	init_netio();		/* This needs to be setup early ! -- adrian */

	/* Init the event subsystem */
	eventInit();
	init_sys();

	init_main_logfile();
	initBlockHeap();
	init_dlink_nodes();
	init_patricia();
	newconf_init();
	init_s_conf();
	init_s_newconf();
	linebuf_init();		/* set up some linebuf stuff to control paging */
	init_hash();
	clear_scache_hash_table();	/* server cache name table */
	init_host_hash();
	clear_hash_parse();
	init_client();
	initUser();
	init_channels();
	initclass();
	initwhowas();
	init_stats();
	init_hook();
	init_reject();
	init_cache();
	init_monitor();
	load_all_modules(1);
#ifndef STATIC_MODULES
	load_core_modules(1);
#endif
	init_auth();		/* Initialise the auth code */
	init_resolver();	/* Needs to be setup before the io loop */

	if (testing_conf)
		fprintf(stderr, "\nBeginning config test\n");
	read_conf_files(YES);	/* cold start init conf files */
	rehash_bans(0);
#ifndef STATIC_MODULES

	mod_add_path(MODULE_DIR); 
	mod_add_path(MODULE_DIR "/autoload"); 
#endif

	initialize_server_capabs();	/* Set up default_server_capabs */
	initialize_global_set_options();

	if(ServerInfo.name == NULL)
	{
		fprintf(stderr, "ERROR: No server name specified in serverinfo block.\n");
		ilog(L_MAIN, "No server name specified in serverinfo block.");
		exit(EXIT_FAILURE);
	}
	strlcpy(me.name, ServerInfo.name, sizeof(me.name));

	if(ServerInfo.sid[0] == '\0')
	{
		fprintf(stderr, "ERROR: No server sid specified in serverinfo block.\n");
		ilog(L_MAIN, "No server sid specified in serverinfo block.");
		exit(EXIT_FAILURE);
	}
	strcpy(me.id, ServerInfo.sid);
	init_uid();

	/* serverinfo{} description must exist.  If not, error out. */
	if(ServerInfo.description == NULL)
	{
		fprintf(stderr, "ERROR: No server description specified in serverinfo block.\n");
		ilog(L_MAIN, "ERROR: No server description specified in serverinfo block.");
		exit(EXIT_FAILURE);
	}
	strlcpy(me.info, ServerInfo.description, sizeof(me.info));

	if (testing_conf)
	{
		fprintf(stderr, "\nConfig testing complete.\n");
		fflush(stderr);
		exit(EXIT_SUCCESS);
	}

	me.from = &me;
	me.servptr = &me;
	SetMe(&me);
	make_server(&me);
	me.serv->up = me.name;
	startup_time = CurrentTime;
	add_to_client_hash(me.name, &me);
	add_to_id_hash(me.id, &me);

	dlinkAddAlloc(&me, &global_serv_list);

	check_class();
	write_pidfile(pidFileName);
	load_help();
	open_logfiles();

	ilog(L_MAIN, "Server Ready");

	eventAddIsh("cleanup_glines", cleanup_glines, NULL, CLEANUP_GLINES_TIME);

	/* We want try_connections to be called as soon as possible now! -- adrian */
	/* No, 'cause after a restart it would cause all sorts of nick collides */
	/* um.  by waiting even longer, that just means we have even *more*
	 * nick collisions.  what a stupid idea. set an event for the IO loop --fl
	 */
	eventAddIsh("try_connections", try_connections, NULL, STARTUP_CONNECTIONS_TIME);
	eventAddOnce("try_connections_startup", try_connections, NULL, 0);

	eventAddIsh("collect_zipstats", collect_zipstats, NULL, ZIPSTATS_TIME);

	/* Setup the timeout check. I'll shift it later :)  -- adrian */
	eventAddIsh("comm_checktimeouts", comm_checktimeouts, NULL, 1);

	if(ConfigServerHide.links_delay > 0)
		eventAddIsh("cache_links", cache_links, NULL,
			    ConfigServerHide.links_delay);
	else
		ConfigServerHide.links_disabled = 1;

	if(splitmode)
		eventAdd("check_splitmode", check_splitmode, NULL, 2);

	ServerRunning = 1;

	io_loop();
	return 0;
}
Esempio n. 21
0
int main(int argc,char *args[])
{
	int n,c;
	unsigned long long prof,start,end;

	end_of_data_ptr=sbrk(0);

	time_now=time(NULL);

	printf("\n");
	printf("   ********************************************\n");
        printf("   *     Astonia 3 - The Conflict Server      *\n");
	printf("   *             Version %d.%02d.%02d              *\n",VERSION>>16,(VERSION>>8)&255,VERSION&255);
	printf("   ********************************************\n");
        printf("   * Copyright (C) 2001-2008 Intent Software  *\n");
	printf("   * Copyright (C) 1997-2001 Daniel Brockhaus *\n");
	printf("   ********************************************\n");
	printf("\n");

        if (argc>1) {
		while (1) {
			c=getopt(argc,args,"a:m:i:dhc");
			if (c==-1) break;

			switch (c) {
				case 'a': 	if (optarg) areaID=atoi(optarg); break;
				case 'm': 	if (optarg) areaM=atoi(optarg); break;
				case 'd': 	demon=1; break;
				case 'h':	fprintf(stderr,"Usage: %s [-a <areaID>] [-m <mirror>] [-n <use this class A net>] [-d] [-c]\n\n-d Demonize\n-c Disable concurrent database access\n\n",args[0]); exit(0);
				case 'c':	multi=0; break;
				//case 'n':	if (optarg) server_net=atoi(optarg); break;
				case 'i':	if (optarg) serverID=atoi(optarg); break;
			}
		}
	}

	if (!areaID) {
		printf("No areaID given, assuming areaID=1\n");
		areaID=1;
	}
	if (!areaM) {
		printf("No mirror given, assuming areaM=1\n");
		areaM=1;
	}
	if (!serverID) {
		printf("No serverID given, assuming serverID=1\n");
		serverID=1;
	}

#ifdef STAFF
	while (!check_staff_start()) sleep(1);
#endif


        // set character number limit depending on area
	switch(areaID) {
		case 1:		maxchars=512; break;
		case 2:		maxchars=896; break;
		case 3:		maxchars=384; break;
		case 4:		maxchars=2048; break;
		case 5:		maxchars=768; break;
		case 6:		maxchars=384; break;
		case 7:		maxchars=1280; break;
		case 8:		maxchars=384; break;
		case 9:		maxchars=1280; break;
		case 10:	maxchars=512; break;
		case 11:	maxchars=384; break;
		case 12:	maxitem=1024*48; maxchars=384; break;
		case 13:	maxchars=9*50+200; break;
		case 14:	maxchars=16*50+200; break;
		case 15:	maxchars=384; break;
		case 16:	maxchars=384; break;
		case 17:	maxchars=512; break;
		case 18:	maxchars=768; break;
		case 19:	maxchars=384; break;
		case 20:	maxchars=768; break;
		case 21:	maxchars=768; break;
		case 22:	maxchars=512; break;
		case 23:	maxchars=512; break;
		case 24:	maxchars=384; break;
		case 25:	maxchars=384+8*25*2; break;
		case 26:	maxchars=256; break;
		case 27:	maxchars=2048; break;
		case 28:	maxchars=384; break;
		case 29:	maxchars=512; break;
		case 30:	maxchars=384; break;
		case 31:	maxitem=1024*40; maxchars=512; break;
		case 32:	maxchars=1280; break;
		case 33:	maxchars=1600; break;
		case 34:	maxchars=1280; break;
		case 35:	maxchars=768; break;
		case 36:	maxchars=768; break;
		case 37:	maxchars=1024; break;

		default:	maxchars=768; break;
	}
	
	// set item and effect limit
	if (!maxitem) maxitem=max(maxchars*12+10240,20480);
	if (!maxeffect) maxeffect=max(maxchars*2,1024);

	printf("serverID=%d, areaID=%d, areaM=%d, maxchars=%d, maxitem=%d, maxeffect=%d\n\n",
	       serverID,areaID,areaM,maxchars,maxitem,maxeffect);

	if (demon) {
		printf("Demonizing...\n\n");
		
		if (fork()) exit(0);
		for (n=0; n<256; n++) close(n);
		setsid();
#ifndef STAFF
		nologin=1;
#endif
	}

        // ignore the silly pipe errors:
        signal(SIGPIPE,SIG_IGN);

	// ignore sighup - just to be safe
        signal(SIGHUP,SIG_IGN);

	/*signal(SIGSEGV,sig_crash);
	signal(SIGFPE,sig_crash);
	signal(SIGBUS,sig_crash);
	signal(SIGSTKFLT,sig_crash);*/

        // shutdown gracefully if possible:
        signal(SIGQUIT,sig_leave);
        signal(SIGINT,sig_leave);
        signal(SIGTERM,sig_leave);

	// show profile info on CTRL-Z
	signal(SIGTSTP,sig_showprof);

	// init random number generator
        srand(time_now);

	if (!init_smalloc()) exit(1);
	if (!init_mem()) exit(1);
        if (!init_prof()) exit(1);
	if (!init_log()) exit(1);	
        if (!init_database()) exit(1);
	if (!init_lookup())  exit(1);
        if (!init_sector())  exit(1);
        if (!init_los()) exit(1);
	if (!init_timer()) exit(1);
        if (!init_notify()) exit(1);
	if (!init_create()) exit(1);
        if (!init_lib()) exit(1);
	if (!init_io()) exit(1);
        if (!init_path()) exit(1);	
	if (!init_effect()) exit(1);
	if (!init_container()) exit(1);
	if (!init_store()) exit(1);
	if (!init_chat()) exit(1);

	init_sound_sector();

	xlog("AreaID=%d, AreaM=%d, entering game loop...",areaID,areaM);

	dlog(0,0,"Server started");
	prof_reset();

        while (!quit) {
		sprintf(args[0],"./server -a %d -m %d -i %d # %d on %d%% load (busy)",areaID,areaM,serverID,online,(10000-server_idle)/100);
		start=rdtsc();
		lock_server();

		time_now=time(NULL);
		prof=prof_start(26); tick_date(); prof_stop(26,prof);
		prof=prof_start(22); tick_timer(); prof_stop(22,prof);
                prof=prof_start(4); tick_char(); prof_stop(4,prof);
                prof=prof_start(24); tick_effect(); prof_stop(24,prof);
		prof=prof_start(36); tick_clan(); prof_stop(36,prof);
		prof=prof_start(39); tick_club(); prof_stop(39,prof);
		prof=prof_start(5); tick_player(); prof_stop(5,prof);
		prof=prof_start(34); tick_login(); prof_stop(34,prof);
                prof=prof_start(6); pflush(); prof_stop(6,prof);
		prof=prof_start(7); io_loop(); prof_stop(7,prof);
                prof=prof_start(3); tick_chat(); prof_stop(3,prof);

		if (showprof) {
			show_prof();
			showprof=0;
		}
		
		prof=prof_start(8); prof_update(); prof_stop(8,prof);

		end=rdtsc();
		cycles=end-start;

		if ((ticker&2047)==0) {
			prof=prof_start(27); area_alive(0); prof_stop(27,prof);
			prof=prof_start(28); backup_players(); prof_stop(28,prof);
			call_stat_update();
			read_motd();			
			reinit_log();
		}

		if ((ticker&255)==0) {
			call_check_task();
			call_area_load();
			shutdown_warn();
#ifdef STAFF
			check_staff_stop();
#endif
		}

		if ((ticker&255)==168) {
			prof=prof_start(38);
			consistency_check_items();
			consistency_check_map();
			consistency_check_chars();
			consistency_check_containers();
			prof_stop(38,prof);
		}

                unlock_server();

		sprintf(args[0],"./server -a %d -m %d -i %d # %d on %d%% load (idle)",areaID,areaM,serverID,online,(10000-server_idle)/100);

		prof=prof_start(1); tick_sleep(0); prof_stop(1,prof);
		
		ticker++;
	}

        xlog("Left game loop");
	respawn_check();

	for (n=1; n<MAXCHARS; n++) {
		if (ch[n].flags&CF_PLAYER) {
			exit_char(n);
		}
	}
	area_alive(1);

        show_prof();

	dlog(0,0,"Server stopped");

	xlog("map check");
	check_map();

        exit_lib();
	exit_database();

	xlog("Clean shutdown");
	showmem();
	exit_log();
	exit_io();

        return 0;
}
Esempio n. 22
0
int main(int argc, char **argv) {
   int ret, opt, conn, plugins_loaded = 0, banner_displayed = 0;
   unsigned long now, lastconn = time(NULL);
   FILE *urandom;

   runlevel = RL_OFFLINE;   

   while ((opt = getopt(argc, argv, "c:dj:u:vh")) != -1) {
      switch(opt) {
         case 'c':
            settings.config = optarg;
            break;
         case 'd':
            settings.daemonize = 1;
            break;
         case 'j':
            settings.chroot = optarg;
            break;
         case 'u':
            settings.chuser = optarg;
            break;
         case 'v':
            print_version();
            break;
         case 'h':
         default:
            print_usage(argv[0]);
            break;
      }
   }

   srand(time(NULL));
   
   urandom = fopen("/dev/urandom", "r");
   srrand(time(NULL) ^ getpid(), urandom);

   if (config_parse(settings.config)) {
      fprintf(stderr, "Unable to load configuration file '%s'.\n",
	settings.config);
      return -1;
   }

   if (checkconfig())
      return -1;

   if (settings.daemonize) {
      ret = fork();
      switch(ret) {
         case -1:
            fprintf(stderr, "Unable to fork to background\n");
            return -1;
        default:
            return 0;
      }
   }

   if (secure_it(settings.chroot, settings.chuser)) {
      fprintf(stderr, "Failed to chroot/setuid\n");
      return -1;
   }

#ifdef TLS
  if (gnutls_global_init() == GNUTLS_E_SUCCESS)
    atexit(gnutls_global_deinit);
  else
    fprintf(stderr, "Unable to initialize TLS library\n");
#endif

  if (dns_init() == -1)
      warn("Unable to initialize dns resolver\n");
  
   for(runlevel = RL_RUNNING; runlevel;) {
      if (irc_init() == -1) {
         warn("Unable to init irc data structure");
         return -1;
      }

      if(!plugins_loaded) {
         plugins_load();
         plugins_loaded = 1;
      }

      if(!banner_displayed) {
         banner_displayed = banner("Welcome to " PACKAGE_STRING
#ifdef SVN_REV
            "." SVN_REV
#endif
         );
      }

      while ((runlevel == RL_RUNNING) && (irc_conn() == -1)) {
         warn("Unable to establish irc connection\n");
         sleep(RECONNECT_DELAY);
      }

      lastconn = time(NULL);
      while(runlevel == RL_RUNNING)
         io_loop(100);
      
      irc_free();

      if((runlevel != RL_RUNNING) && plugins_loaded) { 
         plugins_unload();
         plugins_loaded = 0;
      }
      
      if(runlevel == RL_RELOAD) {
         printc("Reloading config file '%s'...\n", settings.config);
         if(config_parse(settings.config)) {
            warn("Error reloading config file.\n");
            runlevel = RL_OFFLINE;
         } else if(checkconfig()) {
            runlevel = RL_OFFLINE;
         }
         runlevel = RL_RUNNING;
      }

      conn = 0;
      now = time(NULL);
      if(runlevel != RL_OFFLINE) {
        runlevel = RL_RUNNING;
        if (now < lastconn + RECONNECT_DELAY)
          sleep(lastconn + RECONNECT_DELAY - now);
      }
   }

   if(urandom)
      fclose(urandom);
   return 0;
}
Esempio n. 23
0
int main(int argc, char *argv[])
{
	bool have_conf = false;
	bool have_log = false;
	char buf[32];
	int i, pid, r;
	FILE *pid_file;
	const char *pidfilename = RUNDIR "/atheme.pid";
#ifdef HAVE_GETRLIMIT
	struct rlimit rlim;
#endif
	curr_uplink = NULL;

	mowgli_init();

	/* Prepare gettext */
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);
#endif

	/* change to our local directory */
	if (chdir(PREFIX) < 0)
	{
		perror(PREFIX);
		return 20;
	}

#ifdef HAVE_GETRLIMIT
	/* it appears certian systems *ahem*linux*ahem*
	 * don't dump cores by default, so we do this here.
	 */
	if (!getrlimit(RLIMIT_CORE, &rlim))
	{
		rlim.rlim_cur = rlim.rlim_max;
		setrlimit(RLIMIT_CORE, &rlim);
	}
#endif
	
	/* do command-line options */
	while ((r = getopt(argc, argv, "c:dhrl:np:v")) != -1)
	{
		switch (r)
		{
		  case 'c':
			  config_file = sstrdup(optarg);
			  have_conf = true;
			  break;
		  case 'd':
			  log_force = true;
			  break;
		  case 'h':
			  print_help();
			  exit(EXIT_SUCCESS);
			  break;
		  case 'r':
			  readonly = true;
			  break;
		  case 'l':
			  log_path = sstrdup(optarg);
			  have_log = true;
			  break;
		  case 'n':
			  runflags |= RF_LIVE;
			  break;
		  case 'p':
			  pidfilename = optarg;
			  break;
		  case 'v':
			  print_version();
			  exit(EXIT_SUCCESS);
			  break;
		  default:
			  printf("usage: atheme [-dhnvr] [-c conf] [-l logfile] [-p pidfile]\n");
			  exit(EXIT_SUCCESS);
			  break;
		}
	}

	if (!have_conf)
		config_file = sstrdup(SYSCONFDIR "/atheme.conf");

	if (!have_log)
		log_path = sstrdup(LOGDIR "/atheme.log");

	cold_start = true;

	runflags |= RF_STARTING;

	me.kline_id = 0;
	me.start = time(NULL);
	CURRTIME = me.start;
	srand(arc4random());
	me.execname = argv[0];

	/* set signal handlers */
	init_signal_handlers();

	/* initialize strshare */
	strshare_init();

	/* open log */
	log_open();
	mowgli_log_set_cb(process_mowgli_log);

	slog(LG_INFO, "%s is starting up...", PACKAGE_STRING);

	/* check for pid file */
	if ((pid_file = fopen(pidfilename, "r")))
	{
		if (fgets(buf, 32, pid_file))
		{
			pid = atoi(buf);

			if (!kill(pid, 0))
			{
				fprintf(stderr, "atheme: daemon is already running\n");
				exit(EXIT_FAILURE);
			}
		}

		fclose(pid_file);
	}

#if HAVE_UMASK
	/* file creation mask */
	umask(077);
#endif

        event_init();
        hooks_init();
        init_netio();
        init_socket_queues();
	db_init();

	translation_init();
#ifdef ENABLE_NLS
	language_init();
#endif
	init_nodes();
	init_confprocess();
	init_newconf();
	servtree_init();

	modules_init();
	pcommand_init();

	conf_init();
	if (!conf_parse(config_file))
	{
		slog(LG_ERROR, "Error loading config file %s, aborting",
				config_file);
		exit(EXIT_FAILURE);
	}

	if (config_options.languagefile)
	{
		slog(LG_DEBUG, "Using language: %s", config_options.languagefile);
		if (!conf_parse(config_options.languagefile))
			slog(LG_INFO, "Error loading language file %s, continuing",
					config_options.languagefile);
	}

	authcookie_init();
	common_ctcp_init();

	if (!backend_loaded && authservice_loaded)
	{
		slog(LG_ERROR, "atheme: no backend modules loaded, see your configuration file.");
		exit(EXIT_FAILURE);
	}

	/* we've done the critical startup steps now */
	cold_start = false;

	/* load our db */
	if (db_load)
		db_load();
	else if (backend_loaded)
	{
		slog(LG_ERROR, "atheme: backend module does not provide db_load()!");
		exit(EXIT_FAILURE);
	}
	db_check();

#ifdef HAVE_FORK
	/* fork into the background */
	if (!(runflags & RF_LIVE))
	{
		close(0);
		if (open("/dev/null", O_RDWR) != 0)
		{
			slog(LG_ERROR, "unable to open /dev/null??");
			exit(EXIT_FAILURE);
		}
		if ((i = fork()) < 0)
		{
			slog(LG_ERROR, "can't fork into the background");
			exit(EXIT_FAILURE);
		}

		/* parent */
		else if (i != 0)
		{
			slog(LG_INFO, "pid %d", i);
			slog(LG_INFO, "running in background mode from %s", PREFIX);
			exit(EXIT_SUCCESS);
		}

		/* parent is gone, just us now */
		if (setsid() < 0)
		{
			slog(LG_ERROR, "unable to create new session: %s", strerror(errno));
			exit(EXIT_FAILURE);
		}
		dup2(0, 1);
		dup2(0, 2);
	}
	else
	{
		slog(LG_INFO, "pid %d", getpid());
		slog(LG_INFO, "running in foreground mode from %s", PREFIX);
	}
#else
	slog(LG_INFO, "running in foreground mode from %s", PREFIX);
#endif

#ifdef HAVE_GETPID
	/* write pid */
	if ((pid_file = fopen(pidfilename, "w")))
	{
		fprintf(pid_file, "%d\n", getpid());
		fclose(pid_file);
	}
	else
	{
		fprintf(stderr, "atheme: unable to write pid file\n");
		exit(EXIT_FAILURE);
	}
#endif
	/* no longer starting */
	runflags &= ~RF_STARTING;

	/* we probably have a few open already... */
	me.maxfd = 3;

	/* DB commit interval is configurable */
	if (db_save && !readonly)
		event_add("db_save", db_save, NULL, config_options.commit_interval);

	/* check expires every hour */
	event_add("expire_check", expire_check, NULL, 3600);

	/* check k/x/q line expires every minute */
	event_add("kline_expire", kline_expire, NULL, 60);
	event_add("xline_expire", xline_expire, NULL, 60);
	event_add("qline_expire", qline_expire, NULL, 60);

	/* check authcookie expires every ten minutes */
	event_add("authcookie_expire", authcookie_expire, NULL, 600);

	/* reseed rng a little every five minutes */
	event_add("rng_reseed", rng_reseed, NULL, 293);

	me.connected = false;
	uplink_connect();

	/* main loop */
	io_loop();

	/* we're shutting down */
	hook_call_shutdown();

	if (db_save && !readonly)
		db_save(NULL);

	remove(pidfilename);
	errno = 0;
	if (curr_uplink != NULL && curr_uplink->conn != NULL)
		sendq_flush(curr_uplink->conn);
	connection_close_all();

	me.connected = false;

	/* should we restart? */
	if (runflags & RF_RESTART)
	{
		slog(LG_INFO, "main(): restarting");

#ifdef HAVE_EXECVE
		execv(BINDIR "/atheme-services", argv);
#endif
	}

	slog(LG_INFO, "main(): shutting down");

	log_shutdown();

	return 0;
}
Esempio n. 24
0
int
main(int argc, char *argv[])
{
   uid_t         uid, euid;
   int           portarg = 0,  fd;
#ifdef SAVE_MAXCLIENT_STATS
   FILE 	*mcsfp;
#endif

   memset(&me, 0, sizeof(aClient));
	
   if ((timeofday = time(NULL)) == -1) 
   {
      (void) fprintf(stderr, "ERROR: Clock Failure (%d)\n", errno);
      exit(errno);
   }
	
   build_version();
	
   Count.server = 1;		/* us */
   Count.oper = 0;
   Count.chan = 0;
   Count.local = 0;
   Count.total = 0;
   Count.invisi = 0;
   Count.unknown = 0;
   Count.max_loc = 0;
   Count.max_tot = 0;
   Count.today = 0;
   Count.weekly = 0;
   Count.monthly = 0;
   Count.yearly = 0;
   Count.start = NOW;
   Count.day = NOW;
   Count.week = NOW;
   Count.month = NOW;
   Count.year = NOW;

#ifdef SAVE_MAXCLIENT_STATS
	mcsfp=fopen(DPATH "/.maxclients", "r");
	if(mcsfp!=NULL) {
		fscanf(mcsfp, "%d %d %li %li %li %ld %ld %ld %ld", &Count.max_loc, 
			&Count.max_tot, &Count.weekly, &Count.monthly, &Count.yearly, 
			&Count.start, &Count.week, &Count.month, &Count.year);
		fclose(mcsfp);
	}
#endif
	

	
   /*
    * this code by [email protected] 
    * it is intended to keep the ircd from being swapped out. BSD
    * swapping criteria do not match the requirements of ircd
    */
	
#ifdef INITIAL_DBUFS
   dbuf_init();			/* set up some dbuf stuff to control paging */
#endif

   sbrk0 = (char *) sbrk((size_t) 0);
   uid = getuid();
   euid = geteuid();
#ifdef	PROFIL
   (void) monstartup(0, etext);
   (void) moncontrol(1);
   (void) signal(SIGUSR1, s_monitor);
#endif
	
   myargv = argv;
   (void) umask(077);		/* better safe than sorry --SRB  */
   memset((char *) &me, '\0', sizeof(me));
	
   setup_signals();
   /*
    * * All command line parameters have the syntax "-fstring"  or "-f
    * string" (e.g. the space is optional). String may  be empty. Flag
    * characters cannot be concatenated (like "-fxyz"), it would
    * conflict with the form "-fstring".
    */
   while (--argc > 0 && (*++argv)[0] == '-') 
   {
	char       *p = argv[0] + 1;
	int         flag = *p++;
		
        if (flag == '\0' || *p == '\0') 
	{
	   if (argc > 1 && argv[1][0] != '-') 
	   {
		p = *++argv;
		argc -= 1;
	   }
	   else
		p = "";
	   }
		
      switch (flag) 
      {
		 case 'a':
			bootopt |= BOOT_AUTODIE;
			break;
		 case 'c':
			bootopt |= BOOT_CONSOLE;
			break;
		 case 'q':
			bootopt |= BOOT_QUICK;
			break;
		 case 'd':
			(void) setuid((uid_t) uid);
			dpath = p;
			break;
		 case 'o':		/* Per user local daemon... */
			(void) setuid((uid_t) uid);
			bootopt |= BOOT_OPER;
			break;
#ifdef CMDLINE_CONFIG
		 case 'f':
			(void) setuid((uid_t) uid);
			configfile = p;
			break;
			
# ifdef KPATH
		 case 'k':
			(void) setuid((uid_t) uid);
			klinefile = p;
			break;
# endif
			
#endif
		 case 'h':
			strncpyzt(me.name, p, sizeof(me.name));
			break;
		 case 'i':
			bootopt |= BOOT_INETD | BOOT_AUTODIE;
			break;
		 case 'p':
			if ((portarg = atoi(p)) > 0)
			  portnum = portarg;
			break;
		 case 's':
			bootopt |= BOOT_STDERR;
			break;
		 case 't':
			(void) setuid((uid_t) uid);
			bootopt |= BOOT_TTY;
			break;
		 case 'v':
			(void) printf("ircd %s\n", version);
			exit(0);
		 case 'x':
#ifdef	DEBUGMODE
			(void) setuid((uid_t) uid);
			debuglevel = atoi(p);
			debugmode = *p ? p : "0";
			bootopt |= BOOT_DEBUG;
			break;
#else
			(void) fprintf(stderr,
				"%s: DEBUGMODE must be defined for -x y\n",
								myargv[0]);
			exit(0);
#endif
		 default:
			bad_command();
			break;
      }
   }
	
   if (chdir(dpath)) 
   {
      perror("chdir");
      exit(-1);
   }
   if ((uid != euid) && !euid) 
   {
      (void) fprintf(stderr,
	"ERROR: do not run ircd setuid root. Make it setuid a normal user.\n");
      exit(-1);
   }
	
   if (argc > 0)
	  return bad_command();	/* This should exit out  */
   initialize_ssl();

   motd = (aMotd *) NULL;
   helpfile = (aMotd *) NULL;
   motd_tm = NULL;
#ifdef SHORT_MOTD
   shortmotd = NULL;
#endif
	
   read_motd(MOTD);
   read_help(HELPFILE);
#ifdef SHORT_MOTD
   read_shortmotd(SHORTMOTD);
#endif
	
   clear_client_hash_table();
   clear_channel_hash_table();
   clear_scache_hash_table();	/* server cache name table */
   clear_ip_hash_table();	/* client host ip hash table */

   initlists();
   initclass();
   initwhowas();
   initstats();
   init_tree_parse(msgtab);
   init_send();
   NOW = time(NULL);
   open_debugfile();
   NOW = time(NULL);
   init_fdlist(&serv_fdlist);
   init_fdlist(&oper_fdlist);
   init_fdlist(&listen_fdlist);
	
#ifndef NO_PRIORITY
   init_fdlist(&busycli_fdlist);
#endif
	
   init_fdlist(&default_fdlist);
	  {
		  int i;
		  
		  for (i = MAXCONNECTIONS + 1; i > 0; i--) 
		  {
			  default_fdlist.entry[i] = i - 1;
		  }
	  }

   if ((timeofday = time(NULL)) == -1) 
   {
#ifdef USE_SYSLOG
      syslog(LOG_WARNING, "Clock Failure (%d), TS can be corrupted", errno);
#endif
      sendto_ops("Clock Failure (%d), TS can be corrupted", errno);
   }

#ifdef WINGATE_NOTICE
   strcpy(ProxyMonURL, "http://");
   strncpyzt((ProxyMonURL + 7), DEFAULT_PROXY_INFO_URL, (TOPICLEN + 1) - 7);
   strncpyzt(ProxyMonHost, MONITOR_HOST, (HOSTLEN + 1));
#endif
	
   if (portnum < 0)
	  portnum = PORTNUM;
   me.port = portnum;
   (void) init_sys();
   me.flags = FLAGS_LISTEN;
#ifndef _WIN32
   if (bootopt & BOOT_INETD) 
   {
      me.fd = 0;
      local[0] = &me;
      me.flags = FLAGS_LISTEN;
   }
   else
#endif
	  me.fd = -1;
	
#ifdef USE_SYSLOG
# define SYSLOG_ME     "ircd"
   openlog(SYSLOG_ME, LOG_PID | LOG_NDELAY, LOG_FACILITY);
#endif
   if ((fd = openconf(configfile)) == -1) 
   {
      Debug((DEBUG_FATAL, "Failed in reading configuration file %s",
				 configfile));
      (void) printf("Couldn't open configuration file %s\n",
						  configfile);
      exit(-1);
   }
   (void) initconf(bootopt, fd);
	
   /* comstuds SEPARATE_QUOTE_KLINES_BY_DATE code */
#ifdef SEPARATE_QUOTE_KLINES_BY_DATE
	  {
		  struct tm  *tmptr;
		  char        timebuffer[20], filename[200];
		  
		  tmptr = localtime(&NOW);
		  (void) strftime(timebuffer, 20, "%y%m%d", tmptr);
		  ircsprintf(filename, "%s.%s", klinefile, timebuffer);
		  if ((fd = openconf(filename)) == -1) 
		  {
			  Debug((DEBUG_ERROR, "Failed reading kline file %s",
						filename));
			  (void) printf("Couldn't open kline file %s\n",
								 filename);
		  }
		  else
			 (void) initconf(0, fd);
	  }
#else
# ifdef KPATH
   if ((fd = openconf(klinefile)) == -1) 
   {
      Debug((DEBUG_ERROR, "Failed reading kline file %s", klinefile));
      (void) printf("Couldn't open kline file %s\n", klinefile);
   }
   else
	  (void) initconf(0, fd);
# endif
#endif
   if (!(bootopt & BOOT_INETD)) 
   {
		static char star[] = "*";
		aConfItem  *aconf;
		u_long      vaddr;
		
      if ((aconf = find_me()) && portarg <= 0 && aconf->port > 0)
		  portnum = aconf->port;

      Debug((DEBUG_ERROR, "Port = %d", portnum));

      if ((aconf->passwd[0] != '\0') && (aconf->passwd[0] != '*'))
		  vaddr = inet_addr(aconf->passwd);
      else
		  vaddr = (u_long) NULL;
		
      if (inetport(&me, star, portnum, vaddr)) 
      {
			if (bootopt & BOOT_STDERR)
			  fprintf(stderr, "Couldn't bind to primary port %d\n", portnum);
#ifdef USE_SYSLOG
			(void) syslog(LOG_CRIT, "Couldn't bind to primary port %d\n", portnum);
#endif
			exit(1);
      }
   }
   else if (inetport(&me, "*", 0, 0)) 
   {
      if (bootopt & BOOT_STDERR)
		  fprintf(stderr, "Couldn't bind to port passed from inetd\n");
#ifdef USE_SYSLOG
      (void) syslog(LOG_CRIT, "Couldn't bind to port passed from inetd\n");
#endif
      exit(1);
   }
	
   (void) get_my_name(&me, me.sockhost, sizeof(me.sockhost) - 1);
   if (me.name[0] == '\0')
	  strncpyzt(me.name, me.sockhost, sizeof(me.name));
   me.hopcount = 0;
   me.authfd = -1;
   me.confs = NULL;
   me.next = NULL;
   me.user = NULL;
   me.from = &me;
   SetMe(&me);
   make_server(&me);
   me.serv->up = me.name;
   me.lasttime = me.since = me.firsttime = NOW;
   (void) add_to_client_hash_table(me.name, &me);
	
   /* We don't want to calculate these every time they are used :) */
	
   sprintf(REPORT_DO_DNS, REPORT_DO_DNS_, me.name);
   sprintf(REPORT_FIN_DNS, REPORT_FIN_DNS_, me.name);
   sprintf(REPORT_FIN_DNSC, REPORT_FIN_DNSC_, me.name);
   sprintf(REPORT_FAIL_DNS, REPORT_FAIL_DNS_, me.name);
   sprintf(REPORT_DO_ID, REPORT_DO_ID_, me.name);
   sprintf(REPORT_FIN_ID, REPORT_FIN_ID_, me.name);
   sprintf(REPORT_FAIL_ID, REPORT_FAIL_ID_, me.name);
   R_do_dns = strlen(REPORT_DO_DNS);
   R_fin_dns = strlen(REPORT_FIN_DNS);
   R_fin_dnsc = strlen(REPORT_FIN_DNSC);
   R_fail_dns = strlen(REPORT_FAIL_DNS);
   R_do_id = strlen(REPORT_DO_ID);
   R_fin_id = strlen(REPORT_FIN_ID);
   R_fail_id = strlen(REPORT_FAIL_ID);
	
   check_class();
   if (bootopt & BOOT_OPER) 
   {
      aClient    *tmp = add_connection(&me, 0);
		
      if (!tmp)
		  exit(1);
      SetMaster(tmp);
   }
   else
	  write_pidfile();
	
   Debug((DEBUG_NOTICE, "Server ready..."));
#ifdef USE_SYSLOG
   syslog(LOG_NOTICE, "Server Ready");
#endif
   NOW = time(NULL);
	
#ifndef NO_PRIORITY
   check_fdlists();
#endif
	
   if ((timeofday = time(NULL)) == -1) 
   {
#ifdef USE_SYSLOG
      syslog(LOG_WARNING, "Clock Failure (%d), TS can be corrupted", errno);
#endif
      sendto_ops("Clock Failure (%d), TS can be corrupted", errno);
   }

#ifdef DUMP_DEBUG
   dumpfp=fopen("dump.log", "w");
#endif

   io_loop();
   return 0;
}
Esempio n. 25
0
int
main(int argc, char *argv[])
{
  /* Check to see if the user is running us as root, which is a nono */
  if (!geteuid())
  {
    fprintf(stderr, "ERROR: This server won't run as root/superuser\n");
    return -1;
  }

  /* Setup corefile size immediately after boot -kre */
  setup_corefile();

  /* Save server boot time right away, so getrusage works correctly */
  set_time();

  /* It's not random, but it ought to be a little harder to guess */
  init_genrand(SystemTime.tv_sec ^ (SystemTime.tv_usec | (getpid() << 20)));

  dlinkAdd(&me, &me.node, &global_client_list);

  ConfigGeneral.dpath      = DPATH;
  ConfigGeneral.spath      = SPATH;
  ConfigGeneral.mpath      = MPATH;
  ConfigGeneral.configfile = CPATH;    /* Server configuration file */
  ConfigGeneral.klinefile  = KPATH;    /* Server kline file         */
  ConfigGeneral.glinefile  = GPATH;    /* Server gline file         */
  ConfigGeneral.xlinefile  = XPATH;    /* Server xline file         */
  ConfigGeneral.dlinefile  = DLPATH;   /* dline file                */
  ConfigGeneral.resvfile   = RESVPATH; /* resv file                 */

  myargv = argv;
  umask(077);  /* umask 077: u=rwx,g=,o= */

  parseargs(&argc, &argv, myopts);

  if (printVersion)
  {
    printf("ircd: version %s(%s)\n", ircd_version, serno);
    exit(EXIT_SUCCESS);
  }

  if (chdir(ConfigGeneral.dpath))
  {
    perror("chdir");
    exit(EXIT_FAILURE);
  }

  ssl_init();

  if (!server_state.foreground)
  {
    make_daemon();
    close_standard_fds(); /* this needs to be before init_netio()! */
  }
  else
    print_startup(getpid());

  setup_signals();

  /* We need this to initialise the fd array before anything else */
  fdlist_init();
  log_set_file(LOG_TYPE_IRCD, 0, logFileName);

  init_netio();         /* This needs to be setup early ! -- adrian */

  /* Check if there is pidfile and daemon already running */
  check_pidfile(pidFileName);

  mp_pool_init();
  init_dlink_nodes();
  init_isupport();
  dbuf_init();
  hash_init();
  ipcache_init();
  client_init();
  class_init();
  whowas_init();
  watch_init();
  auth_init();          /* Initialise the auth code */
  init_resolver();      /* Needs to be setup before the io loop */
  modules_init();
  read_conf_files(1);   /* cold start init conf files */
  init_uid();
  initialize_server_capabs();   /* Set up default_server_capabs */
  initialize_global_set_options();  /* Has to be called after read_conf_files() */
  channel_init();
  read_links_file();
  motd_init();
  user_usermodes_init();
#ifdef HAVE_LIBGEOIP
  geoip_ctx = GeoIP_new(GEOIP_MEMORY_CACHE);
#endif

  if (EmptyString(ConfigServerInfo.sid))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server id specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.id, ConfigServerInfo.sid, sizeof(me.id));

  if (EmptyString(ConfigServerInfo.name))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server name specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.name, ConfigServerInfo.name, sizeof(me.name));

  /* serverinfo{} description must exist.  If not, error out.*/
  if (EmptyString(ConfigServerInfo.description))
  {
    ilog(LOG_TYPE_IRCD, "ERROR: No server description specified in serverinfo block.");
    exit(EXIT_FAILURE);
  }

  strlcpy(me.info, ConfigServerInfo.description, sizeof(me.info));

  me.from = &me;
  me.servptr = &me;
  me.connection->lasttime = CurrentTime;
  me.connection->since = CurrentTime;
  me.connection->firsttime = CurrentTime;

  SetMe(&me);
  make_server(&me);

  hash_add_id(&me);
  hash_add_client(&me);

  dlinkAdd(&me, make_dlink_node(), &global_server_list);

  load_kline_database();
  load_dline_database();
  load_gline_database();
  load_xline_database();
  load_resv_database();

  load_all_modules(1);
  load_conf_modules();
  load_core_modules(1);

  write_pidfile(pidFileName);

  ilog(LOG_TYPE_IRCD, "Server Ready");

  event_addish(&event_cleanup_glines, NULL);
  event_addish(&event_cleanup_tklines, NULL);

  /* We want try_connections to be called as soon as possible now! -- adrian */
  /* No, 'cause after a restart it would cause all sorts of nick collides */
  event_addish(&event_try_connections, NULL);

  /* Setup the timeout check. I'll shift it later :)  -- adrian */
  event_add(&event_comm_checktimeouts, NULL);

  event_addish(&event_save_all_databases, NULL);

  if (ConfigServerHide.links_delay > 0)
  {
    event_write_links_file.when = ConfigServerHide.links_delay;
    event_addish(&event_write_links_file, NULL);
  }
  else
    ConfigServerHide.links_disabled = 1;

  if (splitmode)
    event_addish(&splitmode_event, NULL);

  io_loop();
  return 0;
}
Esempio n. 26
0
int
main(int argc, char **argv)
{
	int x;

	umask(0077);

	/* initialize stuff */
	memset(&me, 0, sizeof(me));
	me.argc       = argc;
	me.argv       = argv;
	me.start      = time(NULL);
	me.settime    = time(NULL) + (60*60*4);

	/* setup signals */
	signal(SIGHUP,  do_signal);
	signal(SIGINT,  do_signal);
	signal(SIGQUIT, do_signal);
	signal(SIGILL,  do_signal);
	signal(SIGTRAP, do_signal);
	signal(SIGBUS,  do_signal);
	signal(SIGSEGV, do_signal);
	signal(SIGSYS,  do_signal);
	signal(SIGALRM, SIG_IGN);
	signal(SIGTERM, do_signal);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGUSR1, SIG_IGN);
	signal(SIGUSR2, SIG_IGN);

	while ((x = getopt(me.argc, me.argv, "qd")) != -1) {
		switch (x) {
			case 'd':
				me.debug = 1;
				break;
		}
	}

	if (me.debug == 0)
		printf("%s by %s\n", VER_STR, MYEMAIL);

	if (read_conf())
		err(1, "ERROR! Unable to read configuration file");

	if (!me.servname || !me.servdesc)
		errx(1, "ERROR! Your M: line is invalid, incomplete, or missing!");

	for (x = 0; x < ALL; x++)
		if (!me.sclients[x].nick || check_nick(NULL, me.sclients[x].nick) ||
			!me.sclients[x].username || check_um(NULL, me.sclients[x].username) ||
			!me.sclients[x].realname || check_rm(NULL, me.sclients[x].realname))
			errx(1, "ERROR! Your N: line for %d is invalid, incomplete, or missing!", x);

	if (!me.chans[0])
		errx(1, "ERROR! You need at least one R: line in %s", CONF);

	if (!(me.logfd = fopen(PIDFILE, "w")))
		err(1, "ERROR! Unable to open pidfile");
	fprintf(me.logfd, "%d\n", getpid());
	fclose(me.logfd);

	if (!(me.logfd = fopen(LOGFILE, "a")))
		err(1, "ERROR! Unable to open logfile");

	if ((x = read_db(0)) > 0)
		err(1, "ERROR! Unable to read %s", databases[x]);

	if (me.ip.s_addr == NULL) {
		if (!self_lookup())
			err(1, "ERROR! self-lookup failed!");
		else
			printf("WARNING: no vhost defined in conf, using default of %s\n", inet_ntoa(me.ip));
	}

	if (me.debug == 0)
		switch (me.pid = fork())
		{
			case -1:
				err(1, "ERROR! Unable to fork");
			case 0:
				for (x = 0; x < 12; x++)
					if (x != fileno(me.logfd))
						close(x);
				break;
			default:
				printf("forked into the background: pid = %d\n", me.pid);
				return 0;
		}
	listen_sock(7272);
	try_next_hub();
	add_event(1, SERVTIMEOUT / 2, &ping_hub);
	add_event(1, CONNTIMEOUT / 3, &cleanup_dcc);
	io_loop();
	/* NOTREACHED */
	exit(0);
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
  time_t      delay = 0;
  aConfItem*  aconf;
  
  if(geteuid() == 0)
  {
  	fprintf(stderr, "ERROR: Don't run ircd as root!\n");
  	return -1;
  }

  /*
   * save server boot time right away, so getrusage works correctly
   */
  if ((CurrentTime = time(0)) == -1)
    {
      fprintf(stderr, "ERROR: Clock Failure: %s\n", strerror(errno));
      exit(errno);
    }

  /*
   * Setup corefile size immediately after boot
   */
  setup_corefile();

  /* 
   * set initialVMTop before we allocate any memory
   */
  initialVMTop = get_vm_top();

  /*
   * Initialize the Blockheap allocator
   */
  initBlockHeap();

  ServerRunning = 0;
  memset(&me, 0, sizeof(me));
  GlobalClientList = &me;       /* Pointer to beginning of Client list */
  cold_start = YES;             /* set when server first starts up */

  memset(&Count, 0, sizeof(Count));
  Count.server = 1;     /* us */

  initialize_global_set_options();

#ifdef REJECT_HOLD
  reject_held_fds = 0;
#endif

  ConfigFileEntry.dpath = DPATH;

  ConfigFileEntry.configfile = CPATH;   /* Server configuration file */

#ifdef KPATH
  ConfigFileEntry.klinefile = KPATH;         /* Server kline file */
#else
  ConfigFileEntry.klinefile = CPATH;
#endif /* KPATH */

#ifdef DLPATH
  ConfigFileEntry.dlinefile = DLPATH;
#else
  ConfigFileEntry.dlinefile = CPATH;
#endif /* DLPATH */

#ifdef GLINES
  ConfigFileEntry.glinefile = GLINEFILE;
#endif

#ifdef  ZIP_LINKS
  /* Make sure the include files match the library version number. */
  /* configure takes care of looking for zlib and zlibVersion(). */
  if (strcmp(zlibVersion(), ZLIB_VERSION) != 0)
  {
    fprintf(stderr, "WARNING: zlib include files differ from library.\n");
    fprintf(stderr, "WARNING: ZIPLINKS may fail!\n");
    fprintf(stderr, "WARNING: library %s, include files %s\n",
            zlibVersion(), ZLIB_VERSION);
  }
#endif

  myargv = argv;
  umask(077);                /* better safe than sorry --SRB */

  parse_command_line(argc, argv); 

  if (chdir(ConfigFileEntry.dpath))
    {
      perror("chdir");
      exit(-1);
    }

  /*
   * Check if daemon is already running
   */
  check_pidfile();

  init_sys(bootDaemon);
  init_log(logFileName);

  setup_signals();
  initialize_message_files();

  isupport = make_isupport();

  dbuf_init();  /* set up some dbuf stuff to control paging */
  init_hash();

  clear_scache_hash_table();    /* server cache name table */
  clear_ip_hash_table();        /* client host ip hash table */
  clear_Dline_table();          /* d line tree */
  initlists();
  initclass();
  initwhowas();
  init_stats();
  init_tree_parse(msgtab);      /* tree parse code (orabidoo) */

  fdlist_init();
  init_netio();

  read_conf_files(YES);         /* cold start init conf files */

  aconf = find_me();
  if (EmptyString(me.name))
    strncpy_irc(me.name, aconf->host, HOSTLEN);
  strncpy_irc(me.host, aconf->host, HOSTLEN);

  me.fd = -1;
  me.from = &me;
  me.servptr = &me;
  SetMe(&me);
  make_server(&me);

  me.serv->up = me.name;
  me.lasttime = me.since = me.firsttime = CurrentTime;
  add_to_client_hash_table(me.name, &me);
  
  check_class();
  write_pidfile();

  log(L_NOTICE, "Server Ready");

  ServerRunning = 1;
  while (ServerRunning) {
    usleep(100000);
    do_adns_io();
    delay = io_loop(delay);
    do_adns_io();

  }
  return 0;
}
Esempio n. 28
0
int main(int argc, char *argv[])
{
	struct client client;
	unsigned int i, j;
	struct sockaddr_un addr;
	struct timespec start, end;
	int fd, wake[2];
	char buf;

	addr.sun_family = AF_UNIX;
	sprintf(addr.sun_path, "/tmp/run-different-speed.sock.%u", getpid());

	if (pipe(wake) != 0 || pipe(timeout) != 0)
		err(1, "Creating pipes");

	fd = socket(AF_UNIX, SOCK_STREAM, 0);
	if (fd < 0)
		err(1, "Creating socket");

	if (bind(fd, (void *)&addr, sizeof(addr)) != 0)
		err(1, "Binding to %s", addr.sun_path);

	if (listen(fd, NUM_CONNS) != 0)
		err(1, "Listening on %s", addr.sun_path);

	for (i = 0; i < NUM_CHILDREN; i++) {
		switch (fork()) {
		case -1:
			err(1, "forking");
		case 0:
			close(wake[1]);
			create_clients(&addr, wake[0]);
			break;
		}
		for (j = 0; j < NUM_CONNS; j++) {
			int ret = accept(fd, NULL, 0);
			if (ret < 0)
				err(1, "Accepting fd");
			/* For efficiency, we share client structure */
			io_new_conn(ret,
				    io_read(client.request_buffer, REQUEST_SIZE,
					    write_reply, &client));
		}
	}

	io_new_conn(timeout[0], io_read(&buf, 1, do_timeout, &buf));

	close(wake[0]);
	for (i = 0; i < NUM_CHILDREN; i++)
		write(wake[1], "1", 1);

	signal(SIGALRM, sigalarm);
	alarm(10);
	start = time_now();
	io_loop();
	end = time_now();
	close(fd);

	printf("%u connections complete (%u ns per conn)\n",
	       completed,
	       (int)time_to_nsec(time_divide(time_sub(end, start), completed)));
	return 0;
}
Esempio n. 29
0
int atheme_main(int argc, char *argv[])
{
	int daemonize_pipe[2];
	bool have_conf = false;
	bool have_log = false;
	bool have_datadir = false;
	char buf[32];
	int pid, r;
	FILE *pid_file;
	const char *pidfilename = RUNDIR "/atheme.pid";
	char *log_p = NULL;
	mowgli_getopt_option_t long_opts[] = {
		{ NULL, 0, NULL, 0, 0 },
	};

	atheme_bootstrap();

	/* do command-line options */
	while ((r = mowgli_getopt_long(argc, argv, "c:dhrl:np:D:v", long_opts, NULL)) != -1)
	{
		switch (r)
		{
		  case 'c':
			  config_file = sstrdup(mowgli_optarg);
			  have_conf = true;
			  break;
		  case 'd':
			  log_force = true;
			  break;
		  case 'h':
			  print_help();
			  exit(EXIT_SUCCESS);
			  break;
		  case 'r':
			  readonly = true;
			  break;
		  case 'l':
			  log_p = sstrdup(mowgli_optarg);
			  have_log = true;
			  break;
		  case 'n':
			  runflags |= RF_LIVE;
			  break;
		  case 'p':
			  pidfilename = mowgli_optarg;
			  break;
		  case 'D':
			  datadir = mowgli_optarg;
			  have_datadir = true;
			  break;
		  case 'v':
			  print_version();
			  exit(EXIT_SUCCESS);
			  break;
		  default:
			  printf("usage: atheme [-dhnvr] [-c conf] [-l logfile] [-p pidfile]\n");
			  exit(EXIT_FAILURE);
			  break;
		}
	}

	if (!have_conf)
		config_file = sstrdup(SYSCONFDIR "/atheme.conf");

	if (!have_log)
		log_p = sstrdup(LOGDIR "/atheme.log");

	if (!have_datadir)
		datadir = sstrdup(DATADIR);

	cold_start = true;

	runflags |= RF_STARTING;

	atheme_init(argv[0], log_p);

	slog(LG_INFO, "%s is starting up...", PACKAGE_STRING);

	/* check for pid file */
#ifndef MOWGLI_OS_WIN
	if ((pid_file = fopen(pidfilename, "r")))
	{
		if (fgets(buf, 32, pid_file))
		{
			pid = atoi(buf);

			if (!kill(pid, 0))
			{
				fprintf(stderr, "atheme: daemon is already running\n");
				exit(EXIT_FAILURE);
			}
		}

		fclose(pid_file);
	}
#endif

	if (!(runflags & RF_LIVE))
		daemonize(daemonize_pipe);

	atheme_setup();

	conf_init();
	if (!conf_parse(config_file))
	{
		slog(LG_ERROR, "Error loading config file %s, aborting",
				config_file);
		exit(EXIT_FAILURE);
	}

	if (config_options.languagefile)
	{
		slog(LG_DEBUG, "Using language: %s", config_options.languagefile);
		if (!conf_parse(config_options.languagefile))
			slog(LG_INFO, "Error loading language file %s, continuing",
					config_options.languagefile);
	}

	if (!backend_loaded && authservice_loaded)
	{
		slog(LG_ERROR, "atheme: no backend modules loaded, see your configuration file.");
		exit(EXIT_FAILURE);
	}

	/* we've done the critical startup steps now */
	cold_start = false;

	/* load our db */
	if (db_load)
		db_load(NULL);
	else if (backend_loaded)
	{
		slog(LG_ERROR, "atheme: backend module does not provide db_load()!");
		exit(EXIT_FAILURE);
	}
	db_check();

#ifdef HAVE_GETPID
	/* write pid */
	if ((pid_file = fopen(pidfilename, "w")))
	{
		fprintf(pid_file, "%d\n", getpid());
		fclose(pid_file);
	}
	else
	{
		fprintf(stderr, "atheme: unable to write pid file\n");
		exit(EXIT_FAILURE);
	}
#endif

	/* detach from terminal */
	if ((runflags & RF_LIVE) || !detach_console(daemonize_pipe))
	{
#ifdef HAVE_GETPID
		slog(LG_INFO, "pid %d", getpid());
#endif
		slog(LG_INFO, "running in foreground mode from %s", PREFIX);
	}

	/* no longer starting */
	runflags &= ~RF_STARTING;

	/* we probably have a few open already... */
	me.maxfd = 3;

	/* DB commit interval is configurable */
	if (db_save && !readonly)
		mowgli_timer_add(base_eventloop, "db_save", db_save, NULL, config_options.commit_interval);

	/* check expires every hour */
	mowgli_timer_add(base_eventloop, "expire_check", expire_check, NULL, 3600);

	/* check k/x/q line expires every minute */
	mowgli_timer_add(base_eventloop, "kline_expire", kline_expire, NULL, 60);
	mowgli_timer_add(base_eventloop, "xline_expire", xline_expire, NULL, 60);
	mowgli_timer_add(base_eventloop, "qline_expire", qline_expire, NULL, 60);

	/* check authcookie expires every ten minutes */
	mowgli_timer_add(base_eventloop, "authcookie_expire", authcookie_expire, NULL, 600);

	/* reseed rng a little every five minutes */
	mowgli_timer_add(base_eventloop, "rng_reseed", rng_reseed, NULL, 293);

	me.connected = false;
	uplink_connect();

	/* main loop */
	io_loop();

	/* we're shutting down */
	hook_call_shutdown();

	if (db_save && !readonly)
		db_save(NULL);

	remove(pidfilename);
	errno = 0;
	if (curr_uplink != NULL && curr_uplink->conn != NULL)
		sendq_flush(curr_uplink->conn);
	connection_close_all();

	me.connected = false;

	/* should we restart? */
	if (runflags & RF_RESTART)
	{
		slog(LG_INFO, "main(): restarting");

#ifdef HAVE_EXECVE
		execv(BINDIR "/atheme-services", argv);
#endif
	}

	slog(LG_INFO, "main(): shutting down");

	mowgli_eventloop_destroy(base_eventloop);
	log_shutdown();

	return 0;
}
Esempio n. 30
0
int idle()
{
	static struct timeval	pta = { 0, 0 };
	static int			process_time_count = 0;
	struct timeval		now;

	if (pta.tv_sec == 0)
		gettimeofday(&pta, (struct timezone *) 0);

	int passed_pulses;

	if (!(passed_pulses = thecore_idle()))
		return 0;

	assert(passed_pulses > 0);

	DWORD t;

	while (passed_pulses--) {
		heartbeat(thecore_heart, ++thecore_heart->pulse);

		// To reduce the possibility of abort() in checkpointing
		thecore_tick();
	}

	t = get_dword_time();
	CHARACTER_MANAGER::instance().Update(thecore_heart->pulse);
	db_clientdesc->Update(t);
	s_dwProfiler[PROF_CHR_UPDATE] += (get_dword_time() - t);

	t = get_dword_time();
	if (!io_loop(main_fdw)) return 0;
	s_dwProfiler[PROF_IO] += (get_dword_time() - t);

	log_rotate();

	gettimeofday(&now, (struct timezone *) 0);
	++process_time_count;

	if (now.tv_sec - pta.tv_sec > 0)
	{
		pt_log("[%3d] event %5d/%-5d idle %-4ld event %-4ld heartbeat %-4ld I/O %-4ld chrUpate %-4ld | WRITE: %-7d | PULSE: %d",
				process_time_count,
				num_events_called,
				event_count(),
				thecore_profiler[PF_IDLE],
				s_dwProfiler[PROF_EVENT],
				s_dwProfiler[PROF_HEARTBEAT],
				s_dwProfiler[PROF_IO],
				s_dwProfiler[PROF_CHR_UPDATE],
				current_bytes_written,
				thecore_pulse());

		num_events_called = 0;
		current_bytes_written = 0;

		process_time_count = 0; 
		gettimeofday(&pta, (struct timezone *) 0);

		memset(&thecore_profiler[0], 0, sizeof(thecore_profiler));
		memset(&s_dwProfiler[0], 0, sizeof(s_dwProfiler));
	}

#ifdef _WIN32
	if (_kbhit()) {
		int c = _getch();
		switch (c) {
			case 0x1b: // Esc
				return 0; // shutdown
				break;
			default:
				break;
		}
	}
#endif

	return 1;
}