1 /* 2 * Copyright (c) 2021-2023 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 #ifndef SOCKET_CONTEXT_H 17 #define SOCKET_CONTEXT_H 18 19 #include <cstdint> 20 #ifndef NO_PROTOBUF 21 #include <google/protobuf/message.h> 22 #endif 23 #include <thread> 24 25 #if defined(__i386__) || defined(__x86_64__) 26 const static char DEFAULT_UNIX_SOCKET_PATH[] = "hiprofiler_unix_socket"; 27 const static char DEFAULT_UNIX_SOCKET_HOOK_PATH[] = "hook_unix_socket"; 28 #else 29 const static char DEFAULT_UNIX_SOCKET_PATH[] = "hiprofiler_unix_socket"; 30 const static char DEFAULT_UNIX_SOCKET_HOOK_PATH[] = "hook_unix_socket"; 31 32 const static char DEFAULT_UNIX_SOCKET_FULL_PATH[] = "/dev/unix/socket/hiprofiler_unix_socket"; 33 const static char DEFAULT_UNIX_SOCKET_HOOK_FULL_PATH[] = "/dev/unix/socket/hook_unix_socket"; 34 #endif 35 36 class ServiceBase; 37 38 enum ClientState { 39 CLIENT_STAT_WORKING, 40 CLIENT_STAT_WAIT_THREAD_EXIT, 41 CLIENT_STAT_THREAD_EXITED, 42 }; 43 44 enum RawProtocol { 45 RAW_PROTOCOL_POINTTO_SERVICE = 1, 46 }; 47 struct RawPointToService { 48 char serviceName_[64]; 49 }; 50 51 class SocketContext { 52 public: 53 SocketContext(); 54 virtual ~SocketContext(); 55 56 bool SendRaw(uint32_t pnum, const int8_t* data, uint32_t size, int sockfd = -1); 57 #ifndef NO_PROTOBUF 58 bool SendProtobuf(uint32_t pnum, google::protobuf::Message& pmsg); 59 #endif 60 bool SendFileDescriptor(int fd); 61 bool SendHookConfig(const uint8_t* config, size_t len); 62 bool SendHeartBeat(); 63 int ReceiveFileDiscriptor(); GetClientState()64 enum ClientState GetClientState() { return clientState_; } 65 protected: 66 int socketHandle_; 67 bool CreateRecvThread(); 68 enum ClientState clientState_; 69 uint64_t lastProcMS_; 70 71 ServiceBase* serviceBase_; 72 73 virtual int RawProtocolProc(uint32_t pnum, const int8_t* buf, const uint32_t size); 74 75 private: 76 static bool ReceiveData(int sock, uint8_t* databuf, uint32_t size); 77 static void* UnixSocketRecv(void* pp); 78 std::thread recvThread_; 79 }; 80 81 #endif