int main(void)
{
  int n;
  usCount start;
  pthread_permit1_t permit1;

  printf("Press key to continue ...\n");
  getchar();
  printf("Wait ...\n");
  start=GetUsCount();
  while(GetUsCount()-start<3000000000000ULL);
  printf("Calculating timing overhead ...\n");
  for(n=0; n<5000000; n++)
  {
    start=GetUsCount();
    timingoverhead+=GetUsCount()-start;
  }
  timingoverhead/=5000000;
  printf("Timing overhead on this machine is %u us. Go!\n", (size_t) timingoverhead);

  pthread_permit1_init(&permit1, 1);
  permitaddr=&permit1;
  for(n=0; n<THREADS; n++)
  {
    thrd_create(&threads[n], (thrd_start_t) threadfunc<pthread_permit1_t, pthread_permit1_grant, pthread_permit1_revoke, pthread_permit1_wait>, (void *)(size_t)n);
  }
  printf("Press key to kill all\n");
  getchar();
  done=1;
  mssleep(2000);
  printf("Press key to exit\n");
  getchar();
  return 0;
}
Example #2
0
void cl_reboot(int msdelaybeforereboot, const char * reason)
{
	int	rebootflag = 0;
	int	systemrc = 0;
#ifdef RB_AUTOBOOT
	rebootflag = RB_AUTOBOOT;
#endif
#ifdef RB_NOSYNC
	rebootflag = RB_NOSYNC;
#endif
#ifdef RB_DUMP
	if (coredump == REBOOT_COREDUMP) {
		rebootflag = RB_DUMP;
	}
#endif
	cl_log(LOG_EMERG, "Rebooting system.  Reason: %s", reason);
	sync();
	mssleep(msdelaybeforereboot);
#if REBOOT_ARGS == 1
	reboot(rebootflag);
#elif REBOOT_ARGS == 2
	reboot(rebootflag, NULL);
#else
#error "reboot() call needs to take one or two args"
#endif
	/* Shouldn't ever get here, but just in case... */
	systemrc=system(REBOOT " " REBOOT_OPTIONS);
	cl_log(LOG_EMERG, "ALL REBOOT OPTIONS FAILED: %s returned %d"
	,	REBOOT " " REBOOT_OPTIONS, systemrc);
	exit(1);
}
Example #3
0
void*
thfunc(void *arg) {
    int i;
    for(i=0; i<N; i++) {
	printf("thfunc: arg=%p i=%d\n", arg, i);
	mssleep(.5);
    }
    return arg;
}
Example #4
0
int
service_main_func(int argc, char **argv) {
    char buf[1024];
    while( !service_exited ) {
	debug(DEBUG_INFO, 
	      ("service: main time=%s\n",
	       mstime_fmt(mstime(), buf, sizeof(buf))
	       ));
	mssleep(1);
    }
    debug(DEBUG_INFO, ("service: stopping\n"));
    return 0;
}
Example #5
0
int os_send_udp(option_block *opts, char *str, size_t len)
{
#ifdef __WIN32__
    WSADATA wsaData;
#endif

    FILE *log = stdout;
    struct timeval tv;
    fd_set fds;
    unsigned long int to = MAX(100, opts->time_out);
    struct addrinfo hints, *servinfo, *p;
    int sockfd = -1;
    int ret;
    
    if(opts->fp_log)
        log = opts->fp_log;
    
#ifdef __WIN32__
    if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0)
    {
        fprintf(stderr, "[%s]: error: Unable to init winsock!\n",
                get_time_as_log());
        fprintf(log, "[%s]: error: Unable to init winsock!\n",
                get_time_as_log());
        return -1;
    }
#endif

    memset(&hints, 0, sizeof(hints));
    
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;
    
    if(getaddrinfo(opts->host_spec, opts->port_spec, &hints, &servinfo) != 0)
    {
        fprintf(stderr, "[%s]: error: unable to get addrinfo\n",
                get_time_as_log());
        fprintf(log, "[%s]: error: unable to get addrinfo\n",
                get_time_as_log());
#ifdef __WIN32__
        WSACleanup();
#endif
        return -1;
    }

    for(p = servinfo; p!= NULL; p = p->ai_next)
    {
        sockfd = socket(p->ai_family, p->ai_socktype,
                        p->ai_protocol);
        if(sockfd < 0)
            continue;

        opts->sockfd = sockfd;
        break; /* p won't be equal to NULL in this case */
    }

    if(p == NULL)
    {
        fprintf(stderr,"[%s] error: unable to acquire socket.\n",
                get_time_as_log());
        
        fprintf(log,"[%s] error: unable to acquire socket.\n",
                get_time_as_log());
        freeaddrinfo(servinfo);
#ifdef __WIN32__
        WSACleanup();
#endif
        return -1;
    }
    
    ret = sendto(sockfd, str, len, 0,
                 p->ai_addr, p->ai_addrlen);

    freeaddrinfo(servinfo);
    
    if(ret < 0)
    {
        fprintf(stderr,"[%s] error: udp send() failed.\n", get_time_as_log());
        fprintf(log,"[%s] error: udp send() failed.\n", get_time_as_log());
#ifdef __WIN32__
        WSACleanup();
#endif
        return -1;
    }

    if(opts->verbosity != QUIET)
        fprintf(log, "[%s] info: tx fuzz - scanning for reply.\n",
                get_time_as_log());
    
    FD_ZERO(&fds);
    FD_SET(sockfd, &fds);

    tv.tv_sec  = to / 1000;
    tv.tv_usec = (to % 1000) * 1000; /*time out*/

    mssleep(opts->reqw_inms);

    ret = select(sockfd+1, &fds, NULL, NULL, &tv);
    if(ret > 0)
    {
        if(FD_ISSET(sockfd, &fds))
        {
            char buf[8193] = {0};
            int r_len = 0;
            r_len = read(sockfd, &buf, 8192);
            buf[8192] = 0;
            if(opts->verbosity != QUIET)
                fprintf(log, "[%s] read:\n%s\n===============================================================================\n", 
                        get_time_as_log(),
                        buf);
#ifndef NOPLUGIN
            if((g_plugin != NULL) &&
               ((g_plugin->capex() & PLUGIN_PROVIDES_POST_FUZZ) ==
                PLUGIN_PROVIDES_POST_FUZZ))
            {
                g_plugin->post_fuzz(opts, buf, r_len);
            }
#endif

            
        }
    }
#ifdef __WIN32__
    closesocket(sockfd);
    WSACleanup();
#else
    close(sockfd);
#endif
    return 0;
}
Example #6
0
int os_send_tcp(option_block *opts, char *str, size_t len)
{
#ifdef __WIN32__
    WSADATA wsaData;
#endif
    FILE *log = stdout;
    struct timeval tv;
    fd_set fds;
    int sockfd = -1;

    struct addrinfo hints, *servinfo, *p;

    int ret;
    int snt = 0;
    unsigned long int to = MAX(100, opts->time_out);

    if(opts->fp_log)
        log = opts->fp_log;

#ifdef __WIN32__
    if(WSAStartup(MAKEWORD(2,0), &wsaData) != 0)
    {
        fprintf(stderr, "[%s]: error: Unable to init winsock!\n",
                get_time_as_log());
        fprintf(log, "[%s]: error: Unable to init winsock!\n",
                get_time_as_log());
        return -1;
    }
#endif

    
    if(opts->sockfd != -1)
    {
        sockfd = opts->sockfd;
    }
    else
    {
        memset(&hints, 0, sizeof(hints));

        hints.ai_family   = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;

        if(getaddrinfo(opts->host_spec, opts->port_spec, &hints, &servinfo) != 0)
        {
            fprintf(stderr, "[%s]: error: unable to get addrinfo\n",
                    get_time_as_log());
            fprintf(log, "[%s]: error: unable to get addrinfo\n",
                    get_time_as_log());
#ifdef __WIN32__
            WSACleanup();
#endif
            return -1;
        }
        
        for(p = servinfo; p!= NULL; p = p->ai_next)
        {
            sockfd = socket(p->ai_family, p->ai_socktype,
                            p->ai_protocol);
            if(sockfd < 0)
                continue;

            opts->sockfd = sockfd;
            
            if(connect(sockfd, 
                       p->ai_addr, p->ai_addrlen) < 0)
            {
#ifdef __WIN32__
                closesocket(sockfd);
#else
                close(sockfd);
#endif
                opts->sockfd = sockfd = -1;
                continue;
            }
            break; /* faster than setting p = NULL; (I think)*/
        }
        freeaddrinfo(servinfo);
    }

    if(sockfd == -1)
    {
        fprintf(stderr,
                "[%s] error: unable to connect to remote system [%s].\n",
                get_time_as_log(), process_error());
        fprintf(log,
                "[%s] error: unable to connect to remote system [%s].\n",
                get_time_as_log(), process_error());
#ifdef __WIN32__
        WSACleanup();
#endif
        return -1;
    }

    while(len)
    {
        ret = send(sockfd, str + snt, len, 0);
    
        if(ret < 0)
        {
            fprintf(stderr,"[%s] error: tcp send() failed.\n", get_time_as_log());
            fprintf(log,"[%s] error: tcp send() failed.\n", get_time_as_log());
#ifdef __WIN32__
            WSACleanup();
#endif
            return -1;
        }
        len -= ret;
        snt += ret;
    }
    

    if(opts->verbosity != QUIET)
        fprintf(log, "[%s] info: tx fuzz - (%d bytes) - scanning for reply.\n",
                get_time_as_log(), snt);
    
    FD_ZERO(&fds);
    FD_SET(sockfd, &fds);

    tv.tv_sec  = to / 1000;
    tv.tv_usec = (to % 1000) * 1000; /*time out*/

    mssleep(opts->reqw_inms);

    ret = select(sockfd+1, &fds, NULL, NULL, &tv);
    if(ret > 0)
    {
        if(FD_ISSET(sockfd, &fds))
        {
            char buf[8193] = {0};
            int r_len = 0;
            r_len = read(sockfd, &buf, 8192);
            buf[8192] = 0;
            if(opts->verbosity != QUIET)
                fprintf(log, "[%s] read:\n%s\n===============================================================================\n", 
                        get_time_as_log(),
                        buf);
            if((opts->s_syms_count) && (opts->repl_pol))
            {
                for(ret = 0; ret < opts->s_syms_count; ++ret)
                {
                    sym_t *pSym = &(opts->s_syms[ret]);
                    int    cpy_len = pSym->is_len;

                    if((opts->repl_pol == 2) &&
                       pSym->increment)
                        continue;

                    if(cpy_len > r_len)
                        continue;
                    memset(pSym->sym_val, 0, 1024);
                    memcpy(pSym->sym_val, buf+(pSym->offset),cpy_len);
                    pSym->sym_val[cpy_len] = 0;
                    pSym->s_len = cpy_len;
                    pSym->increment = 1;
                }
            }
#ifndef NOPLUGIN
            if((g_plugin != NULL) &&
               ((g_plugin->capex() & PLUGIN_PROVIDES_POST_FUZZ) ==
                PLUGIN_PROVIDES_POST_FUZZ))
            {
                g_plugin->post_fuzz(opts, buf, r_len);
            }
#endif
        }
    }
    
    if(opts->close_conn)
        opts->sockfd = -1;
    
    if((opts->close_conn) && (!opts->forget_conn))
    {
#ifdef __WIN32__
        closesocket(sockfd);
#else
        close(sockfd);
#endif
    }
    
#ifdef __WIN32__
    WSACleanup();
#endif
    return 0;
}
Example #7
0
static void* HW_CaptureThread(void* arg)
{
	HWCapture* capture = (HWCapture*)arg;
	z_stream stream;
	unsigned char* zbuffer = 0;
	int result;
	unsigned int nodecount = 0;
	unsigned int have = 0;
	int savecapture = 1;
	

	capture->done = 0;
   
   
	if (capture->outputFile == 0)
	{
		savecapture = 0;
	}

	if (savecapture)
	{
		zbuffer = malloc(ZCHUNK);
		if (zbuffer == 0)
		{
			fprintf(stderr, "Error allocating zbuffer\n");
			exit(1);
		}

		stream.zalloc = Z_NULL;
		stream.zfree = Z_NULL;
		stream.opaque = Z_NULL;
		result = deflateInit(&stream, ZCOMPLEVEL);
		if (result != Z_OK)
		{
			fprintf(stderr, "Error initializing ZLIB\n");
			exit(1);
		}
	}

	while(capture->running)
	{
		
		HWBuffer* node = 0;
		unsigned int available;
		unsigned int capacity;
		unsigned char* buffer;
      unsigned int buffersize;
      unsigned int bufferpos;
   
		pthread_mutex_lock(&capture->mutex);
		
		node = HW_BufferChainGetFirst(&capture->chain);
		
		if (node)
		{
			available = node->capacity - node->size;
         buffersize = node->size;
         bufferpos = node->pos;
			buffer = node->buffer;
			capacity = node->capacity;
         
         node->pos = node->size;
		}
		
		pthread_mutex_unlock(&capture->mutex);
      
      
      if (node && (buffersize - bufferpos > 0))
         HW_Process(&capture->process, buffer + bufferpos, buffersize - bufferpos);
		
		if (node == 0 || available != 0)
		{
			mssleep(1);
			continue;
		}
      
	    if (savecapture)
		{
			stream.avail_in = capacity;
			stream.next_in = buffer;
			
			do
			{
				stream.avail_out = ZCHUNK;
				stream.next_out = zbuffer;
				
				result = deflate(&stream, Z_NO_FLUSH);
				
				if (result == Z_STREAM_ERROR)
				{
					fprintf(stderr, "Error compressing stream\n");
					exit(1);
				}
				
				have = ZCHUNK - stream.avail_out;
				capture->compressedsize += have;
				if (capture->outputFile) 
				{
					if (fwrite(zbuffer, have, 1, capture->outputFile) != 1) 
					{
						deflateEnd(&stream);
						fprintf(stderr, "Write error\n");
						exit(1);
					}			
				}
			} while(stream.avail_out == 0);
		}

		
		nodecount = 0;
		pthread_mutex_lock(&capture->mutex);
		HW_BufferChainDestroyFirst(&capture->chain);
		node = HW_BufferChainGetFirst(&capture->chain);
		while(1)
		{			
			if (node == 0)
				break;
			node = node->next;
			nodecount++;
		}
		pthread_mutex_unlock(&capture->mutex);
		if (nodecount > 1)
			fprintf(stdout, "WARNING: %d hwbuffers still remaining\n", nodecount);
	}
	
	if (savecapture)
	{
		// Write last remaining data in the buffers
		while(1)
		{		
			HWBuffer* node = 0;
			unsigned int available;
			unsigned int capacity;
			unsigned char* buffer;
					
			pthread_mutex_lock(&capture->mutex);
			
			node = HW_BufferChainGetFirst(&capture->chain);
			
			if (node)
			{
				available = node->capacity - node->size;
				buffer = node->buffer;
				capacity = node->capacity;
			}
			
			pthread_mutex_unlock(&capture->mutex);
			
			if (node == 0)
				break;
			
			if (available == capacity)
				break;
			
			
			stream.avail_in = capacity - available;
			stream.next_in = buffer;
			
			do
			{
				stream.avail_out = ZCHUNK;
				stream.next_out = zbuffer;
				
				result = deflate(&stream, Z_NO_FLUSH);
				
				if (result == Z_STREAM_ERROR)
				{
					fprintf(stderr, "Error compressing stream\n");
					exit(1);
				}
				
				have = ZCHUNK - stream.avail_out;
				capture->compressedsize += have;
				if (capture->outputFile) 
				{
					if (fwrite(zbuffer, have, 1, capture->outputFile) != 1)
					{
						deflateEnd(&stream);
						fprintf(stderr, "Write error\n");
						exit(1);
					}
				}
				
			} while(stream.avail_out == 0);
					
			pthread_mutex_lock(&capture->mutex);
			HW_BufferChainDestroyFirst(&capture->chain);
			pthread_mutex_unlock(&capture->mutex);		
		}
		
		stream.avail_in = 0;
		stream.next_in = NULL;
		
		do
		{
			stream.avail_out = ZCHUNK;
			stream.next_out = zbuffer;
			
			result = deflate(&stream, Z_FINISH);
			
			if (result == Z_STREAM_ERROR)
			{
				fprintf(stderr, "Error compressing stream\n");
				exit(1);
			}
			
			have = ZCHUNK - stream.avail_out;
			capture->compressedsize += have;
			if (capture->outputFile)
			{
				if (fwrite(zbuffer, have, 1, capture->outputFile) != 1)
				{
					deflateEnd(&stream);
					fprintf(stderr, "Write error\n");
					exit(1);
				}		
			}
		} while(stream.avail_out == 0);
		
		
		deflateEnd(&stream);
		free(zbuffer);
	}
   
   capture->done = 1;
   

	return 0;
}
Example #8
0
File: wat.c Project: jkoz/wat
int
main(int argc, const char **argv){
	if (1 == argc) usage();
	int interval = DEFAULT_INTERVAL;

	int len = 0;
	int interpret = 1;
	char *args[ARGS_MAX] = {0};

	for (int i = 1; i < argc; ++i) {
		const char *arg = argv[i];
		if (!interpret) goto arg;

		// -h, --help
		if (option("-h", "--help", arg)) usage();

		// -q, --quiet
		if (option("-q", "--quiet", arg)) {
			quiet = 1;
			continue;
		}

		// -x, --halt
		if (option("-x", "--halt", arg)) {
			halt = 1;
			continue;
		}

		// -v, --version
		if (option("-v", "--version", arg)) {
			printf("%s\n", VERSION);
			exit(1);
		}

		// -i, --interval <n>
		if (option("-i", "--interval", arg)) {
			if (argc-1 == i) {
				fprintf(stderr, "\n  --interval requires an argument\n\n");
				exit(1);
			}

			arg = argv[++i];
			char last = arg[strlen(arg) - 1];
			// seconds or milliseconds
			interval = last >= 'a' && last <= 'z'
				? string_to_milliseconds(arg)
				: atoi(arg) * 1000;
			continue;
		}

		// cmd args
		if (len == ARGS_MAX) {
			fprintf(stderr, "number of arguments exceeded %d\n", len);
			exit(1);
		}

	arg:
		args[len++] = (char *) arg;
		interpret = 0;
	}

	// <cmd>
	if (!len) {
		fprintf(stderr, "\n  <cmd> required\n\n");
		exit(1);
	}

	// cmd
	char *val = join(args, len, " ");
	char *cmd[4] = { "sh", "-c", val, 0 };

	// exec loop
	loop: {
		  pid_t pid;
		  int status;
		  switch (pid = fork()) {
			  // error
			  case -1:
				  perror("fork()");
				  exit(1);
				  // child
			  case 0:
				  if (quiet) redirect_stdout("/dev/null");
				  execvp(cmd[0], cmd);
				  // parent
			  default:
				  if (waitpid(pid, &status, 0) < 0) {
					  perror("waitpid()");
					  exit(1);
				  }

				  // exit > 0
				  if (WEXITSTATUS(status)) {
					  fprintf(stderr, "\033[90mexit: %d\33[0m\n\n", WEXITSTATUS(status));
					  if (halt) exit(WEXITSTATUS(status));
				  }

				  mssleep(interval);
				  goto loop;
		  }
	  }

	  return 0;
}
Example #9
0
int
main(int argc, char *argv[])
{
	int	c = -1;
	char	errbuf[LIBNET_ERRBUF_SIZE];
	char*	device;
	char*	ipaddr;
	char*	macaddr;
	char*	broadcast;
	char*	netmask;
	u_int32_t	ip;
	u_char  src_mac[6];
	LTYPE*	l;
	int	repeatcount = 1;
	int	j;
	long	msinterval = 1000;
	int	flag;
	char    pidfilenamebuf[64];
	char    *pidfilename = NULL;

	CL_SIGNAL(SIGTERM, byebye);
	CL_SIGINTERRUPT(SIGTERM, 1);

        cl_log_set_entity(SENDARPNAME);
        cl_log_enable_stderr(TRUE);
        cl_log_set_facility(LOG_USER);
	cl_inherit_logging_environment(0);

	while ((flag = getopt(argc, argv, "i:r:p:")) != EOF) {
		switch(flag) {

		case 'i':	msinterval= atol(optarg);
				break;

		case 'r':	repeatcount= atoi(optarg);
				break;

		case 'p':	pidfilename= optarg;
				break;

		default:	fprintf(stderr, "%s\n\n", print_usage);
				return 1;
				break;
		}
	}
	if (argc-optind != 5) {
		fprintf(stderr, "%s\n\n", print_usage);
		return 1;
	}

	/*
	 *	argv[optind+1] DEVICE		dc0,eth0:0,hme0:0,
	 *	argv[optind+2] IP		192.168.195.186
	 *	argv[optind+3] MAC ADDR		00a0cc34a878
	 *	argv[optind+4] BROADCAST	192.168.195.186
	 *	argv[optind+5] NETMASK		ffffffffffff
	 */

	device    = argv[optind];
	ipaddr    = argv[optind+1];
	macaddr   = argv[optind+2];
	broadcast = argv[optind+3];
	netmask   = argv[optind+4];

	if (!pidfilename) {
		if (snprintf(pidfilenamebuf, sizeof(pidfilenamebuf), "%s%s", 
					PIDFILE_BASE, ipaddr) >= 
				(int)sizeof(pidfilenamebuf)) {
			cl_log(LOG_INFO, "Pid file truncated");
			return EXIT_FAILURE;
		}
		pidfilename = pidfilenamebuf;
	}

	if(write_pid_file(pidfilename) < 0) {
		return EXIT_FAILURE;
	}

#if defined(HAVE_LIBNET_1_0_API)
#ifdef ON_DARWIN
	if ((ip = libnet_name_resolve((unsigned char*)ipaddr, 1)) == -1UL) {
#else
	if ((ip = libnet_name_resolve(ipaddr, 1)) == -1UL) {
#endif
		cl_log(LOG_ERR, "Cannot resolve IP address [%s]", ipaddr);
		unlink(pidfilename);
		return EXIT_FAILURE;
	}

	l = libnet_open_link_interface(device, errbuf);
	if (!l) {
		cl_log(LOG_ERR, "libnet_open_link_interface on %s: %s"
		,	device, errbuf);
		unlink(pidfilename);
		return EXIT_FAILURE;
	}
#elif defined(HAVE_LIBNET_1_1_API)
	if ((l=libnet_init(LIBNET_LINK, device, errbuf)) == NULL) {
		cl_log(LOG_ERR, "libnet_init failure on %s: %s", device, errbuf);
		unlink(pidfilename);
		return EXIT_FAILURE;
	}
	if ((signed)(ip = libnet_name2addr4(l, ipaddr, 1)) == -1) {
		cl_log(LOG_ERR, "Cannot resolve IP address [%s]", ipaddr);
		unlink(pidfilename);
		return EXIT_FAILURE;
	}
#else
#	error "Must have LIBNET API version defined."
#endif

	if (!strcasecmp(macaddr, AUTO_MAC_ADDR)) {
		if (get_hw_addr(device, src_mac) < 0) {
			 cl_log(LOG_ERR, "Cannot find mac address for %s", 
					 device);
			 unlink(pidfilename);
			 return EXIT_FAILURE;
		}
	}
	else {
		convert_macaddr((unsigned char *)macaddr, src_mac);
	}

/*
 * We need to send both a broadcast ARP request as well as the ARP response we
 * were already sending.  All the interesting research work for this fix was
 * done by Masaki Hasegawa <*****@*****.**> and his colleagues.
 */
	for (j=0; j < repeatcount; ++j) {
		c = send_arp(l, ip, (unsigned char*)device, src_mac
			, (unsigned char*)broadcast, (unsigned char*)netmask
			, ARPOP_REQUEST);
		if (c < 0) {
			break;
		}
		mssleep(msinterval / 2);
		c = send_arp(l, ip, (unsigned char*)device, src_mac
			, (unsigned char *)broadcast
			, (unsigned char *)netmask, ARPOP_REPLY);
		if (c < 0) {
			break;
		}
		if (j != repeatcount-1) {
			mssleep(msinterval / 2);
		}
	}

	unlink(pidfilename);
	return c < 0  ? EXIT_FAILURE : EXIT_SUCCESS;
}


void
convert_macaddr (u_char *macaddr, u_char enet_src[6])
{
	int i, pos;
	u_char bits[3];

	pos = 0;
	for (i = 0; i < 6; i++) {
		/* Inserted to allow old-style MAC addresses */
		if (*macaddr == ':') {
			pos++;
		}
		bits[0] = macaddr[pos++];
		bits[1] = macaddr[pos++];
		bits[2] = '\0';

		enet_src[i] = strtol((const char *)bits, (char **)NULL, 16);
	}

}
Example #10
0
File: server.c Project: atupac/ctr
static void* ServerReceiveThread(void* arg)
{
	Server* server = (Server*)arg;
	int shutdownfd = server->shutdownpipe[0];
	int remotesockfd;
	int fdmax;
	fd_set readfds;
	int authenticated = 0;
	int challengepos = 0;
	unsigned char challenge[SERVER_MAX_CHALLENGESIZE];
	
	while(server->running)
	{
		unsigned char buf[4096];
		int nbytes;
		struct timeval timeout;
		unsigned int maxsize = sizeof(buf);
		unsigned int availablesize = server->receivebuffer.capacity - server->receivebuffer.size;
		
		if (maxsize > availablesize)
			maxsize = availablesize;
			
		remotesockfd = server->remotesockfd;
		
		if (server->remoteflush)
		{
			authenticated = 0;
			challengepos = 0;
			
			server->remoteflush = 0;
			
			pthread_mutex_lock(&server->receivemutex);
			HW_BufferClear(&server->receivebuffer);
			pthread_mutex_unlock(&server->receivemutex);			
		}

		if (remotesockfd == 0 || maxsize == 0)
		{
			mssleep(1);
			continue;	
		}
		
	
		timeout.tv_sec = 5;
		timeout.tv_usec = 0;			

		FD_ZERO(&readfds);
		FD_SET(remotesockfd, &readfds);
		FD_SET(shutdownfd, &readfds);
		
		fdmax = remotesockfd;
		if (fdmax < shutdownfd)
			fdmax = shutdownfd;
		if (select(fdmax+1, &readfds, NULL, NULL, &timeout) == -1) 
		{
			perror("select");
			
			fprintf(stdout, "> Server: Connection closed by %s\n", server->remoteIP);
			close(remotesockfd);
			server->remotesockfd = 0;			
			
			continue;
		} 
		
		if (FD_ISSET(shutdownfd, &readfds))
		{
			break;
		}
		if (FD_ISSET(remotesockfd, &readfds))
		{
			if ((nbytes = recv(remotesockfd, buf, maxsize, 0)) <= 0) 
			{
				if (nbytes == 0) {
					fprintf(stdout, "> Server: Connection closed by %s\n", server->remoteIP);
				} else {
					perror("recv");
				}
				close(remotesockfd);
				
				server->remotesockfd = 0;
			}
			else
			{
				if (!authenticated)
				{
					unsigned int i;
					unsigned int maxsize = server->authsize - challengepos;
					
					if (maxsize > nbytes)
						maxsize = nbytes;
					
					memcpy(challenge + challengepos, buf, maxsize);					
					memmove(buf, buf + maxsize, nbytes-maxsize);
					challengepos += maxsize;
					nbytes -= maxsize;
					
					
					if (challengepos == server->authsize)
					{
						authenticated = 1;
					
						for(i=0; i<challengepos; i++)
						{
							if (challenge[i] != server->auth[i])
								authenticated = 0;
						}
						
						if (!authenticated)
						{
							fprintf(stderr, "> Server: Incorrect authentication detected.\n");
						}
					}
				}
				
				pthread_mutex_lock(&server->receivemutex);
				HW_BufferFill(&server->receivebuffer, buf, nbytes);
				pthread_mutex_unlock(&server->receivemutex);
			}
		}
	}
   
	return 0;
}
Example #11
0
int main(int argc, char **argv)
{
	/* SELECT */
	int max_fd;
	fd_set readfds;
	struct timeval timeout;
	/* END SELECT */
	int i,j,ret;
	unsigned char bufout[BUF_SIZE];
	struct avr_msg dummy_msg = {t: 255, v: 254};
	struct avr_msg status_msg = {t: 255, v: 0};
	long dt_ms = 0;

	clock_gettime(CLOCK_REALTIME, &time_now);

	clock_gettime(CLOCK_REALTIME, &spi_time_prev);

	//we use this to measure UDP connection time each second
	clock_gettime(CLOCK_REALTIME, &udp_time_prev);

	int option;
	verbose = 1;
	background = 0;
	echo = 0;
	while ((option = getopt(argc, argv,"dep:fv:u:y:")) != -1) {
		switch (option)  {
			case 'd': background = 1; verbose=0; break;
			case 'p': portno = atoi(optarg);  break;
			case 'v': verbose = atoi(optarg);  break;
			case 'y': initTimeout = atoi(optarg);  break;
			case 'f': spi=0; break;
			case 'e': echo=1; break;
			case 'u': strcpy(socket_path,optarg); break;
			default:
				  print_usage();
				  return -1;
		}
	}

	signal(SIGTERM, catch_signal);
	signal(SIGINT, catch_signal);

	unix_sock = 0;
	for (i=0; i<MAX_UNIX_CLIENTS; i++) { 
		sock[i] = 0;
		sock_type[i] = -1;
		if (i>0) {
			buf_c[i] = 0;
		}
	}

	unix_sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (unix_sock < 0) {
		perror("opening unix socket");
		exit(1);
	}

	usock = socket(AF_INET, SOCK_DGRAM, 0);
	if (usock < 0) {
		perror("opening datagram socket");
		exit(1);
	}

	/* Create name sock, usock */
	bzero((char *) &address, sizeof(address));
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = INADDR_ANY;
	address.sin_port = htons(portno);

	if (bind(usock, (struct sockaddr *) &address, sizeof(struct sockaddr_in))) {
		perror("binding datagram socket");
		exit(1);
	}

	printf("Socket created on port %i\n", portno);


	/* UNIX */
	bzero((char *) &local, sizeof(local));
	local.sun_family = AF_UNIX;
	strcpy(local.sun_path, socket_path);
	unlink(local.sun_path);
	locallen = strlen(local.sun_path) + sizeof(local.sun_family);
	if (bind(unix_sock, (struct sockaddr *) &local, locallen)) {
		perror("binding unix socket");
		exit(1);
	}


	flog_init(CFG_PATH);
	log_mode = flog_getmode();

	if (listen(unix_sock,3) < 0) {
		perror("listen");
		stop=1;
	}

	if (background) {
		if (daemon(0,1) < 0) { 
			perror("daemon");
			return -1;
		}
		if (verbose) printf("Running in the background\n");
	}


	if (spi) {
		ret = spi_init();
		if (ret < 0) {
			printf("Error initiating SPI! %i\n",ret);
			stop = 1;
		}
	}

	reset_avr();

	clock_gettime(CLOCK_REALTIME, &spi_last_msg);

	if (verbose) printf("Starting main loop\n");

	while (!stop) {
		FD_ZERO(&readfds);
		max_fd = unix_sock;
		FD_SET(unix_sock, &readfds);
		for (i=0;i<MAX_UNIX_CLIENTS;i++) {
			if (sock[i]<=0) continue;
			FD_SET(sock[i], &readfds);
			max_fd = sock[i]>max_fd?sock[i]:max_fd;
		}
		FD_SET(usock, &readfds);
		max_fd = usock>max_fd?usock:max_fd;

		timeout.tv_sec = 0;
		timeout.tv_usec = MSG_PERIOD*1000L; //ms 
		int sel = select( max_fd + 1 , &readfds , NULL , NULL , &timeout);
		if ((sel<0) && (errno!=EINTR)) {
			perror("select");
			stop=1;
		}

		clock_gettime(CLOCK_REALTIME, &time_now);

		//check for orphan UDP connections
		dt = TimeSpecDiff(&time_now,&udp_time_prev);
		dt_ms = dt->tv_sec*1000 + dt->tv_nsec/1000000;
		if (dt_ms>1000) {
			udp_time_prev = time_now;
			for (i=0;i<MAX_UDP_CLIENTS;i++)
				if (uclients[i]>0) {
					uclients[i]--;
					if (uclients[i]<=0) {
						if (verbose) printf("Client %i timeout.\n",i);
					}
				}
		}
		//check UDP
		if (!stop && FD_ISSET(usock, &readfds)) {
                        ret = 0;
                        int t = 0;
                        do {
                                t = recvfrom(usock, ubuf+ret, BUF_SIZE-ret, MSG_DONTWAIT, (struct sockaddr *)&tmpaddress, &addrlen);
                                if (t>0) ret+=t;
                        } while (t>0);
			if (ret<=0) {
				printf("UDP recvfrom error? %i\n",ret);
			} else {
				int msg_c = ret / LOCAL_MSG_SIZE;
				if (verbose) printf("UDP received %i msgs\n", msg_c);
				for (i=0;i<msg_c;i++) { 
					struct local_msg m;
					unpack_lm(ubuf+i*LOCAL_MSG_SIZE,&m);
					process_udp_msg(&m,&tmpaddress); 
				}
			}
		}

		//If something happened on the master socket , then its an incoming connection
		if (!stop && FD_ISSET(unix_sock, &readfds)) {
			int t = accept(unix_sock, NULL, NULL);
			if (t<0) {
				perror("accept");
				continue;
			}
			for (i=0;i<MAX_UNIX_CLIENTS;i++)
				if (sock[i] == 0) {
					if (verbose) printf("Incoming client: %i\n",i);
					sock[i] = t;
					sock_type[i] = -1;
					buf_c[i] = 0;
					break;
				}
			if (i==MAX_UNIX_CLIENTS) {
				printf("AVRSPI: No space in connection pool! Disconnecting client.\n");
				close(t);
			}
		} 
		for (i=0;(i<MAX_UNIX_CLIENTS) && (!stop) && sock[i]>0;i++) {
			if (FD_ISSET(sock[i], &readfds)) {
				if (sock_type[i]==-1) {
					ret = read(sock[i],&sock_type[i],1);
					if (ret<=0) {
						perror("Reading error");
						close(sock[i]);
						sock[i] = 0;
					}
					continue;
				}
				ret = read(sock[i] , buf[i]+buf_c[i], BUF_SIZE - buf_c[i]); 
				if (ret < 0) {
					perror("Reading error");
					close(sock[i]);
					sock[i] = 0;
				}
				else if (ret == 0) {	//client disconnected
					if (verbose) printf("Client %i disconnected.\n",i);
					close(sock[i]);
					sock[i] = 0;
					buf_c[i] = 0;
				} else { //got data
					buf_c[i] += ret;
					if (verbose) printf("Received: %i bytes. Buf size: %i\n",ret,buf_c[i]);
					process_socket_queue(i);
				}
			}
		}
		//process of SPI received messages
		for (i=0;i<spi_buf_c;i++) {
			process_avr_msg(&spi_buf[i]);
			avr2local(&spi_buf[i],&local_buf[local_buf_c++]);
		}
		spi_buf_c = 0;

		//send out any available messages to clients
		if (local_buf_c*LOCAL_MSG_SIZE>BUF_SIZE) {
			printf("output buffer overflow (bufout)!");
			local_buf_c = 0;
		}

		for (j=0;j<local_buf_c;j++) {
			if (verbose>=2) printf("To clients: c: %u, t: %u, v: %i\n",local_buf[j].c,local_buf[j].t,local_buf[j].v);
			//local_buf[j].c = 0;
			pack_lm(bufout+j*LOCAL_MSG_SIZE,&local_buf[j]);
		}

		if (local_buf_c) {
			if (verbose) printf("To clients msgs: %i bytes: %i\n",local_buf_c,local_buf_c*LOCAL_MSG_SIZE);
			for (int k=0;k<MAX_UNIX_CLIENTS;k++) {
				if (sock[k]!=0 && sock_type[k]==0) { 
					ret = send(sock[k], bufout, local_buf_c*LOCAL_MSG_SIZE, MSG_NOSIGNAL );
					if (ret == -1) {
						if (verbose) printf("Lost connection to client %i.\n",k);
						close(sock[k]);
						sock[k] = 0;
					}
				}
			}
			for (int k=0;k<MAX_UDP_CLIENTS;k++) {
				if (uclients[k]>0) { 
					ret = sendto(usock,bufout,LOCAL_MSG_SIZE,0,(struct sockaddr *)&uaddress[k],addrlen);
					if (ret<0) {
						printf("Error sending datagram packet\n");
						uclients[k] = 0;
					}
				}
			}
		}

		local_buf_c = 0;

		do_avr_init(); 
		flog_loop();

		//ping avr if needed
		dt = TimeSpecDiff(&time_now,&spi_time_prev);
		dt_ms = dt->tv_sec*1000 + dt->tv_nsec/1000000;
		if (dt_ms>=MSG_PERIOD) {
			spi_time_prev = time_now;
			if (spi) for (i=msg_counter;i<MSG_RATE;i++) 
					if (i==msg_counter && autoconfig && avrstatus<5) spi_sendMsg(&status_msg);
					else spi_sendMsg(&dummy_msg);
			msg_counter = 0;
		}

	}

	if (echo) spi_close();

	bufout[0] = 1; //disconnect msg
	for (int k=0;k<MAX_UNIX_CLIENTS;k++) {
		if (sock[k]!=0) 
			send(sock[k], bufout, LOCAL_MSG_SIZE, MSG_NOSIGNAL );
	}

	close(unix_sock);
	mssleep(1000);

	if (verbose) {
		printf("closing\n");
		fflush(NULL);
	}

	for (i=0;i<MAX_UNIX_CLIENTS;i++)
		if (sock[i]!=0) close(sock[i]);


	close(usock);

}
int ssl_transport_insecure_send(option_block *opts, void *d, int i)
{
  FILE *log = stdout;
  char spec[2048] = {0};
  struct timeval tv;
  int sockfd;
  fd_set fds;
  unsigned long int to = MAX(100, opts->time_out);
  int ret;

  if(opts->fp_log)
    log = opts->fp_log;

  if(ssl_bio == NULL)
    {
      snprintf(spec, 2048, "%s:%d", opts->host_spec, opts->port);
      ssl_bio = BIO_new_connect(spec);
      if(ssl_bio == NULL)
	{
	  fprintf(stderr, "<ssl_transport:i-send> failure to acquire BIO: [%s]\n",
		  spec);
	  return -1;
	}
      
      if(BIO_do_connect(ssl_bio) <= 0)
	{
	  fprintf(stderr, "<ssl_transport:i-send> failure to simple connect to: [%s]\n",
		  spec);
	  return -1;
	}
    }
  
 retx:
  if(BIO_write(ssl_bio, d, i) <= 0)
    {
      if(!BIO_should_retry(ssl_bio))
	{
	  fprintf(stderr, "<ssl_transport:i-send> failure to transmit!\n");
	  ssl_transport_close();
	}
      goto retx;
    }
  
  if(opts->verbosity != QUIET)
    fprintf(log, "[%s] <ssl_transport:send> tx fuzz - scanning for reply.\n",
	    get_time_as_log());

    BIO_get_fd(ssl_bio, &sockfd);

    FD_ZERO(&fds);
    FD_SET(sockfd, &fds);

    tv.tv_sec  = to / 1000;
    tv.tv_usec = (to % 1000) * 1000; /*time out*/

    ret = select(sockfd+1, &fds, NULL, NULL, &tv);
    if(ret > 0)
    {
        if(FD_ISSET(sockfd, &fds))
        {
            char buf[8192] = {0};
            int r_len = 0;

	    ret = BIO_read(ssl_bio, buf, 8192);
	    if(ret == 0)
	      {
		fprintf(stderr, "<ssl_transport:send> remote closed xon\n");
		ssl_transport_close();
	      }
	    else if(ret > 0)
	      {
		if(opts->verbosity != QUIET)
		  fprintf(log, 
			  "[%s] read:\n%s\n===============================================================================\n", 
			  get_time_as_log(),
			  buf);
	      }
	}
    }
    
    if((opts->close_conn) || ((opts->close_conn) && (!opts->forget_conn)))
      {
	ssl_transport_close();
      }
    
    mssleep(opts->reqw_inms);
    return 0;
}