Beispiel #1
0
int main(int argc, char *argv[])
{
	int opt;
    bool dump_flag = false;
	
    buffer = (char *)malloc(BUFFER_SIZE);
    
	while ((opt = getopt(argc, argv, "d")) != -1) {
		switch (opt) {
			case 'd':
				dump_flag = true;
				break;
			default:
				print_usage(argv[0]);
				exit(EXIT_FAILURE);
		}
	}
	
	if (argc - optind < 2 || argc - optind > 4) {
		fprintf(stderr, "wrong argument count\n");
		print_usage(argv[0]);
		exit(EXIT_FAILURE);
	}
	
    if (strcmp(argv[optind], "listen") == 0) {
        optind++;
        _server_socket = open_server_socket(atoi(argv[optind]));
        server_with_select(NULL, dump_flag);
    } else if (strcmp(argv[optind], "send") == 0) {
        UDPClient *client;
        struct sockaddr_in from_address, to_address;
        size_t len;
        ssize_t read;
        
        optind++;
        
        to_address = socket_address(argv[optind], atoi(argv[optind + 1]));
        from_address = socket_address(NULL, atoi(argv[optind + 1]));
        
        read = getline(&buffer, &len, stdin);
        if (read > 0) {
            client = new UDPClient(from_address, to_address, -1, dump_flag);
            client->send_to_server(buffer, read);
        }
    } else if (strcmp(argv[optind], "relay") == 0) {
        struct sockaddr_in to_address;
        
        optind++;
        _server_socket = open_server_socket(atoi(argv[optind]));
        to_address = socket_address(argv[optind + 1], atoi(argv[optind + 2]));
        server_with_select(&to_address, dump_flag);
    }
    
	return 0;
}
Beispiel #2
0
static void
test_connect_first (void)
{
    int s = open_server_socket ();
    struct sockaddr_in ia;
    socklen_t addrlen;

    int c1, c2;

    if (poll1_nowait (s, POLLIN | POLLRDNORM | POLLRDBAND) != 0)
        failed ("can read, socket not connected");

    c1 = connect_to_socket (false);

    if (poll1_wait (s, POLLIN | POLLRDNORM | POLLRDBAND) != (POLLIN | POLLRDNORM))
        failed ("expecting POLLIN | POLLRDNORM on passive socket");
    if (poll1_nowait (s, POLLIN | POLLRDBAND) != POLLIN)
        failed ("expecting POLLIN on passive socket");
    if (poll1_nowait (s, POLLRDNORM | POLLRDBAND) != POLLRDNORM)
        failed ("expecting POLLRDNORM on passive socket");

    addrlen = sizeof (ia);
    c2 = accept (s, (struct sockaddr *) &ia, &addrlen);
    close (s);
    close (c1);
    close (c2);
}
Beispiel #3
0
/*
 * main() - parse command line, create a socket, handle requests
 */
int main(int argc, char **argv) {
    /* for getopt */
    long opt;
    int  lru_size = 10;
    int  port     = 9000;

    check_team(argv[0]);

    /* parse the command-line options.  They are 'p' for port number,  */
    /* and 'l' for lru cache size.  'h' is also supported. */
    while ((opt = getopt(argc, argv, "hl:p:")) != -1) {
        switch(opt) {
        case 'h':
            help(argv[0]);
            break;
        case 'l':
            lru_size = atoi(argv[0]);
            break;
        case 'p':
            port = atoi(optarg);
            break;
        }
    }

    /* open a socket, and start handling requests */
    int fd = open_server_socket(port);
    handle_requests(fd, file_server, lru_size);

    exit(0);
}
Beispiel #4
0
static void
test_connect_first (void)
{
  int s = open_server_socket ();
  struct sockaddr_in ia;
  socklen_t addrlen;

  int c1, c2;

  if (do_select_nowait (s, SEL_IN | SEL_EXC) != 0)
    failed ("can read, socket not connected");

  c1 = connect_to_socket (false);

  if (do_select_wait (s, SEL_IN | SEL_EXC) != SEL_IN)
    failed ("expecting readability on passive socket");
  if (do_select_nowait (s, SEL_IN | SEL_EXC) != SEL_IN)
    failed ("expecting readability on passive socket");

  addrlen = sizeof (ia);
  c2 = accept (s, (struct sockaddr *) &ia, &addrlen);
  close (s);
  close (c1);
  close (c2);
}
Beispiel #5
0
void * socket_uart_send_manager(void * arg)
{
    int listen_fd = open_server_socket(UNIX_SOCKET_UART_SEND);
    int com_fd;
    socklen_t len;
    struct sockaddr_un clt_addr;
    pthread_t real_send;
    pthread_create(&real_send,
                   NULL,
                   uart_send_worker,
                   NULL);
    while(1)
    {
        len = sizeof(clt_addr);
        com_fd = accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
        if(com_fd < 0)
        {
            perror("cannot accept client connect request");
            close(listen_fd);
            unlink(UNIX_SOCKET_UART_SEND);
            exit(-1);
        }
        int n = 0;
        uint8_t recv_buf[MAX_BUFSIZ];
        if( (n = read(com_fd,recv_buf,sizeof(recv_buf))) < 0)
        {
            LOG_ERROR("[%s] Read Error\n",__func__);
            exit(-1);
        }
        LOG_DEBUG("I read a request message, the request is: %s",recv_buf);
        if(is_invalid_message((char *)recv_buf, n))
        {
            LOG_ERROR("InvalidMessage");
            process_message_invalid_message(com_fd);
            close(com_fd);
        }
        else
        {
            message_t * message = deserialized_message(recv_buf,n);
            uart_dev_t * dev = get_dev_by_name(message->name);
            if(dev == NULL)
            {
                LOG_ERROR("InvalidName");
                process_message_invalid_name(com_fd, message->name);
                close(com_fd);
            }
            else
            {
                LOG_DEBUG("ValidMessage");
                message->dev = dev;
                queue_enqueue(context->send_queue, message);
                process_message_succeed(com_fd);
                close(com_fd);
            }
        }
    }
    return NULL;
}
int main()
{

	int sockid = open_server_socket("localhost", 5555);

	int newsockid = accept(sockid,0,0);

	handle_connection(newsockid);

}
Beispiel #7
0
int main(int argc, char **argv)
{
  int serfd;

  if (argc != 4)
    {
      fprintf(stderr,
	      "Usage: %s <port> <device> <rate> - act as a serial forwarder on <port>\n"
	      "(listens to serial port <device> at baud rate <rate>)\n" ,
	      argv[0]);
      exit(2);
    }

  if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
    fprintf(stderr, "Warning: failed to ignore SIGPIPE.\n");

  open_serial(argv[2], platform_baud_rate(argv[3]));
  serfd = serial_source_fd(src);
  open_server_socket(atoi(argv[1]));

  for (;;)
    {
      fd_set rfds;
      int maxfd = -1;
      struct timeval zero;
      int serial_empty;
      int ret;

      zero.tv_sec = zero.tv_usec = 0;

      FD_ZERO(&rfds);
      fd_wait(&rfds, &maxfd, serfd);
      fd_wait(&rfds, &maxfd, server_socket);
      wait_clients(&rfds, &maxfd);

      serial_empty = serial_source_empty(src);
      if (serial_empty)
	ret = select(maxfd + 1, &rfds, NULL, NULL, NULL);
      else
	{
	  ret = select(maxfd + 1, &rfds, NULL, NULL, &zero);
	  check_serial();
	}
      if (ret >= 0)
	{
	  if (FD_ISSET(serfd, &rfds))
	    check_serial();

	  if (FD_ISSET(server_socket, &rfds))
	    check_new_client();

	  check_clients(&rfds);
	}
    }
}
Beispiel #8
0
int main(int argc, char *argv[])
{
  int socket_fd = 0, conn_fd = 0;
  int n, last;
	
  char send_buffer[1025];
	char receive_buffer[1025];
	
	memset(receive_buffer, 0, sizeof(receive_buffer));
	memset(send_buffer, 0, sizeof(send_buffer));
	

    socket_fd = open_server_socket(5000);
	printf("socket opened\n");
	
	listen(socket_fd, 10); 
	printf("listening\n");
 
  int f = open("destfile.txt", O_CREAT | O_WRONLY, (S_IWUSR | S_IRUSR | S_IWOTH | S_IROTH));
  fchmod(f, (S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH));

	while(1)
    {
        printf("accepting connection\n");
		conn_fd = accept(socket_fd, (struct sockaddr*)NULL, NULL); 
		
		printf("writing\n");
		snprintf(send_buffer, sizeof(send_buffer), "server says hello world!\n");
        write(conn_fd, send_buffer, strlen(send_buffer)); 
		
		printf("reading\n");
		
		n = read(conn_fd, receive_buffer, sizeof(receive_buffer));
		if (n >= 0){
			if (n){
				write(1, receive_buffer, n);//stdout
				write(f, receive_buffer, n);
				last = n-1;
			}
		}else{
			printf("socket error\n");
		}
    
		
		printf("closing connection\n");
		close(conn_fd);
        sleep(1);
     }
}
Beispiel #9
0
static void
test_socket_pair (void)
{
  struct sockaddr_in ia;

  socklen_t addrlen = sizeof (ia);
  int s = open_server_socket ();
  int c1 = connect_to_socket (false);
  int c2 = accept (s, (struct sockaddr *) &ia, &addrlen);

  close (s);

  test_pair (c1, c2);
  close (c1);
  write (c2, "foo", 3);
  close (c2);
}
Beispiel #10
0
static void
test_accept_first (void)
{
#ifndef WINDOWS_NATIVE
    int s = open_server_socket ();
    struct sockaddr_in ia;
    socklen_t addrlen;
    char buf[3];
    int c, pid;

    pid = fork ();
    if (pid < 0)
        return;

    if (pid == 0)
    {
        addrlen = sizeof (ia);
        c = accept (s, (struct sockaddr *) &ia, &addrlen);
        ASSERT (c >= 0);
        close (s);
        ASSERT (write (c, "foo", 3) == 3);
        ASSERT (read (c, buf, 3) == 3);
        shutdown (c, SHUT_RD);
        close (c);
        exit (0);
    }
    else
    {
        close (s);
        c = connect_to_socket (true);
        ASSERT (c >= 0);
        if (poll1_nowait (c, POLLOUT | POLLWRNORM | POLLRDBAND)
                != (POLLOUT | POLLWRNORM))
            failed ("cannot write after blocking connect");
        ASSERT (write (c, "foo", 3) == 3);
        wait (&pid);
        if (poll1_wait (c, POLLIN) != POLLIN)
            failed ("cannot read data left in the socket by closed process");
        ASSERT (read (c, buf, 3) == 3);
        ASSERT (write (c, "foo", 3) == 3);
        if ((poll1_wait (c, POLLIN | POLLOUT) & (POLLHUP | POLLERR)) == 0)
            failed ("expecting POLLHUP after shutdown");
        close (c);
    }
#endif
}
Beispiel #11
0
int main()
{

	int sockid = open_server_socket("localhost", 5555);

	while(true){

		int newsockid = accept(sockid,0,0);
		int pid = fork();
		if (pid == -1){
			throw std::runtime_error("Forking error");
		}
		if (pid == 0){
			handle_connection(newsockid);
			return 0;
		}

	}

}
Beispiel #12
0
static void
test_accept_first (void)
{
#ifndef WIN32_NATIVE
  int s = open_server_socket ();
  struct sockaddr_in ia;
  socklen_t addrlen;
  char buf[3];
  int c, pid;

  pid = fork ();
  if (pid < 0)
    return;

  if (pid == 0)
    {
      addrlen = sizeof (ia);
      c = accept (s, (struct sockaddr *) &ia, &addrlen);
      close (s);
      write (c, "foo", 3);
      read (c, buf, 3);
      shutdown (c, SHUT_RD);
      close (c);
      exit (0);
    }
  else
    {
      close (s);
      c = connect_to_socket (true);
      if (do_select_nowait (c, SEL_OUT) != SEL_OUT)
        failed ("cannot write after blocking connect");
      write (c, "foo", 3);
      wait (&pid);
      if (do_select_wait (c, SEL_IN) != SEL_IN)
        failed ("cannot read data left in the socket by closed process");
      read (c, buf, 3);
      write (c, "foo", 3);
      close (c);
    }
#endif
}
Beispiel #13
0
static void
test_socket_pair (void)
{
    struct sockaddr_in ia;

    socklen_t addrlen = sizeof (ia);
    int s = open_server_socket ();
    int c1 = connect_to_socket (false);
    int c2 = accept (s, (struct sockaddr *) &ia, &addrlen);
    ASSERT (s >= 0);
    ASSERT (c1 >= 0);
    ASSERT (c2 >= 0);

    close (s);

    test_pair (c1, c2);
    close (c1);
    ASSERT (write (c2, "foo", 3) == 3);
    if ((poll1_nowait (c2, POLLIN | POLLOUT) & (POLLHUP | POLLERR)) == 0)
        failed ("expecting POLLHUP after shutdown");

    close (c2);
}
Beispiel #14
0
void * socket_uart_recv_manager(void * arg)
{
    int listen_fd = open_server_socket(UNIX_SOCKET_UART_RECV);
    pthread_t real_recv;
    int result = pthread_create(&real_recv,
                                NULL,
                                uart_recv_worker,
                                NULL);
    assert(result == 0);
    socklen_t len = -1;
    struct sockaddr_un clt_addr;
    int com_fd = -1;
    while(1)
    {
        len = sizeof(clt_addr);
        com_fd = accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
        if(com_fd < 0)
        {
            perror("cannot accept client connect request");
            close(listen_fd);
            unlink(UNIX_SOCKET_UART_SEND);
            exit(-1);
        }
        int n = 0;
        uint8_t recv_buf[MAX_BUFSIZ];
        if( (n = read(com_fd,recv_buf,sizeof(recv_buf))) < 0)
        {
            LOG_ERROR("[%s] Read Error\n",__func__);
        }
        if(is_invalid_message((char *)recv_buf, n))
        {
            process_message_invalid_message(com_fd);
            close(com_fd);
        }
        else
        {
            message_t * message = deserialized_message(recv_buf,n);
#if 0
            LOG_DEBUG("XXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            view_message(message);
            LOG_DEBUG("____________________________");
#endif
            uart_dev_t * dev = get_dev_by_name(message->name);
            if(dev == NULL)
            {
                process_message_invalid_name(com_fd, message->name);
                close(com_fd);
            }
            else
            {
                struct timeval now;
                gettimeofday(&now,NULL);
                message_t * fit = NULL;
                socket_recv_handler * process_socket_recv = get_socket_recv_handler_by_protocol(dev->protocol);
                process_socket_recv->func(dev, message, &fit);
                if((fit == NULL))
                {
                    process_message_not_fit(com_fd);
                }
                else if((now.tv_sec - fit->stamp.tv_sec) > 10)
                {
                    free_message(fit);
                    process_message_not_fit(com_fd);
                }
                else
                {
                    process_message_fitted(com_fd, fit);
                }
                free_message(message);
                close(com_fd);
            }
        }
    }
    return NULL;
}
Beispiel #15
0
Datei: tgc.c Projekt: BwRy/tgcd
/*-----------------------------------------------------------------------------
 * LL node
------------------------------------------------------------------------------*/
int tgc_ll(TGC *tgc)
{
	fd_set		rfds, reads;
	struct	sockaddr_in addr;
	socklen_t 	in_addrlen = sizeof(addr);
	int		rc=0, sdi, sdx, sd;
	socket_pair_list	*conn, *prev_conn;
	char		cmd;
	struct in_addr	cc_addr = { 0 } ;
	char		ip[16];
	int		close_control = 0;
	struct timeval	tv;

	if (!tgc)
		return E_TGC_IE;

	if ( (tgc->sdx_accept=open_server_socket(tgc->node.ll.port)) < 0 ) {
		PRINT_LOG(1, "Can't bind to port %d", tgc->node.ll.port);
		return E_TGC_NOCANDO;
	}

	if ( (tgc->sdi_accept=open_server_socket(tgc->node.ll.ll_port)) < 0 ) {
		PRINT_LOG(1, "Can't bind to port %d", tgc->node.ll.ll_port);
		return E_TGC_NOCANDO;
	}

	PRINT_LOG(3, "waiting for client on port %d ...", tgc->node.ll.port);
	PRINT_LOG(3, "waiting for CC on %d!", tgc->node.ll.ll_port);
	
	FD_ZERO(&rfds);
	FD_SET(tgc->sdi_accept, &rfds);
	FD_SET(tgc->sdx_accept, &rfds);

	tgc->node.ll.control_sd = -1;

	while(1) {
		tv.tv_sec = tgc->node.ll.timeout;
		tv.tv_usec = 0;
		reads = rfds;
		if ( (rc = select(FD_SETSIZE, &reads, NULL, NULL, &tv)) < 0 )
			continue;
		if (rc == 0 && tgc->node.ll.control_sd >= 0) {
			PRINT_LOG(1, "time out, closing control connection");
			FD_CLR(tgc->node.ll.control_sd, &rfds);
			close_connection(&(tgc->node.ll.control_sd));
			close_control = 0;
			continue;
		}

		if (FD_ISSET(tgc->sdx_accept, &reads)) { // incoming client connection
			sdx = accept_connection(tgc->sdx_accept, (struct sockaddr_in *)&addr, 
				       		(socklen_t *)&in_addrlen);

			if (sdx==-1) {
				if (errno==EINTR)
					continue;
				PRINT_LOG(1, "Error accepting new client connection");
				continue; //break; // exit
			}

			if (tgc->node.ll.control_sd<0) { 
				//client came in while there is no control connection, so we close it
				PRINT_LOG(3, "rejecting client connection before control connection received ");
				close_connection(&sdx);
				continue;
			}

			strncpy(ip, inet_ntoa(addr.sin_addr), 16);
			PRINT_LOG(3, "client (%s) connected on %d!", ip, tgc->node.ll.ll_port);
			// run the filter
			if (!tgc_check_filter(tgc, ip)) {
				close_connection(&sdx);
				continue;
			}
			PRINT_LOG(3, "Ask CC for a connection for the new client");

			if (tgc_send(tgc->node.ll.control_sd, TGC_COMM_CCC)>=0) {
				if (tgc_add_queue( &(tgc->node.ll.socketq), sdx)<0) {
					PRINT_LOG(1, "Error adding socket to queue!");
					close_connection(&sdx);
					return E_TGC_NOCANDO;
				}
				PRINT_LOG(5, "client connection added to the queue");
		 	} else 
				close_connection(&sdx); // couldn't ask CC for a new connection, close the client
		} 
		
		if (FD_ISSET(tgc->sdi_accept, &reads)) { // from CC
			sdi = accept_connection(tgc->sdi_accept, (struct sockaddr_in *)&addr, 
				       (socklen_t *)&in_addrlen);

			if (sdi==-1) {
				if (errno==EINTR)
					continue;
				PRINT_LOG(1, "Error accepting new CC connection");
				break; // exit
			}

			strncpy(ip, inet_ntoa(addr.sin_addr), 16);
			PRINT_LOG(3, "CC connected from %s", ip);
			// run the filter
			if (!tgc_check_filter(tgc, ip)) {
				close_connection(&sdi);
                                continue;
			}

			if (tgc->node.ll.control_sd<0) { 
				// it's the control connection
				tgc->node.ll.control_sd = sdi;
				cc_addr.s_addr = addr.sin_addr.s_addr;
				FD_SET(sdi, &rfds);
				PRINT_LOG(4, "Control connection established");
			} else { // it's a normal CC connection
				if (addr.sin_addr.s_addr!=cc_addr.s_addr || !tgc->node.ll.socketq) {
					// if this CC's address is different from control_sd's OR
					// if there are no client connections waiting in the queue
					// we reject the CC
					close_connection(&sdi);
					PRINT_LOG(1, "Suspicious CC rejected");
				} else { //everything seems good, lets do our thing!
					sdx = tgc_remove_queue(&(tgc->node.ll.socketq));
					if (sdx>=0) {
						if (tgc->method==TGC_METHOD_SELECT) {
							if (!tgc_add_list( &(tgc->pairs), sdi, sdx)) {
								FD_SET(sdi, &rfds);
								FD_SET(sdx, &rfds);
							} 
						} else {
#ifdef HAVE_FORK
							// FORK
							if (fork()==0) { // child
								close_connection(&(tgc->sdi_accept));
								close_connection(&(tgc->sdx_accept));
								close_connection(&(tgc->node.ll.control_sd));
								tgc_pump(sdi, sdx, tgc->buf, tgc->key);
								break; //exit(0);
							} else { // parent
								close_connection(&sdi);
								close_connection(&sdx);
							}
#endif
						}
					}
				}
			}
		} 
		
		if (tgc->node.ll.control_sd>=0 && FD_ISSET(tgc->node.ll.control_sd, &reads)) {
			close_control = 0;
			if (tgc_read(tgc->node.ll.control_sd, &cmd) == E_TGC_OK) {
				switch (cmd) {
					case TGC_COMM_PING:
						PRINT_LOG(2, "Received a ping from CC");
						if (tgc_send(tgc->node.ll.control_sd, TGC_COMM_PING)<0) {
							PRINT_LOG(1, "Internal Error: can't write to control connection");
							FD_CLR(tgc->node.ll.control_sd, &rfds);
							close_connection(&(tgc->node.ll.control_sd));
							tgc->node.ll.control_sd = -1;
							continue;
						}
						break;
					case TGC_COMM_CLOSE:
						PRINT_LOG(3, "CC wants us to close the lingering client connection!");
						if ((sd=tgc_remove_queue(&(tgc->node.ll.socketq)))>=0)
							close_connection(&sd);
						break;
					default:
						PRINT_LOG(1, "Internal Error: Uknown code (0x%x) recieved from CC!", cmd);
						close_control = 1;
				}
			} else {
				close_control = 1;
			}

			if (close_control) {
				PRINT_LOG(1, "closing control connection");
				FD_CLR(tgc->node.ll.control_sd, &rfds);
				close_connection(&(tgc->node.ll.control_sd));
				tgc->node.ll.control_sd = -1;
				close_control = 0;
				continue;
			}
		}

		// pump the data for each and every connection pairs
		if (tgc->method==TGC_METHOD_SELECT) {
			conn = tgc->pairs; 
			while (conn) {
				if (FD_ISSET(conn->sdi , &reads)) { // from CC?
					if ( (rc=tgc_rxtx(conn->sdi, conn->sdx, tgc->buf, tgc->key)) < 0 ) {
						FD_CLR(conn->sdi, &rfds);
						FD_CLR(conn->sdx, &rfds);
						close_connection(&(conn->sdi));
						close_connection(&(conn->sdx));
						prev_conn = conn;
						conn = conn->next;
						tgc_remove_list( &(tgc->pairs), prev_conn);
						continue;
					}
				}

				if (FD_ISSET(conn->sdx, &reads)) { // from client?
					if ( (rc=tgc_rxtx(conn->sdx, conn->sdi, tgc->buf, tgc->key)) < 0 ) {
						FD_CLR(conn->sdi, &rfds);
						FD_CLR(conn->sdx, &rfds);
						close_connection(&(conn->sdi));
						close_connection(&(conn->sdx));
						prev_conn = conn;
						conn = conn->next;
						tgc_remove_list( &(tgc->pairs), prev_conn);
						continue;
					}
				}
				conn=conn->next;
			}
		}
	}
	
	return 0;
}
Beispiel #16
0
int main (int argc, char** argv)
{
  StackDescription_t stkd ;
  Analysis_t         analysis ;
  Output_t           output ;
  ThermalData_t      tdata ;

  Error_t error ;

  struct timespec t1,t2;
  struct timespec res;
  res.tv_sec=0;
  res.tv_nsec=0;
  Quantity_t server_port ;

  Socket_t server_socket, client_socket ;

  NetworkMessage_t request, reply , tmapReply;

  bool headers = false ;

    /* Checks if all arguments are there **************************************/

  if (argc != 3)
  {
    fprintf (stderr, "Usage: \"%s file.stk server_port\n", argv[0]) ;

    return EXIT_FAILURE ;
  }

  server_port = atoi (argv[2]) ;

  /* Parses stack file (fills stack descrition and analysis) ****************/

  fprintf (stdout, "Preparing stk data ... ") ; fflush (stdout) ;

  stack_description_init (&stkd) ;
  analysis_init          (&analysis) ;
  output_init            (&output) ;
  
    error = parse_stack_description_file (argv[1], &stkd, &analysis, &output) ;

  /* Initialise the compression related data ********************************/

  Quantity_t nflpel_ = get_total_number_of_floorplan_elements (&stkd) ;

  float hist_table_d[nflpel_][HIST_TABLE_SIZE];
  
  int tail_d[nflpel_];
  
  for (unsigned int i = 0; i < nflpel_; i++)
  {
    tail_d[i] = 0;
  
    for (int j = 0; j < HIST_TABLE_SIZE; j++)
      hist_table_d[i][j] = -1.0;
  }

  for(int i=0;i<MAXRES;i++)
    for(int j=0;j<MAXROWS;j++)
      for(int k=0;k<MAXCOLS;k++)
        for(int l=0;l<HIST_TABLE_SIZE;l++)
          histTableMap[i][j][k][l] = -1.0;
  int compressionUsed;



  if (error != TDICE_SUCCESS)    return EXIT_FAILURE ;

  if (analysis.AnalysisType != TDICE_ANALYSIS_TYPE_TRANSIENT)
  {
    fprintf (stderr, "only transient analysis!\n") ;

    goto wrong_analysis_error ;
  }

  fprintf (stdout, "done !\n") ;

  /* Prepares thermal data **************************************************/

  fprintf (stdout, "Preparing thermal data ... ") ; fflush (stdout) ;

  thermal_data_init (&tdata) ;

  error = thermal_data_build

    (&tdata, &stkd.StackElements, stkd.Dimensions, &analysis) ;


  if (error != TDICE_SUCCESS)    goto ftd_error ;

  fprintf (stdout, "done !\n") ;

  /* Creates socket *********************************************************/

  fprintf (stdout, "Creating socket ... ") ; fflush (stdout) ;

  socket_init (&server_socket) ;

  error = open_server_socket (&server_socket, server_port) ;



  if (error != TDICE_SUCCESS)    goto socket_error ;

  fprintf (stdout, "done !\n") ;

  /* Waits for a client to connect ******************************************/

  fprintf (stdout, "Waiting for client ... ") ; fflush (stdout) ;

  socket_init (&client_socket) ;

  error = wait_for_client (&server_socket, &client_socket) ;

  if (error != TDICE_SUCCESS)    goto wait_error ;

  fprintf (stdout, "done !\n") ;

  //float timeForTmap = 0.0;
  /* Runs the simlation *****************************************************/

  do
  {
    network_message_init (&request) ;

    receive_message_from_socket (&client_socket, &request) ;

    switch (*request.Type)
    {

      /**********************************************************************/
      case TDICE_COMPRESSION_USED :
        {
          extract_message_word (&request, &compressionUsed,0);
          break;
        }
      case TDICE_EXIT_SIMULATION :
        {
          network_message_destroy (&request) ;

          goto quit ;
        }

        /**********************************************************************/

      case TDICE_RESET_THERMAL_STATE :
        {
          reset_thermal_state (&tdata, &analysis) ;

          break ;
        }

        /**********************************************************************/

      case TDICE_TOTAL_NUMBER_OF_FLOORPLAN_ELEMENTS :
        {
          network_message_init (&reply) ;

          build_message_head   (&reply, TDICE_TOTAL_NUMBER_OF_FLOORPLAN_ELEMENTS) ;

          Quantity_t nflpel = get_total_number_of_floorplan_elements (&stkd) ;

          insert_message_word (&reply, &nflpel) ;

          send_message_to_socket (&client_socket, &reply) ;

          network_message_destroy (&reply) ;

          break ;
        }

        /**********************************************************************/

      case TDICE_INSERT_POWERS_AND_SIMULATE_SLOT :
        {
          Quantity_t nflpel, index ;

          PowersQueue_t queue ;

          powers_queue_init (&queue) ;

          extract_message_word (&request, &nflpel, 0) ;

          powers_queue_build (&queue, nflpel) ;
          if(compressionUsed)
          {
            unsigned int tmp[3];
            int ret=-1;
            unsigned int compressedWord;
            float power=0.0;
            int readIndex=1;
            index=1;
            initTmp(tmp);
            extract_message_word (&request, &compressedWord,readIndex);
            while(index<=nflpel)
            {
              ret=getNextDecompressedWord(compressedWord,tmp,0);
              switch(ret)
              {
                case WI_DC:
                case WC_DC: 
                  switch(tmp[0])
                  {
                    case 0:
                      power=(int)hist_table_d[index-1][tmp[1]]+(hist_table_d[index-1][tmp[2]]-(int)hist_table_d[index-1][tmp[2]]);
                      break; 
                    case 1:
                      power=tmp[1]+(hist_table_d[index-1][tmp[2]]-(int)hist_table_d[index-1][tmp[2]]);
                      hist_table_d[index-1][tail_d[index-1]]=power;
                      tail_d[index-1]=(tail_d[index-1]+1)%HIST_TABLE_SIZE;
                      break;
                    case 2:
                      power=(int)hist_table_d[index-1][tmp[1]]+((float)tmp[2])/(pow(10,DECIMAL_DIGITS));
                      hist_table_d[index-1][tail_d[index-1]]=power;
                      tail_d[index-1]=(tail_d[index-1]+1)%HIST_TABLE_SIZE;
                      break;
                    case 3:
                      power=tmp[1]+((float)tmp[2])/(pow(10,DECIMAL_DIGITS));
                      hist_table_d[index-1][tail_d[index-1]]=power;
                      tail_d[index-1]=(tail_d[index-1]+1)%HIST_TABLE_SIZE;
                      break;
                  }
                  put_into_powers_queue(&queue,power);
                  index++;
                  initTmp(tmp);
                  if(ret==WC_DC)
                  {
                    readIndex++;
                    extract_message_word (&request, &compressedWord,readIndex);
                  }
                  break;
                case WC_DI:
                  readIndex++;
                  extract_message_word (&request, &compressedWord,readIndex);
                  break;
                default:
                  break;
              }
            }
            ret=getNextDecompressedWord(compressedWord,tmp,1);
          }
          /* NO COMPRESSION *************************************/
          else 
          {
            for (index = 1, nflpel++ ; index != nflpel ; index++)
            {
              float power_value ;

              extract_message_word (&request, &power_value, index) ;

              put_into_powers_queue (&queue, power_value) ;
            }

          }
          error = insert_power_values (&tdata.PowerGrid, &queue) ;

          if (error != TDICE_SUCCESS)
          {
            fprintf (stderr, "error: insert power values\n") ;

            powers_queue_destroy (&queue) ;

            goto sim_error ;
          }

          powers_queue_destroy (&queue) ;

          network_message_init (&reply) ;
          build_message_head   (&reply, TDICE_INSERT_POWERS_AND_SIMULATE_SLOT) ;

          SimResult_t result = emulate_slot

            (&tdata, stkd.Dimensions, &analysis) ;

          insert_message_word (&reply, &result) ;

          send_message_to_socket (&client_socket, &reply) ;

          network_message_destroy (&reply) ;

          if (result != TDICE_SLOT_DONE)
          {
            fprintf (stderr, "error %d: emulate slot\n", result) ;

            goto sim_error ;
          }

          break ;
        }

        /**********************************************************************/

      case TDICE_SEND_OUTPUT :
        {
          OutputInstant_t  instant ;
          OutputType_t     type ;
          OutputQuantity_t quantity ;
          //clock_t Time;          

          extract_message_word (&request, &instant,  0) ;
          extract_message_word (&request, &type,     1) ;
          extract_message_word (&request, &quantity, 2) ;

          network_message_init (&reply) ;
          build_message_head   (&reply, TDICE_SEND_OUTPUT) ;

          float   time = get_simulated_time (&analysis) ;
          Quantity_t n = get_number_of_inspection_points (&output, instant, type, quantity) ;

          insert_message_word (&reply, &time) ;
          insert_message_word (&reply, &n) ;

          if (n > 0)
          {
            error = fill_output_message

              (&output, stkd.Dimensions,
               tdata.Temperatures, tdata.PowerGrid.Sources,
               instant, type, quantity, &reply) ;

            if (error != TDICE_SUCCESS)
            {
              fprintf (stderr, "error: generate message content\n") ;

              network_message_destroy (&reply) ;

              goto sim_error ;
            }
          }
          if(type == TDICE_OUTPUT_TYPE_TMAP && compressionUsed)
          {
            //init histTableMap tailMap for compression
            //New packet tmapReply is being initialised /
            //clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t1);
            network_message_init (&tmapReply);
            build_message_head (&tmapReply, TDICE_SEND_OUTPUT);

            insert_message_word (&tmapReply, &time);
            insert_message_word (&tmapReply, &n);

            CellIndex_t nrows, ncols;

            int readIndex = 4;

            //get the no of rows and cols from reply packet
            extract_message_word (&reply, &nrows, 2);
            extract_message_word (&reply, &ncols, 3);

            //insert nrows and ncols into my packet
            insert_message_word (&tmapReply, &nrows);
            insert_message_word (&tmapReply, &ncols);

            int ret=-1, f1, f2;
            unsigned int compressedWord, i, j, k, l;
            unsigned int flag=0, intPart, decPart;

            unsigned int tmp[3];
            float temper;

            for(i=0; i<n; i++)
              for(j=0; j<nrows; j++)
                for(k=0; k<ncols; k++)
                {
                  f1 = -1;f2 = -1;

                  extract_message_word (&reply, &temper, readIndex);
                  readIndex++;
                  unsigned int intPartTemper, decPartTemper;
                  getParts (temper, &intPartTemper, &decPartTemper);
                  for (l=0;l<HIST_TABLE_SIZE;l++)
                  {
                    if(histTableMap[i][j][k][l] != -1.0)
                    {
                      getParts (histTableMap[i][j][k][l], &intPart, &decPart);
                      if(intPart == intPartTemper)f1 = l;
                      float val=((float)decPart-decPartTemper);
                      val=val/(float)pow(10,DECIMAL_DIGITS);
                      val=abs (val);
                      if(val <= TOLERANCE)
                        f2=l;
                    }
                  }
                  flag = getFlag (f1,f2);

                  switch (flag)
                  {
                    case 1:
                      histTableMap[i][j][k][tailMap[i][j][k]] = intPartTemper + 
                        (histTableMap[i][j][k][f2] - (int)histTableMap[i][j][k][f2]);
                      tailMap[i][j][k] = (tailMap[i][j][k] + 1)%HIST_TABLE_SIZE;
                      break;

                    case 2:
                      histTableMap[i][j][k][tailMap[i][j][k]] = (int)histTableMap[i][j][k][f1] + 
                        ((float)decPartTemper)/(pow(10,DECIMAL_DIGITS));
                      tailMap[i][j][k] = (tailMap[i][j][k] + 1)%HIST_TABLE_SIZE;
                      break;

                    case 3:
                      histTableMap[i][j][k][tailMap[i][j][k]] = intPartTemper + 
                        ((float)decPartTemper)/(pow(10,DECIMAL_DIGITS));
                      tailMap[i][j][k] = (tailMap[i][j][k] + 1)%HIST_TABLE_SIZE;
                      break;

                    default:
                      break;
                  }
                  getArgsInArray (f1, f2, flag, intPartTemper, decPartTemper, tmp);
                  ret = getNextCompressedWord (tmp[1], tmp[2], flag, &compressedWord, !WRAP_UP);
                  if(ret != WORD_INCOMPLETE)
                    insert_message_word (&tmapReply, &compressedWord);
                }
            switch(ret)
            {
              case WORD_INCOMPLETE:
              case WORD_IN_TEMP:
                getNextCompressedWord (tmp[1], tmp[2], flag, &compressedWord, WRAP_UP);
                insert_message_word (&tmapReply, &compressedWord);
                break;
              default:
                break;
            }
            clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t1);
            send_message_to_socket (&client_socket, &tmapReply);
            clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t2);
            diff(t1,t2,&res); 
            network_message_destroy (&reply);
            network_message_destroy (&tmapReply);
          }
          else
          {
            if(type == TDICE_OUTPUT_TYPE_TMAP)
            {
            //Time = clock();            
            clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t1);
            send_message_to_socket (&client_socket, &reply);
            //timeForTmap +=  ((double)clock() - Time) / CLOCKS_PER_SEC  ;
            clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t2);
            diff(t1,t2,&res); 
            }
            else
            send_message_to_socket (&client_socket, &reply) ;

            network_message_destroy (&reply) ;
          }
          break ;
        }

        /**********************************************************************/

      case TDICE_PRINT_OUTPUT :
        {
          OutputInstant_t  instant ;

          extract_message_word (&request, &instant,  0) ;

          if (headers == false)
          {
            Error_t error = generate_output_headers

              (&output, stkd.Dimensions, (String_t)"% ") ;

            if (error != TDICE_SUCCESS)
            {
              fprintf (stderr, "error in initializing output files \n ");

              goto sim_error ;
            }

            headers = true ;
          }

          generate_output

            (&output, stkd.Dimensions,
             tdata.Temperatures, tdata.PowerGrid.Sources,
             get_simulated_time (&analysis), instant) ;

          break ;
        }

        /**********************************************************************/

      case TDICE_SIMULATE_SLOT :
        {
          network_message_init (&reply) ;
          build_message_head   (&reply, TDICE_SIMULATE_SLOT) ;

          SimResult_t result = emulate_slot (&tdata, stkd.Dimensions, &analysis) ;

          insert_message_word (&reply, &result) ;

          send_message_to_socket (&client_socket, &reply) ;

          network_message_destroy (&reply) ;

          if (result == TDICE_END_OF_SIMULATION)
          {
            network_message_destroy (&request) ;

            goto quit ;
          }
          else if (result != TDICE_SLOT_DONE)
          {
            fprintf (stderr, "error %d: emulate slot\n", result) ;

            goto sim_error ;
          }

          break ;
        }

        /**********************************************************************/

      case TDICE_SIMULATE_STEP :
        {
          network_message_init (&reply) ;
          build_message_head   (&reply, TDICE_SIMULATE_STEP) ;

          SimResult_t result = emulate_step (&tdata, stkd.Dimensions, &analysis) ;

          insert_message_word (&reply, &result) ;

          send_message_to_socket (&client_socket, &reply) ;

          network_message_destroy (&reply) ;

          if (result == TDICE_END_OF_SIMULATION)
          {
            network_message_destroy (&request) ;

            goto quit ;
          }
          else if (result != TDICE_STEP_DONE && result != TDICE_SLOT_DONE)
          {
            fprintf (stderr, "error %d: emulate step\n", result) ;

            goto sim_error ;
          }

          break ;
        }

        /**********************************************************************/

      default :

        fprintf (stderr, "ERROR :: received unknown message type") ;
    }

    network_message_destroy (&request) ;

  } while (1) ;

  /**************************************************************************/

quit :

  socket_close              (&client_socket) ;
  socket_close              (&server_socket) ;
  thermal_data_destroy      (&tdata) ;
  stack_description_destroy (&stkd) ;
  output_destroy            (&output) ;

  printf("Time taken %d sec %d nsec \n",(int)res.tv_sec,(int)res.tv_nsec);
  return EXIT_SUCCESS ;

sim_error :
  network_message_destroy   (&request) ;
  socket_close              (&client_socket) ;
wait_error :
  socket_close              (&server_socket) ;
socket_error :
  thermal_data_destroy      (&tdata) ;
ftd_error :
wrong_analysis_error :
  stack_description_destroy (&stkd) ;
  output_destroy            (&output) ;

  return EXIT_FAILURE ;
}
Beispiel #17
0
Datei: tgc.c Projekt: BwRy/tgcd
/*-----------------------------------------------------------------------------
  Become a port forwarder
------------------------------------------------------------------------------*/
int tgc_pf(TGC *tgc)
{
	struct sockaddr_in 	addr;
	socklen_t    		in_addrlen = sizeof(addr);
	fd_set 			rfds, reads;
	int			sdi, sdx, rc=0;
	socket_pair_list	*conn, *prev_conn;
	char			ip[16];


	signal(SIGCLD, SIG_DFL); // to avoid zombie process

 	if ( (tgc->sdi_accept=open_server_socket(tgc->node.pf.port)) < 0 ) {
		PRINT_LOG(1, "Can't bind to port %d", tgc->node.pf.port);
		return E_TGC_NOCANDO;
	}
	
	PRINT_LOG(3, "waiting for incomming connections on port %d ...", tgc->node.pf.port);

	FD_ZERO(&rfds);
	FD_SET(tgc->sdi_accept, &rfds);

	while (1) {

		reads = rfds;
		if ( select(FD_SETSIZE, &reads, NULL, NULL, NULL) < 0 ) 
			continue;

		if (FD_ISSET(tgc->sdi_accept, &reads)) {
		
			sdi = accept_connection(tgc->sdi_accept, (struct sockaddr_in *) &addr, 
					                     (socklen_t *)&in_addrlen);

			if (sdi==-1) {
				if (errno==EINTR)
					continue;

				PRINT_LOG(0, "Error accepting new connection!");
				close_connection(&(tgc->sdi_accept));
				break; //exit
			}

			// run the filter
			strncpy(ip, inet_ntoa(addr.sin_addr), 16);
			PRINT_LOG(3, "Received a client from %s", ip);
			if (!tgc_check_filter(tgc, ip)) {
				close_connection(&sdi);
				sdi = -1;
				continue;
			}

			if ( (sdx=connect_server(tgc->node.pf.dst_host, tgc->node.pf.dst_port))<0 ) {
				PRINT_LOG(1, "failed connecting to %s:%d", tgc->node.pf.dst_host, tgc->node.pf.dst_port);
				close_connection(&sdi);
				sdi = -1;
				continue;
			}
			PRINT_LOG(3, "connected to the server");

			if (tgc->method == TGC_METHOD_SELECT) {
				if (!tgc_add_list( &(tgc->pairs), sdi, sdx)) {
					FD_SET(sdi, &rfds);
					FD_SET(sdx, &rfds);
					PRINT_LOG(3, "Added socket pairs to the list");
					continue;
				}
			} else { //fork method
#ifdef HAVE_FORK
				if (fork()==0) { //child
					close_connection(&(tgc->sdi_accept));
					tgc_pump(sdi, sdx, tgc->buf, tgc->key);
					break;
				} else {// parent
					close_connection(&sdi);
					close_connection(&sdx);
					PRINT_LOG(3, "waiting for incomming connections on port %d again...", tgc->node.pf.port);
				}
#endif
			}
		}

		// pump the data for each and every connection pairs
		if (tgc->method==TGC_METHOD_SELECT) {
			conn = tgc->pairs;
			while (conn) {
				if (FD_ISSET(conn->sdi , &reads)) { // from client
					if ( (rc=tgc_rxtx(conn->sdi, conn->sdx, tgc->buf, tgc->key)) < 0 ) {
						PRINT_LOG(3, "Error reading socket, closing pair");
						FD_CLR(conn->sdi, &rfds);
						FD_CLR(conn->sdx, &rfds);
						close_connection(&(conn->sdi));
						close_connection(&(conn->sdx));
						prev_conn = conn;
						conn = conn->next;
						tgc_remove_list( &(tgc->pairs), prev_conn);
						continue;
					}
				}

				if (FD_ISSET(conn->sdx, &reads)) { // from server
					if ( (rc=tgc_rxtx(conn->sdx, conn->sdi, tgc->buf, tgc->key)) < 0 ) {
						PRINT_LOG(3, "Error reading socket, closing pair.");
						FD_CLR(conn->sdi, &rfds);
						FD_CLR(conn->sdx, &rfds);
						close_connection(&(conn->sdi));
						close_connection(&(conn->sdx));
						prev_conn = conn;
						conn=conn->next;
						tgc_remove_list( &(tgc->pairs), prev_conn);
						continue;
					}
				}
				conn=conn->next;
			}
		}
	}
	return E_TGC_NOCANDO;
}