コード例 #1
0
ファイル: rfx-common.c プロジェクト: hyper/librisp
int sock_connect(char *szHost, int nPort)
{
    int nSocket = 0;
    struct sockaddr_in sin;

    assert(szHost != NULL);
    assert(nPort > 0);

    if (sock_resolve(szHost,nPort,&sin) >= 0) {
        // CJW: Create the socket
        nSocket = socket(AF_INET,SOCK_STREAM,0);
        if (nSocket >= 0) {
            // CJW: Connect to the server
            if (connect(nSocket, (struct sockaddr*)&sin, sizeof(struct sockaddr)) >= 0) {
                sock_nonblock(nSocket);   // and set the socket for non-blocking mode.
            }
            else {
                close(nSocket);
                nSocket = 0;
            }
        }
    }
    
    return(nSocket);
}
コード例 #2
0
ファイル: fdselect_t.c プロジェクト: noelbk/bklib
int
main() {
    fdselect_t sel;
    sock_t pipe[2];
    int i, n;
    tid_t tid;
    
    debug_init(DEBUG_INFO, 0, 0);
    sock_init();
    fdselect_init(&sel);
    
    for(i=0; i<CHILD_FORK_MAX; i++) {
	pipe_child_arg_t *a;

	n = sock_pair(pipe);
	assertb_sockerr(n>=0);
	n = sock_nonblock(pipe[0], 1);
	assertb_sockerr(n>=0);

	a = calloc(1, sizeof(*a));
	a->sock = pipe[1];
	a->id    = i;
	tid = thread_start(pipe_child, a);
	fdselect_set(&sel, pipe[0], FDSELECT_READ, pipe_select_read, (void*)tid);
    }

    while(1) {
	i = fdselect_count(&sel);
	printf("fdselect_select: count=%d\n", i);
	if( i<=0 ) break;
	fdselect_select(&sel, 1000);
    }
    return 0;
}
コード例 #3
0
ファイル: sock_serv.c プロジェクト: ilart/Yarrow
void
accept_connect(int *nelems)
{
	int client_fd, idx;
	struct sockaddr saddr;
	socklen_t slen;

	while (1) {
		client_fd = accept(poll_fd[0].fd, &saddr, &slen);
		if (client_fd > 0) {
			idx = find_unused_fd(nelems);
			poll_fd[idx].fd = client_fd;
			poll_fd[idx].events = (POLLIN|POLLPRI);
		
			peer_ctx[idx].sfd = client_fd;
			peer_ctx[idx].bufused = 0;
		
			sock_nonblock(client_fd);
			printf("we recive connect fd=%d nelems %d\n",
			       client_fd, *nelems);
		} else if (client_fd == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
			return;
		} else if (client_fd == -1 && errno != EINTR) {
			printf("accept returned %d: %s", client_fd, strerror(client_fd));
			exit(1);	
		}
	}
	return;
}
コード例 #4
0
ファイル: sockfuncs.cpp プロジェクト: melchor629/butt
int sock_connect(const char *addr, short port, int timout_ms)
{

    int sock;
    struct hostent *host_ptr;
    struct sockaddr_in hostname;

#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2),&wsa);
#endif

    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sock == -1)
          return SOCK_ERR_CREATE;

    host_ptr = gethostbyname(addr);
    if(host_ptr == NULL)
    {
        host_ptr = gethostbyaddr(addr, (unsigned) strlen(addr), AF_INET);
        if(host_ptr == NULL)
        {
            sock_close(&sock);
            return SOCK_ERR_RESOLVE;
        }
    }

    hostname.sin_family = AF_INET;
    hostname.sin_port = htons(port);

    memcpy(&hostname.sin_addr, host_ptr->h_addr, host_ptr->h_length);

    
    sock_nonblock(&sock);

    connect(sock, (struct sockaddr*) &hostname, sizeof(hostname));

    if(sock_select(&sock, timout_ms, WRITE) <= 0)
    {
        sock_close(&sock);
        return SOCK_TIMEOUT;
    }

    if(!sock_isvalid(&sock))
    {
        sock_close(&sock);
        return SOCK_INVALID;
    }

    return sock;
}
コード例 #5
0
ファイル: leda_udpdb_thread.c プロジェクト: jkocz/LEDA
int leda_udpdb_prepare (udpdb_t * ctx)
{
  if (ctx->verbose)
    multilog(ctx->log, LOG_INFO, "leda_udpdb_prepare()\n");

  // open socket
  if (ctx->verbose)
    multilog(ctx->log, LOG_INFO, "prepare: creating udp socket on %s:%d\n", ctx->interface, ctx->port);
  ctx->sock->fd = dada_udp_sock_in(ctx->log, ctx->interface, ctx->port, ctx->verbose);
  if (ctx->sock->fd < 0) {
    multilog (ctx->log, LOG_ERR, "Error, Failed to create udp socket\n");
    return -1;
  }

  // set the socket size to 256 MB
  int sock_buf_size = 256*1024*1024;
  if (ctx->verbose)
    multilog(ctx->log, LOG_INFO, "prepare: setting buffer size to %d\n", sock_buf_size);
  dada_udp_sock_set_buffer_size (ctx->log, ctx->sock->fd, ctx->verbose, sock_buf_size);

  // set the socket to non-blocking
  if (ctx->verbose)
    multilog(ctx->log, LOG_INFO, "prepare: setting non_block\n");
  sock_nonblock(ctx->sock->fd);

  // clear any packets buffered by the kernel
  if (ctx->verbose)
    multilog(ctx->log, LOG_INFO, "prepare: clearing packets at socket\n");
  size_t cleared = dada_sock_clear_buffered_packets(ctx->sock->fd, UDP_PAYLOAD);

  // setup the next_seq to the initial value
  ctx->last_seq = 0;
  ctx->last_byte = 0;
  ctx->n_sleeps = 0;

  // lock as writer on the HDU
  if (dada_hdu_lock_write (ctx->hdu) < 0)
  {
    multilog (ctx->log, LOG_ERR, "open_hdu: could not lock write\n");
    return -1;
  }

  return 0;
}
コード例 #6
0
ファイル: test_network.c プロジェクト: EmuxEvans/sailing
void onaccept_proc(void* userptr, SOCK_HANDLE sock, const SOCK_ADDR* pname)
{
	char addr[50];
	NETWORK_EVENT event;

	printf("accept from %s\n", sock_addr2str(pname, addr));
	sock_nonblock(sock);

	event.OnConnect = onconnect_proc;
	event.OnData = ondata_proc;
	event.OnDisconnect = ondisconnect_proc;
	event.recvbuf_pool = recvbuf_pool;
	event.recvbuf_buf = NULL;
	event.recvbuf_max = recvbuf_size;

	if(!network_add(sock, &event, NULL)) {
		sock_disconnect(sock);
		sock_close(sock);
	}
}
コード例 #7
0
ファイル: http_redirect.c プロジェクト: noelbk/bklib
void
http_redirect_client_select_read(fdselect_t *sel, fd_t fd, int state, void *arg) {
    http_redirect_client_t *client = (http_redirect_client_t *)arg;
    http_redirect_t *server = client->server;
    struct stat st;
    int i, n, err=-1;
    char buf[4096];
    char buf1[1024];

    do {
	i = client->recv_max - client->recv_len;
	if( i <= 0 ) {
	    err = 405; /* request too big */
	    break;
	}

	i = recv(client->sock, client->recv_buf+client->recv_len, i, 0);
	if( i <= 0 ) {
	    if( sock_wouldblock(client->sock, i) ) {
		/* ignore spurious blocking reads */
		err = 0;
		break;
	    }
	    assertb_sockerr(i);
	}
	client->recv_len += i;
	client->recv_buf[client->recv_len] = 0;

	debug(DEBUG_INFO,
	      ("http_redirect_client_select_read: addr=%s recv=%d\n"
	       "recv_buf=\n%s\n"
	       ,iaddr_fmt(&client->addr, buf1, sizeof(buf1))
	       ,i
	       ,client->recv_buf
	       ));

	i = http_header_parse(&client->http_req, client->recv_buf, client->recv_len);
	if( i == 0 ) {
	    /* header not complete yet, continue */
	    err = 0;
	    break;
	}
	else if( i < 0 ) {
	    err = -i;
	    break;
	}

	/* find a remote server to redirect to */

	if( strcmp(req_url->path, "/p2p_router", strlen("/p2p_router"))==0 ) {
	    addrlen = iaddr_pack(&addr, INADDR_ANY, 8969);
	}
	else {
	    addrlen = iaddr_pack(&addr, INADDR_ANY, 80);
	}

	/* start connecting to remote server */
	client->redirect_sock = socket(AF_INET, SOCK_STREAM, 0);
	assertb_sockerr(client->redirect_sock>=0);
	i = sock_nonblock(client->redirect_sock, 1);
	assertb_sockerr(i==0);
	i = connect(client->redirect_sock, (struct sockaddr*)&addr, addrlen);
	assertb_sockerr(i==0 || sock_wouldblock(client->redirect_sock, i));
	
	/* stop reading from client, and wait for connection to complete */
	fdselect_unset(server->fdselect, client->sock, FDSELECT_READ);
	fdselect_set(server->fdselect, client->redirect_sock, FDSELECT_READ, 
		     http_redirect_client_select_redirect_connect, client);


	i = snprintf(buf, sizeof(buf), "%s%s", 
		     server->root_dir, client->http_req.uri);
	err = 404; /* file not found */
	i = stat(buf, &st);
	assertb(i==0);
	client->send_file = fopen(buf, "r");
	assertb(client->send_file);

	debug(DEBUG_INFO,
	      ("http_redirect_client_select_read: sending file=%s\n", buf));

	i = snprintf(buf, sizeof(buf),
		     "HTTP/1.0 200 Ok\r\n"
		     "Pragma: no-cache\r\n"
		     "Cache-Control: no-cache\r\n"
		     "Connection: keep-alive\r\n"
		     "Content-Length: %lu\r\n"
		     "Content-Type: text/plain\r\n"
		     "\r\n"
		     ,st.st_size);
	n = i;
	i = send(client->sock, buf, n, 0);
	assertb(i==n);
	
	/* stop reading and start writing */
	fdselect_unset(server->fdselect, client->sock, FDSELECT_READ);
	fdselect_set(server->fdselect, client->sock, FDSELECT_WRITE, 
		     http_redirect_client_select_write, client);

	err = 0;

    } while(0);
    if( err > 0 ) {
	i = snprintf(buf, sizeof(buf),
		     "HTTP/1.0 %d\r\n"
		     "Content-Type: text/html; charset=iso-8859-1\r\n"
		     "\r\n"
		     "<HTML><HEAD>\r\n"
		     "<TITLE>HTTP Error %d</TITLE>\r\n"
		     "</HEAD><BODY>\r\n"
		     "<H1>HTTP Error %d</H1>\r\n"
		     "%s<br>\r\n"
		     "<HR>\r\n"
		     "</BODY></HTML>\r\n"
		     
		     , err, err, err
		     , client->http_req.uri);
	send(client->sock, buf, i, 0);
    }
    if( err ) {
	http_redirect_client_free(client);
    }
}
コード例 #8
0
ファイル: leda_udptest.c プロジェクト: jkocz/LEDA
int main (int argc, char **argv)
{

  // for stats thread
  leda_udptest_t udptest;

  /* Interface on which to listen for udp packets */
  char * interface = "any";

  /* port for incoming UDP packets */
  int inc_port = 4000;

  /* Flag set in verbose mode */
  unsigned verbose = 0;

  /* UDP packet size */
  size_t pkt_size = 8208;

  /* statistics thread */
  pthread_t stats_thread_id;

  int arg = 0;

  int core = -1;

  while ((arg=getopt(argc,argv,"b:c:i:p:vh")) != -1) 
  {
    switch (arg) 
    {
      case 'b':
        if (optarg)
          pkt_size = atoi(optarg);
        break;

      case 'c': 
        if (optarg)
          core = atoi(optarg);
        break;

      case 'i':
        if (optarg)
          interface = strdup(optarg);
        break;
    
      case 'p':
        inc_port = atoi (optarg);
        break;

      case 'v':
        verbose++;
        break;

      case 'h':
        usage();
        return 0;
      
      default:
        usage ();
        return 0;
    }
  }
  
  signal(SIGINT, signal_handler);

  stats_t * packets = init_stats_t();
  stats_t * bytes   = init_stats_t();

  udptest.packets = packets;
  udptest.bytes = bytes;
  udptest.verbose = verbose;
  udptest.pkt_size = pkt_size;
  udptest.n_sleeps = 0;

  multilog_t * log = multilog_open ("leda_udptest", 0);
  multilog_add (log, stderr);

  if (core >= 0)
    if (dada_bind_thread_to_core(core) < 0)
      multilog(log, LOG_INFO, "Error bindinf to core: %d\n", core);

  if (verbose)
    multilog(log, LOG_INFO, "starting stats_thread()\n");
  int rval = pthread_create (&stats_thread_id, 0, (void *) stats_thread, (void *) &udptest);
  if (rval != 0) {
    multilog(log, LOG_INFO, "Error creating stats_thread: %s\n", strerror(rval));
    return -1;
  }

  // UDP file descriptor
  int fd = dada_udp_sock_in (log, interface, inc_port, verbose);

  // set the socket size to 16 MB
  int sock_buf_size = 16*1024*1024;
  multilog(log, LOG_INFO, "start_function: setting buffer size to %d\n", sock_buf_size);
  dada_udp_sock_set_buffer_size (log, fd, verbose, sock_buf_size);

  // set the socket to non-blocking
  multilog(log, LOG_INFO, "start_function: setting non_block\n");
  sock_nonblock(fd);

  // clear any packets buffered by the kernel
  multilog(log, LOG_INFO, "start_function: clearing packets at socket\n");
  size_t cleared = dada_sock_clear_buffered_packets(fd, pkt_size);

  // allocate some nicely aligned memory
  void * buffer;
  posix_memalign (&buffer, 512, pkt_size);

  void * dst;
  posix_memalign (&dst, 512, pkt_size);

  unsigned char * arr = 0;
  unsigned have_packet = 0;
  unsigned got = 0;
  uint64_t tmp = 0;
  uint64_t seq_no = 0;
  uint64_t prev_seq_no = 0;
  unsigned i=0;

  while (!quit_threads) 
  {
    have_packet = 0;

    // incredibly tight loop to try and get a packet
    while (!have_packet && !quit_threads)
    {
      // receive 1 packet into the socket buffer
      got = recvfrom (fd, buffer, pkt_size, 0, NULL, NULL);

      if (got == pkt_size)
      {
        have_packet = 1;
      }
      else if (got == -1)
      {
        udptest.n_sleeps++;
      }
      else // we received a packet of the WRONG size, ignore it
      {
        multilog (log, LOG_ERR, "receive_obs: received %d bytes, expected %d\n", got, pkt_size);
      }
    }

    // we have a valid packet within the timeout
    if (have_packet)
    {
      // decode the packet sequence number
      arr = (unsigned char *)buffer;
      seq_no = UINT64_C (0);
      for (i = 0; i < 8; i++ )
      {
        tmp = UINT64_C (0);
        tmp = arr[8 - i - 1];
        seq_no |= (tmp << ((i & 7) << 3));

      }

      if (prev_seq_no)
      {
        if (seq_no == prev_seq_no + 1)
        {
          bytes->received += pkt_size;
          packets->received += 1;
          memcpy (dst, buffer, pkt_size);
        } 
        else if (seq_no <= prev_seq_no)
        {
          multilog (log, LOG_ERR, "main: impossible! seq=%"PRIu64", prev=%"PRIu64"\n", seq_no, prev_seq_no);
        }
        else
        {
          uint64_t diff = seq_no - prev_seq_no;
	  if (verbose > 2)
	          multilog(log, LOG_ERR, "dropped %"PRIu64" pkts seq=%"PRIu64", prev=%"PRIu64"\n", diff, seq_no, prev_seq_no);
          packets->dropped += diff;
          bytes->dropped += diff * (pkt_size);
        }
      }
      prev_seq_no = seq_no;
    }
  }

  if (verbose)
    multilog(log, LOG_INFO, "joining stats_thread\n");
  void * result;
  pthread_join (stats_thread_id, &result);

  close(fd);

  /* clean up memory */
  free(buffer);
  free(dst);


  return EXIT_SUCCESS;

}
コード例 #9
0
ファイル: sock_serv.c プロジェクト: ilart/Yarrow
int main (int argc, char **argv) 
{
	int server_fd, fifo_fd, res, i, nelems;
	char buf[LINE_MAX], packet[PACKET_SIZE];
	
	entropy_src[0].id = 0;
	entropy_src[0].path = "/dev/random";
	entropy_src[0].estimate = 0.4;
	entropy_src[0].len = 100;

	entropy_src[0].id = 1;
	entropy_src[0].path = "/dev/urandom";
	entropy_src[0].estimate = 0.5;
	entropy_src[0].len = 120;

	entropy_src[0].id = 2;
	entropy_src[0].path = NULL;
	entropy_src[0].estimate = 0.8;
	entropy_src[0].len = 120;

	mkfifo(FIFO_PATH, 0777);
	fifo_fd = open(FIFO_PATH, O_NONBLOCK);
	if (fifo_fd == -1)
		printf("open returned %d: %s\n",
			fifo_fd, strerror(fifo_fd));

	nsources = 2; // this value will be taken from entropy_pool.nsources

	// create children for accumulate entropy from i source
	// All information about source will be obtained from config file.
	for (i = 0; i < nsources; i++) {
		if ((pid = fork()) < 0) {
			printf("Fork returned %d: %s\n",
			       pid, strerror(pid));
			exit(1);
		} else if (pid == 0) {
			accumulate_samples(i); 
	}
		
	server_fd = sock_unix_listen("/var/run/yarrow.socket");
	if (server_fd <= 0) {
		perror("Sock unix listen");
		exit(1);
	}

	printf("server_fd %d\n", server_fd);
	sock_nonblock(server_fd);

	poll_fd = calloc(2, sizeof(struct pollfd));
	if (poll_fd == NULL) {
		perror("Calloc returned NULL.");
		exit(1);
	}

	poll_fd[0].fd = server_fd;
	poll_fd[0].events = POLLIN;
	poll_fd[1].fd = fifo_fd;
	poll_fd[1].events = (POLLIN|POLLPRI);

	peer_ctx = calloc(2, sizeof(struct peer));
	if (peer_ctx == NULL) {
		perror("Calloc returned NULL");
		exit(1);
	}
	
	peer_ctx[0].sfd = server_fd;
	peer_ctx[0].bufused = 0;
	peer_ctx[1].sfd = fifo_fd;
	peer_ctx[1].bufused = 0;

	nelems = 2;
	i = 0;
	
	while (1) {
		res = poll(poll_fd, nelems, -1);
		if (res > 0) {
			if (poll_fd[0].revents & POLLIN) {
				accept_connect(&nelems);
			} else if (poll_fd[1].revents & POLLIN) {
				accumulate_entropy(packet);	
			}
 		
			process_events(nelems); 
		} else if (res < 0 && errno != EINTR) {
			printf("poll returned %d: %s\n",
			      res, strerror(errno));
			break;
		} 
	}	
	
	close(server_fd);
	unlink("/var/run/yarrow.socket");
return 0;
}