1 /* 2 * Copyright (C) 2021-2022 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_H 17 #define SOCKET_H 18 19 #include <map> 20 #include <mutex> 21 #include <string> 22 #include <vector> 23 #include "base_def.h" 24 #include "transport/transport.h" 25 #include "transport/transport_factory.h" 26 #include "transport/transport_rfcomm.h" 27 28 #include "socket_def.h" 29 #include "socket_gap_client.h" 30 #include "socket_gap_server.h" 31 #include "socket_sdp_client.h" 32 #include "socket_sdp_server.h" 33 34 namespace OHOS { 35 namespace bluetooth { 36 // result of sending data to app 37 typedef enum { 38 SOCKET_SEND_NONE = 0, 39 SOCKET_SEND_ERROR, 40 SOCKET_SEND_PARTIAL, 41 SOCKET_SEND_ALL, 42 } SocketSendRet; 43 44 /** 45 * @brief This Socket class provides a set of methods that client initiates the connection and 46 * server listen and accept the connection. 47 */ 48 class Socket { 49 public: 50 /** 51 * @brief Constructor. 52 */ 53 Socket(); 54 55 /** 56 * @brief Destructor. 57 */ 58 virtual ~Socket(); 59 60 /** 61 * @brief The client initiates the connection. 62 * @details The client queries the SDP and finds the channel to be connected through UUID. 63 * Client sets security level to GAP. 64 * @param addr address. 65 * @param uuid server record uuid to search scn. 66 * @param securityFlag require the connection to be encrypted and authenticated. 67 * @param sockfd the upper socket fd that generated by the socketpair. 68 * @return int 69 */ 70 int Connect(const std::string &addr, const Uuid &uuid, int securityFlag, int &sockfd); 71 72 /** 73 * @brief The server listen and accept the connection. 74 * @details The server registers service records to SDP with service name, uuid and server channel 75 * number that assigned by rfcomm. Server sets security level to GAP. 76 * @param name server service name. 77 * @param uuid server uuid. 78 * @param securityFlag require the connection to be encrypted and authenticated. 79 * @param sockfd the upper socket fd that generated by the socketpair. 80 * @return int 81 */ 82 int Listen(const std::string &name, const Uuid &uuid, int securityFlag, int &sockfd); 83 84 /** 85 * @brief SDP query completed. 86 * 87 * @param context socket object. 88 * @return int 89 */ 90 int ReceiveSdpResult(uint8_t scn); 91 92 /** 93 * @brief close socket. 94 * 95 */ 96 void CloseSocket(bool isDisable); 97 98 /** 99 * @brief erase socket 100 * 101 * @param socket 102 */ 103 void RemoveServerSocket(); 104 105 /** 106 * @brief close socket fd 107 * 108 * @param socket 109 */ 110 void CloseSocketFd(); 111 112 /** 113 * @brief clear up socket 114 * 115 * @param socket 116 */ 117 static void ClearUpAllSocket(); 118 119 /** 120 * @brief Poll thread notify the socket that it has data. 121 * 122 * @param context socket object. 123 */ 124 static void OnSocketReadReady(Socket &sock); 125 126 /** 127 * @brief Poll thread notify the socket that it can receive data. 128 * 129 * @param context socket object. 130 */ 131 static void OnSocketWriteReady(Socket &sock); 132 133 /** 134 * @brief Poll thread notify the socket that it exception occurred. 135 * 136 * @param context socket object. 137 */ 138 static void OnSocketException(Socket &sock); 139 140 private: 141 // remote device address. 142 BtAddr remoteAddr_ {{0}, 0}; 143 // server channel number. 144 uint8_t scn_ {0}; 145 // send mtu. 146 uint16_t sendMTU_ {0}; 147 // recv mtu 148 uint16_t recvMTU_ {0}; 149 // is server or not. 150 bool isServer_ {false}; 151 // connect state. 152 SocketState state_ {}; 153 // the transport socket fd that generated by the socketpair. 154 int upperlayerFd_ {-1}; 155 // the transport socket fd that generated by the socketpair. 156 int transportFd_ {-1}; 157 // require the connection to be encrypted and authenticated. 158 int securityFlag_ {0}; 159 // number of connected clients. 160 int clientNumber_ {0}; 161 // The maximum number of connected devices. 162 int maxConnectedNum_ {SOCK_MAX_CLIENT}; 163 // service id. 164 GAP_Service serviceId_ {SPP_ID_START}; 165 // can read data from Rfcomm. 166 bool isCanRead_ {true}; 167 // can read data from Rfcomm. 168 bool isCanWrite_ {true}; 169 // is or not new socket 170 bool isNewSocket_ {false}; 171 // length of data that send to app failed. 172 size_t recvBufLen_ {0}; 173 // length of data that send to stack failed. 174 size_t sendBufLen_ {0}; 175 // save data that sent to app failed. 176 uint8_t recvDataBuf_[SOCK_DEF_RFC_MTU] = {0}; 177 // save data that sent to stack failed. 178 uint8_t sendDataBuf_[SOCK_DEF_RFC_MTU] = {0}; 179 std::mutex mutex_ {}; 180 std::mutex fdMutex_ {}; 181 std::recursive_mutex writeMutex_ {}; 182 static std::recursive_mutex g_socketMutex; 183 // new transport that server accept 184 DataTransport *newSockTransport_ {nullptr}; 185 // the pointer of the SockTransport. 186 std::unique_ptr<DataTransport> sockTransport_ {nullptr}; 187 // the pointer of the transportFactory_. 188 std::unique_ptr<TransportFactory> transportFactory_ {nullptr}; 189 // the pointer of the SocketSdpClient. 190 std::unique_ptr<SocketSdpClient> sdpClient_ {nullptr}; 191 // the pointer of the SocketSdpServer. 192 std::unique_ptr<SocketSdpServer> sdpServer_ {nullptr}; 193 // the pointer of the SocketGapClient. 194 std::unique_ptr<SocketGapClient> socketGapClient_ {nullptr}; 195 // the pointer of the SocketGapServer. 196 std::unique_ptr<SocketGapServer> socketGapServer_ {nullptr}; 197 // the map manages the correspondence between new socket and transport. 198 std::map<DataTransport *, std::unique_ptr<Socket>> socketMap_ {}; 199 // the map manages all sockets; 200 static std::vector<Socket *> g_allServerSockets; 201 202 /** 203 * @brief is server or not. 204 * 205 * @return true: the role is server. 206 * @return false :the role is client. 207 */ IsServer()208 bool IsServer() const 209 { 210 return isServer_; 211 } 212 213 /** 214 * @brief address translation. 215 * 216 * @param addr remote device address. 217 */ 218 void SetRemoteAddr(std::string addr); 219 220 /** 221 * @brief Send connection information to app. 222 * 223 * @param fd socket fd. 224 * @param addr remote device address. 225 * @param status connect state. 226 * @param send_fd accept socket fd. 227 * @return true 228 * @return false 229 */ 230 static bool SendAppConnectInfo(int fd, BtAddr addr, bool status, int acceptFd); 231 232 /** 233 * @brief When server accept a connection request, generate a new socket. 234 * 235 * @param addr remote device address. 236 * @param transport transport object. 237 */ 238 int AddSocketInternal(BtAddr addr, DataTransport *transport, uint16_t sendMTU, uint16_t recvMTU); 239 240 /** 241 * @brief PPoll thread notify the socket that it can receive data. 242 * 243 * @param context socket object. 244 */ 245 void OnSocketWriteReadyNative(Socket &sock); 246 247 /** 248 * @brief Poll thread notify the socket that it exception occurred. 249 * 250 * @param context socket object. 251 */ 252 void OnSocketExceptionNative(Socket &sock); 253 254 /** 255 * @brief Assign serviceId to service 256 * 257 * @return int 258 */ 259 static GAP_Service AssignServiceId(); 260 261 /** 262 * @brief free serviceId 263 * 264 * @param serviceId 265 */ 266 static void FreeServiceId(GAP_Service serviceId); 267 268 /** 269 * @brief Send data to app. 270 * 271 * @param fd socket fd. 272 * @param buf data to send. 273 * @param len the size of the data to send. 274 * @return SocketSendRet 275 */ 276 static SocketSendRet SendDataToApp(int fd, const uint8_t *buf, size_t len); 277 278 /** 279 * @brief Read data from Rfcomm. 280 * 281 */ 282 void ReadData(); 283 284 /** 285 * @brief Write data from Rfcomm. 286 * 287 */ 288 void WriteData(); 289 290 /** 291 * @brief Write data to transport. 292 * 293 */ 294 int TransportWrite(Packet *subPkt); 295 296 /** 297 * @brief Notify Service Delete Socket 298 * 299 * @param socket 300 */ 301 static void NotifyServiceDeleteSocket(Socket &sock); 302 303 /** 304 * @brief erase socket 305 * 306 * @param socket 307 */ 308 static void EraseSocket(Socket &socket); 309 310 /** 311 * @brief write data to app 312 * 313 * @param socket 314 */ 315 void WriteDataToAPP(const uint8_t *buffer, size_t len); 316 317 /** 318 * @brief process disconnect 319 * 320 * @param socket 321 */ 322 void ProcessDisconnection(Socket &socket, DataTransport *transport); 323 324 /** 325 * @brief Get service dispatcher. 326 * 327 * @return service dispatcher. 328 */ 329 utility::Dispatcher *GetDispatchter(); 330 331 BT_DISALLOW_COPY_AND_ASSIGN(Socket); 332 DECLARE_IMPL(); 333 }; 334 } // namespace bluetooth 335 } // namespace OHOS 336 #endif // SOCKET_H