Fix issue where state is not restored when adv operation fails
[platform/core/connectivity/bluetooth-frwk.git] / bt-api / bt-l2cap-le-client.c
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *              http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 #include <string.h>
19 #include <gio/gunixfdlist.h>
20 #include <sys/socket.h>
21
22 #include "bluetooth-api.h"
23 #include "bt-internal-types.h"
24
25 #include "bt-common.h"
26 #include "bt-request-sender.h"
27 #include "bt-event-handler.h"
28
29 /* Variable for privilege, only for write API,
30   before we should reduce time to bt-service dbus calling
31   -1 : Don't have a permission to access API
32   0 : Initial value, not yet check
33   1 : Have a permission to access API
34 */
35 static int privilege_token;
36
37 GSList *l2cap_le_clients;
38
39 typedef struct {
40         int psm;
41         char *remote_addr;
42         int sock_fd;
43         int watch_id;
44 } l2cap_le_client_conn_info_t;
45
46 static gboolean __is_error_by_disconnect(GError *err)
47 {
48         return !g_strcmp0(err->message, "Connection reset by peer") ||
49                 !g_strcmp0(err->message, "Connection timed out") ||
50                 !g_strcmp0(err->message, "Software caused connection abort");
51 }
52
53 static l2cap_le_client_conn_info_t *__find_l2cap_le_conn_info_with_fd(int fd)
54 {
55         GSList *l;
56
57         BT_DBG("+");
58
59         for (l = l2cap_le_clients; l != NULL; l = l->next) {
60                 l2cap_le_client_conn_info_t *info = l->data;
61
62                 if (info && info->sock_fd == fd) {
63                         BT_INFO("Match found");
64                         return info;
65                 }
66         }
67
68         BT_DBG("-");
69         return NULL;
70 }
71
72 static void __l2cap_le_remove_client_conn_info_t(
73                                                 l2cap_le_client_conn_info_t *info)
74 {
75         ret_if(info == NULL);
76
77         l2cap_le_clients = g_slist_remove(l2cap_le_clients, info);
78         g_free(info->remote_addr);
79
80         if (info->sock_fd > 0) {
81             shutdown(info->sock_fd, SHUT_RDWR);
82             close(info->sock_fd);
83         }
84
85         if (info->watch_id > 0)
86                 g_source_remove(info->watch_id);
87         g_free(info);
88 }
89
90 static void __bt_l2cap_le_client_disconnected(
91                                                 l2cap_le_client_conn_info_t *conn_info)
92 {
93         bluetooth_l2cap_le_disconnection_t disconn_info;
94         bt_event_info_t *event_info = NULL;
95
96         BT_DBG("+");
97
98         ret_if(conn_info == NULL);
99
100         event_info = _bt_event_get_cb_data(BT_L2CAP_LE_CLIENT_EVENT);
101         ret_if(event_info == NULL);
102
103         memset(&disconn_info, 0x00, sizeof(bluetooth_l2cap_le_disconnection_t));
104         disconn_info.device_role = L2CAP_LE_ROLE_CLIENT;
105         disconn_info.socket_fd = conn_info->sock_fd;
106         disconn_info.psm = conn_info->psm;
107         _bt_convert_addr_string_to_type(disconn_info.device_addr.addr,
108                         conn_info->remote_addr);
109
110         BT_INFO("Disconnection Result[%d] BT_ADDRESS[%s] FD[%d] PSM[%d]",
111                         BLUETOOTH_ERROR_NONE, conn_info->remote_addr,
112                         conn_info->sock_fd, conn_info->psm);
113         _bt_common_event_cb(BLUETOOTH_EVENT_L2CAP_LE_DISCONNECTED,
114                         BLUETOOTH_ERROR_NONE, &disconn_info,
115                         event_info->cb, event_info->user_data);
116
117         BT_DBG("-");
118 }
119
120 static gboolean __client_data_received_cb(GIOChannel *chan, GIOCondition cond,
121                                                 gpointer data)
122 {
123         bt_event_info_t *event_info;
124         bluetooth_l2cap_le_received_data_t data_r;
125         l2cap_le_client_conn_info_t *conn_info;
126         int fd;
127         gsize len = 0;
128         char *buffer;
129         GError *err = NULL;
130         GIOStatus status = G_IO_STATUS_NORMAL;
131         static int resource_unavailable_cnt = 0;
132
133         BT_DBG("+");
134
135         fd = g_io_channel_unix_get_fd(chan);
136         if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) {
137                 BT_ERR_C("L2cap_le Client disconnected: %d", fd);
138                 goto fail;
139         }
140
141         buffer = g_malloc0(BT_L2CAP_LE_BUFFER_LEN + 1);
142         g_io_channel_set_buffer_size(chan, BT_L2CAP_LE_BUFFER_LEN);
143         status = g_io_channel_read_chars(chan, buffer, BT_L2CAP_LE_BUFFER_LEN,
144                         &len, &err);
145         if (status != G_IO_STATUS_NORMAL) {
146                 BT_ERR("IO Channel read is failed with %d", status);
147                 g_free(buffer);
148                 if (err) {
149                         BT_ERR("IO Channel read error [%s]", err->message);
150                         if (status == G_IO_STATUS_ERROR &&
151                                         __is_error_by_disconnect(err)) {
152                                 BT_ERR("cond : %d", cond);
153                                 g_error_free(err);
154                                 goto fail;
155                         }
156                         g_error_free(err);
157                 }
158
159                 if (status == G_IO_STATUS_ERROR ||
160                         status == G_IO_STATUS_EOF) {
161                         goto fail;
162                 } else if (status == G_IO_STATUS_AGAIN) {
163                         resource_unavailable_cnt++;
164                         if (resource_unavailable_cnt > 10)
165                                 goto fail;
166                 }
167
168                 return TRUE;
169         }
170         resource_unavailable_cnt = 0;
171
172         if (len == 0) {
173                 BT_ERR("Length is zero, remote end hang up");
174                 g_free(buffer);
175                 goto fail;
176         }
177
178         BT_DBG("fd: %d, len: %zd, buffer: %s", fd, len, buffer);
179
180         event_info = _bt_event_get_cb_data(BT_L2CAP_LE_CLIENT_EVENT);
181         if (event_info == NULL) {
182                 BT_INFO("event_info == NULL");
183                 g_free(buffer);
184                 return TRUE;
185         }
186
187         data_r.socket_fd = fd;
188         data_r.buffer_size = len;
189         data_r.buffer = buffer;
190
191         _bt_common_event_cb(BLUETOOTH_EVENT_L2CAP_LE_DATA_RECEIVED,
192                         BLUETOOTH_ERROR_NONE, &data_r,
193                         event_info->cb, event_info->user_data);
194
195         g_free(buffer);
196         return TRUE;
197
198 fail:
199         conn_info = __find_l2cap_le_conn_info_with_fd(fd);
200         if (conn_info) {
201                 BT_INFO("Disconnecting client, fd %d", fd);
202                 close(conn_info->sock_fd);
203                 __bt_l2cap_le_client_disconnected(conn_info);
204                 __l2cap_le_remove_client_conn_info_t(conn_info);
205         } else {
206                 BT_ERR("l2cap_le client conn_info not found");
207         }
208
209         BT_DBG("-");
210         return FALSE;
211 }
212
213 static void __l2cap_le_client_connection_create_watch(
214                                                 l2cap_le_client_conn_info_t *conn_info)
215 {
216         GIOChannel *data_io;
217
218         BT_DBG("+");
219
220         ret_if(NULL == conn_info);
221
222         data_io = g_io_channel_unix_new(conn_info->sock_fd);
223         g_io_channel_set_encoding(data_io, NULL, NULL);
224         g_io_channel_set_flags(data_io, G_IO_FLAG_NONBLOCK, NULL);
225         conn_info->watch_id = g_io_add_watch(data_io,
226                         G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
227                         __client_data_received_cb, NULL);
228         g_io_channel_unref(data_io);
229
230         BT_DBG("-");
231 }
232
233 static void __bt_l2cap_le_handle_new_client_connection(
234                                                 bluetooth_l2cap_le_connection_t *info)
235 {
236         l2cap_le_client_conn_info_t *conn_info;
237
238         BT_DBG("+");
239
240         ret_if(NULL == info);
241
242         conn_info = g_malloc0(sizeof(l2cap_le_client_conn_info_t));
243         conn_info->remote_addr = g_malloc0(BT_ADDRESS_STRING_SIZE);
244         _bt_convert_addr_type_to_string(
245                         conn_info->remote_addr, info->device_addr.addr);
246         conn_info->sock_fd = info->socket_fd;
247         conn_info->psm = info->psm;
248
249         BT_INFO("Address:%s, Socket: %d, psm: %d",
250                         conn_info->remote_addr, conn_info->sock_fd, conn_info->psm);
251
252         l2cap_le_clients = g_slist_append(l2cap_le_clients, conn_info);
253         __l2cap_le_client_connection_create_watch(conn_info);
254
255         BT_DBG("-");
256 }
257
258 static void __async_req_cb_with_unix_fd_list(GDBusProxy *proxy,
259                                                 GAsyncResult *res, gpointer user_data)
260 {
261         int result = BLUETOOTH_ERROR_NONE;
262         int event_type = BT_LE_ADAPTER_EVENT;
263         gboolean fail = false;
264
265         bt_req_info_t *cb_data = user_data;
266         bluetooth_event_param_t bt_event;
267         GArray *out_param1 = NULL;
268         GUnixFDList *out_fd_list = NULL;
269         bt_l2cap_user_info_t *l2cap_user_info = NULL;
270
271         BT_DBG("+");
272
273         if (cb_data)
274                 l2cap_user_info = (bt_l2cap_user_info_t *)cb_data->user_data;
275
276         if (l2cap_user_info)
277                 cb_data->user_data = (void *)l2cap_user_info->user_data;
278
279         _bt_get_fd_list_info(proxy, res, user_data, &bt_event, &out_param1,
280                 &event_type, &out_fd_list, &result, &fail);
281
282         if (fail) {
283                 BT_INFO("Connection failed due to error: %d", result);
284                 bluetooth_l2cap_le_connection_t *conn_info;
285
286                 conn_info = g_malloc0(sizeof(bluetooth_l2cap_le_connection_t));
287                 memset(conn_info, 0x00, sizeof(bluetooth_l2cap_le_connection_t));
288
289                 if (l2cap_user_info) {
290                         conn_info->psm = l2cap_user_info->psm;
291                         memcpy(&conn_info->device_addr, &l2cap_user_info->device_addr,
292                                 sizeof(bluetooth_device_address_t));
293                 }
294
295                 bt_event.param_data = (void *)conn_info;
296                 goto failed;
297         }
298
299         if (!cb_data)
300                 goto done;
301
302         if (result == BLUETOOTH_ERROR_NONE && out_param1) {
303                 if (BT_L2CAP_LE_CLIENT_CONNECT == cb_data->service_function) {
304                         int *fd_list_array;
305                         int len = 0;
306                         bluetooth_l2cap_le_connection_t *conn_info;
307
308                         conn_info = (bluetooth_l2cap_le_connection_t *)bt_event.param_data;
309                         if (!out_fd_list) {
310                                 BT_ERR("out_fd_list is NULL");
311                                 goto failed;
312                         }
313
314                         fd_list_array = g_unix_fd_list_steal_fds(out_fd_list, &len);
315                         BT_INFO("Num fds in fd_list is : %d, fd_list[0]: %d", len, fd_list_array[0]);
316                         conn_info->socket_fd = fd_list_array[0];
317
318                         BT_INFO("conn_info->socket_fd: %d", conn_info->socket_fd);
319                         __bt_l2cap_le_handle_new_client_connection(conn_info);
320
321                         if (cb_data->cb != NULL) {
322                                 /* Send client connected event */
323                                 bt_event.result = result;
324                                 BT_INFO("send client connected event event_type[%d], result=[%d]", event_type, result);
325                                 ((bluetooth_cb_func_ptr)cb_data->cb)(
326                                         bt_event.event, &bt_event, cb_data->user_data);
327                         }
328
329                         g_free(fd_list_array);
330                         g_object_unref(out_fd_list);
331                 }
332                 goto done;
333         }
334
335 failed:
336         if (cb_data->cb == NULL)
337                 goto done;
338
339         /* Only if fail case, call the callback function*/
340         bt_event.result = result;
341
342         BT_INFO("send fail event event_type[%d], result=[%d]", event_type, result);
343         if (event_type == BT_L2CAP_LE_CLIENT_EVENT) {
344                 BT_INFO("l2cap_le client event");
345                 ((bluetooth_cb_func_ptr)cb_data->cb)(bt_event.event,
346                         &bt_event, cb_data->user_data);
347         } else {
348                 BT_INFO("Not handled event type : %d", event_type);
349         }
350 done:
351         if (out_param1)
352                 g_array_free(out_param1, TRUE);
353
354         g_free(l2cap_user_info);
355         g_free(cb_data);
356         BT_DBG("-");
357 }
358
359 BT_EXPORT_API int bluetooth_l2cap_le_connect(
360                 const bluetooth_device_address_t *remote_bt_address, int psm)
361 {
362         int result;
363         bt_user_info_t *user_info;
364         int t_psm;
365         bt_l2cap_user_info_t *l2cap_user_info;
366
367         BT_CHECK_PARAMETER(remote_bt_address, return);
368         BT_CHECK_ENABLED_LE(return);
369
370         BT_INFO_C("connect l2cap_le psm %d", psm);
371         user_info = _bt_get_user_data(BT_COMMON);
372         retv_if(user_info->cb == NULL, BLUETOOTH_ERROR_INTERNAL);
373
374
375         if (_bt_check_privilege_le(BT_CHECK_PRIVILEGE, BT_L2CAP_LE_CLIENT_CONNECT)
376              == BLUETOOTH_ERROR_PERMISSION_DEINED) {
377                 BT_ERR("Don't have a privilege to use this API");
378         }
379
380         l2cap_user_info = g_malloc0(sizeof(bt_l2cap_user_info_t));
381         l2cap_user_info->psm = psm;
382         l2cap_user_info->user_data = user_info->user_data;
383         memcpy(&l2cap_user_info->device_addr, remote_bt_address,
384                         sizeof(bluetooth_device_address_t));
385
386         BT_INIT_PARAMS();
387         BT_ALLOC_PARAMS(in_param1, in_param2, in_param3, in_param4, out_param);
388
389         g_array_append_vals(in_param1, remote_bt_address,
390                                 sizeof(bluetooth_device_address_t));
391
392         t_psm = psm;
393         g_array_append_vals(in_param2, &t_psm, sizeof(int));
394
395         result = _bt_send_request_async_with_unix_fd_list(BT_BLUEZ_SERVICE,
396                                 BT_L2CAP_LE_CLIENT_CONNECT,
397                                 in_param1, in_param2,
398                                 in_param3, in_param4,
399                                 user_info->cb, (void *)l2cap_user_info,
400                                 NULL, (GAsyncReadyCallback)__async_req_cb_with_unix_fd_list);
401
402         BT_INFO("result: %x", result);
403
404         BT_FREE_PARAMS(in_param1, in_param2, in_param3, in_param4, out_param);
405
406         return result;
407 }
408
409 BT_EXPORT_API int bluetooth_l2cap_le_client_is_connected(
410                 const bluetooth_device_address_t *device_address, gboolean *connected)
411 {
412         GSList *l;
413         char address[BT_ADDRESS_STRING_SIZE] = { 0 };
414
415         BT_CHECK_PARAMETER(device_address, return);
416         BT_CHECK_PARAMETER(connected, return);
417
418         BT_DBG("+");
419
420         *connected = FALSE;
421         _bt_convert_addr_type_to_string(address, (unsigned char *)device_address->addr);
422         BT_INFO("Client address: [%s]", address);
423
424         for (l = l2cap_le_clients; l != NULL; l = l->next) {
425                 l2cap_le_client_conn_info_t *info = l->data;
426
427                 if (info && !strncasecmp(info->remote_addr, address, BT_ADDRESS_STRING_SIZE)) {
428                         BT_INFO("Match found");
429                         *connected = TRUE;
430                         return BLUETOOTH_ERROR_NONE;
431                 }
432         }
433
434         BT_DBG("-");
435         return BLUETOOTH_ERROR_NONE;
436 }
437
438 BT_EXPORT_API int bluetooth_l2cap_le_disconnect(int socket_fd)
439 {
440         l2cap_le_client_conn_info_t *conn_info;
441
442         BT_INFO_C("<<<<<<<<< L2CAP_LE Disconnect request from app >>>>>>>>");
443
444         BT_CHECK_ENABLED_ANY(return);
445         retv_if(socket_fd < 0, BLUETOOTH_ERROR_INVALID_PARAM);
446
447         if (_bt_check_privilege_le(BT_CHECK_PRIVILEGE, BT_L2CAP_LE_SOCKET_DISCONNECT)
448                         == BLUETOOTH_ERROR_PERMISSION_DEINED) {
449                 BT_ERR("Don't have a privilege to use this API");
450         }
451
452         BT_INFO("FD %d", socket_fd);
453
454         conn_info = __find_l2cap_le_conn_info_with_fd(socket_fd);
455         if (conn_info == NULL) {
456                 BT_INFO("Could not find in client, so check in server");
457                 /* Check for fd in server list and perform the disconnection if present */
458                 return bluetooth_l2cap_le_server_disconnect(socket_fd);
459         }
460
461         if (conn_info->watch_id <= 0) {
462                 BT_ERR("Invalid state");
463                 return BLUETOOTH_ERROR_NOT_CONNECTED;
464         }
465
466         close(conn_info->sock_fd);
467         __bt_l2cap_le_client_disconnected(conn_info);
468         __l2cap_le_remove_client_conn_info_t(conn_info);
469
470         return BLUETOOTH_ERROR_NONE;
471 }
472
473 static int __write_all(int fd, const char *buf, int len)
474 {
475         int sent = 0, try = 0;
476
477         BT_DBG("+");
478         while (len > 0) {
479                 int written;
480
481                 written = write(fd, buf, len);
482                 BT_DBG("written: %d, len %d", written, len);
483                 if (written < 0) {
484                         if (errno == EINTR || errno == EAGAIN) {
485                                 try++;
486                                 if (try <= 49)
487                                         continue;
488                         }
489                         return -1;
490                 }
491
492                 if (!written)
493                         return 0;
494
495                 len -= written;
496                 buf += written;
497                 sent += written;
498                 try = 0;
499         }
500
501         BT_DBG("-");
502         return sent;
503 }
504
505 BT_EXPORT_API int bluetooth_l2cap_le_write(int fd, const char *buf, int length)
506 {
507         int result;
508
509         BT_CHECK_ENABLED_LE(return);
510         BT_CHECK_PARAMETER(buf, return);
511
512         if (fd < 0) {
513                 BT_ERR("Invalid FD");
514                 return BLUETOOTH_ERROR_INVALID_PARAM;
515         }
516
517         retv_if(length <= 0, BLUETOOTH_ERROR_INVALID_PARAM);
518
519         switch (privilege_token) {
520         case 0:
521                 result = _bt_check_privilege_le(BT_CHECK_PRIVILEGE, BT_L2CAP_LE_SOCKET_WRITE);
522
523                 if (result == BLUETOOTH_ERROR_NONE) {
524                         privilege_token = 1; /* Have a permission */
525                 } else if (result == BLUETOOTH_ERROR_PERMISSION_DEINED) {
526                         BT_ERR("Don't have a privilege to use this API");
527                         privilege_token = -1; /* Don't have a permission */
528                         return BLUETOOTH_ERROR_PERMISSION_DEINED;
529                 } else {
530                         BT_ERR("Some error occurred");
531                         /* Just break - It is not related with permission error */
532                 }
533                 break;
534         case 1:
535                 /* Already have a privilege */
536                 break;
537         case -1:
538                 return BLUETOOTH_ERROR_PERMISSION_DEINED;
539         default:
540                 /* Invalid privilge token value */
541                 return BLUETOOTH_ERROR_INTERNAL;
542         }
543
544         result = __write_all(fd, buf, length);
545
546         return result;
547 }