2 * Copyright (c) 2021 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.
20 #include <sys/socket.h>
21 #include <sys/types.h>
25 #include "abstract_socket.hh"
27 namespace pkgmgr_common {
30 AbstractSocket::AbstractSocket(std::string path)
31 : path_(std::move(path)), fd_(-1), addr_{} {}
33 AbstractSocket::AbstractSocket(int fd) : fd_(fd), addr_{} {}
35 AbstractSocket::~AbstractSocket() { Destroy(); }
37 int AbstractSocket::SendData(const void* buf, unsigned int size) {
38 auto buffer = static_cast<const unsigned char*>(buf);
39 unsigned int left = size;
41 ssize_t send_byte = send(fd_, buffer, left, MSG_NOSIGNAL);
43 LOGE("send() is failed. fd(%d), errno(%d)", fd_, errno);
54 int AbstractSocket::ReceiveData(void* buf, unsigned int size) {
55 bool is_blocking = true;
56 if (fcntl(fd_, F_GETFL, 0) & O_NONBLOCK) is_blocking = false;
58 auto buffer = static_cast<unsigned char*>(buf);
59 unsigned int left = size;
61 ssize_t recv_byte = recv(fd_, buffer, left, 0);
63 LOGW("Socket was disconnected. fd(%d)", fd_);
65 } else if (recv_byte < 0) {
68 } else if (errno == EAGAIN) {
70 LOGE("Timed out. fd(%d)", fd_);
77 LOGE("recv() is failed. fd(%d), errno(%d)", fd_, errno);
88 int AbstractSocket::GetFd() { return fd_; }
90 std::string AbstractSocket::GetPath() { return path_; }
92 void AbstractSocket::SetOption() {
94 int ret = setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
96 LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
100 ret = setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
101 if (ret < 0) LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
104 int AbstractSocket::Create() {
105 fd_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
107 LOGE("socket() is failed. errno(%d)", errno);
111 addr_.sun_family = AF_UNIX;
112 snprintf(addr_.sun_path, sizeof(addr_.sun_path), "%s", path_.c_str());
116 void AbstractSocket::Destroy() {
117 if (fd_ > 0) close(fd_);
120 } // namespace socket
121 } // namespace pkgmgr_common