-
-/** how many pending connections queue will hold */
-#define BACKLOG 10
-
-/**
- * create a socket, bind it and listen
- *
- * \param port the tcp port to listen on
- *
- * \return The file descriptor of the created socket, negative
- * on errors.
- *
- * \sa get_socket()
- * \sa setsockopt(2)
- * \sa bind(2)
- * \sa listen(2)
- */
-int init_tcp_socket(int port)
-{
- struct sockaddr_in my_addr;
- int fd, ret = get_socket();
-
- if (ret < 0)
- return ret;
- fd = ret;
- ret = setserversockopts(fd);
- if (ret < 0)
- goto err;
- init_sockaddr(&my_addr, port, NULL);
- ret = -E_BIND;
- if (bind(fd, (struct sockaddr *)&my_addr,
- sizeof(struct sockaddr)) == -1) {
- PARA_CRIT_LOG("bind error: %s\n", strerror(errno));
- goto err;
- }
- ret = -E_LISTEN;
- if (listen(fd, BACKLOG) == -1)
- goto err;
- PARA_INFO_LOG("listening on port %d, fd %d\n", port, fd);
- return fd;
-err:
- close(fd);
- return ret;
-}
-
-/**
- * receive a buffer and check for a pattern
- *
- * \param fd the file descriptor to receive from
- * \param pattern the expected pattern
- * \param bufsize the size of the internal buffer
- *
- * \return Positive if \a pattern was received, negative otherwise.
- *
- * This function creates a buffer of size \a bufsize and tries
- * to receive at most \a bufsize bytes from file descriptor \a fd.
- * If at least \p strlen(\a pattern) bytes were received, the beginning of
- * the received buffer is compared with \a pattern, ignoring case.
- *
- * \sa recv_buffer()
- * \sa strncasecmp(3)
- */
-int recv_pattern(int fd, const char *pattern, size_t bufsize)
-{
- size_t len = strlen(pattern);
- char *buf = para_malloc(bufsize + 1);
- int ret = -E_RECV_PATTERN, n = recv_buffer(fd, buf, bufsize);
-
- if (n < len)
- goto out;
- if (strncasecmp(buf, pattern, len))
- goto out;
- ret = 1;
-out:
- if (ret < 0) {
- PARA_NOTICE_LOG("n = %d, did not receive pattern '%s'\n", n, pattern);
- if (n > 0)
- PARA_NOTICE_LOG("recvd: %s\n", buf);
- }
- free(buf);
- return ret;
-}