Esempio n. 1
0
/* Name: insert_socket
 * Notes: See the insert_[socket|core|thread] description above
 */
struct cpu_socket *insert_socket(struct cpu_socket *s, struct rawsyscpu *r)
{
   struct cpu_socket *slist;  /* for walking through list */
   struct cpu_socket *slast;  /* Ordered list insert (last item) */
   struct cpu_socket *thiss;  /* The item we are working with */

   /* If the linked list is empty, then make it the new list */
   if ( NULL == s )
   {
      if ( NULL == (thiss = new_socket(r->physical_package_id)) )
         return(NULL);

      return(thiss);
   }

   /* See if the value is in the list now. This is:
      1. Likely to be a hit (it is likely in the list)
      2. A very in-expensive lookup
   */
   slist = s;
   while ( slist )
   {
      if ( slist->id == r->physical_package_id )
      {
         return(s); /* got it, return list unmodified */
      }
      slist = slist->next;
   }

   if ( NULL == (thiss = new_socket(r->physical_package_id)) )
      return(NULL);

   /*** ordered insert ***/

   /* Insert at top */
   if ( s->id > thiss->id )
   {
      thiss->next = s;
      return(thiss);
   }

   /* insert in middle */
   slist = s->next;
   slast = s;
   while (slist)
   {
      if ( slist->id > thiss->id )
      {
         thiss->next = slast->next;
         slast->next = thiss;
         return(s);
      }
      slast = slist;
      slist = slist->next;
   }

   /* if we got here append at end */
   slast->next = thiss;
   return(s);
}
Esempio n. 2
0
 static void yield_accept(boost::asio::yield_context yield,
                          boost::system::error_code &ec,
                          boost::shared_ptr<boost::asio::ip::tcp::acceptor> ptr_)
 {
     auto s = new_socket();
     ptr_->async_accept(*s, yield[ec]);
 }
Esempio n. 3
0
void new_connection(TCPsocket sock) {
   TCPsocket tmp;
   struct socket_node *socket;
   IPaddress *ip;
 
/* accept the connection temporarily */
   tmp = SDLNet_TCP_Accept(sock);
   if (!tmp)
      do_error(SDLNet_GetError());

/* are we full or game already started? */
   if (get_active_players() + 1 > NUM_PLAYERS || current_turn)
      SDLNet_TCP_Close(tmp);
   else {
   /* nope! */
      socket = new_socket(SOCKET_CLIENT);
      socket->sock = tmp;
      if (SDLNet_TCP_AddSocket(sockset, tmp) < 0)
         do_error(SDLNet_GetError());

      ip = SDLNet_TCP_GetPeerAddress(tmp);
      if (!ip)
         do_error(SDLNet_GetError());
      if (SDLNet_ResolveIP(ip))
         strcpy(socket->host, SDLNet_ResolveIP(ip));
      else
         sprintf(socket->host, "Unknown IP");

      join_player(socket);	/*	add player to game	*/
   }
}
Esempio n. 4
0
int server_socket(int port) {
    int sfd;
    struct linger ling = {0, 0};
    struct sockaddr_in addr;
    int flags =1;

    if ((sfd = new_socket()) == -1) {
        return -1;
    }

    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags));
    setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags));
    setsockopt(sfd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr = settings.interface;
    if (bind(sfd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
        perror("bind()");
        close(sfd);
        return -1;
    }
    if (listen(sfd, 1024) == -1) {
        perror("listen()");
        close(sfd);
        return -1;
    }
    return sfd;
}
Esempio n. 5
0
int set_flags(char *dev, u_int flags, u_int mask)
{
	struct ifreq ifr;
	int s;

	strcpy(ifr.ifr_name, dev);
	if((s=new_socket(AF_INET)) < 0) {
		error("Error while setting \"%s\" flags: Cannot open socket", dev);
		return -1;
	}

	if(ioctl(s, SIOCGIFFLAGS, &ifr)) {
		error("Error while setting \"%s\" flags: %s", dev, strerror(errno));
		close(s);
		return -1;
	}

	ifr.ifr_flags &= ~mask;
	ifr.ifr_flags |= mask&flags;
	if(ioctl(s, SIOCSIFFLAGS, &ifr)) {
		error("Error while setting \"%s\" flags: %s", dev, strerror(errno));
		close(s);
		return -1;
	}
	close(s);
	return 0;
}
  asio::error_code accept(implementation_type& impl,
      Socket& peer, endpoint_type* peer_endpoint, asio::error_code& ec)
  {
    // We cannot accept a socket that is already open.
    if (peer.is_open())
    {
      ec = asio::error::already_open;
      return ec;
    }

    std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0;
    socket_holder new_socket(socket_ops::sync_accept(impl.socket_,
          impl.state_, peer_endpoint ? peer_endpoint->data() : 0,
          peer_endpoint ? &addr_len : 0, ec));

    // On success, assign new connection to peer socket object.
    if (new_socket.get() != invalid_socket)
    {
      if (peer_endpoint)
        peer_endpoint->resize(addr_len);
      if (!peer.assign(impl.protocol_, new_socket.get(), ec))
        new_socket.release();
    }

    return ec;
  }
Esempio n. 7
0
/*
 * set_dev_ip: Assign the given `ip' to the interface named `dev'
 * On success 0 is returned, -1 otherwise.
 */
int set_dev_ip(inet_prefix ip, char *dev)
{
	int s=-1;

	if(ip.family == AF_INET) {
		struct ifreq req;

		if((s=new_socket(AF_INET)) < 0) {
			error("Error while setting \"%s\" ip: Cannot open socket", dev);
			return -1;
		}

		strncpy(req.ifr_name, dev, IFNAMSIZ);
		inet_to_sockaddr(&ip, 0, &req.ifr_addr, 0);

		if(ioctl(s, SIOCSIFADDR, &req)) {
			error("Error while setting \"%s\" ip: %s", dev, strerror(errno));
			close(s);
			return -1;
		}
	} else if(ip.family == AF_INET6) {
		struct in6_ifreq req6;
		struct sockaddr_in6 sin6;
		struct sockaddr *sa=(struct sockaddr *)&sin6;

		if((s=new_socket(AF_INET6)) < 0) {
			error("Error while setting \"%s\" ip: Cannot open socket", dev);
			return -1;
		}
		
		req6.ifr6_ifindex=ll_name_to_index(dev);
		req6.ifr6_prefixlen=0;
		inet_to_sockaddr(&ip, 0, sa, 0);
		memcpy(&req6.ifr6_addr, sin6.sin6_addr.s6_addr32, ip.len);

		if(ioctl(s, SIOCSIFADDR, &req6)) {
			error("Error while setting \"%s\" ip: %s", dev, strerror(errno));
			close(s);
			return -1;
		}

	}

	close(s);
	return 0;
}
Esempio n. 8
0
int main(int argc, char * argv[])
{
	if(argc < 2)
	{
		cout<<"please enter a file name\n";
		exit(-1);
	}
	char * filename = argv[1];
	FILE * comfile = fopen(filename,"r");
	if(!comfile)
	{
		perror("failed to open command file");
		exit(-1);
	}

	map<int,int> ports = parseMembers();
	map<int,int> nodeToSocket;
	
	map<int, int>::const_iterator endports = ports.end();
	for(map<int, int>::const_iterator it = ports.begin(); it != endports; it++) 
	{
		nodeToSocket[it->first] = new_socket();
		connect(nodeToSocket[it->first],it->second);
	}
	ports.clear();
	s_send(nodeToSocket[0],"-1");
	
	char com[BUFFER_SIZE];
	char tmp[BUFFER_SIZE];
	while(fgets(com, BUFFER_SIZE,comfile) != NULL){
		strcpy(tmp,com);
		unsigned int sleeptime = atoi(strtok(com,"\n:"));
		sleeptime = sleeptime * 1000;
		usleep(sleeptime);
		int nodeID = atoi(strtok(NULL,"\n:"));

		//locate the 2nd colon for commandID options
		int i,j;
		for(i = 0,j = 0; j < 2 && i < BUFFER_SIZE; i++){
			if(tmp[i] == ':')
				j++;
		}

		char * comAndOpt = tmp + i;
		char moretmp[BUFFER_SIZE];
		strcpy(moretmp,"0:C:");
		strcat(moretmp,strtok(comAndOpt,"\n")); //strtok strips new line from command
		//send comAndOpt to nodeID
		printf("sending %s to %d\n",moretmp,nodeID);
		s_send(nodeToSocket[nodeID],moretmp);
	}
	return 0;
}
Esempio n. 9
0
// int main(int argc, char *argv[]) {
int main(void) {
  const char *title = "Small Size League Simulator by RoboIME";
  puts(title);

  {
    // Handle SIGINT (Ctrl+C)
    struct sigaction sa;
    sa.sa_handler = sigint_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGINT, &sa, NULL);
  }

  // Create a world
  struct World *world = new_world(&FIELD_2015);

  // Add some robots
  for (int i = 0; i < 6; i++) {
    world_add_robot(world, i, TEAM_BLUE);
    world_add_robot(world, i, TEAM_YELLOW);
  }

  // Create and bind socket
  struct Socket *socket = new_socket(11002, "224.5.23.2");
  socket_sender_bind(socket);

#define BUFFER_SIZE 10240
  char buffer[BUFFER_SIZE];
  int send_size;
  int send_geometry = 0;

  while (keep_going) {
    world_step(world, 1.0 / 60, 10, 1.0 / 600);

    // TODO: log errors
    send_size = serialize_world(world, buffer, BUFFER_SIZE);
    if (send_size > 0)
      socket_send(socket, buffer, send_size);

    if (send_geometry++ % 120 == 0) {
      send_size = serialize_field(world_get_field(world), buffer, BUFFER_SIZE);
      if (send_size > 0)
        socket_send(socket, buffer, send_size);
    }

    // TODO: realtime update
    // sleep for 16ms, prevents going too fast and intensive
    nanosleep(&(struct timespec){.tv_nsec=16000000}, NULL);
  }
Esempio n. 10
0
int socket_server::bind_socket(struct request_bind * request, struct socket_message * result)
{
    int id = request->id;
    result->id = id;
    result->opaque = request->opaque;
    result->ud = 0;
    struct socket * s = new_socket(id, request->fd, PROTOCOL_TCP, request->opaque, true);
    if (s == nullptr) {
        result->data = nullptr;
        return SOCKET_ERROR;
    }
    nonblocking(request->fd);
    s->type = SOCKET_TYPE_BIND;
    result->data = (char *)"binding";
    return SOCKET_OPEN;
}
Esempio n. 11
0
static int maybe_new_socket(uv_tcp_t* handle, int domain, unsigned long flags) {
  struct sockaddr_storage saddr;
  socklen_t slen;

  if (domain == AF_UNSPEC) {
    handle->flags |= flags;
    return 0;
  }

  if (uv__stream_fd(handle) != -1) {

    if (flags & UV_HANDLE_BOUND) {

      if (handle->flags & UV_HANDLE_BOUND) {
        /* It is already bound to a port. */
        handle->flags |= flags;
        return 0;
      }
      
      /* Query to see if tcp socket is bound. */
      slen = sizeof(saddr);
      memset(&saddr, 0, sizeof(saddr));
      if (getsockname(uv__stream_fd(handle), (struct sockaddr*) &saddr, &slen))
        return -errno;

      if ((saddr.ss_family == AF_INET6 &&
          ((struct sockaddr_in6*) &saddr)->sin6_port != 0) ||
          (saddr.ss_family == AF_INET &&
          ((struct sockaddr_in*) &saddr)->sin_port != 0)) {
        /* Handle is already bound to a port. */
        handle->flags |= flags;
        return 0;
      }

      /* Bind to arbitrary port */
      if (bind(uv__stream_fd(handle), (struct sockaddr*) &saddr, slen))
        return -errno;
    }

    handle->flags |= flags;
    return 0;
  }

  return new_socket(handle, domain, flags);
}
Esempio n. 12
0
int main(int argc, char *argv[]) {
	int sfd;

	sfd = create_client_socket("127.0.0.1", "12345");

	ClientSocket new_socket(sfd);

	if (argc > 1) {
		struct MSG_IdentifyConnection identify;
		identify.type = MSG_IDENTIFY_CONNECTION;
		identify.len = strlen(argv[1]) + sizeof(identify);
		new_socket.txfifo_in( (unsigned char*)	&identify, sizeof(identify));
		new_socket.txfifo_in( (unsigned char*)argv[1],   strlen(argv[1]));
	}

	eventloop();
	
	exit(EXIT_SUCCESS);
}
Esempio n. 13
0
/*
 * get_dev_ip: fetches the ip currently assigned to the interface named `dev'
 * and stores it to `ip'.
 * On success 0 is returned, -1 otherwise.
 */
int get_dev_ip(inet_prefix *ip, int family, char *dev)
{
	int s=-1;
	int ret=0;

	setzero(ip, sizeof(inet_prefix));

	if((s=new_socket(family)) < 0) {
		error("Error while setting \"%s\" ip: Cannot open socket", dev);
		return -1;
	}

	if(family == AF_INET) {
		struct ifreq req;

		strncpy(req.ifr_name, dev, IFNAMSIZ);
		req.ifr_addr.sa_family = family;
		
		if(ioctl(s, SIOCGIFADDR, &req))
			ERROR_FINISH(ret, -1, finish);

		sockaddr_to_inet(&req.ifr_addr, ip, 0);
	} else if(family == AF_INET6) {
		struct in6_ifreq req6;

		/*
		 * XXX: NOT TESTED
		 */

		req6.ifr6_ifindex=ll_name_to_index(dev);
		req6.ifr6_prefixlen=0;

		if(ioctl(s, SIOCGIFADDR, &req6))
			ERROR_FINISH(ret, -1, finish);

		inet_setip(ip, (u_int *)&req6.ifr6_addr, family);
	}

finish:
	if(s != -1)
		close(s);
	return ret;
}
Esempio n. 14
0
int socket_server::listen_socket(struct request_listen * request, struct socket_message * result)
{
    int id = request->id;
    int listen_fd = request->fd;
    struct socket * s = new_socket(id, listen_fd, PROTOCOL_TCP, request->opaque, false);
    if (s == nullptr) {
        goto _failed;
    }
    s->type = SOCKET_TYPE_PLISTEN;
    return -1;
_failed:
    close(listen_fd);
    result->opaque = request->opaque;
    result->id = id;
    result->ud = 0;
    result->data = nullptr;
    slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;
     
    return SOCKET_ERROR;
}
Esempio n. 15
0
File: server.c Progetto: hyper/rq
static void server_listen_ai(server_t *server, struct addrinfo *ai)
{
  struct linger ling = {0, 0};
	int flags;

	assert(server);
	assert(ai);

	assert(server->handle == INVALID_HANDLE);
	assert(server->event == NULL);
	
	// create the new socket.  if that fails, free the memory we've already allocated, and return NULL.
	server->handle = new_socket(ai);
	assert(server->handle != INVALID_HANDLE);

	flags = 1;
	setsockopt(server->handle, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
	setsockopt(server->handle, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
	setsockopt(server->handle, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));

	if (bind(server->handle, ai->ai_addr, ai->ai_addrlen) == -1) {
		close(server->handle);
		server->handle = INVALID_HANDLE;
	} else {
		if (listen(server->handle, 1024) == -1) {
			perror("listen()");
			close(server->handle);
			server->handle = INVALID_HANDLE;
		}
		else {
			// Now that we are actually listening on the socket, we need to set the event.
			assert(server->handle >= 0);
			assert(server->event == NULL);
			assert(server->sysdata->evbase);
			server->event = event_new(server->sysdata->evbase, server->handle, EV_READ | EV_PERSIST, server_event_handler, (void *)server);
			event_add(server->event, NULL);
		}
	}

	assert((server->handle == INVALID_HANDLE && server->event == NULL) || (server->handle >= 0 && server->event));
}
Esempio n. 16
0
int	main(int ac, const char **av)
{
  int	r;
  char	buff[4242];
  const t_socket	*socket;

  if (ac != 2)
    return puts("Not enought arg.");
  socket = new_socket(atoi(av[1]), "localhost", SOCK_CLIENT);
  if (socket && socket->is_valid(deconst_cast(socket)))
    {
      socket->write(socket, "voi\n");
      bzero(buff, 4242);
      while ((r = read(0, buff, 4242)) > 0)
	{
	  socket->write(socket, buff);
	  bzero(buff, 4242);
	}
    }
  return 0;
}
Esempio n. 17
0
static int server_socket(const int port, const bool is_udp) {
    int sfd;
    struct linger ling = {0, 0};
    struct sockaddr_in addr;
    int flags =1;

    if ((sfd = new_socket(is_udp)) == -1) {
        return -1;
    }

    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
    if (is_udp) {
        ;//maximize_sndbuf(sfd);
    } else {
        setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
        setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
        setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
    }

    /*
     * the memset call clears nonstandard fields in some impementations
     * that otherwise mess things up.
     */
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr = settings.interf;
    if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
        perror("bind()");
        close(sfd);
        return -1;
    }
    if (!is_udp && listen(sfd, 1024) == -1) {
        perror("listen()");
        close(sfd);
        return -1;
    }
    return sfd;
}
Esempio n. 18
0
void run_server()
{
    zctx_t *ctx;
    void *socket;
    int i, n, nclient;
    char buf[256];
    char data[256];
    char client[256];

    ctx = new_context();
    socket = new_socket(ctx, ZMQ_ROUTER);
//  socket = new_socket(ctx, ZMQ_REP);
    assert_result(socket_bind(socket, host), 0);
//  assert_result(zmq_bind(socket, host), 0);

    log_printf(0, "my identity=%s\n", zsocket_identity(socket));

    i = 0;
    for (;;) {
        log_printf(0, "Waiting %d\n", i);
        nclient = zmq_recv(socket, client, sizeof(client), 0);
        client[nclient] = 0;
        log_printf(0, "From %s [%d]\n", client, nclient);
        n = zmq_recv(socket, buf, sizeof(buf), 0);
        buf[n] = 0;
        if (n != 0) log_printf(0, "Missing EMPTY frame! buf=%s\n", buf);
        n = zmq_recv(socket, buf, sizeof(buf), 0);
        buf[n] = 0;
        log_printf(0, "Got %s\n", buf);

        zmq_send(socket, client, nclient, ZMQ_SNDMORE);
        zmq_send(socket, NULL, 0, ZMQ_SNDMORE);
        snprintf(data, sizeof(buf), "(%s) World %d", buf, i);
        zmq_send(socket, data, strlen(data)+1, 0);
        i++;
    }

    destroy_context(ctx);
}
Esempio n. 19
0
int server_socket(int port) {
    int sfd;
    struct linger ling = {0, 0};
    struct sockaddr_in addr;
    int flags =1;

    if ((sfd = new_socket()) == -1) {
        return -1;
    }

    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags));
    setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags));
    setsockopt(sfd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
#if !defined(TCP_NOPUSH)
    setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags));
#endif

    /*
     * the memset call clears nonstandard fields in some impementations
     * that otherwise mess things up.
     */
    memset(&addr, 0, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr = settings.interface;
    if (bind(sfd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
        perror("bind()");
        close(sfd);
        return -1;
    }
    if (listen(sfd, 1024) == -1) {
        perror("listen()");
        close(sfd);
        return -1;
    }
    return sfd;
}
Esempio n. 20
0
/* starts server if address is NULL */
void server_connect(char *address, int port) {
   IPaddress ip;
   TCPsocket sock;
   struct socket_node *socket;

   if (port < 0 || port > 65535)
      telegram("\nIllegal port.\n");
   else  if (SDLNet_ResolveHost(&ip, address, port) < 0) {
      if (!address)
         do_error(SDLNet_GetError());
      else
         telegram("\nFailed resolving host.\n");
   }
   else {
      sock = SDLNet_TCP_Open(&ip);
      if (!sock) {
         if (!address)
            do_error(SDLNet_GetError());
         else
            telegram("\nFailed connecting to the\nserver.\n");
      }
      else {
         socket = new_socket(SOCKET_SERVER);
         socket->sock = sock;
         if (SDLNet_TCP_AddSocket(sockset, socket->sock) < 0)
            do_error(SDLNet_GetError());

         online = 1;	/*	we are online!	*/
         if (!address) {
            server = 1;		/*	and we are the server	*/
            telegram("\nServer opened on port\n%d. Waiting for other\nplayers.\n", port);
         }
         else
            telegram("\nConnected to server.\n");
      }
   }
}
Esempio n. 21
0
int socket_server::report_accept(struct socket *s, struct socket_message *result)
{
    union sockaddr_all u;
    socklen_t len = sizeof(u);
    int client_fd = accept(s->fd, &u.s, &len);
    if (client_fd < 0) {
        return 0;
    }
    int id = reserve_id();
    if (id < 0) {
        close(client_fd);
        return 0;
    }
    keepalive(client_fd);
    nonblocking(client_fd);

    struct socket *ns = new_socket(id, client_fd, PROTOCOL_TCP, s->opaque, false);
    if (ns == nullptr) {
        close(client_fd);
        return 0;
    }
    ns->type = SOCKET_TYPE_PACCEPT;
    result->opaque = s->opaque;
    result->id = s->id;
    result->ud = id;
    result->data = nullptr;

    void * sin_addr = (u.s.sa_family == AF_INET) ? (void *)&u.v4.sin_addr : (void *)&u.v6.sin6_addr;
    int sin_port = ntohs((u.s.sa_family == AF_INET) ? u.v4.sin_port : u.v6.sin6_port);
    char tmp[INET6_ADDRSTRLEN];
    if (inet_ntop(u.s.sa_family, sin_addr, tmp, sizeof(tmp))) {
        snprintf(buffer, sizeof(buffer), "%s:%d", tmp, sin_port);
        result->data = buffer;
    }

    return 1;
}
Esempio n. 22
0
  // Accept a new connection.
  typename Protocol::socket accept(implementation_type& impl,
      io_context* peer_io_context, endpoint_type* peer_endpoint,
      asio::error_code& ec)
  {
    typename Protocol::socket peer(
        peer_io_context ? *peer_io_context : io_context_);

    std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0;
    socket_holder new_socket(socket_ops::sync_accept(impl.socket_,
          impl.state_, peer_endpoint ? peer_endpoint->data() : 0,
          peer_endpoint ? &addr_len : 0, ec));

    // On success, assign new connection to peer socket object.
    if (new_socket.get() != invalid_socket)
    {
      if (peer_endpoint)
        peer_endpoint->resize(addr_len);
      peer.assign(impl.protocol_, new_socket.get(), ec);
      if (!ec)
        new_socket.release();
    }

    return peer;
  }
Esempio n. 23
0
void run_client()
{
    zctx_t *ctx;
    void *socket;
    int i, n;
    char buf[256];
    char *me;

    ctx = new_context();
    socket = new_socket(ctx, ZMQ_REQ);
    socket_connect(socket, host);
//  zmq_connect(socket, host);

    me = zsocket_identity(socket);
    log_printf(0, "my identity=%s\n", me);
    i = 0;
    for (;;) {
        log_printf(0, "Sending %d\n", i);
//     zmq_send(socket, host, strlen(host), ZMQ_SNDMORE);
//     zmq_send(socket, me, strlen(me), ZMQ_SNDMORE);

        snprintf(buf, sizeof(buf), "Hello %d", i);
        zmq_send(socket, buf, strlen(buf)+1, 0);

//     zmq_recv(socket, buf, sizeof(buf), 0);
//     log_printf(0, "From %s\n", buf);
        n = zmq_recv(socket, buf, sizeof(buf), 0);
        buf[n] = 0;
        log_printf(0, "Got %s\n", buf);

        sleep(1);
        i++;
    }

    destroy_context(ctx);
}
Esempio n. 24
0
static int server_socket(const char *interface,
                         int port,
                         enum network_transport transport,
                         FILE *portnumber_file){

    /*
        该函数主要作用:
        1.监听端口,注册监听端口事件.
        2.一旦有端口有数据,建立连接,将连接放到连接池中,conn_new为每一个连接注册时间监听
        3.通知线程有连接需要处理
    */

    int sfd;
    struct linger ling = {0, 0};
    struct addrinfo *ai;
    struct addrinfo *next;
    struct addrinfo hints = { .ai_flags = AI_PASSIVE,
                              .ai_family = AF_UNSPEC };
    char port_buf[NI_MAXSERV];
    int error;
    int success = 0;
    int flags =1;

    hints.ai_socktype = SOCK_STREAM;

    if (port == -1) {
        port = 0;
    }
    snprintf(port_buf, sizeof(port_buf), "%d", port);
    error= getaddrinfo(interface, port_buf, &hints, &ai);
    if (error != 0) {
        if (error != EAI_SYSTEM)
          fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
        else
          perror("getaddrinfo()");
        return 1;
    }

    for (next= ai; next; next= next->ai_next) {
        conn *listen_conn_add;
        if ((sfd = new_socket(next)) == -1) {
            /* getaddrinfo can return "junk" addresses,
             * we make sure at least one works before erroring.
             */
            if (errno == EMFILE) {
                /* ...unless we're out of fds */
                perror("server_socket");
                exit(EX_OSERR);
            }
            continue;
        }

        setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
        
        error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
        if (error != 0)
            perror("setsockopt");

        error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
        if (error != 0)
            perror("setsockopt");

        error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
        if (error != 0)
            perror("setsockopt");


        if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
            if (errno != EADDRINUSE) {
                perror("bind()");
                close(sfd);
                freeaddrinfo(ai);
                return 1;
            }
            close(sfd);
            continue;
        } else {
            success++;
            if (!IS_UDP(transport) && listen(sfd, 1024) == -1) {
                perror("listen()");
                close(sfd);
                freeaddrinfo(ai);
                return 1;
            }
            if (portnumber_file != NULL &&
                (next->ai_addr->sa_family == AF_INET ||
                 next->ai_addr->sa_family == AF_INET6)) {
                union {
                    struct sockaddr_in in;
                    struct sockaddr_in6 in6;
                } my_sockaddr;
                socklen_t len = sizeof(my_sockaddr);
                if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) {
                    if (next->ai_addr->sa_family == AF_INET) {
                        fprintf(portnumber_file, "%s INET: %u\n",
                                IS_UDP(transport) ? "UDP" : "TCP",
                                ntohs(my_sockaddr.in.sin_port));
                    } else {
                        fprintf(portnumber_file, "%s INET6: %u\n",
                                IS_UDP(transport) ? "UDP" : "TCP",
                                ntohs(my_sockaddr.in6.sin6_port));
                    }
                }
            }
        }


        if (!(listen_conn_add = conn_new(sfd, conn_listening,
                                         EV_READ | EV_PERSIST, 1,
                                         transport, main_base))) {
            fprintf(stderr, "failed to create listening connection\n");
            exit(EXIT_FAILURE);
        }
        listen_conn_add->next = listen_conn;
        listen_conn = listen_conn_add;
    }

    freeaddrinfo(ai);

    /* Return zero iff we detected no errors in starting up connections */
    return success == 0;


}
Esempio n. 25
0
/* ---- example xml handler */
void* handler (SimpleXmlParser parser, SimpleXmlEvent event, 
	const char* szName, const char* szAttribute, const char* szValue)
{
	static int nDepth= 0;
	char *tmp;
	char szHandlerName[32];
	char szHandlerAttribute[32];
	char *szHandlerValue;
	//struct socket_data *news;
	//struct core_data *newc;
	//struct thread_data *newt;
	int last_cid=0;

	szHandlerValue=malloc(32);
	memset(szHandlerValue,0,32);

	if (szName != NULL) {
		trim(szName, szHandlerName);
	}
	if (szAttribute != NULL) {
		trim(szAttribute, szHandlerAttribute);
	}
	if (szValue != NULL) {
		trim(szValue, szHandlerValue);
	}

	if (event == ADD_SUBTAG) {
		fprintf(stderr,"depth: %d, val: %s\n",nDepth,szHandlerName);
		fprintf(stderr, "%6li: %s add subtag (%s)\n", 
			simpleXmlGetLineNumber(parser), getIndent(nDepth), szHandlerName);
		nDepth++;
	} else if (event == ADD_ATTRIBUTE) {
//		printf("attribute tag:%s %s=%s\n",szHandlerName, szHandlerAttribute, szHandlerValue);
		fprintf(stderr, "%6li: %s ///add attribute to tag %s ([%s]=[%s])\n", 
			simpleXmlGetLineNumber(parser), getIndent(nDepth), szHandlerName, szHandlerAttribute, szHandlerValue);

		if ( (!strcmp(szHandlerAttribute,"cache-level")) && (!strcmp(szHandlerValue,"3")) ) {
			//attribute cache-level=3 detected: new L3 domain
			fprintf(stderr,"\n* NEW SOCKET *\n");
			new_socket(last_sid,last_sid);
			push_socket_id(last_sid);
			last_sid++;
			level=3;
		}

		if ( (!strcmp(szHandlerAttribute,"name")) && (!strcmp(szHandlerValue,"SMT")) ) {
			//attribute cache-level=2 detected: new L2 domain
			fprintf(stderr,"\n       * NEW CORE, Sock %d *     \n", last_sid - 1);
			//uncomment for noSMP:
			//level=10;

			//ucomment for SMP:
			last_cid=pop_core_id();
			new_core(0,last_cid,last_sid - 1);
		} else if ( (!strcmp(szHandlerAttribute,"name")) && (!strcmp(szHandlerValue,"THREAD")) ) {
			//attribute cache-level=2 detected: new L2 domain
			fprintf(stderr,"\n* NEW THREAD, Sock %d *\n", last_sid - 1);
			last_cid=pop_core_id();
			new_thread(0,last_cid,last_sid - 1);
		}

		if ( (!strcmp(szHandlerAttribute,"level")) && (!strcmp(szHandlerValue,"3")) ) {
			//no cpu count="2"/SMT/THREAD Routing!
			level=300;
		} else if ( (!strcmp(szHandlerAttribute,"level")) && (!strcmp(szHandlerValue,"2")) ) {
			//attribute cache-level=2 detected: new L2 domain
			fprintf(stderr,"\n* !NEW LOGICAL CORE %d!, Sock: %d*\n", last_cid,last_sid - 1);
			//We have "cpu count="2" and SMT/THREAD flag name
			level=200;
		}

	} else if (event == ADD_CONTENT) {
		fprintf(stderr,"depth: %d, LEVEL %d, context for:[%s] [%s]\n",nDepth,level,szHandlerName, szHandlerValue);

		if (level==200) {
			if (!strcmp(szHandlerName,"cpu")) {
				fprintf(stderr,"  !ROUTE LEVEL 10: Cores ID processed: %s, SOCKET: %d\n",szHandlerValue, last_sid - 1 );
				while ((tmp = strsep(&szHandlerValue, ",")) != NULL) {
					if (tmp[0] == '\0')
						break; /* XXX */
					trim_spaces(tmp);
// comment for no SMP?
					push_core_id(atoi(tmp));
					fprintf(stderr,"\n\n\nHA: [%d]\n\n\n",atoi(tmp));
// uncomment for no SMP:
//					last_cid=pop_core_id();
//					new_core(0,atoi(tmp),last_sid - 1);
				}
			// drop level
//			level=9;
			}
		} else if (level==300) {
		//no cpu count="2"/SMT/THREAD Routing!
			if (!strcmp(szHandlerName,"cpu")) {
				fprintf(stderr,"  !ROUTE LEVEL 10: Cores ID processed: %s, SOCKET: %d\n",szHandlerValue, last_sid - 1 );
				while ((tmp = strsep(&szHandlerValue, ",")) != NULL) {
					if (tmp[0] == '\0')
						break; /* XXX */
					trim_spaces(tmp);
// comment for no SMP?
					push_core_id(atoi(tmp));
					fprintf(stderr,"\n\n\nHA: [%d]\n\n\n",atoi(tmp));
// uncomment for no SMP:
					last_cid=pop_core_id();
					new_core(0,atoi(tmp),last_sid - 1);
				}
			// drop level
//			level=9;
			}
		}

		fprintf(stderr, "%6li: %s add content to tag %s (%s)\n", 
			simpleXmlGetLineNumber(parser), getIndent(nDepth), szHandlerName, szHandlerValue);
	} else if (event == FINISH_ATTRIBUTES) {
		fprintf(stderr,"finish for:%s\n",szHandlerName);
		fprintf(stderr, "%6li: %s finish attributes (%s)\n", 
			simpleXmlGetLineNumber(parser), getIndent(nDepth), szHandlerName);
	} else if (event == FINISH_TAG) {
		fprintf(stderr,"finish for:%s\n",szHandlerName);
		fprintf(stderr, "%6li: %s finish tag (%s)\n", 
			simpleXmlGetLineNumber(parser), getIndent(nDepth), szHandlerName);
		nDepth--;
		if (level==10) {
			if (!strcmp(szHandlerName,"cpu"))
				level=0;
		}
	}

	//list_sockets();
	return handler;
}
Esempio n. 26
0
 net_base(boost::shared_ptr<boost::asio::io_service> net_io)
     :socket_(new_socket(net_io))
 {
 };
Esempio n. 27
0
static int server_socket(const int port, const bool is_udp)
{
	int sfd;
	struct linger ling =
	{ 0, 0 };
	struct addrinfo *ai;
	struct addrinfo *next;
	struct addrinfo hints;
	char port_buf[NI_MAXSERV];
	int error;
	int success = 0;

	int flags = 1;

	/*
	 * the memset call clears nonstandard fields in some impementations
	 * that otherwise mess things up.
	 */
	memset(&hints, 0, sizeof(hints));
	hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
	if (is_udp)
	{
		hints.ai_protocol = IPPROTO_UDP;
		hints.ai_socktype = SOCK_DGRAM;
		hints.ai_family = AF_INET; /* This left here because of issues with OSX 10.5 */
	}
	else
	{
		hints.ai_family = AF_UNSPEC;
		hints.ai_protocol = IPPROTO_TCP;
		hints.ai_socktype = SOCK_STREAM;
	}

	snprintf(port_buf, NI_MAXSERV, "%d", port);
	error = getaddrinfo(settings.inter, port_buf, &hints, &ai);
	if (error != 0)
	{
		if (error != EAI_SYSTEM)
			fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
		else
			perror("getaddrinfo()");

		return 1;
	}

	for (next = ai; next; next = next->ai_next)
	{
		conn *listen_conn_add;
		if ((sfd = new_socket(next)) == -1)
		{
			freeaddrinfo(ai);
			return 1;
		}

		setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *) &flags, sizeof(flags));
		if (is_udp)
		{
			maximize_sndbuf(sfd);
		}
		else
		{
			setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *) &flags, sizeof(flags));
			setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *) &ling, sizeof(ling));
			setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *) &flags, sizeof(flags));
		}

		if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1)
		{
			if (errno != EADDRINUSE)
			{
				perror("bind()");
				close(sfd);
				freeaddrinfo(ai);
				return 1;
			}
			close(sfd);
			continue;
		}
		else
		{
			success++;
			if (!is_udp && listen(sfd, 1024) == -1)
			{
				perror("listen()");
				close(sfd);
				freeaddrinfo(ai);
				return 1;
			}
		}

		if (is_udp)
		{
			int c;

			for (c = 0; c < settings.num_threads; c++)
			{
				/* this is guaranteed to hit all threads because we round-robin */
				dispatch_conn_new(sfd, conn_read, EV_READ | EV_PERSIST,
						UDP_READ_BUFFER_SIZE, 1);
			}
		}
		else
		{
			if (!(listen_conn_add = conn_new(sfd, conn_listening,
					EV_READ | EV_PERSIST, 1, false, main_base)))
			{
				fprintf(stderr, "failed to create listening connection\n");
				exit (EXIT_FAILURE);
			}

			listen_conn_add->next = listen_conn;
			listen_conn = listen_conn_add;
		}
	}

	freeaddrinfo(ai);

	/* Return zero iff we detected no errors in starting up connections */
	return success == 0;
}
Esempio n. 28
0
int socket_server::open_socket(struct request_open * request, struct socket_message * result)
{
    int id = request->id;
    result->id = id;
    result->opaque = request->opaque;
    result->ud = 0;
    result->data = nullptr;
    struct socket *ns;
    int status;
    struct addrinfo ai_hints;
    struct addrinfo * ai_list = nullptr;
    struct addrinfo * ai_ptr = nullptr;
    char port[16];
    sprintf(port, "%d", request->port);
    memset(&ai_hints, 0, sizeof(ai_hints));
    ai_hints.ai_family = AF_UNSPEC;
    ai_hints.ai_socktype = SOCK_STREAM;
    ai_hints.ai_protocol = IPPROTO_TCP;

    status = getaddrinfo(request->host, port, &ai_hints, &ai_list);
    int sock = -1;
    if (status != 0) {
        goto _failed;
    }
    for (ai_ptr = ai_list; ai_list != nullptr; ai_ptr = ai_ptr->ai_next) {
        sock = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
        if (sock < 0) {
            continue;
        }
        keepalive(sock);
        nonblocking(sock);
        status = connect(sock, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
        if (status != 0 && errno != EINPROGRESS) {
            close(sock);
            sock = -1;
            continue;
        }
        break;
    }

    if (sock < 0) {
        goto _failed;
    }

    ns = new_socket(id, sock, PROTOCOL_TCP, request->opaque, true);
    if (status == 0) {
        ns-> type = SOCKET_TYPE_CONNECTED;
        struct sockaddr * addr = ai_ptr->ai_addr;
        void * sin_addr = (ai_ptr->ai_family == AF_INET) ? (void *)&((struct sockaddr_in *)addr)->sin_addr : (void *)&((struct sockaddr_in6 *)addr)->sin6_addr;
        if (inet_ntop(ai_ptr->ai_family, sin_addr, buffer, sizeof(buffer))) {
            result->data = buffer;
        }
        freeaddrinfo(ai_list);
        return SOCKET_OPEN;
    } else {
        ns->type = SOCKET_TYPE_CONNECTING;
        event_fd.write(ns->fd, ns, true);
    }

    freeaddrinfo(ai_list);
    return -1;

_failed:
    freeaddrinfo(ai_list);
    slot[HASH_ID(id)].type = SOCKET_TYPE_INVALID;
    return SOCKET_ERROR;
}
Esempio n. 29
0
int server_socket(const char *interface, int port, int backlog) {
  int sfd;
  struct linger ling;
  struct addrinfo *ai;
  struct addrinfo *next;
  struct addrinfo hints;
  char port_buf[NI_MAXSERV];
  int error;
  int success = 0;
  int flags = 1;

  ling.l_onoff = 0;
  ling.l_linger = 0;
  memset(&hints, 0, sizeof(hints));
  hints.ai_flags = AI_PASSIVE;
  hints.ai_family = base_conf.support_ipv6 ? AF_UNSPEC : AF_INET;
  hints.ai_socktype = SOCK_STREAM;

  if (port == -1) {
    port = 0;
  }
  
  snprintf(port_buf, sizeof(port_buf), "%d", port);
  error= getaddrinfo(interface, port_buf, &hints, &ai);
  if (error != 0) {
    if (error != EAI_SYSTEM)
      fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
    else
      perror("getaddrinfo()");
    return 1;
  }
  
  for (next= ai; next; next= next->ai_next) {
    conn *listen_conn_add;
    if ((sfd = new_socket(next)) == -1) {
      close(sfd);
      freeaddrinfo(ai);
      return 1; 
    }

#ifdef IPV6_V6ONLY
    if (next->ai_family == AF_INET6) {
      error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY,
                         (char *) &flags, sizeof(flags));
      if (error != 0) {
        perror("setsockopt");
        close(sfd);
        continue;
      }
    }
#endif

    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));

    error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags,
                       sizeof(flags));
    if (error != 0)
      perror("setsockopt");

    error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
    if (error != 0)
      perror("setsockopt");

    error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags,
                       sizeof(flags));
    if (error != 0)
      perror("setsockopt");

    if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
      perror("bind()");
      close(sfd);
      freeaddrinfo(ai);
      return 1;
    } else {
      success++;
      if (listen(sfd, backlog) == -1) {
        perror("listen()");
        close(sfd);
        freeaddrinfo(ai);
        return 1;
      }
    }

    if (!(listen_conn_add = conn_new(sfd, conn_listening,
                                     EV_READ | EV_PERSIST, get_main_thread()))) {
      fprintf(stderr, "failed to create listening connection\n");
      exit(EXIT_FAILURE);
    }
    
    listen_conn_add->host->assign(interface?interface:"0.0.0.0");
    listen_conn_add->port = port;
    listen_conn_add->next = listen_conn;
    listen_conn = listen_conn_add;
  }

  freeaddrinfo(ai);
  return success == 0;
}
Esempio n. 30
0
File: rfxd.c Progetto: hyper/librisp
//-----------------------------------------------------------------------------
// Initialise and return a server struct that we will use to control the nodes 
// that we are connected to.   We will bind the listening port on the socket.
//
//	** Will we ever need to listen on more than one port?  How will we add that 
//	   to the system?   Currently, wont bother with it, but will include a 
//	   'next' pointer so that we can have a list of listeners.  The problem 
//	   will be with our list of nodes.  All the servers would need to share 
//	   the nodes list, and various other shared resources.  This could be a 
//	   little cumbersome, but possible.
//
//
server_t *server_new(int port, int maxconns, char *address)
{
	server_t *ptr = NULL;
	int i;
  struct linger ling = {0, 0};
	struct addrinfo *ai;
	struct addrinfo *next;
	struct addrinfo hints;
	char port_buf[NI_MAXSERV];
	int error;
	int sfd;
	int flags =1;
	
	assert(port > 0);
	assert(maxconns > 5);
	assert(address == NULL || (address != NULL && address[0] != '\0'));
	
	memset(&hints, 0, sizeof (hints));
	hints.ai_flags = AI_PASSIVE|AI_ADDRCONFIG;
	hints.ai_family = AF_UNSPEC;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_socktype = SOCK_STREAM;

	snprintf(port_buf, NI_MAXSERV, "%d", port);
  error = getaddrinfo(address, port_buf, &hints, &ai);
	if (error != 0) {
		if (error != EAI_SYSTEM)
			fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error));
		else
			perror("getaddrinfo()");
		return(NULL);
	}

	sfd	= 0;

	for (next= ai; next; next= next->ai_next) {
	
		assert(sfd == 0);
	
		// create the new socket.  if that fails, free the memory we've already allocated, and return NULL.
		sfd = new_socket(next);
		if (sfd == INVALID_HANDLE) {
			freeaddrinfo(ai);
			return(NULL);
		}

		setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
		setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
		setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
// 		setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));

    if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) {
			if (errno != EADDRINUSE) {
				perror("bind()");
				close(sfd);
				freeaddrinfo(ai);
				return(NULL);
			}
            
			close(sfd);
			sfd = INVALID_HANDLE;
			continue;
		} else {
			if (listen(sfd, 1024) == -1) {
				perror("listen()");
				close(sfd);
				freeaddrinfo(ai);
				return(NULL);
			}
    }
	}
    
	freeaddrinfo(ai);

	ptr = (server_t *) malloc(sizeof(server_t));
	assert(ptr != NULL);
	
	ptr->handle = sfd;
	ptr->stats = NULL;
	ptr->risp = NULL;
	ptr->verbose = false;
	
	// We will create an array of empty pointers for our nodes.
	ptr->maxconns = maxconns;
	ptr->nodes = (node_t **) malloc(sizeof(node_t *) * maxconns);
	for (i=0; i<maxconns; i++) {
		ptr->nodes[i] = NULL;
	}
		
	return(ptr);
}