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
34namespace OHOS {
35namespace bluetooth {
36// result of sending data to app
37typedef 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 */
48class Socket {
49public:
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
140private:
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     */
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 scn to app.
222     *
223     * @param fd socket fd.
224     * @param scn socket scn.
225     * @return true
226     * @return false
227     */
228    static bool SendAppConnectScn(int fd, int scn);
229
230    /**
231     * @brief Send connection information to app.
232     *
233     * @param fd socket fd.
234     * @param addr remote device address.
235     * @param status connect state.
236     * @param send_fd accept socket fd.
237     * @return true
238     * @return false
239     */
240    static bool SendAppConnectInfo(int fd, int acceptFd, const SocketConnectInfo &connectInfo);
241
242    /**
243     * @brief When server accept a connection request, generate a new socket.
244     *
245     * @param addr remote device address.
246     * @param transport transport object.
247     */
248    int AddSocketInternal(BtAddr addr, DataTransport *transport, uint16_t sendMTU, uint16_t recvMTU);
249
250    /**
251     * @brief PPoll thread notify the socket that it can receive data.
252     *
253     * @param context socket object.
254     */
255    void OnSocketWriteReadyNative(Socket &sock);
256
257    /**
258     * @brief Poll thread notify the socket that it exception occurred.
259     *
260     * @param context socket object.
261     */
262    void OnSocketExceptionNative(Socket &sock);
263
264    /**
265     * @brief Assign serviceId to service
266     *
267     * @return int
268     */
269    static GAP_Service AssignServiceId();
270
271    /**
272     * @brief free  serviceId
273     *
274     * @param serviceId
275     */
276    static void FreeServiceId(GAP_Service serviceId);
277
278    /**
279     * @brief Send data to app.
280     *
281     * @param fd socket fd.
282     * @param buf data to send.
283     * @param len the size of the data to send.
284     * @return SocketSendRet
285     */
286    static SocketSendRet SendDataToApp(int fd, const uint8_t *buf, size_t len);
287
288    /**
289     * @brief Read data from Rfcomm.
290     *
291     */
292    void ReadData();
293
294    /**
295     * @brief Write data from Rfcomm.
296     *
297     */
298    void WriteData();
299
300    /**
301     * @brief Write data to transport.
302     *
303     */
304    int TransportWrite(Packet *subPkt);
305
306    /**
307     * @brief Notify Service Delete Socket
308     *
309     * @param socket
310     */
311    static void NotifyServiceDeleteSocket(Socket &sock);
312
313    /**
314     * @brief erase socket
315     *
316     * @param socket
317     */
318    static void EraseSocket(Socket &socket);
319
320    /**
321     * @brief write data to app
322     *
323     * @param socket
324     */
325    void WriteDataToAPP(const uint8_t *buffer, size_t len);
326
327    /**
328     * @brief process disconnect
329     *
330     * @param socket
331     */
332    void ProcessDisconnection(Socket &socket, DataTransport *transport);
333
334    /**
335     * @brief Get service dispatcher.
336     *
337     * @return service dispatcher.
338     */
339    utility::Dispatcher *GetDispatchter();
340
341    BT_DISALLOW_COPY_AND_ASSIGN(Socket);
342    DECLARE_IMPL();
343};
344}  // namespace bluetooth
345}  // namespace OHOS
346#endif  // SOCKET_H