1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "unix_socket_client.h"
17 #include <cstdint>
18 #include <sys/socket.h>
19 #include <unistd.h>
20 #include <linux/un.h>
21 #include "logging.h"
22 #include "securec.h"
23 #include "service_base.h"
24
UnixSocketClient()25 UnixSocketClient::UnixSocketClient()
26 {
27 serviceBase_ = nullptr;
28 socketHandle_ = -1;
29 }
30
~UnixSocketClient()31 UnixSocketClient::~UnixSocketClient() {}
32
Connect(const std::string addrname,ServiceBase & serviceBase)33 bool UnixSocketClient::Connect(const std::string addrname, ServiceBase& serviceBase)
34 {
35 HILOG_ERROR(LOG_CORE, "UnixSocketClient connect");
36 CHECK_TRUE(socketHandle_ == -1, false, "socketHandle_ != -1 Already Connected");
37
38 int sock = socket(AF_UNIX, SOCK_STREAM, 0);
39 CHECK_TRUE(sock != -1, false, "Unix Socket Create FAIL");
40
41 struct sockaddr_un addr;
42 if (memset_s(&addr, sizeof(struct sockaddr_un), 0, sizeof(struct sockaddr_un)) != EOK) {
43 HILOG_ERROR(LOG_CORE, "memset_s error!");
44 }
45 addr.sun_family = AF_UNIX;
46 if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), addrname.c_str(), sizeof(addr.sun_path) - 1) != EOK) {
47 HILOG_ERROR(LOG_CORE, "strncpy_s error!");
48 }
49
50 CHECK_TRUE(connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) != -1, close(sock) != 0,
51 "Unix Socket Connect FAIL");
52
53 serviceBase_ = &serviceBase;
54 struct RawPointToService rrs;
55 if (strncpy_s(rrs.serviceName_, sizeof(rrs.serviceName_),
56 serviceBase_->serviceName_.c_str(), serviceBase_->serviceName_.size()) != EOK) {
57 HILOG_ERROR(LOG_CORE, "strncpy_s error!");
58 }
59 rrs.serviceName_[serviceBase_->serviceName_.size()] = 0;
60 CHECK_TRUE(
61 SendRaw(RAW_PROTOCOL_POINTTO_SERVICE, reinterpret_cast<int8_t*>(&rrs), sizeof(struct RawPointToService), sock),
62 close(sock) != 0, "Unix Socket SendRaw FAIL");
63 socketHandle_ = sock;
64 CHECK_TRUE(CreateRecvThread(), close(sock) != 0, "Unix Socket Create Recv Thread FAIL");
65
66 return true;
67 }
68