2 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * @author Aleksander Zdyb <a.zdyb@samsung.com>
20 * @brief Helpers for Unix Domain Sockets
25 #include <sys/socket.h>
28 #include <dpl/test/test_runner.h>
33 namespace UDSHelpers {
35 int createServer(const struct sockaddr_un *sockaddr) {
36 int sock = socket(AF_UNIX, SOCK_STREAM, 0);
37 RUNNER_ASSERT_ERRNO_MSG(sock >= 0, "socket failed");
39 SockUniquePtr sockPtr(&sock);
41 int bindResult = bind(sock, (const struct sockaddr*) sockaddr, sizeof(struct sockaddr_un));
42 RUNNER_ASSERT_ERRNO_MSG(bindResult == 0, "bind failed");
44 int listenResult = listen(sock, 1);
45 RUNNER_ASSERT_ERRNO_MSG(listenResult == 0, "listen failed");
51 int createClient(const struct sockaddr_un *sockaddr) {
52 int sock = socket(AF_UNIX, SOCK_STREAM, 0);
53 RUNNER_ASSERT_ERRNO_MSG(sock >= 0, "socket failed");
55 SockUniquePtr sockPtr(&sock);
57 int connectResult = TEMP_FAILURE_RETRY(
58 connect(sock, (const struct sockaddr*) sockaddr, sizeof(struct sockaddr_un)));
59 RUNNER_ASSERT_ERRNO_MSG(connectResult == 0, "connect failed");
65 int acceptClient(int sock) {
66 int clientSock = TEMP_FAILURE_RETRY(accept(sock, NULL, NULL));
67 RUNNER_ASSERT_ERRNO_MSG(clientSock >= 0, "accept failed");
71 void waitForDisconnect(int sock) {
72 const nfds_t fdCount = 1;
73 const int timeout = -1; // no timeout
75 struct pollfd pfd { sock, POLLRDHUP, 0 };
76 int ret = TEMP_FAILURE_RETRY(poll(&pfd, fdCount, timeout));
77 RUNNER_ASSERT_ERRNO_MSG(ret >= 0, "poll failed");
80 struct sockaddr_un makeAbstractAddress(const std::string &path) {
81 struct sockaddr_un sockaddr;
82 RUNNER_ASSERT_MSG(path.size() <= sizeof(sockaddr.sun_path) - 1, "Socket path too long");
83 memset(&sockaddr, 0, sizeof(struct sockaddr_un));
84 sockaddr.sun_family = AF_UNIX;
85 // Leave '\0' as a first character of path
86 memcpy(sockaddr.sun_path + 1, path.c_str(), path.size());
90 } // namespace UDSHelpers