• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
18 #include <cstdio>
19 #include <pthread.h>
20 #include <sys/socket.h>
21 #include <unistd.h>
22 #include <linux/un.h>
23 
24 #include "logging.h"
25 #include "securec.h"
26 #include "service_base.h"
27 
UnixSocketClient()28 UnixSocketClient::UnixSocketClient()
29 {
30     serviceBase_ = nullptr;
31     socketHandle_ = -1;
32 }
33 
~UnixSocketClient()34 UnixSocketClient::~UnixSocketClient() {}
35 
Connect(const std::string addrname,ServiceBase & serviceBase)36 bool UnixSocketClient::Connect(const std::string addrname, ServiceBase& serviceBase)
37 {
38     HILOG_ERROR(LOG_CORE, "UnixSocketClient connect");
39     CHECK_TRUE(socketHandle_ == -1, false, "socketHandle_ != -1 Already Connected");
40 
41     int sock = socket(AF_UNIX, SOCK_STREAM, 0);
42     CHECK_TRUE(sock != -1, false, "Unix Socket Create FAIL");
43 
44     struct sockaddr_un addr;
45     if (memset_s(&addr, sizeof(struct sockaddr_un), 0, sizeof(struct sockaddr_un)) != EOK) {
46         HILOG_ERROR(LOG_CORE, "memset_s error!");
47     }
48     addr.sun_family = AF_UNIX;
49     if (strncpy_s(addr.sun_path, sizeof(addr.sun_path), addrname.c_str(), sizeof(addr.sun_path) - 1) != EOK) {
50         HILOG_ERROR(LOG_CORE, "strncpy_s error!");
51     }
52 
53     CHECK_TRUE(connect(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) != -1, close(sock) != 0,
54         "Unix Socket Connect FAIL");
55 
56     serviceBase_ = &serviceBase;
57     struct RawPointToService rrs;
58     if (strncpy_s(rrs.serviceName_, sizeof(rrs.serviceName_),
59         serviceBase_->serviceName_.c_str(), serviceBase_->serviceName_.size()) != EOK) {
60         HILOG_ERROR(LOG_CORE, "strncpy_s error!");
61     }
62     rrs.serviceName_[serviceBase_->serviceName_.size()] = 0;
63     CHECK_TRUE(
64         SendRaw(RAW_PROTOCOL_POINTTO_SERVICE, reinterpret_cast<int8_t*>(&rrs), sizeof(struct RawPointToService), sock),
65         close(sock) != 0, "Unix Socket SendRaw FAIL");
66     socketHandle_ = sock;
67     CHECK_TRUE(CreateRecvThread(), close(sock) != 0, "Unix Socket Create Recv Thread FAIL");
68 
69     return true;
70 }
71