Beispiel #1
0
void run_and_record_output(pcap_list_t *pkt_list, char *pcap_base, uint16_t num_pcaps, int debug) {
    int *sockfds = init_sockets(pcap_base, num_pcaps);
    feed_packets(sockfds, pkt_list);
    close_sockets(sockfds, num_pcaps);
    /* Sleep a bit to allow the remaining processes to finish */
    sleep(2);
}
int main(int argc, char **argv){
    if (argc != 5){
        printf("Wrong args\n");
        exit(0);
    }
    fd = open(argv[4], O_WRONLY|O_CREAT);
    if (fd == -1){
        printf("Error opening log file\n");
        exit(1);
    }
    connected = 0;
    all_get = 0;
    start_seq_num = (unsigned int)rand();
    expected_seq = 0;
    last_seq = 0;
    passive_fin = 0;
    create_sockets();
    ini_send_addr(argv[2]);
    int recv_port = ini_recv_addr();
    conn_server(argv[1], argv[2], argv[3], recv_port);
    printf("Connection established!\n");
    receive_data(argv[1], argv[2], argv[3], recv_port);
    disconnect(argv[1], argv[2], argv[3], recv_port);
    close_sockets();
    close(fd);
    return 0;
}
Beispiel #3
0
BOOL
send_null_session_msg (int fd)
{
    ssize_t ret;
    uint32 blank = 0;
    size_t len = 4;
    size_t nwritten = 0;
    char *buffer = (char *) ␣

    while (nwritten < len)
    {
        ret = write_socket (fd, buffer + nwritten, len - nwritten);
        if (ret <= 0)
        {
            DEBUG (0,
                   ("send_null_session_msg: Error writing %d bytes to client. %d. Exiting\n",
                    (int) len, (int) ret));
            close_sockets ();
            exit (1);
        }
        nwritten += ret;
    }

    DEBUG (10, ("send_null_session_msg: sent 4 null bytes to client.\n"));
    return True;
}
Beispiel #4
0
void exit_func ()
{
    pthread_join (node_send_thread, NULL);
    close_sockets ();
    cout << "Total host entries freed: " << hosts.free_list() << endl;
    cout << "Total port entries freed: " << ports.free_list() << endl;
    cout << "Total links entries freed: " << links.free_list() << endl;
    cout << "Total reply entries freed: " << sw_replys.free_list() << endl;
}
Beispiel #5
0
/* clear all status and exit program. */
static void
close_session()
{
	flushph1();
	close_sockets();
	backupsa_clean();

	plog(LLV_INFO, LOCATION, NULL, "racoon shutdown\n");
	exit(0);
}
Beispiel #6
0
void main_err(char *message)
{
  fprintf(stderr,"%s\n",message);
  if( errno )
    perror(NULL);

  close_sockets();

  exit(1);
}
void signal_fatal(int sig)
{
  signal(sig,SIG_DFL);
  nlog("A fatal signal (%d) was caught.", sig);
  if(crash_save){
    close_sockets(0);
    nlog("All sockets were closed.");
    kill(getpid(),SIGABRT);
  }
  /*return SIG_RET_VAL;*/
}
Beispiel #8
0
int receiver(McastResult** test_results, int n_addr, int n_stream, int test_inc, char *start_addr, int start_port, int buf_len, int mbps, int timeout, int verbose){
	// test_inc = 0, just do one test
	// test_inc = n, test  1,1+n, 1+2n... n_addr addresses.
	int n_tests;	
	n_tests =  3 + n_addr/(test_inc);
	sockets = malloc(sizeof(int) * n_addr * n_stream + sizeof(int));
	sockets[n_addr * n_stream] = -1;
	int j, ind = 0;
	open_sockets(n_addr, n_stream,start_port, start_addr);
	j = 1;
	//test level.
	n_tests = 0;
	int jitterSize = 0;
	
	while(j <= n_addr ){
		/* hack needed for vms... */
		if (n_tests > 0 && n_tests % 15 == 0){
			close_sockets();
			open_sockets(n_addr, n_stream,start_port, start_addr);
		}
				
		int tout = timeout;
		if (n_tests == 0 && restarted == 0) tout = 300;
		test_results[ind] =  run_tests(j, n_stream, start_addr, start_port, buf_len, &jitterSize, tout,verbose);
		if (test_results[ind] == NULL){
			break;
		}
		if (verbose == 1) disp_results(test_results[ind]);
		n_tests++;
		ind++;
		if (j == n_addr) break;
		if (j == 1 && test_inc != 1) j = 0;
		j += test_inc;
		if (j > n_addr) j = n_addr;
	}
	
	close_sockets();
	free(sockets);
	restarted = 1;
	return n_tests;
}
// Main function here.
int main() {
    putchar('\n');
    printf("The Server %c is up and running.\n", SERVER_NAME_CHAR);
    set_up_UDP_socket();
    read_file();
    set_up_TCP_socket();
    connect_to_client_over_TCP();
    send_neighbor_info_over_TCP();
    receive_network_topology_over_UDP();
    close_sockets();
    return 0;
}
Beispiel #10
0
/* clear all status and exit program. */
static void
close_session()
{
#ifdef ENABLE_FASTQUIT
	flushph2();
#endif
	flushph1();
	close_sockets();
	backupsa_clean();

	plog(LLV_INFO, LOCATION, NULL, "racoon shutdown\n");
	exit(0);
}
Beispiel #11
0
void fatal_error(char *message)
{
    fprintf(stderr,"%s\n",message);
    if( errno )
        perror(NULL);
    fflush(stderr);

    close(client_socket);
    if( !will_fork ) {
        close_sockets();
        abort();
    } else
        exit(-1);
}
Beispiel #12
0
BOOL send_smb(int fd,char *buffer)
{
  size_t len;
  size_t nwritten=0;
  ssize_t ret;
  len = smb_len(buffer) + 4;

  while (nwritten < len)
  {
    ret = write_socket(fd,buffer+nwritten,len - nwritten);
    if (ret <= 0)
    {
      DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",(int)len,(int)ret));
      close_sockets();
      exit(1);
    }
    nwritten += ret;
  }

  return True;
}
Beispiel #13
0
void
prim_armageddon(PRIM_PROTOTYPE)
{
    char buf[BUFFER_LEN];

    /* ( s<message> -- ) */

    CHECKOP(1);
    oper1 = POP();

    if (mlev < LBOY)
        abort_interp("W4 primitive.");
    if (oper1->type != PROG_STRING)
        abort_interp("String expected.");

    sprintf(buf, "\r\nImmediate shutdown by %s.\r\n", NAME(PSafe));
    if (oper1->data.string) {
        strcat(buf, SYSWHITE MARK SYSNORMAL);
        strcat(buf, oper1->data.string->data);
        strcat(buf, "\r\n");
    }

    CLEAR(oper1);
    log_status("DDAY(MUF: %d): by %s(%d)\n", program,
               OkObj(player) ? NAME(player) : "(login)", player);
    fprintf(stderr, "DDAY(MUF: %d): by %s(%d)\n", program,
            OkObj(player) ? NAME(player) : "(login)", player);
    close_sockets(buf);

#ifdef SPAWN_HOST_RESOLVER
    kill_resolver();
#endif
#ifdef USE_RESLVD
    reslvd_close();
#endif

    exit(1);
}
Beispiel #14
0
/** Connect to another talk client. */
int TalkConnection::connect()
{
    ktalk_debug("Waiting to connect");
    do {
        errno = 0;
        if (::connect(sockt, (const sockaddr *)(&lookup_addr), sizeof (struct talk_addr)) != -1)
            return 1;
    } while (errno == EINTR);
    if (errno == ECONNREFUSED) {
        /*
         * The caller gave up, but his invitation somehow
         * was not cleared. Clear it and initiate an
         * invitation. (We know there are no newer invitations,
         * the talkd works LIFO.)
         */
        ktalk_debug("ECONNREFUSED");
        ctl_transact(DELETE, 0);
        close_sockets();
        return 0;
    }
    p_error("Unable to connect with initiator");
    /*NOTREACHED*/
    return 0;
}
Beispiel #15
0
static void lock_cachefile(int cachefile, int type)
{
	struct flock fl = {
		.l_len = 0,
		.l_start = 0,
		.l_whence = SEEK_SET,
	};

	fl.l_pid = getpid();
	fl.l_type = type;

	if (verbose)
		output(2, "waiting on lock for cachefile\n");

	if (fcntl(cachefile, F_SETLKW, &fl) == -1) {
		perror("fcntl F_SETLKW");
		exit(1);
	}

	if (verbose)
		output(2, "took lock for cachefile\n");
}

static void unlock_cachefile(int cachefile)
{
	struct flock fl = {
		.l_len = 0,
		.l_start = 0,
		.l_whence = SEEK_SET,
	};

	fl.l_pid = getpid();
	fl.l_type = F_UNLCK;

	if (fcntl(cachefile, F_SETLK, &fl) == -1) {
		perror("fcntl F_UNLCK F_SETLK ");
		exit(1);
	}

	if (verbose)
		output(2, "dropped lock for cachefile\n");
}

static void generate_sockets(void)
{
	int fd, n;
	int cachefile;
	unsigned int nr_to_create = NR_SOCKET_FDS;
	unsigned int buffer[3];

	cachefile = creat(cachefilename, S_IWUSR|S_IRUSR);
	if (cachefile < 0) {
		outputerr("Couldn't open cachefile for writing! (%s)\n",
			strerror(errno));
		exit(EXIT_FAILURE);
	}

	lock_cachefile(cachefile, F_WRLCK);

	/*
	 * Don't loop forever if all protos all are disabled.
	 */
	if (!do_specific_proto) {
		for (n = 0; n < (int)ARRAY_SIZE(no_protos); n++) {
			if (!no_protos[n])
				break;
		}

		if (n >= (int)ARRAY_SIZE(no_protos))
			nr_to_create = 0;
	}

	while (nr_to_create > 0) {

		struct socket_triplet st;

		if (shm->exit_reason != STILL_RUNNING) {
			close(cachefile);
			return;
		}

		for (st.family = 0; st.family < TRINITY_PF_MAX; st.family++) {

			if (do_specific_proto == TRUE)
				st.family = specific_proto;

			if (get_proto_name(st.family) == NULL)
				goto skip;

			BUG_ON(st.family >= ARRAY_SIZE(no_protos));
			if (no_protos[st.family])
				goto skip;

			if (sanitise_socket_triplet(&st) == -1)
				rand_proto_type(&st);

			fd = open_socket(st.family, st.type, st.protocol);
			if (fd > -1) {
				nr_to_create--;

				buffer[0] = st.family;
				buffer[1] = st.type;
				buffer[2] = st.protocol;
				n = write(cachefile, &buffer, sizeof(int) * 3);
				if (n == -1) {
					outputerr("something went wrong writing the cachefile!\n");
					exit(EXIT_FAILURE);
				}

				if (nr_to_create == 0)
					goto done;
			} else {
				//outputerr("Couldn't open family:%d (%s)\n", st.family, get_proto_name(st.family));
			}
skip:

			/* check for ctrl-c */
			if (shm->exit_reason != STILL_RUNNING)
				return;

			//FIXME: If we've passed -P and we're spinning here without making progress
			// then we should abort after a few hundred loops.
		}
	}

done:
	unlock_cachefile(cachefile);

	output(1, "created %d sockets\n", nr_sockets);

	close(cachefile);
}


void close_sockets(void)
{
	unsigned int i;
	int fd;
	int r = 0;
	struct linger ling = { .l_onoff = FALSE, .l_linger = 0 };

	for (i = 0; i < nr_sockets; i++) {

		//FIXME: This is a workaround for a weird bug where we hang forevre
		// waiting for bluetooth sockets when we setsockopt.
		// Hopefully at some point we can remove this when someone figures out what's going on.
		if (shm->sockets[i].triplet.family == PF_BLUETOOTH)
			continue;

		/* Grab an fd, and nuke it before someone else uses it. */
		fd = shm->sockets[i].fd;
		shm->sockets[i].fd = 0;

		/* disable linger */
		r = setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(struct linger));
		if (r)
			perror("setsockopt");

		r = shutdown(fd, SHUT_RDWR);
		if (r)
			perror("shutdown");

		if (close(fd) != 0)
			output(1, "failed to close socket [%d:%d:%d].(%s)\n",
				shm->sockets[i].triplet.family,
				shm->sockets[i].triplet.type,
				shm->sockets[i].triplet.protocol,
				strerror(errno));
	}

	nr_sockets = 0;
}

void open_sockets(void)
{
	int cachefile;
	unsigned int domain, type, protocol;
	unsigned int buffer[3];
	int bytesread=-1;
	int fd;

	cachefile = open(cachefilename, O_RDONLY);
	if (cachefile < 0) {
		output(1, "Couldn't find socket cachefile. Regenerating.\n");
		generate_sockets();
		return;
	}

	lock_cachefile(cachefile, F_RDLCK);

	while (bytesread != 0) {
		bytesread = read(cachefile, buffer, sizeof(int) * 3);
		if (bytesread == 0)
			break;

		domain = buffer[0];
		type = buffer[1];
		protocol = buffer[2];

		if ((do_specific_proto == TRUE && domain != specific_proto) ||
		    (domain < ARRAY_SIZE(no_protos) && no_protos[domain] == TRUE)) {
			output(1, "ignoring socket cachefile due to specific "
			       "protocol request (or protocol disabled), "
			       "and stale data in cachefile.\n");
regenerate:
				unlock_cachefile(cachefile);	/* drop the reader lock. */
				close(cachefile);
				unlink(cachefilename);
				generate_sockets();
				return;
		}

		fd = open_socket(domain, type, protocol);
		if (fd < 0) {
			output(1, "Cachefile is stale. Need to regenerate.\n");
			close_sockets();
			goto regenerate;
		}

		/* check for ctrl-c */
		if (shm->exit_reason != STILL_RUNNING) {
			close(cachefile);
			return;
		}
	}

	if (nr_sockets < NR_SOCKET_FDS) {
		output(1, "Insufficient sockets in cachefile (%d). Regenerating.\n", nr_sockets);
		goto regenerate;
	}

	output(1, "%d sockets created based on info from socket cachefile.\n", nr_sockets);

	unlock_cachefile(cachefile);
	close(cachefile);
}
Beispiel #16
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
  fstring base_directory;
  char *pname = argv[0];
  int opt;
  extern FILE *dbf;
  extern char *optarg;
  extern int optind;
  pstring query_host;
  BOOL nt_domain_logon = False;
  static pstring servicesf = CONFIGFILE;
  pstring term_code;
  char *p;

#ifdef KANJI
  pstrcpy(term_code, KANJI);
#else /* KANJI */
  *term_code = 0;
#endif /* KANJI */

  *query_host = 0;
  *base_directory = 0;

  DEBUGLEVEL = 2;

  setup_logging(pname,True);

  TimeInit();
  charset_initialise();

  pid = getpid();
  uid = getuid();
  gid = getgid();
  mid = pid + 100;
  myumask = umask(0);
  umask(myumask);

  if (getenv("USER"))
  {
    pstrcpy(username,getenv("USER"));

    /* modification to support userid%passwd syntax in the USER var
       25.Aug.97, [email protected] */

    if ((p=strchr(username,'%')))
    {
      *p = 0;
      pstrcpy(password,p+1);
      got_pass = True;
      memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
    }
    strupper(username);
  }

 /* modification to support PASSWD environmental var
  25.Aug.97, [email protected] */

  if (getenv("PASSWD"))
    pstrcpy(password,getenv("PASSWD"));

  if (*username == 0 && getenv("LOGNAME"))
    {
      pstrcpy(username,getenv("LOGNAME"));
      strupper(username);
    }

  if (argc < 2)
    {
      usage(pname);
      exit(1);
    }
  
  if (*argv[1] != '-')
    {

      pstrcpy(service, argv[1]);  
      /* Convert any '/' characters in the service name to '\' characters */
      string_replace( service, '/','\\');
      argc--;
      argv++;

      if (count_chars(service,'\\') < 3)
	{
	  usage(pname);
	  printf("\n%s: Not enough '\\' characters in service\n",service);
	  exit(1);
	}

      if (argc > 1 && (*argv[1] != '-'))
	{
	  got_pass = True;
	  pstrcpy(password,argv[1]);  
	  memset(argv[1],'X',strlen(argv[1]));
	  argc--;
	  argv++;
	}
    }

  while ((opt = 
	  getopt(argc, argv,"s:B:O:M:S:i:Nn:d:Pp:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
    switch (opt)
      {
      case 'm':
	max_protocol = interpret_protocol(optarg,max_protocol);
	break;
      case 'O':
	pstrcpy(user_socket_options,optarg);
	break;	
      case 'S':
	pstrcpy(desthost,optarg);
	strupper(desthost);
	nt_domain_logon = True;
	break;
      case 'B':
	iface_set_default(NULL,optarg,NULL);
	break;
      case 'D':
	pstrcpy(base_directory,optarg);
	break;
      case 'i':
	pstrcpy(scope,optarg);
	break;
      case 'U':
	{
	  char *lp;
	pstrcpy(username,optarg);
	if ((lp=strchr(username,'%')))
	  {
	    *lp = 0;
	    pstrcpy(password,lp+1);
	    got_pass = True;
	    memset(strchr(optarg,'%')+1,'X',strlen(password));
	  }
	}
	    
	break;
      case 'W':
	pstrcpy(workgroup,optarg);
	break;
      case 'E':
	dbf = stderr;
	break;
      case 'I':
	{
	  dest_ip = *interpret_addr2(optarg);
	  if (zero_ip(dest_ip)) exit(1);
	  have_ip = True;
	}
	break;
      case 'n':
	pstrcpy(myname,optarg);
	break;
      case 'N':
	got_pass = True;
	break;
      case 'd':
	if (*optarg == 'A')
	  DEBUGLEVEL = 10000;
	else
	  DEBUGLEVEL = atoi(optarg);
	break;
      case 'l':
	slprintf(debugf,sizeof(debugf)-1,"%s.client",optarg);
	break;
      case 'p':
	port = atoi(optarg);
	break;
      case 'c':
	cmdstr = optarg;
	got_pass = True;
	break;
      case 'h':
	usage(pname);
	exit(0);
	break;
      case 's':
	pstrcpy(servicesf, optarg);
	break;
      case 't':
        pstrcpy(term_code, optarg);
	break;
      default:
	usage(pname);
	exit(1);
      }

  if (!*query_host && !*service)
    {
      usage(pname);
      exit(1);
    }


  DEBUG(3,("%s client started (version %s)\n",timestring(),VERSION));

  if(!get_myname(myhostname,NULL))
  {
    DEBUG(0,("Failed to get my hostname.\n"));
  }

  if (!lp_load(servicesf,True)) {
    fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
  }

  codepage_initialise(lp_client_code_page());

  interpret_coding_system(term_code);

  if (*workgroup == 0)
    pstrcpy(workgroup,lp_workgroup());

  load_interfaces();
  get_myname((*myname)?NULL:myname,NULL);  
  strupper(myname);

#ifdef NTDOMAIN

	if (nt_domain_logon)
	{
		int ret = 0;
		slprintf(service,sizeof(service), "\\\\%s\\IPC$",query_host);
		strupper(service);
		connect_as_ipc = True;

		DEBUG(5,("NT Domain Logon.  Service: %s\n", service));

		if (cli_open_sockets(port))
		{
			if (!cli_send_login(NULL,NULL,True,True,NULL)) return(1);

			do_nt_login(desthost, myhostname, Client, cnum);

			cli_send_logout();
			close_sockets();
		}

		return(ret);
	}
#endif 

  if (cli_open_sockets(port))
    {
      if (!process(base_directory))
	{
	  close_sockets();
	  return(1);
	}
      close_sockets();
    }
  else
    return(1);

  return(0);
}
Beispiel #17
0
/*
 * Call the smbfs ioctl to install a connection socket,
 * then wait for a signal to reconnect. Note that we do
 * not exit after open_sockets() or send_login() errors,
 * as the smbfs mount would then have no way to recover.
 */
static void
send_fs_socket(char *mount_point, char *inbuf, char *outbuf)
{
	int fd, closed = 0, res = 1;

	while (1)
	{
		if ((fd = open(mount_point, O_RDONLY)) < 0)
		{
			DEBUG(0, ("smbmount: can't open %s\n", mount_point));
			break;
		}		

		/*
		 * Call the ioctl even if we couldn't get a socket ...
		 * there's no point in making smbfs wait for a timeout.
		 */
		conn_options.fd = -1;
		if (res)
			conn_options.fd = Client;
		res = ioctl(fd, SMB_IOC_NEWCONN, &conn_options);
		if (res != 0)
		{
			DEBUG(0, ("smbmount: ioctl failed, res=%d\n", res));
		}

		close_sockets();
		close(fd);
		/*
		 * Close all open files if we haven't done so yet.
		 */
#ifndef SMBFS_DEBUG
		if (!closed)
		{
			closed = 1;
			close_our_files();
		}
#endif

		/*
		 * Wait for a signal from smbfs ...
		 */
		signal(SIGUSR1, &usr1_handler);
		pause();
		DEBUG(0, ("smbmount: got signal, getting new socket\n"));

		res = cli_open_sockets(port);
		if (!res)
		{
			DEBUG(0, ("smbmount: can't open sockets\n"));
			continue;
		}

		res = mount_send_login(inbuf, outbuf);
		if (!res)
		{
			DEBUG(0, ("smbmount: login failed\n"));
		}
	}
	DEBUG(0, ("smbmount: exit\n"));
	exit(1);
}
Beispiel #18
0
int main(int argc, char* argv[])
{
	int ret = EXIT_SUCCESS;
	int childstatus;
	pid_t pid;
	const char taskname[13]="trinity-main";

	outputstd("Trinity " VERSION "  Dave Jones <*****@*****.**>\n");

	progname = argv[0];

	initpid = getpid();

	page_size = getpagesize();
	num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
	max_children = num_online_cpus;	/* possibly overridden in params. */

	if (init_random() == FALSE)
		exit(EXIT_FAILURE);

	set_seed(0);

	select_syscall_tables();

	create_shm();

	/* We do this before the parse_args because --fds will need to
	 * operate on it when implemented.
	 */
	setup_fd_providers();

	parse_args(argc, argv);

	init_uids();

	change_tmp_dir();

	init_logging();

	init_shm();

	kernel_taint_initial = check_tainted();
	if (kernel_taint_initial != 0)
		output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n");

	if (munge_tables() == FALSE) {
		ret = EXIT_FAILURE;
		goto out;
	}

	if (show_syscall_list == TRUE) {
		dump_syscall_tables();
		goto out;
	}

	init_syscalls();

	if (show_ioctl_list == TRUE) {
		dump_ioctls();
		goto out;
	}

	do_uid0_check();

	if (do_specific_domain == TRUE)
		find_specific_domain(specific_domain_optarg);

	setup_initial_mappings();

	parse_devices();

	pids_init();

	setup_main_signals();

	/* check if we ctrl'c or something went wrong during init. */
	if (shm->exit_reason != STILL_RUNNING)
		goto cleanup_fds;

	init_watchdog();

	/* do an extra fork so that the watchdog and the children don't share a common parent */
	fflush(stdout);
	pid = fork();
	if (pid == 0) {
		shm->mainpid = getpid();

		setup_main_signals();

		no_bind_to_cpu = RAND_BOOL();

		output(0, "Main thread is alive.\n");
		prctl(PR_SET_NAME, (unsigned long) &taskname);
		set_seed(0);

		if (open_fds() == FALSE) {
			if (shm->exit_reason != STILL_RUNNING)
				panic(EXIT_FD_INIT_FAILURE);	// FIXME: Later, push this down to multiple EXIT's.

			exit_main_fail();
		}

		if (dropprivs == TRUE)	//FIXME: Push down into child processes later.
			drop_privs();

		main_loop();

		shm->mainpid = 0;
		_exit(EXIT_SUCCESS);
	}

	/* wait for main loop process to exit. */
	(void)waitpid(pid, &childstatus, 0);

	/* wait for watchdog to exit. */
	waitpid(watchdog_pid, &childstatus, 0);

	output(0, "Ran %ld syscalls. Successes: %ld  Failures: %ld\n",
		shm->stats.total_syscalls_done - 1, shm->stats.successes, shm->stats.failures);

cleanup_fds:

	close_sockets();

	destroy_initial_mappings();

	shutdown_logging();

	ret = set_exit_code(shm->exit_reason);
out:

	exit(ret);
}
Beispiel #19
0
void server_shutdown(int signal)
{
  fprintf(stderr,"Caught signal %d.\n", signal);
  close_sockets();
  exit(0);
}
Beispiel #20
0
int main(int argc, char* argv[])
{
	int ret = EXIT_SUCCESS;
	int childstatus;
	unsigned int i;

	outputstd("Trinity v" __stringify(VERSION) "  Dave Jones <*****@*****.**>\n");

	progname = argv[0];

	initpid = getpid();

	page_size = getpagesize();
	num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN);

	select_syscall_tables();

	if (create_shm())
		exit(EXIT_FAILURE);

	parse_args(argc, argv);
	outputstd("Done parsing arguments.\n");

	if (kernel_taint_mask != (int)0xFFFFFFFF) {
		outputstd("Custom kernel taint mask has been specified: 0x%08x (%d).\n", kernel_taint_mask, kernel_taint_mask);
	}

	if (user_specified_children != 0)
		max_children = user_specified_children;
	else
		max_children = sysconf(_SC_NPROCESSORS_ONLN);

	if (max_children > MAX_NR_CHILDREN) {
		outputerr("Increase MAX_NR_CHILDREN!\n");
		exit(EXIT_FAILURE);
	}

	setup_shm_postargs();

	if (logging == TRUE)
		open_logfiles();

	if (munge_tables() == FALSE) {
		ret = EXIT_FAILURE;
		goto out;
	}

	if (show_syscall_list == TRUE) {
		dump_syscall_tables();
		goto out;
	}

	init_syscalls();

	if (show_ioctl_list == TRUE) {
		dump_ioctls();
		goto out;
	}

	if (getuid() == 0) {
		if (dangerous == TRUE) {
			outputstd("DANGER: RUNNING AS ROOT.\n");
			outputstd("Unless you are running in a virtual machine, this could cause serious problems such as overwriting CMOS\n");
			outputstd("or similar which could potentially make this machine unbootable without a firmware reset.\n\n");
			outputstd("ctrl-c now unless you really know what you are doing.\n");
			for (i = 10; i > 0; i--) {
				outputstd("Continuing in %d seconds.\r", i);
				(void)fflush(stdout);
				sleep(1);
			}
		} else {
			outputstd("Don't run as root (or pass --dangerous if you know what you are doing).\n");
			exit(EXIT_FAILURE);
		}
	}

	if (do_specific_proto == TRUE)
		find_specific_proto(specific_proto_optarg);

	init_buffers();

	parse_devices();

	pids_init();

	setup_main_signals();

	kernel_taint_initial = check_tainted();
	if (kernel_taint_initial != 0) {
		output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n");
	}

	change_tmp_dir();

	/* check if we ctrl'c or something went wrong during init. */
	if (shm->exit_reason != STILL_RUNNING)
		goto cleanup_fds;

	init_watchdog();

	do_main_loop();

	/* Shutting down. */
	waitpid(watchdog_pid, &childstatus, 0);

	output(0, "\nRan %ld syscalls. Successes: %ld  Failures: %ld\n",
		shm->total_syscalls_done - 1, shm->successes, shm->failures);

	ret = EXIT_SUCCESS;

cleanup_fds:

	close_sockets();

	destroy_global_mappings();

	if (logging == TRUE)
		close_logfiles();

out:

	exit(ret);
}
Beispiel #21
0
TalkConnection::~TalkConnection()
{
    close_sockets();
}
Beispiel #22
0
static void lock_cachefile(int cachefile, int type)
{
	struct flock fl = {
		.l_len = 0,
		.l_start = 0,
		.l_whence = SEEK_SET,
	};

	fl.l_pid = getpid();
	fl.l_type = type;

	if (verbose)
		output(2, "waiting on lock for cachefile\n");

	if (fcntl(cachefile, F_SETLKW, &fl) == -1) {
		perror("fcntl F_SETLKW");
		exit_main_fail();
	}

	if (verbose)
		output(2, "took lock for cachefile\n");
}

static void unlock_cachefile(int cachefile)
{
	struct flock fl = {
		.l_len = 0,
		.l_start = 0,
		.l_whence = SEEK_SET,
	};

	fl.l_pid = getpid();
	fl.l_type = F_UNLCK;

	if (fcntl(cachefile, F_SETLK, &fl) == -1) {
		perror("fcntl F_UNLCK F_SETLK ");
		exit_main_fail();
	}

	if (verbose)
		output(2, "dropped lock for cachefile\n");
}

static unsigned int valid_proto(unsigned int family)
{
	const char *famstr;

	famstr = get_proto_name(family);

	/* Not used for creating sockets. */
	if (strncmp(famstr, "PF_UNSPEC", 9) == 0)
		return FALSE;
	if (strncmp(famstr, "PF_BRIDGE", 9) == 0)
		return FALSE;
	if (strncmp(famstr, "PF_SECURITY", 11) == 0)
		return FALSE;

	/* Not actually implemented (or now removed). */
	if (strncmp(famstr, "PF_NETBEUI", 10) == 0)
		return FALSE;
	if (strncmp(famstr, "PF_ASH", 6) == 0)
		return FALSE;
	if (strncmp(famstr, "PF_ECONET", 9) == 0)
		return FALSE;
	if (strncmp(famstr, "PF_SNA", 6) == 0)
		return FALSE;
	if (strncmp(famstr, "PF_WANPIPE", 10) == 0)
		return FALSE;

	/* Needs root. */
	if (orig_uid != 0) {
		if (strncmp(famstr, "PF_KEY", 6) == 0)
			return FALSE;
		if (strncmp(famstr, "PF_PACKET", 9) == 0)
			return FALSE;
		if (strncmp(famstr, "PF_LLC", 6) == 0)
			return FALSE;
	}

	return TRUE;
}

static int generate_sockets(void)
{
	int fd, n, ret = FALSE;
	int cachefile;
	unsigned int nr_to_create = NR_SOCKET_FDS;
	unsigned int buffer[3];

	cachefile = creat(cachefilename, S_IWUSR|S_IRUSR);
	if (cachefile == -1)
		outputerr("Couldn't open cachefile for writing! (%s)\n", strerror(errno));
	else
		lock_cachefile(cachefile, F_WRLCK);

	/*
	 * Don't loop forever if all protos all are disabled.
	 */
	if (!do_specific_proto) {
		for (n = 0; n < (int)ARRAY_SIZE(no_protos); n++) {
			if (!no_protos[n])
				break;
		}

		if (n >= (int)ARRAY_SIZE(no_protos))
			nr_to_create = 0;
	}

	while (nr_to_create > 0) {

		struct socket_triplet st;

		for (st.family = 0; st.family < TRINITY_PF_MAX; st.family++) {

			/* check for ctrl-c again. */
			if (shm->exit_reason != STILL_RUNNING)
				goto out_unlock;

			if (do_specific_proto == TRUE) {
				st.family = specific_proto;
				//FIXME: If we've passed -P and we're spinning here without making progress
				// then we should abort after a few hundred loops.
			}

			if (get_proto_name(st.family) == NULL)
				continue;

			if (valid_proto(st.family) == FALSE) {
				if (do_specific_proto == TRUE) {
					outputerr("Can't do protocol %s\n", get_proto_name(st.family));
					goto out_unlock;
				} else {
					continue;
				}
			}

			BUG_ON(st.family >= ARRAY_SIZE(no_protos));
			if (no_protos[st.family])
				continue;

			if (sanitise_socket_triplet(&st) == -1)
				rand_proto_type(&st);

			fd = open_socket(st.family, st.type, st.protocol);
			if (fd > -1) {
				nr_to_create--;

				if (cachefile != -1) {
					buffer[0] = st.family;
					buffer[1] = st.type;
					buffer[2] = st.protocol;
					n = write(cachefile, &buffer, sizeof(int) * 3);
					if (n == -1) {
						outputerr("something went wrong writing the cachefile!\n");
						goto out_unlock;
					}
				}

				if (nr_to_create == 0)
					goto done;
			} else {
				//outputerr("Couldn't open family:%d (%s)\n", st.family, get_proto_name(st.family));
			}
		}
	}

done:
	ret = TRUE;

	output(1, "created %d sockets\n", nr_sockets);

out_unlock:
	if (cachefile != -1) {
		unlock_cachefile(cachefile);
		close(cachefile);
	}

	return ret;
}


void close_sockets(void)
{
	unsigned int i;
	int fd;
	struct linger ling = { .l_onoff = FALSE, .l_linger = 0 };

	for (i = 0; i < nr_sockets; i++) {

		//FIXME: This is a workaround for a weird bug where we hang forevre
		// waiting for bluetooth sockets when we setsockopt.
		// Hopefully at some point we can remove this when someone figures out what's going on.
		if (shm->sockets[i].triplet.family == PF_BLUETOOTH)
			continue;

		/* Grab an fd, and nuke it before someone else uses it. */
		fd = shm->sockets[i].fd;
		shm->sockets[i].fd = 0;

		/* disable linger */
		(void) setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(struct linger));

		(void) shutdown(fd, SHUT_RDWR);

		if (close(fd) != 0)
			output(1, "failed to close socket [%d:%d:%d].(%s)\n",
				shm->sockets[i].triplet.family,
				shm->sockets[i].triplet.type,
				shm->sockets[i].triplet.protocol,
				strerror(errno));
	}

	nr_sockets = 0;
}

static int open_sockets(void)
{
	int cachefile;
	unsigned int domain, type, protocol;
	unsigned int buffer[3];
	int bytesread = -1;
	int fd;
	int ret;

	/* If we're doing victim files we probably don't care about sockets. */
	//FIXME: Is this really true ? We might want to sendfile for eg
	if (victim_path != NULL)
		return TRUE;

	cachefile = open(cachefilename, O_RDONLY);
	if (cachefile < 0) {
		output(1, "Couldn't find socket cachefile. Regenerating.\n");
		ret = generate_sockets();
		return ret;
	}

	lock_cachefile(cachefile, F_RDLCK);

	while (bytesread != 0) {
		bytesread = read(cachefile, buffer, sizeof(int) * 3);
		if (bytesread == 0)
			break;

		domain = buffer[0];
		type = buffer[1];
		protocol = buffer[2];

		if ((do_specific_proto == TRUE && domain != specific_proto) ||
		    (domain < ARRAY_SIZE(no_protos) && no_protos[domain] == TRUE)) {
			output(1, "ignoring socket cachefile due to specific "
			       "protocol request (or protocol disabled), "
			       "and stale data in cachefile.\n");
regenerate:
				unlock_cachefile(cachefile);	/* drop the reader lock. */
				close(cachefile);
				unlink(cachefilename);

				close_sockets();
				ret = generate_sockets();
				return ret;
		}

		fd = open_socket(domain, type, protocol);
		if (fd < 0) {
			output(1, "Cachefile is stale. Need to regenerate.\n");
			goto regenerate;
		}

		/* check for ctrl-c */
		if (shm->exit_reason != STILL_RUNNING) {
			close(cachefile);
			return FALSE;
		}
	}

	if (nr_sockets < NR_SOCKET_FDS) {
		output(1, "Insufficient sockets in cachefile (%d). Regenerating.\n", nr_sockets);
		goto regenerate;
	}

	output(1, "%d sockets created based on info from socket cachefile.\n", nr_sockets);

	unlock_cachefile(cachefile);
	close(cachefile);

	return TRUE;
}
Beispiel #23
0
void open_sockets(void)
{
	struct flock fl = {
		.l_type = F_WRLCK,
		.l_whence = SEEK_SET,
	};

	int cachefile;
	unsigned int domain, type, protocol;
	unsigned int buffer[3];
	int bytesread=-1;
	int fd;

	/* If we have victim files, don't worry about sockets. */
	if (victim_path != NULL)
		return;

	cachefile = open(cachefilename, O_RDONLY);
	if (cachefile < 0) {
		printf("Couldn't find socket cachefile. Regenerating.\n");
		generate_sockets();
		return;
	}

	if (verbose)
		output(2, "taking reader lock for cachefile\n");
	fl.l_pid = getpid();
	fl.l_type = F_RDLCK;
	if (fcntl(cachefile, F_SETLKW, &fl) == -1) {
		perror("fcntl F_RDLCK F_SETLKW");
		exit(1);
	}
	if (verbose)
		output(2, "took reader lock for cachefile\n");

	while (bytesread != 0) {
		bytesread = read(cachefile, buffer, sizeof(int) * 3);
		if (bytesread == 0)
			break;

		domain = buffer[0];
		type = buffer[1];
		protocol = buffer[2];

		if (do_specific_proto == TRUE) {
			if (domain != specific_proto) {
				printf("ignoring socket cachefile due to specific protocol request, and stale data in cachefile.\n");
				generate_sockets();
				return;
			}
		}

		fd = open_socket(domain, type, protocol);
		if (fd < 0) {
			printf("Cachefile is stale. Need to regenerate.\n");
regenerate:
			close(cachefile);
			unlink(cachefilename);

			close_sockets();

			generate_sockets();
			return;
		}

		/* check for ctrl-c */
		if (shm->exit_reason != STILL_RUNNING)
			return;

	}

	if (nr_sockets < NR_SOCKET_FDS) {
		printf("Insufficient sockets in cachefile (%d). Regenerating.\n", nr_sockets);
		goto regenerate;
	}

	output(1, "%d sockets created based on info from socket cachefile.\n", nr_sockets);

	fl.l_pid = getpid();
	fl.l_type = F_UNLCK;
	if (fcntl(cachefile, F_SETLK, &fl) == -1) {
		perror("fcntl F_UNLCK F_SETLK ");
		exit(1);
	}

	if (verbose)
		output(2, "dropped reader lock for cachefile\n");
	close(cachefile);
}
Beispiel #24
0
int main (int argc, char *argv[])
{
    int opt;
    const char *short_options = "p:qcvh";
    const struct option long_options [] = {
        {"port", 1, NULL, 'p'},
        {"quite", 0, NULL, 'q'},
        {"cbench", 0, NULL, 'c'},
        {"version", 0, NULL, 'v'},
        {"help", 0, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };
    
    while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
        switch (opt) {
            case 'p':
                ani_port = atoi (optarg);
                break;
            case 'q':
                verbose = 0;
                break;
            case 'c':
                cbench = 1;
                break;
            case 'h':
                cout << "Usage:\n" << "\t-p, --port controller port e.g. -p 2000" << endl
                     << "\t-q, --quite turn off verbose mode" << endl
                     << "\t-c, --cbench Cbench benchmarking mode" << endl
                     << "\t-v, --version show ANI version" << endl
                     << "\t-h, --help show this help" << endl;
                exit (EXIT_SUCCESS);
            case 'v':
                cout << "ANI OpenFlow Controller" << endl
                     << "Compiled on " << __DATE__ << ' ' << __TIME__ << endl
                     << "version " << ANI_VERSION << endl;
                exit (EXIT_SUCCESS);
            default:
                break;
        }
    }
    
    if (atexit (exit_func) != 0) {
        cerr << "Error: can not set exit function" << endl;
        exit (EXIT_FAILURE);
    }
    
    cout << "Info: creating ANI socket..." << endl;
    
    if (create_ani_socket () == -1) {
        cerr << "Error: can not create ANI socket" << endl << "Exiting..." << endl;
        close_sockets ();
        exit (EXIT_FAILURE);
    }
    cout << "Info: established ANI server!" << endl;

    cout << "Info: waiting for the switch connection..." << endl;
    
    if (create_switch_socket () == -1) {
        cerr << "Error: can not connect to the switch" << endl << "Exiting..." << endl;
        close_sockets ();
        exit (EXIT_FAILURE);
    }
    cout << "Info: connected to the switch!" << endl;
    
    memset (&sigIntHandler, '\0', sizeof (sigIntHandler));
    sigIntHandler.sa_handler = SIG_IGN;
    sigaction (SIGINT, &sigIntHandler, NULL);
    
    memset (&sigIntHandler, '\0', sizeof (sigIntHandler));
    sigIntHandler.sa_handler = &exit_handler;
    sigaction (SIGINT, &sigIntHandler, NULL);

    memset (&sigIntHandler, '\0', sizeof (sigIntHandler));
    sigIntHandler.sa_handler = &exit_handler;
    sigaction (SIGTERM, &sigIntHandler, NULL);
    
    hosts.set_object_size (sizeof(struct switch_host));
    ports.set_object_size (sizeof(struct switch_port));
    links.set_object_size (sizeof(struct switch_link));
    sw_replys.set_object_size(sizeof(struct switch_reply));
    
    while (1) {
        if (communicate_with_switch () == -1) {
            cerr << "Error: can not communicate with the switch" << endl;
            exit (EXIT_FAILURE);
        }
    }

    return EXIT_SUCCESS;
}
Beispiel #25
0
void open_sockets(void)
{
	struct flock fl = {
		.l_type = F_WRLCK,
		.l_whence = SEEK_SET,
	};

	int cachefile;
	unsigned int domain, type, protocol;
	unsigned int buffer[3];
	int bytesread=-1;
	int fd;

	cachefile = open(cachefilename, O_RDONLY);
	if (cachefile < 0) {
		printf("Couldn't find socket cachefile. Regenerating.\n");
		generate_sockets();
		return;
	}

	output(2, "taking reader lock for cachefile\n");
	fl.l_pid = getpid();
	fl.l_type = F_RDLCK;
	if (fcntl(cachefile, F_SETLKW, &fl) == -1) {
		perror("fcntl F_RDLCK F_SETLKW");
		exit(1);
	}
	output(2, "took reader lock for cachefile\n");

	while (bytesread != 0) {
		bytesread = read(cachefile, buffer, sizeof(int) * 3);
		if (bytesread == 0)
			break;

		domain = buffer[0];
		type = buffer[1];
		protocol = buffer[2];

		if (do_specific_proto == TRUE) {
			if (domain != specific_proto) {
				printf("ignoring socket cachefile due to specific protocol request, and stale data in cachefile.\n");
				generate_sockets();
				return;
			}
		}

		fd = socket(domain, type, protocol);
		if (fd < 0) {
			printf("Cachefile is stale. Need to regenerate.\n");
regenerate:
			close(cachefile);
			unlink(cachefilename);

			close_sockets();

			generate_sockets();
			return;
		}
		shm->socket_fds[nr_sockets] = fd;
		output(2, "fd[%i] = domain:%i type:0x%x protocol:%i\n",
				fd, domain, type, protocol);
		nr_sockets++;
	}

	if (nr_sockets < NR_SOCKET_FDS) {
		printf("Insufficient sockets in cachefile (%d). Regenerating.\n", nr_sockets);
		goto regenerate;
	}

	output(1, "%d sockets created based on info from socket cachefile.\n", nr_sockets);

	fl.l_pid = getpid();
	fl.l_type = F_UNLCK;
	if (fcntl(cachefile, F_SETLK, &fl) == -1) {
		perror("fcntl F_UNLCK F_SETLK ");
		exit(1);
	}

	output(2, "dropped reader lock for cachefile\n");
	close(cachefile);
}