Пример #1
0
brain_stroke_server::brain_stroke_server(QObject *parent) :
    QObject(parent){
    connect(&server, SIGNAL(newConnection()), this,SLOT(accept_new_connection()));
    server.listen(QHostAddress::Any, 8888);
    calculate_flag = false;
    puts("listen");
}
Пример #2
0
int
network_process_io(int timeout)
{
    nhandle *h, *hnext;
    nlistener *l;

    mplex_clear();
    for (l = all_nlisteners; l; l = l->next)
	mplex_add_reader(l->fd);
    for (h = all_nhandles; h; h = h->next) {
	if (!h->input_suspended)
	    mplex_add_reader(h->rfd);
	if (h->output_head)
	    mplex_add_writer(h->wfd);
    }
    add_registered_fds();

    if (mplex_wait(timeout))
	return 0;
    else {
	for (l = all_nlisteners; l; l = l->next)
	    if (mplex_is_readable(l->fd))
		accept_new_connection(l);
	for (h = all_nhandles; h; h = hnext) {
	    hnext = h->next;
	    if ((mplex_is_readable(h->rfd) && !pull_input(h))
		|| (mplex_is_writable(h->wfd) && !push_output(h))) {
		server_close(h->shandle);
		close_nhandle(h);
	    }
	}
	check_registered_fds();
	return 1;
    }
}
static gboolean
server_cb (GIOChannel *source, GIOCondition condition, gpointer data)
{
	BaconMessageConnection *conn = (BaconMessageConnection *)data;
	char *message, *subs, buf;
	int cd, rc, offset;
	gboolean finished;

	offset = 0;
	if (conn->is_server && conn->fd == g_io_channel_unix_get_fd (source)) {
		accept_new_connection (conn);
		return TRUE;
	}
	message = g_malloc (1);
	cd = conn->fd;
	rc = read (cd, &buf, 1);
	while (rc > 0 && buf != '\n')
	{
		message = g_realloc (message, rc + offset + 1);
		message[offset] = buf;
		offset = offset + rc;
		rc = read (cd, &buf, 1);
	}
	if (rc <= 0) {
		g_io_channel_shutdown (conn->chan, FALSE, NULL);
		g_io_channel_unref (conn->chan);
		conn->chan = NULL;
		close (conn->fd);
		conn->fd = -1;
		g_free (message);
		conn->conn_id = 0;

		return FALSE;
	}
	message[offset] = '\0';

	subs = message;
	finished = FALSE;

	while (finished == FALSE && *subs != '\0')
	{
		if (conn->func != NULL)
			(*conn->func) (subs, conn->data);

		subs += strlen (subs) + 1;
		if (subs - message >= offset)
			finished = TRUE;
	}

	g_free (message);

	return TRUE;
}
Пример #4
0
int main(void)
{
	unsigned int i;
	int sockfd=0;
	int client_socks[MAX_CLIENTS];

	fd_set reading_set;
	int select_max_nfds=0;

	int ret;

	memset(&client_socks, -1, sizeof(client_socks[0])*MAX_CLIENTS);

	sockfd=listen_newsocket(PORT);

	FD_ZERO(&reading_set);
	FD_SET(sockfd, &reading_set);
	select_max_nfds=sockfd;

	while(1) {
		/* Make sure we always wait for new connections at sockfd */
		FD_SET(sockfd, &reading_set);
		select_max_nfds = find_max(client_socks, MAX_CLIENTS);
		select_max_nfds = (select_max_nfds>sockfd) ? select_max_nfds : sockfd;

		ret=select(select_max_nfds+1, &reading_set, NULL, NULL, NULL);

		/* Check if there's a new connection at sockfd */
		if(FD_ISSET(sockfd, &reading_set)) {
			ret=accept_new_connection(sockfd, client_socks, MAX_CLIENTS);
			if(ret>=0) {
				FD_SET(client_socks[ret], &reading_set);
			}
		}

		for(i=0; i<MAX_CLIENTS; i++) {
			if(client_socks[i]>=0 && FD_ISSET(client_socks[i], &reading_set)) {
				ret=handle_reading_slot(client_socks[i]);
				if(!ret) {
					FD_CLR(client_socks[i], &reading_set);
					close(client_socks[i]);
					client_socks[i]=-1;
				} else {
					FD_SET(client_socks[i], &reading_set);
				}
			} else {
				FD_SET(client_socks[i], &reading_set);
			}
		}
	}
}
Пример #5
0
int main(int argc, char *argv[])
{
    int s, ns;
    int semaphore_id;
    int shared_memory_id = 0;
    uint16_t port;
    pid_t pid;
    struct sockaddr_in client;
    char *tmp_shm_addr;
    shm_t *g_shm;

    check_args(&argc, argv, 0);

    port = (uint16_t) atoi(argv[1]);
    create_tcp_socket(&s, port);

    semaphore_id = semaphore_new(SEM_KEY);
    v(semaphore_id, 1);

    shared_memory_id = create_shared_memory(SHM_KEY);
    tmp_shm_addr = associate_shared_memory(shared_memory_id);
    g_shm = (shm_t *) tmp_shm_addr;


    while (true) {

        accept_new_connection(&s, &ns, &client);

        if ((pid = fork()) == 0)

            shandler(&ns, semaphore_id, client, g_shm);

        else {
            if (pid > 0)

                fprintf(stderr, "#%d# Father - Created child process: %d\n", getpid(), pid);

            else {
                fprintf(stderr, "The fork() function has failed: %s!\n", strerror(errno));
                shared_memory_destroy(shared_memory_id);
                semaphore_destroy(semaphore_id);
                exit(EXIT_FAILURE);
            }
        }
    }

    shared_memory_destroy(shared_memory_id);
    semaphore_destroy(semaphore_id);

    exit(EXIT_SUCCESS);
}
Пример #6
0
static void server_cb(int fd, void* data) {
	SipcServerPrivate* priv = (SipcServerPrivate*)data;

	if(priv->fd == fd) {
		accept_new_connection(priv);
		return;
	}

	char c;
	int  nc, i = 0;
	char buf[MSG_LEN_MAX];
	memset(buf, 0, sizeof(buf));

	nc = ::read(fd, &c, 1);
	while(nc > 0 && c != '\n' && i < MSG_LEN_MAX) {
		buf[i] = c;
		i = i + nc;
		nc = ::read(fd, &c, 1);
	}

	if(nc <= 0) {
		ConnectionListIter it = priv->accepted_connections.begin();
		ConnectionListIter it_end = priv->accepted_connections.end();

		for(; it != it_end; ++it) {
			if((*it)->fd == fd) {
				listener_remove_fd(fd);
				close(fd);
				free((*it)->path);
				delete *it;
				priv->accepted_connections.erase(it);
				break;
			}
		}

		return;
	}

	buf[i] = '\0';

	if(priv->cb)
		priv->cb(buf, priv->arg);
}
Пример #7
0
static void
uim_helper_server_process_connection(int server_fd)
{
    int i;
    fd_set readfds, writefds;

    while (1) {
        /* Copy readfds from s_fdset_read/s_fdset_write because select removes
           readble/writable fd from readfds/writefds */
        memcpy(&readfds, &s_fdset_read, sizeof(fd_set));
        memcpy(&writefds, &s_fdset_write, sizeof(fd_set));

        /* call select(), waiting until a file descriptor became readable */
        if (select(s_max_fd + 1, &readfds, &writefds, NULL, NULL) <= 0) {
            perror("uim-helper_server select(2) failed");
            sleep(3);
            continue;
        }

        /* for accept new connection */
        if (FD_ISSET(server_fd, &readfds)) {
            uim_bool accepted;
            accepted = accept_new_connection(server_fd);
            if (accepted == UIM_FALSE) {
                /* acception failed, go next loop without message processing. */
                continue;
            }
        } else {
            /* check data to write and from clients reached */
            for (i = 0; i < nr_client_slots; i++) {
                if (clients[i].fd != -1 && FD_ISSET(clients[i].fd, &writefds))
                    write_message(&clients[i]);

                if (clients[i].fd != -1 && FD_ISSET(clients[i].fd, &readfds))
                    read_message(&clients[i]);
            }
        }

        if (!check_session_alive())
            return;
    }
}
Пример #8
0
void            psuedo_person(player * p, char *str)
{
   accept_new_connection();
}
Пример #9
0
void mainloop(int socket) {
    uint8_t butts[2048];
    int res, i;
    size_t rcvd;
    pid_t build;
    enum message_type msg_type;
    BuildRequest* msg;
    /* Allocate some handlers on the heap */
    fd_list **subscriptions;
    /* Be super pessimistic about how many pids we might see */
#define ___MAX_PIDS pow(sizeof(pid_t), 8)
    subscriptions = malloc(sizeof(fd_list) * ___MAX_PIDS);
    memset(subscriptions, 0, ___MAX_PIDS);
    fd_list *new_sub;
    fd_list *sub_node;
#undef ___MAX_PIDS
    /* Setup FD sets for monitoring */
    fd_set fds;
    fd_set rfds, wfds, efds;
    FD_ZERO(&fds); FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&efds);

    FD_SET(socket, &fds);
    /* Block SIGCHLD set setup signalfd for monitoring */
    sigset_t signals;
    sigemptyset(&signals);
    sigaddset(&signals, SIGCHLD);
    /* Block sigchld */
    sigprocmask(SIG_BLOCK, &signals, NULL);
    /* Setup a signalfd */
#ifdef __linux
    int sigfd = signalfd(-1, &signals, SFD_NONBLOCK |
                                       SFD_CLOEXEC);
    struct signalfd_siginfo child;
    size_t child_read;
#elif __APPLE__
    int sigfd = kqueue();
    int kq_status;
    struct kevent ke, child;
    EV_SET(&ke, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, NULL);
    i = kevent(sigfd, &ke, 1, NULL, 0, NULL);
    if (i == -1) {
        warn("Couldn't set up sigfd\n");
        return;
    }
#endif
    /* Add sigfd to the main set */
    FD_SET(sigfd, &fds);
    /* Structure to read children into */
    pid_t child_pid;
    int child_status;

    while(1) {
        FD_ZERO(&rfds); FD_ZERO(&wfds); FD_ZERO(&efds);

        memcpy(&rfds, &fds, sizeof(fd_set));
        memcpy(&wfds, &fds, sizeof(fd_set));
        memcpy(&efds, &fds, sizeof(fd_set));

        res = select(FD_SETSIZE, &rfds, NULL, &efds, NULL);
        info("got %d fds\n", res);
        if (res == 0) {
            error("No fd's returned from select\n");
        } else if (res == -1) {
            warn("select call interrupted");
            break;
            // We probably saw a signal. Defer signals and do some stuff.
        } else {
            for (i = 0; i < FD_SETSIZE; ++i) {
                if (FD_ISSET(i, &efds)) {
                    debug("%d has made a whoopsie\n", i);
                }
                if (!FD_ISSET(i, &rfds))
                    continue;

                if (i == socket) {
                    accept_new_connection(socket, &fds);
                    info("Accepted a new connection\n");
                } else if (i == sigfd) {
                    child_status = 0;
#ifdef __linux
                    child_read = read(sigfd, &child, sizeof(child));
                    switch(child_read) {
                        case 0:
                        case -1:
                            warn("Couldn't read from signalfd");
                            continue;
                        default:
                            info("Recieved signal %d from %d\n",
                                    child.ssi_signo,
                                    child.ssi_pid);

                    }
                    if (child.ssi_signo == SIGCHLD) {
                        child_pid = waitpid(child.ssi_pid, &child_status, 0);
                        child_status = WEXITSTATUS(child_status);
                        info("Child %d exited with status %d\n", child_pid, child_status);
                        notify(subscriptions, child_pid, child_status);
                    }
#elif __APPLE__
                    kq_status = kevent(sigfd, NULL, 0, &child, 1, NULL);
                    if (kq_status == -1) {
                        warn("kevent read failed\n");
                        return;
                    }
                    info("Recieved signal %ld\n", child.ident);
                    child_pid = wait(&child_status);
                    child_status = WEXITSTATUS(child_status);
                    info("Child %d exited with status %d\n", child_pid, child_status);
                    notify(subscriptions, child_pid, child_status);
#endif
                } else {
                    // Check if the socket is still alive
                    if (recv(i, butts, 1, MSG_PEEK) < 1) {
                        close(i);
                        FD_CLR(i, &fds);
                        continue;
                    }

                    msg_type = load_message_type(i);
                    switch(msg_type) {
                        case MSG_ERROR:
                            /* Connection is irreperably damaged */
                            error("Couldn't decode message type\n");
                            close(i);
                            FD_CLR(i, &fds);
                            break;
                        case MSG_BUILD_REQUEST:
                            msg = load_request(i);
                            if (!msg) {
                                info("Got a null request from %d\n", i);
                                continue;
                            }
                            info("new payload\n");
                            info(" command  : %s\n", msg->command);
                            info(" workspace: %s\n", msg->workspace);
                            info(" priority : %d\n", msg->priority);
                            info("--\n");
                            if (init_worktree2(msg->workspace) != 0) {
                                /* TODO: Actually bail out of this */
                                error("Couldn't create worktree %s\n", msg->workspace);
                            }
                            build = start_build(msg);
                            info("Started a new build from %d with pid %d\n", i, build);
                            build_request__free_unpacked(msg, NULL);
                            /* Implicitly subscribe whoever kicked off the build */
                            new_sub = malloc(sizeof(fd_list));
                            new_sub->fd = i;
                            new_sub->next = NULL;
                            if (subscriptions[build] == NULL) {
                                subscriptions[build] = new_sub;
                            } else {
                                sub_node = subscriptions[build];
                                while (sub_node != NULL) {
                                    sub_node = sub_node->next;
                                }
                                sub_node->next = new_sub;
                            }
                            /* TODO: Write out the pid + a nonce to the client.
                             * TODO: Implement an implicit subscribe flag in the build request
                             */
                            break;
                        default:
                            error("Unknown message type %d\n", msg_type);
                    }
                }
            }
        }
    }
}
Пример #10
0
int
walk_connection_list(uber_state_t *uber_state) {

  connection_t *temp_connection = uber_state->connection_list;
  connection_t *del_connection;

  int did_something = 0;
  int ret;

  while(temp_connection) {
    switch (temp_connection->flags) {
    case CONNECTION_LISTENING: 
      if (debug > 2) {
	fprintf(stderr,
		"connection at %p is a LISTEN connection\n",temp_connection);
      }
      /* only bother doing an accept on the blind walk of the list
	 when we've done some transactions.  otherwise, the drop into
	 the select loop will catch things for us.  we ass-u-me that
	 for the test the actual connection rate is << the transaction
	 rate.  otherwise we'll need some additional heuristics -
	 perhaps domething involving how long it has been since an
	 accept() or how many consecutive accepts without a new
	 connection we've made. */
      if (uber_state->rdwr_since_accept > 1000) {
	ret = accept_new_connection(uber_state,temp_connection);
	/* did we get one, and are there any more? */
	while (ret > 0) {
	  /* if we came-in here, it means we got a connection above, so
	     we did do something.  it probably isn't worth the added
	     conditional to only set did_something once... */
	  did_something = 1;
	  ret = accept_new_connection(uber_state,temp_connection);
	}
      }
      temp_connection = temp_connection->next;
      break;
    case CONNECTION_READING:
      if (debug > 2) {
	fprintf(stderr,
		"connection at %p is a READING connection\n",temp_connection);
      }
      ret = read_on_connection(uber_state,temp_connection);
      if (ret > 0) did_something = 1;
      temp_connection = temp_connection->next;
      break;
    case CONNECTION_WRITING:
      if (debug > 2) {
	fprintf(stderr,
		"connection at %p is a WRITING connection\n",temp_connection);
      }
      ret = write_on_connection(uber_state,temp_connection);
      if (ret > 0) did_something = 1;
      temp_connection = temp_connection->next;
      break;
    case CONNECTION_CLOSING:
      /* ok, just how should we deal with this then? */
      del_connection = temp_connection;
      temp_connection = temp_connection->next;
      remove_old_connection(uber_state, del_connection);
      break;
    }
  }
  return did_something;
}
Пример #11
0
int
wait_for_events_and_walk(uber_state_t *uber_state) {
  struct timeval timeout;
  event_state_select_t *event_state = uber_state->event_state;

  fd_set loc_readfds;
  fd_set loc_writefds;

  connection_t *temp_connection;

  int ret;
  int i;
  int did_something;

  timeout.tv_sec = 2;
  timeout.tv_usec = 0;

  if (debug) {
    fprintf(stderr,"about to go into select\n");
  }

  /* rather blunt, but should be effective for now */
  memcpy(&loc_readfds, &(event_state->readfds),sizeof(fd_set));
  memcpy(&loc_writefds, &(event_state->writefds),sizeof(fd_set));

  ret = select(event_state->maxfd + 1,
	       &loc_readfds,
	       &loc_writefds,
	       NULL,   /* ignore exception for now */
	       &timeout);

  if (debug) {
    fprintf(stderr,
	    "select returned %d errno %d minfd %d maxfd %d\n",
	    ret,
	    errno,
	    event_state->minfd,
	    event_state->maxfd);
  }

  if (ret > 0) {
    /* first, the reads and accepts */
    for (i = event_state->minfd; i <= event_state->maxfd; i++) {
      if (FD_ISSET(i,&loc_readfds)) {
	temp_connection = find_connection(uber_state,i);
	if (debug) {
	  fprintf(stderr,
		  "fd %d is readable on connection %p\n",
		  i,
		  temp_connection);
	}
	/* is this our listen endpoint or something else? */
	if (temp_connection->flags & CONNECTION_LISTENING ) {
	  /* accept a connection */
	  SOCKET new_sock;
	  new_sock = accept_new_connection(uber_state,
					   temp_connection);
	  if (INVALID_SOCKET != new_sock) {
	    /* on the very good chance that this new connection is for
	       an FD higher than our listen endpoint, we set
	       loc_readfds so we go ahead and try to read from the new
	       connection when we get to that point in our walk of the
	       fdset returned from select(). */
	    FD_SET(new_sock,&loc_readfds);
	  }
	  /* if we got one connection, we should see about draining
	     the accept queue, eventually module some limit on the
	     number of concurrent connections we will allow */
	  while (new_sock >= 0) {
	    new_sock = accept_new_connection(uber_state,
					     temp_connection);
	    if (INVALID_SOCKET != new_sock) {
	      /* on the very good chance that this new connection is for
		 an FD higher than our listen endpoint, we set
		 loc_readfds so we go ahead and try to read from the new
		 connection when we get to that point in our walk of the
		 fdset returned from select(). */
	      FD_SET(new_sock,&loc_readfds);
	    }
	  }
	}
	else if (temp_connection->flags & CONNECTION_READING) {
	  /* read some bytes */
	}
	else {
	  /* something screwy happened */
	  fprintf(stderr,
		  "YO, we got readable on connection %p but we weren't reading\n",
		  temp_connection);
	}
      }
    }
    
    /* now the writes */
    for (i = event_state->minfd; i <= event_state->maxfd; i++) {
      if (FD_ISSET(i,&loc_writefds)) {
	temp_connection = find_connection(uber_state,i);
	fprintf(stderr,
		"fd %d is writable on connection %p\n",i,temp_connection);
      }
    }
  }

  return 0;
}
Пример #12
0
/*
 * Function     : main
 * Description  : entry point
 * Input params : argc, argv
 * Return       : void
 *
 */
int main(int argc, char* argv[])
{
    int fdmax;
    int fd = 0;

    int channel = INVALID_CHANNEL;
    int do_standalone_scan = FALSE;
    
    int optc;
    char *radio_ifname  = NULL;
    char *dev_ifname    = NULL;

    fd_set  master;
    fd_set  read_fds;

    ath_ssd_inet_t *pinet = GET_ADDR_OF_INETINFO(pinfo);
    ath_ssd_nlsock_t *pnl = GET_ADDR_OF_NLSOCKINFO(pinfo);

    /* use TCP by default */
    sock_type_t sock_type = SOCK_TYPE_UDP;

    while ((optc = getopt(argc, argv, "adc:gHhi:j:Tts:")) != -1) {
        switch (optc) {
            case 'a':
                pinfo->current_band = BAND_5GHZ;
                break;
            case 'c':
                pinfo->log_mode = atoi(optarg);
                break;    
            case 'd':
                debug = TRUE;
                break;
            case 'g':
                pinfo->current_band = BAND_2GHZ;
                break;
            case 'T':
            case 't':
                sock_type = SOCK_TYPE_TCP;
                break;
            case 'h':
            case 'H':
                print_usage();
                break;
            case 's':
                channel = atoi(optarg);
                if ((channel < 0 ) || (channel > CHANNEL_11)) {
                    print_usage();
                }
                do_standalone_scan = TRUE;
                break;
            case 'i':
                radio_ifname = optarg;
                break;
            case 'j':
                dev_ifname = optarg;
                break;
            case '?':
                if ((optopt == 's') || (optopt == 'i') || (optopt == 'j') || (optopt == 'c')) {
                    fprintf(stderr, "Option -%c requries an argument.\n", optopt);
                } else {
                    fprintf(stderr, "Unknown option '-%c'.\n", optopt);
                }
                exit(EXIT_FAILURE);
            default:
                break;
        }
    }

    /* init the socket type */
    pinfo->sock_type = sock_type;

    /* init the dwell interval */
    pinfo->dwell_interval = CHANNEL_NORMAL_DWELL_INTERVAL;

    /* init the current channel list */
    if (IS_BAND_5GHZ(pinfo)) {
        pinfo->channel_list = dot11a_channels;
        pinfo->max_channels = ARRAY_LEN(dot11a_channels);
    } else {
        pinfo->channel_list = dot11g_channels;
        pinfo->max_channels = ARRAY_LEN(dot11g_channels);
    }

    /* save the interface name */
    if (radio_ifname) {
        pinfo->radio_ifname = radio_ifname;
    } else {
        pinfo->radio_ifname = DEFAULT_RADIO_IFNAME;
    }

    if (dev_ifname) {
        pinfo->dev_ifname = dev_ifname;
    } else {
        pinfo->dev_ifname = DEFAULT_DEV_IFNAME;
    }

    if (CONFIGURED_SOCK_TYPE(pinfo) == SOCK_TYPE_TCP) {
        /* init TCP socket interface */
        if (init_inet_sockinfo(pinfo) == FAILURE) {
            exit(EXIT_FAILURE);
        }
    }
    else if (CONFIGURED_SOCK_TYPE(pinfo) == SOCK_TYPE_UDP) {
        /* init UDP socket interface */
        if (init_inet_dgram_sockinfo(pinfo) == FAILURE) {
            exit(EXIT_FAILURE);
        }
    } else {
        info("invalid socket type");
        exit(EXIT_FAILURE);
    }

    if (init_nl_sockinfo(pinfo) == FAILURE) {
        exit(EXIT_FAILURE);
    }

    FD_ZERO(&master);
    FD_ZERO(&read_fds);

    FD_SET(pnl->spectral_fd, &master);
    FD_SET(pinet->listener, &master);

    fdmax = (pinet->listener > pnl->spectral_fd)?pinet->listener:pnl->spectral_fd;

    signal(SIGINT, signal_handler);
    signal(SIGALRM, signal_handler);
    signal(SIGCHLD, signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGHUP, signal_handler);

    info("server (built at %s %s )", __DATE__, __TIME__);
    info("interface     : %s", pinfo->radio_ifname);
    info("current band  : %s", (pinfo->current_band == BAND_5GHZ)?"5GHz ":"2.4GHz ");

    if (do_standalone_scan) {
        start_standalone_spectral_scan(pinfo, channel);
    }

    for (;;) {

        read_fds = master;

        if (select(fdmax + 1, &read_fds, NULL, NULL, NULL) == -1) {
                continue;
        }

        for (fd = 0; fd <= fdmax; fd++) {
            if (FD_ISSET(fd, &read_fds)) {
                if (fd ==  pinet->listener ) {

                    if (CONFIGURED_SOCK_TYPE(pinfo) == SOCK_TYPE_UDP) {
                        if (handle_client_data(pinfo, fd) == -1) {
                            cleanup(pinfo);
                            exit(EXIT_FAILURE);
                        }
                    } else if (CONFIGURED_SOCK_TYPE(pinfo) == SOCK_TYPE_TCP) {
                        if (accept_new_connection(pinfo)) {
                            FD_SET(pinet->client_fd, &master);
                            fdmax = (pinet->client_fd > fdmax)?pinet->client_fd:fdmax;
                        }
                    }
                }
                else if (fd ==  pnl->spectral_fd) {
                        if (handle_spectral_data(pinfo) == FAILURE) {
                            cleanup(pinfo);
                            exit(EXIT_FAILURE);
                        }
                }
                else if ((fd == pinet->client_fd) &&
                         (CONFIGURED_SOCK_TYPE(pinfo) == SOCK_TYPE_TCP)) {
                        if (handle_client_data(pinfo, fd ) == -1) {
                            cleanup(pinfo);
                            exit(EXIT_FAILURE);
                        }
                }
            }
        }
    }
    return 0;
}
Пример #13
0
static void
start_epoll(void)
{
	int ret;
	int count;
	int reuse = -1;	
	int opts;
	struct epoll_event new_event;
	struct sockaddr_in listen_addr;
	int listen_fd;

	epl_fd = epoll_create(MAX_CONNECTION);
	if (epl_fd < 0) {
		return;
	}

	/* listen */
	listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	if (-1 == listen_fd) {
		syslog(LOG_ERR, "socket failed : %s\n", strerror(errno));
		goto err_exit;
	}

	/* set port reuse */
	ret = setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
	if (ret < 0) {
		syslog(LOG_ERR, "setsockopt set reuse : %s\n", strerror(errno));
		goto err_exit;
	}

	/* set nonblocking */
	opts = fcntl(listen_fd, F_GETFL);
	if (opts < 0) {
		syslog(LOG_ERR, "fcntl F_GETFL failed : %s\n", strerror(errno));
		goto err_exit;
	}

	opts = opts | O_NONBLOCK;

	ret = fcntl(listen_fd, F_SETFL, opts);
	if (ret < 0) {
		syslog(LOG_ERR, "fcntl F_SETFL failed : %s\n", strerror(errno));
		goto err_exit;
	}

	/* bind */
	bzero(&listen_addr, sizeof(listen_addr));
	listen_addr.sin_family = AF_INET;
	listen_addr.sin_port = htons(LISTEN_PORT);
	listen_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	ret = bind(listen_fd, (struct sockaddr*)&listen_addr, sizeof(listen_addr));
	if (ret < 0) {
		syslog(LOG_ERR, "bind failed : %s\n", strerror(errno));
		goto err_exit;
	}

	/* listen */
	ret = listen(listen_fd, MAX_CONNECTION);
	if (ret < 0) {
		syslog(LOG_ERR, "listen failed : %s\n", strerror(errno));
		goto err_exit;
	}

	/* add epoll event */
	new_event.data.fd = listen_fd;
	new_event.events = EPOLLIN;
	ret = epoll_ctl(epl_fd, EPOLL_CTL_ADD, listen_fd, &new_event);
	if (ret != 0) {
		syslog(LOG_ERR, "epoll_ctl add failed : %s\n", strerror(errno));
		goto err_exit;
	}

	/* start waiting for event */
	while (1) {
		int i;
		count = epoll_wait(epl_fd, s_events, MAX_CONNECTION, -1);

		for (i = 0; i < count; i++) {
			const int cur_fd = s_events[i].data.fd;

			/* new connection, from trader or controller, or bad guy... */
			if (cur_fd == listen_fd) {
				ret = accept_new_connection(listen_fd);
			}
			else {
				/* close the connection */
				if ((s_events[i].events & EPOLLRDHUP) && (s_events[i].events & EPOLLIN)) {
					ret = close_connection(cur_fd);
				}
				/* incoming data */
				else if (s_events[i].events & EPOLLIN) {
					ret = receive_data(cur_fd);
				}
				/* epoll error */
				else if ((s_events[i].events & EPOLLERR) || (s_events[i].events & EPOLLHUP)) {
					syslog(LOG_ERR, "epoll error!\n");
				}
			}
		}
	}

	return;
err_exit:
	return;
}