-
-/**
- * Create a tcp socket, bind it and listen on the given port.
- *
- * \param port The tcp port to listen on.
- *
- * \return The file descriptor of the created socket, negative on errors.
- *
- * \sa get_stream_socket()
- * \sa setsockopt(2)
- * \sa bind(2)
- * \sa listen(2)
- */
-int tcp_listen(int port)
-{
- struct sockaddr_in my_addr;
- int fd, ret = get_stream_socket(AF_INET);
-
- if (ret < 0)
- return ret;
- fd = ret;
- ret = 1;
- ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &ret, sizeof(int));
- if (ret < 0) {
- ret = -ERRNO_TO_PARA_ERROR(errno);
- goto err;
- }
- init_sockaddr(&my_addr, port, NULL);
- ret = bind(fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
- if (ret < 0) {
- ret = -ERRNO_TO_PARA_ERROR(errno);
- goto err;
- }
- ret = listen(fd, BACKLOG);
- if (ret < 0) {
- ret = -ERRNO_TO_PARA_ERROR(errno);
- 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;
-}