blob: 1c9ffa95c20cf21a80c9475af8fc35fabba2c662 [file] [log] [blame]
Finn Williams2ed809c2020-04-20 21:21:07 +01001//
Jim Flynnbbfe6032020-07-20 16:57:44 +01002// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
Finn Williams2ed809c2020-04-20 21:21:07 +01003// SPDX-License-Identifier: MIT
4//
Finn Williams2ed809c2020-04-20 21:21:07 +01005
Jim Flynnbbfe6032020-07-20 16:57:44 +01006#include <server/include/basePipeServer/ConnectionHandler.hpp>
Finn Williamsbadcc3f2020-05-22 14:28:15 +01007
Jim Flynnbbfe6032020-07-20 16:57:44 +01008#include <string>
Finn Williams2ed809c2020-04-20 21:21:07 +01009
Jim Flynnbbfe6032020-07-20 16:57:44 +010010namespace arm
Finn Williams2ed809c2020-04-20 21:21:07 +010011{
Jim Flynnbbfe6032020-07-20 16:57:44 +010012
13namespace pipe
14{
15
Finn Williams2ed809c2020-04-20 21:21:07 +010016ConnectionHandler::ConnectionHandler(const std::string& udsNamespace, const bool setNonBlocking)
17{
Jim Flynnbbfe6032020-07-20 16:57:44 +010018 arm::pipe::Initialize();
Finn Williams2ed809c2020-04-20 21:21:07 +010019 m_ListeningSocket = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
20
21 if (-1 == m_ListeningSocket)
22 {
23 throw SocketConnectionException(": Socket construction failed: ", 1, 1);
24 }
25
26 sockaddr_un udsAddress;
27 memset(&udsAddress, 0, sizeof(sockaddr_un));
28 // We've set the first element of sun_path to be 0, skip over it and copy the namespace after it.
29 memcpy(udsAddress.sun_path + 1, udsNamespace.c_str(), strlen(udsNamespace.c_str()));
30 udsAddress.sun_family = AF_UNIX;
31
32 // Bind the socket to the UDS namespace.
33 if (-1 == bind(m_ListeningSocket, reinterpret_cast<const sockaddr*>(&udsAddress), sizeof(sockaddr_un)))
34 {
35 throw SocketConnectionException(": Binding on socket failed: ", m_ListeningSocket, errno);
36 }
37 // Listen for connections.
38 if (-1 == listen(m_ListeningSocket, 1))
39 {
40 throw SocketConnectionException(": Listen call on socket failed: ", m_ListeningSocket, errno);
41 }
42
43 if (setNonBlocking)
44 {
Jim Flynnbbfe6032020-07-20 16:57:44 +010045 arm::pipe::SetNonBlocking(m_ListeningSocket);
Finn Williams2ed809c2020-04-20 21:21:07 +010046 }
47}
48
49std::unique_ptr<BasePipeServer> ConnectionHandler::GetNewBasePipeServer(const bool echoPackets)
50{
Jim Flynnbbfe6032020-07-20 16:57:44 +010051 arm::pipe::Socket clientConnection = arm::pipe::Accept(m_ListeningSocket, nullptr, nullptr, SOCK_CLOEXEC);
Finn Williams2ed809c2020-04-20 21:21:07 +010052 if (clientConnection < 1)
53 {
54 return nullptr;
55 }
56 return std::make_unique<BasePipeServer>(clientConnection, echoPackets);
57}
58
Jim Flynnbbfe6032020-07-20 16:57:44 +010059} // namespace pipe
60} // namespace arm