Set close on exec
[platform/core/appfw/rpc-port.git] / src / server-socket-internal.cc
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 #include <sys/socket.h>
21 #include <sys/types.h>
22 #include <sys/un.h>
23 #include <unistd.h>
24
25 #include "log-private.hh"
26 #include "server-socket-internal.hh"
27
28 namespace rpc_port {
29 namespace internal {
30
31 ServerSocket::ServerSocket(int fd) : fd_(fd) {
32   SetCloseOnExec();
33 }
34
35 ServerSocket::~ServerSocket() {
36   if (!IsClosed())
37     Close();
38 }
39
40 bool ServerSocket::IsClosed() {
41   return fd_ < 0 ? true : false;
42 }
43
44 ClientSocket* ServerSocket::Accept() {
45   struct sockaddr_un addr = { 0, };
46   socklen_t len = static_cast<socklen_t>(sizeof(struct sockaddr_un));
47   auto* addr_ptr = reinterpret_cast<struct sockaddr*>(&addr);
48   int client_fd = accept(GetFd(), addr_ptr, &len);
49   if (client_fd == -1) {
50     _E("accept() is failed. errno(%d)", errno);  // LCOV_EXCL_LINE
51     return nullptr;  // LCOV_EXCL_LINE
52   }
53
54   return new (std::nothrow) ClientSocket(client_fd);
55 }
56
57 int ServerSocket::GetFd() const {
58   return fd_;
59 }
60
61 // LCOV_EXCL_START
62 int ServerSocket::Listen(int backlog) {
63   int ret = listen(GetFd(), backlog);
64   if (ret < 0) {
65     _E("listen() is failed. errno(%d)", errno);
66     return -1;
67   }
68
69   return 0;
70 }
71
72 void ServerSocket::SetCloseOnExec() {
73   int flags = fcntl(fd_, F_GETFL, 0);
74   fcntl(fd_, F_SETFL, flags | O_CLOEXEC);
75   _I("Close on exec");
76 }
77 // LCOV_EXCL_STOP
78
79 void ServerSocket::Close() {
80   if (fd_ > -1) {
81     close(fd_);
82     fd_ = -1;
83   }
84 }
85
86 }  // namespace internal
87 }  // namespace rpc_port