--- libaitio/src/sock.c 2013/08/26 23:30:27 1.2.2.1 +++ libaitio/src/sock.c 2013/09/02 11:56:32 1.4 @@ -3,7 +3,7 @@ * by Michael Pounov * * $Author: misho $ -* $Id: sock.c,v 1.2.2.1 2013/08/26 23:30:27 misho Exp $ +* $Id: sock.c,v 1.4 2013/09/02 11:56:32 misho Exp $ * ************************************************************************** The ELWIX and AITNET software is distributed under the following @@ -202,6 +202,39 @@ ioUpSocket(sock_t * __restrict s, void *arg) return ret; } +static void +thrCliClean(void *arg) +{ + sock_cli_t *cli = (sock_cli_t*) arg; + sock_t *s = (sock_t*) cli->cli_parent; + + if (s->sock_type == SOCK_STREAM) { + shutdown(cli->cli_fd, SHUT_RDWR); + close(cli->cli_fd); + } + AIT_FREE_VAL(&cli->cli_buf); + + pthread_mutex_lock(&s->sock_mtx); + TAILQ_REMOVE(&s->sock_cli, cli, cli_node); + pthread_mutex_unlock(&s->sock_mtx); + + e_free(cli); +} + +static void * +io_thrCliWrapper(void *arg) +{ + void *ret; + sock_cli_t *cli = (sock_cli_t*) arg; + + pthread_cleanup_push(thrCliClean, arg); + + ret = cli->cli_func(cli); + + pthread_cleanup_pop(42); + pthread_exit(ret); +} + /* * ioAcceptSocket() - Accept clients * @@ -216,8 +249,9 @@ ioAcceptSocket(sock_t * __restrict s, sock_cb_t f, voi struct pollfd pfd[1]; socklen_t salen; sockaddr_t sa; - int c; + int c, rlen; sock_cli_t *cli; + u_char buf[BUFSIZ] = { [0 ... BUFSIZ - 1] = 0 }; if (!s || s->sock_role == IO_SOCK_ROLE_CLIENT || !f) return -1; @@ -225,21 +259,34 @@ ioAcceptSocket(sock_t * __restrict s, sock_cb_t f, voi pfd->fd = s->sock_fd; pfd->events = POLLIN | POLLPRI; do { - if (poll(pfd, 1, -1) < 1) { + if (poll(pfd, 1, -1) < 1 || + pfd->revents & (POLLNVAL | POLLHUP | POLLERR)) { + if (errno == EINTR) + continue; LOGERR; return -1; } else salen = sizeof sa.ss; - if ((c = accept(s->sock_fd, &sa.sa, &salen))) { - LOGERR; - return -1; + if (s->sock_type == SOCK_STREAM) { + if ((c = accept(s->sock_fd, &sa.sa, &salen)) == -1) { + LOGERR; + return -1; + } + } else { + if ((rlen = recvfrom(s->sock_fd, buf, sizeof buf, MSG_PEEK, + &sa.sa, &salen)) == -1) { + LOGERR; + return -1; + } else + c = s->sock_fd; } cli = e_malloc(sizeof(sock_cli_t)); if (!cli) { io_SetErr(elwix_GetErrno(), "%s", elwix_GetError()); - close(c); + if (s->sock_type == SOCK_STREAM) + close(c); return -1; } else memset(cli, 0, sizeof(sock_cli_t)); @@ -251,15 +298,18 @@ ioAcceptSocket(sock_t * __restrict s, sock_cb_t f, voi memcpy(&cli->cli_addr, &sa, sizeof cli->cli_addr); AIT_SET_BUFSIZ(&cli->cli_buf, 0, AIT_LEN(&s->sock_buf)); - if (pthread_create(&cli->cli_tid, NULL, (void*(*)(void*)) f, cli) == -1) { + if (pthread_create(&cli->cli_tid, NULL, io_thrCliWrapper, cli) == -1) { LOGERR; - close(c); + if (s->sock_type == SOCK_STREAM) + close(c); AIT_FREE_VAL(&cli->cli_buf); e_free(cli); return -1; } else { pthread_detach(cli->cli_tid); + pthread_mutex_lock(&s->sock_mtx); TAILQ_INSERT_TAIL(&s->sock_cli, cli, cli_node); + pthread_mutex_unlock(&s->sock_mtx); } } while (42);