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>
24 #include "pkgmgrinfo_debug.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() {}
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), errno(%d)", fd_, errno);
65 } else if (recv_byte < 0) {
68 } else if (errno == EAGAIN) {
70 LOGE("Timed out. fd(%d), errno(%d)", fd_, errno);
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 pid_t AbstractSocket::GetPID() {
94 struct ucred cred = {};
95 socklen_t len = sizeof(cred);
97 r = getsockopt(fd_, SOL_SOCKET, SO_PEERCRED, &cred, &len);
99 LOGE("getsockopt has failed, errno[%d]", errno);
106 void AbstractSocket::SetOption() {
108 int ret = setsockopt(fd_, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
110 LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
114 ret = setsockopt(fd_, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
115 if (ret < 0) LOGE("setsockopt() is failed. fd(%d), errno(%d)", fd_, errno);
118 int AbstractSocket::Create() {
119 if (fd_ != -1) return 0;
120 fd_ = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
122 LOGE("socket() is failed. errno(%d)", errno);
126 addr_.sun_family = AF_UNIX;
127 snprintf(addr_.sun_path, sizeof(addr_.sun_path), "%s", path_.c_str());
132 void AbstractSocket::Disconnect() {
134 LOGW("Close fd(%d)", fd_);
140 } // namespace socket
141 } // namespace pkgmgr_common