1/* 2 * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved. 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#ifndef HIEBPF_IPC_UNIX_SOCKET_H_ 16#define HIEBPF_IPC_UNIX_SOCKET_H_ 17 18#include <functional> 19#include <string> 20#include <thread> 21 22namespace OHOS { 23namespace Developtools { 24namespace Hiebpf { 25const std::string UNIX_SOCKET_DEFAULT_PATHNAME = "/dev/unix/socket/hiebpf"; 26const size_t UNIX_SOCKET_BUFFER_SIZE = 64; 27// this Unix socket server don't support multiple clients 28const int UNIX_SOCKET_LISTEN_COUNT = 1; 29 30class IpcUnixSocketServer { 31public: 32 IpcUnixSocketServer(); 33 ~IpcUnixSocketServer(); 34 35 bool Start(const std::string &pathname = UNIX_SOCKET_DEFAULT_PATHNAME); 36 bool Stop(); 37 38 using HandleCallBack = std::function<void(const void *buf, size_t size)>; 39 void SetHandleCallback(HandleCallBack fn) 40 { 41 handleMessageFn_ = fn; 42 } 43 44 // SendMessage can be called by HandleCallBack 45 bool SendMessage(const void *buf, size_t size); 46 47private: 48 std::string pathName_; 49 std::thread handleThread_; 50 HandleCallBack handleMessageFn_; 51 int serverFd_ = -1; 52 int clientFd_ = -1; 53 bool isRunning_ = false; 54 55 void HandleThreadLoop(); 56}; 57 58class IpcUnixSocketClient { 59public: 60 IpcUnixSocketClient(); 61 ~IpcUnixSocketClient(); 62 63 bool Connect(const std::string &pathname = UNIX_SOCKET_DEFAULT_PATHNAME); 64 void Disconnect(); 65 66 bool SendMessage(const void *buf, size_t size); 67 /* size is size of buf when input, is size of recved data when output. 68 timeout is milliseconds */ 69 bool RecvMessage(void *buf, size_t &size, uint32_t timeout); 70 71private: 72 int sockFd_ = -1; 73}; 74} // namespace Hiebpf 75} // namespace Developtools 76} // namespace OHOS 77#endif // HIEBPF_IPC_UNIX_SOCKET_H_ 78