Colm Donelan | a85e215 | 2019-09-09 11:59:08 +0100 | [diff] [blame] | 1 | // |
| 2 | // Copyright © 2019 Arm Ltd. All rights reserved. |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | // |
| 5 | |
| 6 | #include "GatordMockService.hpp" |
| 7 | |
| 8 | #include <cerrno> |
| 9 | #include <fcntl.h> |
| 10 | #include <iostream> |
| 11 | #include <string> |
| 12 | #include <sys/socket.h> |
| 13 | #include <sys/un.h> |
| 14 | |
| 15 | namespace armnn |
| 16 | { |
| 17 | |
| 18 | namespace gatordmock |
| 19 | { |
| 20 | |
| 21 | |
| 22 | bool GatordMockService::OpenListeningSocket(std::string udsNamespace) |
| 23 | { |
| 24 | m_ListeningSocket = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); |
| 25 | if (-1 == m_ListeningSocket) |
| 26 | { |
| 27 | std::cerr << ": Socket construction failed: " << strerror(errno) << std::endl; |
| 28 | return false; |
| 29 | } |
| 30 | |
| 31 | sockaddr_un udsAddress; |
| 32 | memset(&udsAddress, 0, sizeof(sockaddr_un)); |
| 33 | // We've set the first element of sun_path to be 0, skip over it and copy the namespace after it. |
| 34 | memcpy(udsAddress.sun_path + 1, udsNamespace.c_str(), strlen(udsNamespace.c_str())); |
| 35 | udsAddress.sun_family = AF_UNIX; |
| 36 | |
| 37 | // Bind the socket to the UDS namespace. |
| 38 | if (-1 == bind(m_ListeningSocket, reinterpret_cast<const sockaddr *>(&udsAddress), sizeof(sockaddr_un))) |
| 39 | { |
| 40 | std::cerr << ": Binding on socket failed: " << strerror(errno) << std::endl; |
| 41 | return false; |
| 42 | } |
| 43 | // Listen for 1 connection. |
| 44 | if (-1 == listen(m_ListeningSocket, 1)) |
| 45 | { |
| 46 | std::cerr << ": Listen call on socket failed: " << strerror(errno) << std::endl; |
| 47 | return false; |
| 48 | } |
| 49 | std::cout << "Bound to UDS namespace: \\0" << udsNamespace << std::endl; |
| 50 | return true; |
| 51 | } |
| 52 | |
| 53 | int GatordMockService::BlockForOneClient() |
| 54 | { |
| 55 | std::cout << "Waiting for client connection." << std::endl; |
| 56 | |
| 57 | int accepted = accept4(m_ListeningSocket, nullptr, nullptr, SOCK_CLOEXEC); |
| 58 | if (-1 == accepted) |
| 59 | { |
| 60 | std::cerr << ": Failure when waiting for a client connection: " << strerror(errno) << std::endl; |
| 61 | return -1; |
| 62 | } |
| 63 | |
| 64 | std::cout << "Client connection established." << std::endl; |
| 65 | return accepted; |
| 66 | } |
| 67 | |
| 68 | |
| 69 | } // namespace gatordmock |
| 70 | |
| 71 | } // namespace armnn |