• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 
6 #include <server/include/basePipeServer/ConnectionHandler.hpp>
7 
8 #include <string>
9 
10 namespace arm
11 {
12 
13 namespace pipe
14 {
15 
ConnectionHandler(const std::string & udsNamespace,const bool setNonBlocking)16 ConnectionHandler::ConnectionHandler(const std::string& udsNamespace, const bool setNonBlocking)
17 {
18     arm::pipe::Initialize();
19     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     {
45         arm::pipe::SetNonBlocking(m_ListeningSocket);
46     }
47 }
48 
GetNewBasePipeServer(const bool echoPackets)49 std::unique_ptr<BasePipeServer> ConnectionHandler::GetNewBasePipeServer(const bool echoPackets)
50 {
51     arm::pipe::Socket clientConnection = arm::pipe::Accept(m_ListeningSocket, nullptr, nullptr, SOCK_CLOEXEC);
52     if (clientConnection < 1)
53     {
54         return nullptr;
55     }
56     return std::make_unique<BasePipeServer>(clientConnection, echoPackets);
57 }
58 
59 } // namespace pipe
60 } // namespace arm
61