Beispiel #1
0
uint16_t		unix_get_simple_reply(t_conf *conf, char *buffer, uint16_t id)
{
  fd_set                rfds;
  int                   retval;
  struct timeval        tv;
  struct dns_hdr	*hdr;
  int			len = 0; 
  
  tv.tv_sec = (time_t) conf->conn_timeout;
  tv.tv_usec = 0;
  hdr = (struct dns_hdr	*) buffer;
  FD_ZERO(&rfds);

  add_socket(conf->sd_udp, &rfds, 0);
  while ((retval = select(conf->sd_udp+1, &rfds, NULL, NULL, &tv)) != -1)
    {
      if (!retval)
	{
	  fprintf(stderr, "No response from DNS %s\n", conf->dns_server);
	  return (0);
	}
      if ((IS_THIS_SOCKET(conf->sd_udp, conf->event_udp, &rfds,  retval)) 
	  && ((len = read(conf->sd_udp, buffer, MAX_DNS_LEN)) > 0))
	{
	  if (hdr->id == id)
	    return (len);
	  else 
	    queue_get_udp_data(conf, buffer, len);
	}
      add_socket(conf->sd_udp, &rfds, 0);
      tv.tv_sec = (time_t) conf->conn_timeout;
    }
  MYERROR("Select error");
  return (0);
}
Beispiel #2
0
int		unix_prepare_select(t_conf *conf, fd_set *rfds, struct timeval *tv)
{
  int		max_fd = 0;
  t_simple_list	*client;
  
  FD_ZERO(rfds);
  for (client = conf->client; client; client = client->next)
    {
      if (socket_is_valid(client->fd_ro))
	{
	  queue_put_nop(conf, client);
	  if (!(client->control.data_pending >= MAX_DATA_SIZE)
	      && (!(client->control.data_pending + client->control.nop_pending >= WINDOW_SIZE)))
	    {
	      if (socket_is_valid(client->fd_ro))
		max_fd = add_socket(client->fd_ro, rfds, max_fd);
	    }
	}
    }
  max_fd = add_socket(conf->sd_udp, rfds, max_fd);
  // f**k Windows, not queue debug
  if ((!conf->use_stdin) && (debug > 1))
    max_fd = add_socket(0, rfds, max_fd);
  
  /* select only if sd_tcp is alive */
  if (socket_is_valid(conf->sd_tcp))
    max_fd = add_socket(conf->sd_tcp, rfds, max_fd);
  tv->tv_sec = SOCKET_TIMEOUT;
  tv->tv_usec = 0;
  return (max_fd);
}
Beispiel #3
0
/**
 * Create a new socket handle.
 * @param family    Must be {@code AF_INET}
 * @param type      Either SOCK_DGRAM or SOCK_STREAM
 * @param protocol  Either IPPROTO_UDP or IPPROTO_TCP
 * @return
 */
sock_handle_t socket_create(uint8_t family, uint8_t type, uint8_t protocol, uint16_t port, network_interface_t nif)
{
    if (family!=AF_INET || !((type==SOCK_DGRAM && protocol==IPPROTO_UDP) || (type==SOCK_STREAM && protocol==IPPROTO_TCP)))
        return SOCKET_INVALID;

    sock_handle_t result = SOCKET_INVALID;
    socket_t* socket = new socket_t();
    if (socket) {
        wiced_result_t wiced_result;
        socket->set_type((protocol==IPPROTO_UDP ? socket_t::UDP : socket_t::TCP));
        if (protocol==IPPROTO_TCP) {
            wiced_result = wiced_tcp_create_socket(tcp(socket), wiced_wlan_interface(nif));
        }
        else {
            wiced_result = wiced_udp_create_socket(udp(socket), port, wiced_wlan_interface(nif));
        }
        if (wiced_result!=WICED_SUCCESS) {
            socket->set_type(socket_t::NONE);
            delete socket;
            result = as_sock_result(wiced_result);
        }
        else {
            SocketListLock lock(list_for(socket));
            add_socket(socket);
            result = as_sock_result(socket);
        }
    }
    return result;
}
Beispiel #4
0
/*
 * If your compiler can inline your callback (i.e. it is visible to it at the place of the set call and
 * your compiler is good :), then the method will be fully inlined into the thunking function, making it
 * as fast as a direct C callback.
 *
 * revents was bitset
 *
 * if (revents & EV_READ ) fd->revents |= fd->events & POLLIN;
 * if (revents & EV_WRITE) fd->revents |= fd->events & POLLOUT;
 */
void CNetBackend::accept_cb(ev::io &w, int32 revents)
{
    if ( EV_ERROR & revents )  //error
    {
        GERROR() << "accept_cb error:" << strerror(errno) << "\n";

        w.stop();

        return;
    }

    struct sockaddr_in socket_address;
    int32 length = sizeof( socket_address );

    //w.fd is m_plistenning_socket->get_listen_socket_fd()
    int32 fd = accept( w.fd,(sockaddr *)&socket_address,(socklen_t *)&length );
    if ( fd < 0 )
    {
        if ( EWOULDBLOCK == errno || EAGAIN == errno )  //无连接libev怎么会调用accept_cb
        {
            GERROR() << "accept_cb EWOULDBLOCK or EAGAIN found\n";
            return;
        }

        GERROR() << "accept new connection fail:" << strerror( errno ) << "\n";

        return;
    }

    add_socket( fd,socket_address );
}
Beispiel #5
0
void Gobby::GSelector::set(const net6::socket& sock, net6::io_condition cond)
{
	// Lock mutex - required for connection establishment which happens
	// in a different thread for the GUI to remain responsive.

	// After the connection to Glib::signal_io() the main thread may be
	// woken up immediately by incoming data and call GSelector::set to
	// send out some data even before the assignment to the
	// sigc::connection in the connecting thread has been finished!
	Glib::RecMutex::Lock lock(*m_mutex);

	map_type::iterator iter = m_map.find(&sock);

	if(cond != net6::IO_NONE)
	{
		if(iter == m_map.end() )
			add_socket(sock, cond);
		else
			modify_socket(iter, cond);
	}
	else if(iter != m_map.end() )
	{
		delete_socket(iter);
	}
}
Beispiel #6
0
int main(int argc, char** argv)
{
  struct configuration cfg;
  int parent, sock, got;
  unsigned int pkt_num = 0;

  parse_options(argc, argv, &cfg);

  /* Initialise */
  parent = add_socket(&cfg);
  do_ioctl(&cfg, parent);
  sock = parent;
  if( cfg.cfg_protocol == IPPROTO_TCP )
    sock = accept_child(parent);
  do_ts_sockopt(sock);

  /* Run forever */
  while( 1 ) {
    pkt_num ++;
    got = do_recv(sock, pkt_num);
    /* TCP can detect an exit; for UDP, zero payload packets are valid */
    if ( got == 0 && cfg.cfg_protocol == IPPROTO_TCP ) {
      printf( "recvmsg returned 0 - end of stream\n" );
      break;
    }
  }

  close(sock);
  if( cfg.cfg_protocol == IPPROTO_TCP )
    close(parent);
  return 0;
}
Beispiel #7
0
/* Un client  */
static void* repeater(void* sck)
{
	int sckt = (int) sck;
    char buf[MAX_BUFFER];
    int nbc, i;
    const char WELCOME[] = "mtcs : bienvenu\n";

    pgrs_in();
    write(sckt, WELCOME, strlen(WELCOME));

    pgrs("enregistrement d'une socket");
    add_socket(sckt);
    
    while (1) {
	pgrs("attente read");
	nbc = read(sckt, buf, MAX_BUFFER);
	if (nbc <= 0) {
	    pgrs("fin lecture client");
	    pgrs("desenregistrement d'une socket");
	    del_socket(sckt);
	    close(sckt);
            pgrs_out();
	    return NULL;
	}
	pgrs("boucle ecriture");
	for(i=0; i<MAX_CONNECTION; i++)
	    if (sockets[i])
		write(sockets[i], buf, nbc);
	pgrs("fin boucle ecriture");
    }
    return NULL;
}
Beispiel #8
0
int main()
{
  RSA *keypair = RSA_generate_key(KEY_LENGTH, PUB_EXP, NULL, NULL);//генерация пары ключей
  int listener; 
  int *sockets=calloc(MAX_CLIENTS,sizeof(int));
  pthread_t thread_write[MAX_CLIENTS];
  RSA *all_keys[MAX_CLIENTS];
  int sock=-1;
  try_connect(&listener);
  listen(listener,MAX_CLIENTS);
  while(1)
  {
    
    sock=accept(listener,NULL,NULL);
    if(sock<0)
    {
      perror("Не удалось принять соединение");
      return 3;
    }
    For_server_Thread thread_wr;
    thread_wr.sock=sock;
    thread_wr.sockets=sockets;
    thread_wr.keypair=keypair;
    thread_wr.all_keys=all_keys;
    int result=add_socket(thread_wr,thread_write);
    if(result==-1)
    {
      perror("Слишком много соединений");
    }
  }
}
Beispiel #9
0
/*
 * Opening a UDP socket is a little more tricky, since
 * UDP works in a way which is different from TCP...
 * 
 * Our goal is to hide this difference for the end-user
 */
tree_cell * nasl_open_sock_udp(lex_ctxt * lexic)
{
 int soc;
 tree_cell * retc;
 int port;
 struct sockaddr_in soca;
 struct arglist *  script_infos = lexic->script_infos;
 struct in_addr * ia;

 port = get_int_var_by_num(lexic, 0, -1);
 if(port < 0)
	 return NULL;
   
 ia = plug_get_host_ip(script_infos);
 bzero(&soca, sizeof(soca));
 soca.sin_addr.s_addr = ia->s_addr;
 soca.sin_port = htons(port);
 soca.sin_family = AF_INET;

 soc = socket(AF_INET, SOCK_DGRAM, 0);
 add_socket(script_infos, soc);
 
 set_socket_source_addr(soc, 0);
 
 connect(soc, (struct sockaddr*)&soca, sizeof(soca));

 retc = alloc_tree_cell(0, NULL);
 retc->type = CONST_INT;
 retc->x.i_val = soc < 0 ? 0 : soc;
 return retc;
}
static bool add_client(int sock)
{
	int i;

	if (server.clientnum >= MAX_CLIENTS)
	{
		fprintf(stderr, "client limit hit\n");
		return false;
	}

	for (i = 0; i < MAX_CLIENTS; i++)
	{
		Client *c = server.clients + i;
		if (c->sock >= 0) continue;

		c->sock = sock;
		c->good = true;
		c->msg = NULL;
		c->bufrecved = 0;
		c->expect.id = NOBODY;
		server.clientnum++;
		return add_socket(sock);
	}

	Assert(false); // should not happen
	return false;
}
Beispiel #11
0
sock_result_t socket_create_tcp_server(uint16_t port, network_interface_t nif)
{
    socket_t* socket = new socket_t();
    tcp_server_t* server = new tcp_server_t();
    wiced_result_t result = WICED_OUT_OF_HEAP_SPACE;
    if (socket && server) {
        result = wiced_tcp_server_start(server, wiced_wlan_interface(nif),
            port, WICED_MAXIMUM_NUMBER_OF_SERVER_SOCKETS, server_connected, server_received, server_disconnected, NULL);
    }
    if (result!=WICED_SUCCESS) {
        if (socket) {
            delete socket;
            socket = NULL;
        }
        if (server) {
            server->close();
            delete server;
            server = NULL;
        }
    }
    else {
        socket->set_server(server);
        SocketListLock lock(list_for(socket));
        add_socket(socket);
    }

    return socket ? as_sock_result(socket) : as_sock_result(result);
}
static void worker_main(Datum arg)
{
	WorkerConfig *cfg = (WorkerConfig *)(arg);
	StateP state = (StateP)cfg->getter();

	cfg->raft_config.userdata = state;
	cfg->raft_config.applier = applier;
	cfg->raft_config.snapshooter = snapshooter;

	raft = raft_init(&cfg->raft_config);
	if (raft == NULL)
		elog(ERROR, "couldn't configure raft");

	add_peers(cfg);

	if (!start_server()) elog(ERROR, "couldn't start raftable server");

    signal(SIGINT, die);
    signal(SIGQUIT, die);
    signal(SIGTERM, die);
    sigset_t sset;
    sigfillset(&sset);
    sigprocmask(SIG_UNBLOCK, &sset, NULL);

	server.raftsock = raft_create_udp_socket(raft);
	add_socket(server.raftsock);
	add_socket(server.listener);
	if (server.raftsock == -1) elog(ERROR, "couldn't start raft");

	mstimer_t t;
	mstimer_reset(&t);
	while (!stop)
	{
		raft_msg_t m = NULL;

		int ms = mstimer_reset(&t);
		raft_tick(raft, ms);

		if (tick(cfg->raft_config.heartbeat_ms))
		{
			m = raft_recv_message(raft);
			Assert(m != NULL);
			raft_handle_message(raft, m);
			notify();
		}
	}
}
Beispiel #13
0
/*
 * Initialize short-message handling. 
 * Make one or more sockets and set up to listen on them.
 * This function is xxx ought-to-be ipv6-agnostic, and is even
 * almost UDP/TCP-agnostic.
 */
bool
SMnet::listen_on_port(std::string port)
{
	int s;
	int gotasocket = 0;
	struct addrinfo myhints;
	struct addrinfo *myaddrs, *ap;

	memset(&myhints, 0, sizeof(myhints));
	myhints.ai_family = AF_UNSPEC;		// Any address family eg v4/6
	myhints.ai_socktype = SOCK_DGRAM;	// Datagrams for now FIXME
	myhints.ai_flags = AI_PASSIVE;		// From anybody

	s = getaddrinfo(NULL, (port.c_str()), &myhints, &myaddrs);
	if (s != 0) {
		cerr << "listen_on_port(" << port 
		     << ") can't get addr/port to listen on" << endl;
		return -1;
	}
	
	for (ap = myaddrs; ap != NULL; ap = ap->ai_next) {
	
		int fd, i;

		fd = socket(ap->ai_family, ap->ai_socktype, ap->ai_protocol);
		if (fd < 0)
			continue;		// Try another
		// Set our port number & address.
		i = bind(fd, ap->ai_addr, ap->ai_addrlen);
		if (i < 0) {
			cerr << "listen_on_port(" << port
			     << ") can't bind to addr '"
			     << string_addr (ap, true) << "': " 
			     << strerror(errno) << endl;
			close(fd);		// Don't leave it dangling
			continue;		// Try another
		}
		
		(void) fcntl(fd, F_SETFL, O_NONBLOCK);	// Non-blocking I/O
#ifdef O_CLOEXEC
		(void) fcntl(fd, F_SETFD, O_CLOEXEC);	// Close on exec child
#endif

		// Now set up our class to poll on, and use, this socket.
		add_socket (fd, POLLIN|POLLPRI, ap->ai_family,
			ap->ai_socktype, ap->ai_protocol, ap->ai_addr,
			ap->ai_addrlen);
		// Be slightly verbose here.
		cerr << "Listening at address '"
		     << string_addr (ap, true) << "'." << endl;
		gotasocket++;
		// And keep looping to make several sockets if we can!
	}
	freeaddrinfo(myaddrs);		// Don't leak memory.

	if (!gotasocket)
		return false;
	return true;
}
Beispiel #14
0
static int open_socket(unsigned int domain, unsigned int type, unsigned int protocol)
{
	struct object *obj;
	struct sockaddr *sa = NULL;
	const struct netproto *proto;
	socklen_t salen;
	struct sockopt so = { 0, 0, 0, 0 };
	int fd;

	fd = socket(domain, type, protocol);
	if (fd == -1)
		return fd;

	obj = add_socket(fd, domain, type, protocol);

	proto = net_protocols[domain].proto;
	if (proto != NULL)
		if (proto->socket_setup != NULL)
			proto->socket_setup(fd);

	// FIXME:
	// All of this needs to be broken out into child ops instead of
	// special casing it all at creation time.

	/* Set some random socket options. */
	sso_socket(&obj->sockinfo.triplet, &so, fd);

	nr_sockets++;

	/* Sometimes, listen on created sockets. */
	if (RAND_BOOL()) {
		int ret, one = 1;

		/* fake a sockaddr. */
		generate_sockaddr((struct sockaddr **) &sa, (socklen_t *) &salen, domain);

		ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
		if (ret != -1)
			goto skip_bind;

		ret = bind(fd, sa, salen);
		if (ret != -1)
			(void) listen(fd, RAND_RANGE(1, 128));

//		ret = accept4(fd, sa, &salen, SOCK_NONBLOCK);
//		if (ret != -1) {
//			obj = add_socket(ret, domain, type, protocol);
//			nr_sockets++;
//		}
	}

skip_bind:
	if (sa != NULL)
		free(sa);

	return fd;
}
Beispiel #15
0
/* Version stupide. Pas de creation de thread, 
   Le serveur ne peut plus accepter de connexion car il gère
   l'interaction avec le premier client. 
*/
int
manage_cnct(int fd)
{   
	pthread_t thread;
	int result;
    pgrs_in();
	result = pthread_create(&thread,NULL,repeater,(void*)fd);
	add_socket(fd);
	
	/*repeater(fd);	*/

    pgrs_out();
    return result;
}
static void* accept_callback(void *context)
{
	int return_value = 0;
	sensor_context *sensor = NULL;
	peer *client = NULL;

	sensor = (sensor_context*)context;

	client = (peer*)malloc(sizeof(peer));
	if(!client)
	{
		LOG_DEBUG(("DEBUG: Out of memory\n"));
		return (NULL);
	}

	client->sensor = context;
	client->comm_socket_fd = accept(sensor->server_socket_fd, (struct sockaddr*)NULL, NULL);
	if(client->comm_socket_fd < 0)
	{
		LOG_ERROR(("ERROR: Accept call failed\n"));
		free(client);
		return NULL;
	}

	sensor->recv_peer[sensor->recv_peer_count] = client;
	sensor->recv_peer_count++;

	/* add socket to network read thread */
	return_value = add_socket(sensor->network_thread, client->comm_socket_fd,  (void*)client, &read_callback_peer);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: add_socket() failed\n"));
		free(client);
		return (NULL);
	}
	//client->connection_state = 1;

	LOG_SCREEN(("INFO: All Peers connected successfully\n"));

	if(sensor->send_peer_count == 2 && sensor->recv_peer_count == 2)
	{
		pthread_create(&sensor->set_value_thread, NULL, &set_value_thread, sensor);
	}

	return (NULL);
}
int create_gateway(gateway_handle* handle, gateway_create_params *params)
{
	gateway_context *gateway = NULL;
	int return_value = 0;

	gateway = (gateway_context*)malloc(sizeof(gateway_context));
	if(NULL == gateway)
	{
		LOG_ERROR(("ERROR: Out of memory\n"));
		return (E_OUT_OF_MEMORY);
	}

	gateway->client_count = 0;

	/* create network read thread */
	return_value = create_network_thread(&gateway->network_thread, params->gateway_ip_address);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Error in creating n/w read thread\n"));
		delete_gateway((gateway_handle)gateway);
		return (return_value);
	}

	/* create connection to server */
	return_value = create_server_socket(&gateway->server_socket_fd, params->gateway_ip_address, params->gateway_port_no);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Error in creating the socket\n"));
		delete_gateway((gateway_handle)gateway);
		return (return_value);
	}

	/* add socket to network read thread */
	return_value = add_socket(gateway->network_thread, gateway->server_socket_fd,  (void*)gateway, &accept_callback);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: add_socket() failed\n"));
		delete_gateway((gateway_handle)gateway);
		return (return_value);
	}
	*handle = gateway;

	return (E_SUCCESS);
}
Beispiel #18
0
/**
 * Fetch the next waiting client socket from the server
 * @param sock
 * @return
 */
sock_result_t socket_accept(sock_handle_t sock)
{
    sock_result_t result = SOCKET_INVALID;
    socket_t* socket = from_handle(sock);
    if (is_open(socket) && is_server(socket)) {
        std::lock_guard<socket_t> lk(*socket);
        tcp_server_t* server = socket->s.tcp_server;
        tcp_server_client_t* client = server->next_accept();
        if (client) {
            socket_t* socket = new socket_t();
            socket->set_client(client);
            {
                SocketListLock lock(list_for(socket));
                add_socket(socket);
            }
            result = (sock_result_t)socket;
        }
    }
    return result;
}
Beispiel #19
0
    int socket_callback(CURL* _easy_handle, curl_socket_t _socket, int _what, void* _curl_handler_ptr, void* _connection_ptr)
    {
        const auto handler = static_cast<curl_handler*>(_curl_handler_ptr);

        const auto connection = static_cast<curl_handler::connection_context*>(_connection_ptr);

        if (_what == CURL_POLL_REMOVE)
        {
            connection->free_event();
        }
        else if (connection == NULL)
        {
            add_socket(_socket, _easy_handle, _what, handler);
        }
        else
        {
            connection->update(_socket, _what);
        }

        return 0;
    }
Beispiel #20
0
int main(int argc, char** argv)
{
  struct configuration cfg;
  int sock;
  unsigned int pkt_num = 0;

  parse_options(argc, argv, &cfg);

  /* Initialise */
  sock = add_socket(&cfg);
  do_mcast(&cfg, sock);
  do_ioctl(&cfg, sock);
  do_ts_sockopt(&cfg, sock);

  /* Run until we've got enough packets, or an error occurs */
  while( (pkt_num++ < cfg.cfg_max_packets) || (cfg.cfg_max_packets == 0) )
    TRY( do_echo(sock, pkt_num, cfg.cfg_templated) );

  close(sock);
  return 0;
}
void* accept_callback(void *context)
{
	int return_value = 0;
	gateway_context *gateway = NULL;
	gateway_client *client = NULL;

	gateway = (gateway_context*)context;

	client = (gateway_client*)malloc(sizeof(gateway_client));
	if(!client)
	{
		LOG_DEBUG(("DEBUG: Out of memory\n"));
		return (NULL);
	}

	client->gateway = context;
	client->comm_socket_fd = accept(gateway->server_socket_fd, (struct sockaddr*)NULL, NULL);
	if(client->comm_socket_fd < 0)
	{
		LOG_ERROR(("ERROR: Accept call failed\n"));
		free(client);
		return NULL;
	}

	gateway->clients[gateway->client_count] = client;
	gateway->client_count++;

	/* add socket to network read thread */
	return_value = add_socket(gateway->network_thread, client->comm_socket_fd,  (void*)client, &read_callback);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: add_socket() failed\n"));
		free(client);
		return (NULL);
	}
	client->connection_state = 1;

	return (NULL);
}
Beispiel #22
0
void			select_s(t_server *s_info, fd_set *rfd, struct timeval *time)
{
  int			i;
  int			tmp;
  int			al;
  struct sockaddr_in	addr;
  char			buffer[BUFFER_SIZE + 1];
  int			res;

  res = select(FD_SETSIZE, rfd, NULL, NULL, time);
  al = sizeof(addr);
  if (socket_com_size() <= MAX_CLIENTS && FD_ISSET(socket_s, rfd)) {
    if ((tmp =
	 accept(socket_s, (struct sockaddr *)&addr, (socklen_t *)&al)) == -1) {
      dprintf(1, "accept error\n");
      exit (0);
    }
    add_socket(tmp, &addr, s_info);
  }
  i = 0;
  recv_perso(rfd, s_info);
}
Beispiel #23
0
static PyObject*
PyEvents_CreateSocket(PyObject* unused, PyObject* args)
{
    SocketObject* socket;
    int fd;			/* Handle of stream to watch. */
    int mask;			/* OR'ed combination of PyEvents_READABLE,
				 * PyEvents_WRITABLE, and PyEvents_EXCEPTION:
                                 * indicates conditions under which proc
                                 * should be called. */
    PyObject* callback;         /* Callback function */
    if (!PyArg_ParseTuple(args, "iiO", &fd, &mask, &callback)) return NULL;
    if (!PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "Callback should be callable");
        return NULL;
    }
    Py_INCREF(callback);
    socket = (SocketObject*)PyType_GenericNew(&SocketType, NULL, NULL);
    socket->callback = callback;
    socket->fd = fd;
    socket->mask = mask;
    add_socket(socket);
    return (PyObject*)socket;
}
static bool start_server(void)
{
	int i;

	server.listener = -1;
	server.raftsock = -1;
	FD_ZERO(&server.all);
	server.maxfd = 0;
	server.clientnum = 0;

	server.listener = create_listening_socket(server.host, server.port);
	if (server.listener == -1)
	{
		return false;
	}

	for (i = 0; i < MAX_CLIENTS; i++)
	{
		server.clients[i].sock = -1;
	}

	return add_socket(server.listener);
}
Beispiel #25
0
void runserver(int numthreads, unsigned short serverport) {
    //////////////////////////////////////////////////

    // create your pool of threads here

    //////////////////////////////////////////////////
    
	
	//Initialize socket queue 
	socket_pool_t *mysockets = malloc(sizeof(socket_pool_t));
    	socket_pool_init(mysockets);
	
	struct thread_args *myargs = malloc(sizeof(struct thread_args));
	myargs->sockets = mysockets;
	//myargs->weblog = fopen(NULL,"weblog.txt");

	pthread_t threadpool[numthreads];
	
	int i=0;
    //for loop to initialize threads in threadpool 
    for (; i<numthreads; i++){
        if (0 > pthread_create(&threadpool[i], NULL, (void *)consumer, myargs)){
           fprintf(stderr, "Error creating thread: %s\n", strerror(errno));
		}
	}
  
    
    int main_socket = prepare_server_socket(serverport);
    if (main_socket < 0) {
        exit(-1);
    }
    signal(SIGINT, signal_handler);

    struct sockaddr_in client_address;
    socklen_t addr_len;

    fprintf(stderr, "Server listening on port %d.  Going into request loop.\n", serverport);
    while (still_running) {
        struct pollfd pfd = {main_socket, POLLIN};
        int prv = poll(&pfd, 1, 10000);

        if (prv == 0) {
            continue;
        } else if (prv < 0) {
            PRINT_ERROR("poll");
            still_running = FALSE;
            continue;
        }
        
        addr_len = sizeof(client_address);
        memset(&client_address, 0, addr_len);

        int new_sock = accept(main_socket, (struct sockaddr *)&client_address, &addr_len);
        if (new_sock > 0) {
            
            fprintf(stderr, "Got connection from %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));

           ////////////////////////////////////////////////////////
           /* You got a new connection.  Hand the connection off
            * to one of the threads in the pool to process the
            * request.
            *
            * Don't forget to close the socket (in the worker thread)
            * when you're done.
            */
           ////////////////////////////////////////////////////////
		   pthread_mutex_lock(&mysockets->socket_pool_lock);
		   add_socket(mysockets, new_sock);
		   pthread_mutex_unlock(&mysockets->socket_pool_lock);
		   get_new_socket(mysockets);
		   close(new_sock);

        }
    }
    fprintf(stderr, "Server shutting down.\n");
        
    close(main_socket);
}
Beispiel #26
0
static tree_cell * nasl_open_privileged_socket(lex_ctxt * lexic, int proto)
{
 struct arglist * script_infos = lexic->script_infos;
 int sport, current_sport = -1;
 int dport;
 int sock;
 int e, err;
 struct sockaddr_in addr, daddr;
 struct in_addr * p;
 int to = get_int_local_var_by_name(lexic, "timeout", lexic->recv_timeout);
 tree_cell * retc;
 struct timeval tv;
 fd_set rd;
 int opt, opt_sz;
 
 
 
 sport = get_int_local_var_by_name(lexic, "sport", -1);
 dport = get_int_local_var_by_name(lexic, "dport", -1);
 if(dport <= 0)
   {
     nasl_perror(lexic, "open_private_socket: missing or undefined parameter dport!\n");
     return NULL;
   }
 
 if(sport < 0) current_sport = 1023;


restart: 
 bzero(&addr, sizeof(addr));
 if(proto == IPPROTO_TCP)
  sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 else
  sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  
  
 /*
  * We will bind to a privileged port. Let's declare
  * our socket ready for reuse
  */
 
 if(sock < 0)
	 return NULL;
 add_socket(script_infos, sock);

tryagain :
 if ( current_sport < 128 ) return NULL;
 e =  set_socket_source_addr(sock, sport > 0 ? sport : current_sport--);
 
 /*
  * bind() failed - try again on a lower port
  */
 if(e < 0)
 {
  closesocket ( sock );
  if(sport > 0) 
    return NULL;
   else 
     goto tryagain;
 }
 
 /*
  * Connect to the other end
  */
 p = plug_get_host_ip(script_infos);
 bzero(&daddr, sizeof(daddr));
 daddr.sin_addr = *p;
 daddr.sin_port = htons(dport);
 daddr.sin_family = AF_INET;
 
 unblock_socket(sock);
 e = connect(sock, (struct sockaddr*)&daddr, sizeof(daddr));
 if ( e < 0 )
 {
   err = WSAGetLastError();
   if ( err == WSAEADDRINUSE || err == WSAEADDRNOTAVAIL )
   {
     closesocket(sock);
     if ( sport < 0 ) 
          goto restart;
     else  
          return NULL;
   }
 }

  do {
  tv.tv_sec = to;
  tv.tv_usec = 0;
  FD_ZERO(&rd);
  FD_SET(sock, &rd);
  e = select(sock + 1, NULL, &rd, NULL, to > 0 ? &tv:NULL);
  err = WSAGetLastError();
  } while ( e < 0 && err == WSAEINTR );

 block_socket(sock);
 opt_sz = sizeof(opt);

 if ( getsockopt(sock, SOL_SOCKET, SO_ERROR, &opt, &opt_sz) < 0 )
 {
  fprintf(stderr, "[%d] open_priv_sock()->getsockopt() failed : %s\n", getpid(), strerror(errno));
  closesocket(sock);
  return NULL;
 }
 

 switch ( opt )
 {
   case WSAEADDRINUSE:
   case WSAEADDRNOTAVAIL:
     closesocket ( sock );
     if ( sport < 0 )
 	 goto restart;
      else 
         return FAKE_CELL;

   case 0:
	break;
   default:
       closesocket ( sock );
       return FAKE_CELL;
       break;
 }
 
 if(proto == IPPROTO_TCP)
   sock = nessus_register_connection(sock, NULL);

  retc = alloc_tree_cell(0, NULL);
  retc->type = CONST_INT;
  retc->x.i_val = sock < 0 ? 0 : sock;
  return retc;
}
Beispiel #27
0
static int call0 (FTN_NODE *node, BINKD_CONFIG *config)
{
  int sockfd = INVALID_SOCKET;
  int sock_out;
  char szDestAddr[FTN_ADDR_SZ + 1];
  int i, rc, pid = -1;
  char host[BINKD_FQDNLEN + 5 + 1];       /* current host/port */
  char addrbuf[BINKD_FQDNLEN + 1];
  char servbuf[MAXSERVNAME + 1];
  char *hosts;
  char *port;
  char *dst_host = host;
  const char *save_err;
#ifdef HTTPS
  int use_proxy;
  char *proxy, *socks;
  struct addrinfo *aiProxyHead;
#endif
  struct addrinfo *ai, *aiNodeHead, *aiHead, hints;
  int aiErr;

  /* setup hints for getaddrinfo */
  memset((void *)&hints, 0, sizeof(hints));
  hints.ai_family = node->IP_afamily;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

#ifdef WITH_PERL
  hosts = xstrdup(node->hosts);
#ifdef HTTPS
  proxy = xstrdup(config->proxy);
  socks = xstrdup(config->socks);
#endif
  if (!perl_on_call(node, config, &hosts
#ifdef HTTPS
                    , &proxy, &socks
#endif
                    )) {
    Log(1, "call aborted by Perl on_call()");
    return 0;
  }
#else
  hosts = node->hosts;
#ifdef HTTPS
  proxy = config->proxy;
  socks = config->socks;
#endif
#endif

  ftnaddress_to_str (szDestAddr, &node->fa);
  Log (2, "call to %s", szDestAddr);
  setproctitle ("call to %s", szDestAddr);

#ifdef HTTPS
  use_proxy = (node->NP_flag != NP_ON) && (!node->pipe || !node->pipe[0]) && (proxy[0] || socks[0]);
  if (use_proxy)
  {
    char *sp, *sport;
    strncpy(host, proxy[0] ? proxy : socks, sizeof(host));
    if ((sp=strchr(host, ':')) != NULL)
    {
      *sp++ = '\0';
      sport = sp;
      if ((sp=strchr(sp, '/')) != NULL)
	*sp++ = '\0';
    }
    else
    {
      if ((sp=strchr(host, '/')) != NULL)
	*sp++ = '\0';
      sport = proxy[0] ? "squid" : "socks"; /* default port */
    }
    /* resolve proxy host */
    if ( (aiErr = srv_getaddrinfo(host, sport, &hints, &aiProxyHead)) != 0)
    {
	Log(2, "Port %s not found, try default %d", sp, proxy[0] ? 3128 : 1080);
	aiErr = getaddrinfo(host, proxy[0] ? "3128" : "1080", &hints, &aiProxyHead);
    }
    if (aiErr != 0)
    {
      Log(1, "%s host %s not found", proxy[0] ? "Proxy" : "Socks", host);
#ifdef WITH_PERL
      xfree(hosts);
#ifdef HTTPS
      xfree(proxy);
      xfree(socks);
#endif
#endif
      return 0;
    }
  }
#endif

  for (i = 1; sockfd == INVALID_SOCKET
       && (rc = get_host_and_port
	   (i, host, &port, hosts, &node->fa, config)) != -1; ++i)
  {
    if (rc == 0)
    {
      Log (1, "%s: %i: error parsing host list", hosts, i);
      continue;
    }

    pid = -1;
    if (node->pipe && node->pipe[0])
    {
      char *cmdline = strdup(node->pipe);
      cmdline = ed(cmdline, "*H", host, NULL);
      cmdline = ed(cmdline, "*I", port, NULL);
      pid = run3(cmdline, &sock_out, &sockfd, NULL);
      free(cmdline);
      if (pid != -1)
      {
	Log (4, "connected");
	add_socket(sock_out);
	break;
      }
      if (!binkd_exit)
      {
	Log (1, "connection to %s failed");
	/* bad_try (&node->fa, "exec error", BAD_CALL, config); */
      }
      sockfd = INVALID_SOCKET;
      continue;
    }

#ifdef HTTPS
    if (use_proxy)
      aiHead = aiProxyHead;
    else /* don't resolve if proxy or socks specified */
#endif
    {
      aiErr = srv_getaddrinfo(host, port, &hints, &aiNodeHead);
     
      if (aiErr != 0)
      {
        bad_try(&node->fa, "Cannot getaddrinfo", BAD_CALL, config);
        continue;
      }
      aiHead = aiNodeHead;
    }

    /* Trying... */

    for (ai = aiHead; ai != NULL && sockfd == INVALID_SOCKET; ai = ai->ai_next)
    {
      if ((sockfd = socket (ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == INVALID_SOCKET)
      {
	Log (1, "socket: %s", TCPERR ());

	/* as long as there are more addresses, try those */
        if (ai != NULL) 
          continue;
        else
        {
#ifdef WITH_PERL
	  xfree(hosts);
#ifdef HTTPS
	  xfree(proxy);
	  xfree(socks);
#endif
#endif
	  freeaddrinfo(aiHead);
	  return 0;
	}
      }
      add_socket(sockfd);
      /* Was the socket created after close_sockets loop in exitfunc()? */
      if (binkd_exit)
      {
#ifdef WITH_PERL
	xfree(hosts);
#ifdef HTTPS
	xfree(proxy);
	xfree(socks);
#endif
#endif
	freeaddrinfo(aiHead);
	return 0;
      }
      rc = getnameinfo(ai->ai_addr, ai->ai_addrlen, addrbuf, sizeof(addrbuf),
		       servbuf, sizeof(servbuf), NI_NUMERICHOST | NI_NUMERICSERV);
      if (rc != 0) {
	Log (2, "Error in getnameinfo(): %s (%d)", gai_strerror(rc), rc);
        snprintf(addrbuf, BINKD_FQDNLEN, "invalid");
	*servbuf = '\0';
      }

#ifdef HTTPS
      if (use_proxy)
      {
	char *sp = strchr(host, ':');
	if (sp) *sp = '\0';
	if (port == config->oport)
	  Log (4, "trying %s via %s %s:%s...", host,
	       proxy[0] ? "proxy" : "socks", addrbuf, servbuf);
	else
	  Log (4, "trying %s:%s via %s %s:%s...", host, port,
	       proxy[0] ? "proxy" : "socks", addrbuf, servbuf);
	sprintf(host+strlen(host), ":%s", port);
      }
      else
#endif
      {
	if (port == config->oport)
          Log (4, "trying %s [%s]...", host, addrbuf);
	else
          Log (4, "trying %s [%s]:%s...", host, addrbuf, servbuf);
      }
      /* find bind addr with matching address family */
      if (config->bindaddr[0])
      {
	struct addrinfo *src_ai, src_hints;
	
	memset((void *)&src_hints, 0, sizeof(src_hints));
	src_hints.ai_socktype = SOCK_STREAM;
	src_hints.ai_family = ai->ai_family;
	src_hints.ai_protocol = IPPROTO_TCP;
	if ((aiErr = getaddrinfo(config->bindaddr, NULL, &src_hints, &src_ai)) == 0)
        {
          if (bind(sockfd, src_ai->ai_addr, src_ai->ai_addrlen))
	    Log(4, "bind: %s", TCPERR());
	  freeaddrinfo(src_ai);
	}
        else
	  if (aiErr == EAI_FAMILY)
	    /* address family of target and bind address don't match */
	    continue;
	  else
	    /* otherwise just warn and don't bind() */
	    Log(2, "bind -- getaddrinfo: %s (%d)", gai_strerror(aiErr), aiErr);
      }
#ifdef HAVE_FORK
      if (config->connect_timeout)
      {
	signal(SIGALRM, alrm);
	alarm(config->connect_timeout);
      }
#endif
      if (connect (sockfd, ai->ai_addr, ai->ai_addrlen) == 0)
      {
#ifdef HAVE_FORK
	alarm(0);
#endif
	Log (4, "connected");
	sock_out = sockfd;
	dst_host = addrbuf;
	break;
      }

#ifdef HAVE_FORK
      if (errno == EINTR && config->connect_timeout)
	save_err = strerror (ETIMEDOUT);
      else
	save_err = TCPERR ();
      alarm(0);
#else
      save_err = TCPERR ();
#endif
      if (!binkd_exit)
      {
	Log (1, "connection to %s failed: %s", szDestAddr, save_err);
	bad_try (&node->fa, save_err, BAD_CALL, config);
      }
      del_socket(sockfd);
      soclose (sockfd);
      sockfd = INVALID_SOCKET;
    }
#ifdef HTTPS
    if (!use_proxy)
#endif
      freeaddrinfo(aiNodeHead);
#ifdef HTTPS
    if (sockfd != INVALID_SOCKET && use_proxy) {
      if (h_connect(sockfd, host, config, proxy, socks) != 0) {
        if (!binkd_exit)
          bad_try (&node->fa, TCPERR (), BAD_CALL, config);
        del_socket(sockfd);
        soclose (sockfd);
        sockfd = INVALID_SOCKET;
      }
      else if (port == config->oport) {
        char *pp;
        if( (pp = strchr(host, ':')) ){
          *pp = '\0';
        }
      }
    }
#endif
  }
#ifdef HTTPS
  if (use_proxy)
    freeaddrinfo(aiProxyHead);
#endif
#ifdef WITH_PERL
  xfree(hosts);
#ifdef HTTPS
  xfree(proxy);
  xfree(socks);
#endif
#endif

  if (sockfd == INVALID_SOCKET)
    return 0;

  protocol (sockfd, sock_out, node, NULL, dst_host, config);
  if (pid != -1)
  {
    del_socket(sock_out);
    close(sock_out);
#ifdef HAVE_WAITPID
    if (waitpid (pid, &rc, 0) == -1)
    {
      Log (1, "waitpid(%u) error: %s", pid, strerror(errno));
    }
    else
    {
      if (WIFSIGNALED(rc))
        Log (2, "process %u exited by signal %u", pid, WTERMSIG(rc));
      else
        Log (4, "rc(%u)=%u", pid, WEXITSTATUS(rc));
    }
#endif
    close(sockfd);
  }
  else
  {
    del_socket(sockfd);
    soclose (sockfd);
  }
  return 1;
}
Beispiel #28
0
void IO::OutputScheduler::ScheduleWrite(const IO::Socket& sock,
                                        const std::string& data) {
  Log::i("scheduling write on fd = " + std::to_string(sock.get_fd()));
  volatile std::lock_guard<std::mutex> schedule_lock(_scheduling_mutex);
  add_socket(sock, data);
}
int create_gateway(gateway_handle* handle, gateway_create_params *params)
{
	gateway_context *gateway = NULL;
	int return_value = 0;

	gateway = (gateway_context*)malloc(sizeof(gateway_context));
	if(NULL == gateway)
	{
		LOG_ERROR(("ERROR: Out of memory\n"));
		return (E_OUT_OF_MEMORY);
	}
	memset(gateway, 0, sizeof(gateway_context));

	gateway->client_count = 0;

	gateway->storage_file_pointer = fopen(params->storage_file_name, "w");
	if(!gateway->storage_file_pointer)
	{
		LOG_ERROR(("ERROR: Unable to open persistent storage file\n"));
		delete_gateway((gateway_handle)gateway);
		return E_FAILURE;
	}

	/* create network read thread */
	return_value = create_network_thread(&gateway->network_thread, params->gateway_ip_address);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Error in creating n/w read thread\n"));
		delete_gateway((gateway_handle)gateway);
		return (return_value);
	}

	/* create connection to server */
	return_value = create_socket(&gateway->server_socket_fd, params->gateway_ip_address, params->gateway_port_no);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Error in creating the socket\n"));
		delete_gateway((gateway_handle)gateway);
		return (return_value);
	}

	/* add socket to network read thread */
	return_value = add_socket(gateway->network_thread, gateway->server_socket_fd,  (void*)gateway, &read_callback);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: add_socket() failed\n"));
		delete_gateway((gateway_handle)gateway);
		return (return_value);
	}
	message msg;

	/* register device with gateway */
	msg.type = REGISTER;
	msg.u.s.type = BACK_TIER_GATEWAY;
	msg.u.s.ip_address = params->gateway_ip_address;
	msg.u.s.port_no = params->gateway_port_no;
	msg.u.s.area_id = "0";

	return_value = write_message(gateway->server_socket_fd, gateway->logical_clock, &msg);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Error in registering device\n"));
		return (E_FAILURE);
	}
	*handle = gateway;
	return (E_SUCCESS);
}
Beispiel #30
0
/*
  open the ldap server sockets
*/
static void ldapsrv_task_init(struct task_server *task)
{	
	char *ldapi_path;
#ifdef WITH_LDAPI_PRIV_SOCKET
	char *priv_dir;
#endif
	struct ldapsrv_service *ldap_service;
	NTSTATUS status;
	const struct model_ops *model_ops;

	switch (lp_server_role(task->lp_ctx)) {
	case ROLE_STANDALONE:
		task_server_terminate(task, "ldap_server: no LDAP server required in standalone configuration", 
				      false);
		return;
	case ROLE_DOMAIN_MEMBER:
		task_server_terminate(task, "ldap_server: no LDAP server required in member server configuration", 
				      false);
		return;
	case ROLE_DOMAIN_CONTROLLER:
		/* Yes, we want an LDAP server */
		break;
	}

	task_server_set_title(task, "task[ldapsrv]");

	/* run the ldap server as a single process */
	model_ops = process_model_startup(task->event_ctx, "single");
	if (!model_ops) goto failed;

	ldap_service = talloc_zero(task, struct ldapsrv_service);
	if (ldap_service == NULL) goto failed;

	ldap_service->task = task;

	ldap_service->tls_params = tls_initialise(ldap_service, task->lp_ctx);
	if (ldap_service->tls_params == NULL) goto failed;

	if (lp_interfaces(task->lp_ctx) && lp_bind_interfaces_only(task->lp_ctx)) {
		struct interface *ifaces;
		int num_interfaces;
		int i;

		load_interfaces(task, lp_interfaces(task->lp_ctx), &ifaces);
		num_interfaces = iface_count(ifaces);

		/* We have been given an interfaces line, and been 
		   told to only bind to those interfaces. Create a
		   socket per interface and bind to only these.
		*/
		for(i = 0; i < num_interfaces; i++) {
			const char *address = iface_n_ip(ifaces, i);
			status = add_socket(task->event_ctx, task->lp_ctx, model_ops, address, ldap_service);
			if (!NT_STATUS_IS_OK(status)) goto failed;
		}
	} else {
		status = add_socket(task->event_ctx, task->lp_ctx, model_ops, 
				    lp_socket_address(task->lp_ctx), ldap_service);
		if (!NT_STATUS_IS_OK(status)) goto failed;
	}

	ldapi_path = private_path(ldap_service, task->lp_ctx, "ldapi");
	if (!ldapi_path) {
		goto failed;
	}

	status = stream_setup_socket(task->event_ctx, task->lp_ctx,
				     model_ops, &ldap_stream_nonpriv_ops,
				     "unix", ldapi_path, NULL, 
				     lp_socket_options(task->lp_ctx), 
				     ldap_service);
	talloc_free(ldapi_path);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
			 ldapi_path, nt_errstr(status)));
	}

#ifdef WITH_LDAPI_PRIV_SOCKET
	priv_dir = private_path(ldap_service, task->lp_ctx, "ldap_priv");
	if (priv_dir == NULL) {
		goto failed;
	}
	/*
	 * Make sure the directory for the privileged ldapi socket exists, and
	 * is of the correct permissions
	 */
	if (!directory_create_or_exist(priv_dir, geteuid(), 0750)) {
		task_server_terminate(task, "Cannot create ldap "
				      "privileged ldapi directory", true);
		return;
	}
	ldapi_path = talloc_asprintf(ldap_service, "%s/ldapi", priv_dir);
	talloc_free(priv_dir);
	if (ldapi_path == NULL) {
		goto failed;
	}

	status = stream_setup_socket(task->event_ctx, task->lp_ctx,
				     model_ops, &ldap_stream_priv_ops,
				     "unix", ldapi_path, NULL,
				     lp_socket_options(task->lp_ctx),
				     ldap_service);
	talloc_free(ldapi_path);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("ldapsrv failed to bind to %s - %s\n",
			 ldapi_path, nt_errstr(status)));
	}

#endif
	return;

failed:
	task_server_terminate(task, "Failed to startup ldap server task", true);
}