tizen 2.3.1 release
[framework/connectivity/bluez.git] / android / socket.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2013-2014  Intel Corporation. All rights reserved.
6  *
7  *
8  *  This library is free software; you can redistribute it and/or
9  *  modify it under the terms of the GNU Lesser General Public
10  *  License as published by the Free Software Foundation; either
11  *  version 2.1 of the License, or (at your option) any later version.
12  *
13  *  This library is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  *  Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public
19  *  License along with this library; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <glib.h>
29 #include <stdbool.h>
30 #include <unistd.h>
31 #include <errno.h>
32
33 #include "lib/bluetooth.h"
34 #include "btio/btio.h"
35 #include "lib/sdp.h"
36 #include "lib/sdp_lib.h"
37 #include "src/sdp-client.h"
38 #include "src/sdpd.h"
39 #include "src/log.h"
40
41 #include "hal-msg.h"
42 #include "ipc-common.h"
43 #include "ipc.h"
44 #include "utils.h"
45 #include "bluetooth.h"
46 #include "socket.h"
47
48 #define RFCOMM_CHANNEL_MAX 30
49
50 #define OPP_DEFAULT_CHANNEL     9
51 #define HSP_AG_DEFAULT_CHANNEL  12
52 #define HFP_AG_DEFAULT_CHANNEL  13
53 #define PBAP_DEFAULT_CHANNEL    15
54 #define MAP_MAS_DEFAULT_CHANNEL 16
55
56 #define SVC_HINT_OBEX 0x10
57
58 /* Hardcoded MAP stuff needed for MAS SMS Instance.*/
59 #define DEFAULT_MAS_INSTANCE    0x00
60
61 #define MAP_MSG_TYPE_SMS_GSM    0x02
62 #define MAP_MSG_TYPE_SMS_CDMA   0x04
63 #define DEFAULT_MAS_MSG_TYPE    (MAP_MSG_TYPE_SMS_GSM | MAP_MSG_TYPE_SMS_CDMA)
64
65 static struct ipc *hal_ipc = NULL;
66 struct rfcomm_sock {
67         int channel;    /* RFCOMM channel */
68         BtIOSecLevel sec_level;
69
70         /* for socket to BT */
71         int bt_sock;
72         guint bt_watch;
73
74         /* for socket to HAL */
75         int jv_sock;
76         guint jv_watch;
77
78         bdaddr_t dst;
79         uint32_t service_handle;
80
81         uint8_t *buf;
82         int buf_size;
83 };
84
85 struct rfcomm_channel {
86         bool reserved;
87         struct rfcomm_sock *rfsock;
88 };
89
90 static bdaddr_t adapter_addr;
91
92 static uint8_t hal_mode = HAL_MODE_SOCKET_DEFAULT;
93
94 static const uint8_t zero_uuid[16] = { 0 };
95
96 /* Simple list of RFCOMM connected sockets */
97 static GList *connections = NULL;
98
99 static struct rfcomm_channel servers[RFCOMM_CHANNEL_MAX + 1];
100
101 static uint32_t test_sdp_record_uuid16 = 0;
102 static uint32_t test_sdp_record_uuid32 = 0;
103 static uint32_t test_sdp_record_uuid128 = 0;
104
105 static int rfsock_set_buffer(struct rfcomm_sock *rfsock)
106 {
107         socklen_t len = sizeof(int);
108         int rcv, snd, size, err;
109
110         err = getsockopt(rfsock->bt_sock, SOL_SOCKET, SO_RCVBUF, &rcv, &len);
111         if (err < 0) {
112                 int err = -errno;
113                 error("getsockopt(SO_RCVBUF): %s", strerror(-err));
114                 return err;
115         }
116
117         err = getsockopt(rfsock->bt_sock, SOL_SOCKET, SO_SNDBUF, &snd, &len);
118         if (err < 0) {
119                 int err = -errno;
120                 error("getsockopt(SO_SNDBUF): %s", strerror(-err));
121                 return err;
122         }
123
124         size = MAX(rcv, snd);
125
126         DBG("Set buffer size %d", size);
127
128         rfsock->buf = g_malloc(size);
129         rfsock->buf_size = size;
130
131         return 0;
132 }
133
134 static void cleanup_rfsock(gpointer data)
135 {
136         struct rfcomm_sock *rfsock = data;
137
138         DBG("rfsock %p bt_sock %d jv_sock %d", rfsock, rfsock->bt_sock,
139                                                         rfsock->jv_sock);
140
141         if (rfsock->jv_sock >= 0)
142                 if (close(rfsock->jv_sock) < 0)
143                         error("close() fd %d failed: %s", rfsock->jv_sock,
144                                                         strerror(errno));
145
146         if (rfsock->bt_sock >= 0)
147                 if (close(rfsock->bt_sock) < 0)
148                         error("close() fd %d: failed: %s", rfsock->bt_sock,
149                                                         strerror(errno));
150
151         if (rfsock->bt_watch > 0)
152                 if (!g_source_remove(rfsock->bt_watch))
153                         error("bt_watch source was not found");
154
155         if (rfsock->jv_watch > 0)
156                 if (!g_source_remove(rfsock->jv_watch))
157                         error("stack_watch source was not found");
158
159         if (rfsock->service_handle)
160                 bt_adapter_remove_record(rfsock->service_handle);
161
162         if (rfsock->buf)
163                 g_free(rfsock->buf);
164
165         g_free(rfsock);
166 }
167
168 static struct rfcomm_sock *create_rfsock(int bt_sock, int *hal_sock)
169 {
170         int fds[2] = {-1, -1};
171         struct rfcomm_sock *rfsock;
172
173         if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) < 0) {
174                 error("socketpair(): %s", strerror(errno));
175                 *hal_sock = -1;
176                 return NULL;
177         }
178
179         rfsock = g_new0(struct rfcomm_sock, 1);
180         rfsock->jv_sock = fds[0];
181         *hal_sock = fds[1];
182         rfsock->bt_sock = bt_sock;
183
184         DBG("rfsock %p", rfsock);
185
186         if (bt_sock < 0)
187                 return rfsock;
188
189         if (rfsock_set_buffer(rfsock) < 0) {
190                 cleanup_rfsock(rfsock);
191                 return NULL;
192         }
193
194         return rfsock;
195 }
196
197 static sdp_record_t *create_rfcomm_record(uint8_t chan, uuid_t *uuid,
198                                                 const char *svc_name,
199                                                 bool has_obex)
200 {
201         sdp_list_t *svclass_id;
202         sdp_list_t *seq, *proto_seq, *pbg_seq;
203         sdp_list_t *proto[3];
204         uuid_t l2cap_uuid, rfcomm_uuid, obex_uuid, pbg_uuid;
205         sdp_data_t *channel;
206         sdp_record_t *record;
207
208         record = sdp_record_alloc();
209         if (!record)
210                 return NULL;
211
212         record->handle =  sdp_next_handle();
213
214         svclass_id = sdp_list_append(NULL, uuid);
215         sdp_set_service_classes(record, svclass_id);
216
217         sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
218         proto[0] = sdp_list_append(NULL, &l2cap_uuid);
219         seq = sdp_list_append(NULL, proto[0]);
220
221         sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
222         proto[1] = sdp_list_append(NULL, &rfcomm_uuid);
223         channel = sdp_data_alloc(SDP_UINT8, &chan);
224         proto[1] = sdp_list_append(proto[1], channel);
225         seq = sdp_list_append(seq, proto[1]);
226
227         if (has_obex) {
228                 sdp_uuid16_create(&obex_uuid, OBEX_UUID);
229                 proto[2] = sdp_list_append(NULL, &obex_uuid);
230                 seq = sdp_list_append(seq, proto[2]);
231         }
232
233         proto_seq = sdp_list_append(NULL, seq);
234         sdp_set_access_protos(record, proto_seq);
235
236         sdp_uuid16_create(&pbg_uuid, PUBLIC_BROWSE_GROUP);
237         pbg_seq = sdp_list_append(NULL, &pbg_uuid);
238         sdp_set_browse_groups(record, pbg_seq);
239
240         if (svc_name)
241                 sdp_set_info_attr(record, svc_name, NULL, NULL);
242
243         sdp_data_free(channel);
244         sdp_list_free(proto[0], NULL);
245         sdp_list_free(proto[1], NULL);
246         if (has_obex)
247                 sdp_list_free(proto[2], NULL);
248         sdp_list_free(seq, NULL);
249         sdp_list_free(proto_seq, NULL);
250         sdp_list_free(pbg_seq, NULL);
251         sdp_list_free(svclass_id, NULL);
252
253         return record;
254 }
255
256 static sdp_record_t *create_opp_record(uint8_t chan, const char *svc_name)
257 {
258         uint8_t formats[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xff };
259         uint8_t dtd = SDP_UINT8;
260         uuid_t uuid;
261         sdp_list_t *seq;
262         sdp_profile_desc_t profile[1];
263         void *dtds[sizeof(formats)], *values[sizeof(formats)];
264         sdp_data_t *formats_list;
265         sdp_record_t *record;
266         size_t i;
267
268         sdp_uuid16_create(&uuid, OBEX_OBJPUSH_SVCLASS_ID);
269
270         record = create_rfcomm_record(chan, &uuid, svc_name, true);
271         if (!record)
272                 return NULL;
273
274         sdp_uuid16_create(&profile[0].uuid, OBEX_OBJPUSH_PROFILE_ID);
275         profile[0].version = 0x0100;
276         seq = sdp_list_append(NULL, profile);
277         sdp_set_profile_descs(record, seq);
278
279         for (i = 0; i < sizeof(formats); i++) {
280                 dtds[i] = &dtd;
281                 values[i] = &formats[i];
282         }
283         formats_list = sdp_seq_alloc(dtds, values, sizeof(formats));
284         sdp_attr_add(record, SDP_ATTR_SUPPORTED_FORMATS_LIST, formats_list);
285
286         sdp_list_free(seq, NULL);
287
288         return record;
289 }
290
291 static sdp_record_t *create_pbap_record(uint8_t chan, const char *svc_name)
292 {
293         sdp_list_t *seq;
294         sdp_profile_desc_t profile[1];
295         uint8_t formats = 0x01;
296         sdp_record_t *record;
297         uuid_t uuid;
298
299         sdp_uuid16_create(&uuid, PBAP_PSE_SVCLASS_ID);
300
301         record = create_rfcomm_record(chan, &uuid, svc_name, true);
302         if (!record)
303                 return NULL;
304
305         sdp_uuid16_create(&profile[0].uuid, PBAP_PROFILE_ID);
306         profile[0].version = 0x0101;
307         seq = sdp_list_append(NULL, profile);
308         sdp_set_profile_descs(record, seq);
309
310         sdp_attr_add_new(record, SDP_ATTR_SUPPORTED_REPOSITORIES, SDP_UINT8,
311                                                                 &formats);
312
313         sdp_list_free(seq, NULL);
314
315         return record;
316 }
317
318 static sdp_record_t *create_mas_record(uint8_t chan, const char *svc_name)
319 {
320         sdp_list_t *seq;
321         sdp_profile_desc_t profile[1];
322         uint8_t minst, mtype;
323         sdp_record_t *record;
324         uuid_t uuid;
325         int cnt, ret;
326
327         switch (hal_mode) {
328         case HAL_MODE_SOCKET_DYNAMIC_MAP:
329                 /*
330                  * Service name for MAP is passed as XXYYname
331                  * XX - instance
332                  * YY - message type
333                  */
334                 ret = sscanf(svc_name, "%02hhx%02hhx%n", &minst, &mtype, &cnt);
335                 if (ret != 2 || cnt != 4)
336                         return NULL;
337
338                 svc_name += 4;
339                 break;
340         case HAL_MODE_SOCKET_DEFAULT:
341                 minst = DEFAULT_MAS_INSTANCE;
342                 mtype = DEFAULT_MAS_MSG_TYPE;
343                 break;
344         default:
345                 return NULL;
346         }
347
348         sdp_uuid16_create(&uuid, MAP_MSE_SVCLASS_ID);
349
350         record = create_rfcomm_record(chan, &uuid, svc_name, true);
351         if (!record)
352                 return NULL;
353
354         sdp_uuid16_create(&profile[0].uuid, MAP_PROFILE_ID);
355         profile[0].version = 0x0101;
356         seq = sdp_list_append(NULL, profile);
357         sdp_set_profile_descs(record, seq);
358
359         sdp_attr_add_new(record, SDP_ATTR_MAS_INSTANCE_ID, SDP_UINT8, &minst);
360         sdp_attr_add_new(record, SDP_ATTR_SUPPORTED_MESSAGE_TYPES, SDP_UINT8,
361                                                                         &mtype);
362
363         sdp_list_free(seq, NULL);
364
365         return record;
366 }
367
368 static sdp_record_t *create_spp_record(uint8_t chan, const char *svc_name)
369 {
370         sdp_record_t *record;
371         uuid_t uuid;
372
373         sdp_uuid16_create(&uuid, SERIAL_PORT_SVCLASS_ID);
374
375         record = create_rfcomm_record(chan, &uuid, svc_name, false);
376         if (!record)
377                 return NULL;
378
379         return record;
380 }
381
382 static sdp_record_t *create_app_record(uint8_t chan,
383                                                 const uint8_t *app_uuid,
384                                                 const char *svc_name)
385 {
386         sdp_record_t *record;
387         uuid_t uuid;
388
389         sdp_uuid128_create(&uuid, app_uuid);
390         sdp_uuid128_to_uuid(&uuid);
391
392         record = create_rfcomm_record(chan, &uuid, svc_name, false);
393         if (!record)
394                 return NULL;
395
396         return record;
397 }
398
399 static const struct profile_info {
400         uint8_t         uuid[16];
401         uint8_t         channel;
402         uint8_t         svc_hint;
403         BtIOSecLevel    sec_level;
404         sdp_record_t *  (*create_record)(uint8_t chan, const char *svc_name);
405 } profiles[] = {
406         {
407                 .uuid = {
408                         0x00, 0x00, 0x11, 0x08, 0x00, 0x00, 0x10, 0x00,
409                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB
410                 },
411                 .channel = HSP_AG_DEFAULT_CHANNEL,
412                 .svc_hint = 0,
413                 .sec_level = BT_IO_SEC_MEDIUM,
414                 .create_record = NULL
415         }, {
416                 .uuid = {
417                         0x00, 0x00, 0x11, 0x1F, 0x00, 0x00, 0x10, 0x00,
418                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB
419                 },
420                 .channel = HFP_AG_DEFAULT_CHANNEL,
421                 .svc_hint = 0,
422                 .sec_level = BT_IO_SEC_MEDIUM,
423                 .create_record = NULL
424         }, {
425                 .uuid = {
426                         0x00, 0x00, 0x11, 0x2F, 0x00, 0x00, 0x10, 0x00,
427                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB
428                 },
429                 .channel = PBAP_DEFAULT_CHANNEL,
430                 .svc_hint = SVC_HINT_OBEX,
431                 .sec_level = BT_IO_SEC_MEDIUM,
432                 .create_record = create_pbap_record
433         }, {
434                 .uuid = {
435                         0x00, 0x00, 0x11, 0x05, 0x00, 0x00, 0x10, 0x00,
436                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB
437                   },
438                 .channel = OPP_DEFAULT_CHANNEL,
439                 .svc_hint = SVC_HINT_OBEX,
440                 .sec_level = BT_IO_SEC_LOW,
441                 .create_record = create_opp_record
442         }, {
443                 .uuid = {
444                         0x00, 0x00, 0x11, 0x32, 0x00, 0x00, 0x10, 0x00,
445                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB
446                 },
447                 .channel = MAP_MAS_DEFAULT_CHANNEL,
448                 .svc_hint = SVC_HINT_OBEX,
449                 .sec_level = BT_IO_SEC_MEDIUM,
450                 .create_record = create_mas_record
451         }, {
452                 .uuid = {
453                         0x00, 0x00, 0x11, 0x01, 0x00, 0x00, 0x10, 0x00,
454                         0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB
455                 },
456                 .channel = 0,
457                 .svc_hint = 0,
458                 .sec_level = BT_IO_SEC_MEDIUM,
459                 .create_record = create_spp_record
460         },
461 };
462
463 static uint32_t sdp_service_register(uint8_t channel, const uint8_t *uuid,
464                                         const struct profile_info *profile,
465                                         const void *svc_name)
466 {
467         sdp_record_t *record = NULL;
468         uint8_t svc_hint = 0;
469
470         if (profile && profile->create_record) {
471                 record = profile->create_record(channel, svc_name);
472                 svc_hint = profile->svc_hint;
473         } else if (uuid) {
474                 record = create_app_record(channel, uuid, svc_name);
475         }
476
477         if (!record)
478                 return 0;
479
480         if (bt_adapter_add_record(record, svc_hint) < 0) {
481                 error("Failed to register on SDP record");
482                 sdp_record_free(record);
483                 return 0;
484         }
485
486         return record->handle;
487 }
488
489 static int bt_sock_send_fd(int sock_fd, const void *buf, int len, int send_fd)
490 {
491         ssize_t ret;
492         struct msghdr msg;
493         struct cmsghdr *cmsg;
494         struct iovec iv;
495         char cmsgbuf[CMSG_SPACE(sizeof(int))];
496
497         DBG("len %d sock_fd %d send_fd %d", len, sock_fd, send_fd);
498
499         if (sock_fd == -1 || send_fd == -1)
500                 return -1;
501
502         memset(&msg, 0, sizeof(msg));
503         memset(cmsgbuf, 0, sizeof(cmsgbuf));
504
505         msg.msg_control = cmsgbuf;
506         msg.msg_controllen = sizeof(cmsgbuf);
507
508         cmsg = CMSG_FIRSTHDR(&msg);
509         cmsg->cmsg_level = SOL_SOCKET;
510         cmsg->cmsg_type = SCM_RIGHTS;
511         cmsg->cmsg_len = CMSG_LEN(sizeof(send_fd));
512
513         memcpy(CMSG_DATA(cmsg), &send_fd, sizeof(send_fd));
514
515         iv.iov_base = (unsigned char *) buf;
516         iv.iov_len = len;
517
518         msg.msg_iov = &iv;
519         msg.msg_iovlen = 1;
520
521         ret = sendmsg(sock_fd, &msg, MSG_NOSIGNAL);
522         if (ret < 0) {
523                 error("sendmsg(): sock_fd %d send_fd %d: %s",
524                                         sock_fd, send_fd, strerror(errno));
525                 return ret;
526         }
527
528         return ret;
529 }
530
531 static const struct profile_info *get_profile_by_uuid(const uint8_t *uuid)
532 {
533         unsigned int i;
534
535         for (i = 0; i < G_N_ELEMENTS(profiles); i++) {
536                 if (!memcmp(profiles[i].uuid, uuid, 16))
537                         return &profiles[i];
538         }
539
540         return NULL;
541 }
542
543 static int try_write_all(int fd, unsigned char *buf, int len)
544 {
545         int sent = 0;
546
547         while (len > 0) {
548                 int written;
549
550                 written = write(fd, buf, len);
551                 if (written < 0) {
552                         if (errno == EINTR || errno == EAGAIN)
553                                 continue;
554                         return -1;
555                 }
556
557                 if (!written)
558                         return 0;
559
560                 len -= written; buf += written; sent += written;
561         }
562
563         return sent;
564 }
565
566 static gboolean jv_sock_client_event_cb(GIOChannel *io, GIOCondition cond,
567                                                                 gpointer data)
568 {
569         struct rfcomm_sock *rfsock = data;
570         int len, sent;
571
572         if (cond & G_IO_HUP) {
573                 DBG("Socket %d hang up", g_io_channel_unix_get_fd(io));
574                 goto fail;
575         }
576
577         if (cond & (G_IO_ERR | G_IO_NVAL)) {
578                 error("Socket %d error", g_io_channel_unix_get_fd(io));
579                 goto fail;
580         }
581
582         len = read(rfsock->jv_sock, rfsock->buf, rfsock->buf_size);
583         if (len <= 0) {
584                 error("read(): %s", strerror(errno));
585                 /* Read again */
586                 return TRUE;
587         }
588
589         sent = try_write_all(rfsock->bt_sock, rfsock->buf, len);
590         if (sent < 0) {
591                 error("write(): %s", strerror(errno));
592                 goto fail;
593         }
594
595         return TRUE;
596 fail:
597         DBG("rfsock %p jv_sock %d cond %d", rfsock, rfsock->jv_sock, cond);
598
599         connections = g_list_remove(connections, rfsock);
600         cleanup_rfsock(rfsock);
601
602         return FALSE;
603 }
604
605 static gboolean bt_sock_event_cb(GIOChannel *io, GIOCondition cond,
606                                                                 gpointer data)
607 {
608         struct rfcomm_sock *rfsock = data;
609         int len, sent;
610
611         if (cond & G_IO_HUP) {
612                 DBG("Socket %d hang up", g_io_channel_unix_get_fd(io));
613                 goto fail;
614         }
615
616         if (cond & (G_IO_ERR | G_IO_NVAL)) {
617                 error("Socket %d error", g_io_channel_unix_get_fd(io));
618                 goto fail;
619         }
620
621         len = read(rfsock->bt_sock, rfsock->buf, rfsock->buf_size);
622         if (len <= 0) {
623                 error("read(): %s", strerror(errno));
624                 /* Read again */
625                 return TRUE;
626         }
627
628         sent = try_write_all(rfsock->jv_sock, rfsock->buf, len);
629         if (sent < 0) {
630                 error("write(): %s", strerror(errno));
631                 goto fail;
632         }
633
634         return TRUE;
635 fail:
636         DBG("rfsock %p bt_sock %d cond %d", rfsock, rfsock->bt_sock, cond);
637
638         connections = g_list_remove(connections, rfsock);
639         cleanup_rfsock(rfsock);
640
641         return FALSE;
642 }
643
644 static bool sock_send_accept(struct rfcomm_sock *rfsock, bdaddr_t *bdaddr,
645                                                         int fd_accepted)
646 {
647         struct hal_sock_connect_signal cmd;
648         int len;
649
650         DBG("");
651
652         cmd.size = sizeof(cmd);
653         bdaddr2android(bdaddr, cmd.bdaddr);
654         cmd.channel = rfsock->channel;
655         cmd.status = 0;
656
657         len = bt_sock_send_fd(rfsock->jv_sock, &cmd, sizeof(cmd), fd_accepted);
658         if (len != sizeof(cmd)) {
659                 error("Error sending accept signal");
660                 return false;
661         }
662
663         return true;
664 }
665
666 static gboolean jv_sock_server_event_cb(GIOChannel *io, GIOCondition cond,
667                                                                 gpointer data)
668 {
669         struct rfcomm_sock *rfsock = data;
670
671         DBG("rfsock %p jv_sock %d cond %d", rfsock, rfsock->jv_sock, cond);
672
673         if (cond & G_IO_NVAL)
674                 return FALSE;
675
676         if (cond & (G_IO_ERR | G_IO_HUP)) {
677                 servers[rfsock->channel].rfsock = NULL;
678                 cleanup_rfsock(rfsock);
679         }
680
681         return FALSE;
682 }
683
684 static void accept_cb(GIOChannel *io, GError *err, gpointer user_data)
685 {
686         struct rfcomm_sock *rfsock = user_data;
687         struct rfcomm_sock *new_rfsock;
688         GIOChannel *jv_io;
689         GError *gerr = NULL;
690         bdaddr_t dst;
691         char address[18];
692         int new_sock;
693         int hal_sock;
694         guint id;
695         GIOCondition cond;
696
697         if (err) {
698                 error("%s", err->message);
699                 return;
700         }
701
702         bt_io_get(io, &gerr,
703                         BT_IO_OPT_DEST_BDADDR, &dst,
704                         BT_IO_OPT_INVALID);
705         if (gerr) {
706                 error("%s", gerr->message);
707                 g_error_free(gerr);
708                 g_io_channel_shutdown(io, TRUE, NULL);
709                 return;
710         }
711
712         ba2str(&dst, address);
713         DBG("Incoming connection from %s on channel %d (rfsock %p)", address,
714                                                 rfsock->channel, rfsock);
715
716         new_sock = g_io_channel_unix_get_fd(io);
717         new_rfsock = create_rfsock(new_sock, &hal_sock);
718         if (!new_rfsock) {
719                 g_io_channel_shutdown(io, TRUE, NULL);
720                 return;
721         }
722
723         DBG("new rfsock %p bt_sock %d jv_sock %d hal_sock %d", new_rfsock,
724                         new_rfsock->bt_sock, new_rfsock->jv_sock, hal_sock);
725
726         if (!sock_send_accept(rfsock, &dst, hal_sock)) {
727                 cleanup_rfsock(new_rfsock);
728                 return;
729         }
730
731         connections = g_list_append(connections, new_rfsock);
732
733         /* Handle events from Android */
734         cond = G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL;
735         jv_io = g_io_channel_unix_new(new_rfsock->jv_sock);
736         id = g_io_add_watch(jv_io, cond, jv_sock_client_event_cb, new_rfsock);
737         g_io_channel_unref(jv_io);
738
739         new_rfsock->jv_watch = id;
740
741         /* Handle rfcomm events */
742         cond = G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL;
743         id = g_io_add_watch(io, cond, bt_sock_event_cb, new_rfsock);
744         g_io_channel_set_close_on_unref(io, FALSE);
745
746         new_rfsock->bt_watch = id;
747 }
748
749 static int find_free_channel(void)
750 {
751         int ch;
752
753         /* channel 0 is reserver so we don't use it */
754         for (ch = 1; ch <= RFCOMM_CHANNEL_MAX; ch++) {
755                 struct rfcomm_channel *srv = &servers[ch];
756
757                 if (!srv->reserved && srv->rfsock == NULL)
758                         return ch;
759         }
760
761         return 0;
762 }
763
764 static BtIOSecLevel get_sec_level(uint8_t flags)
765 {
766         /*
767          * HAL_SOCK_FLAG_AUTH should require MITM but in our case setting
768          * security to BT_IO_SEC_HIGH would also require 16-digits PIN code
769          * for pre-2.1 devices which is not what Android expects. For this
770          * reason we ignore this flag to not break apps which use "secure"
771          * sockets (have both auth and encrypt flags set, there is no public
772          * API in Android which should provide proper high security socket).
773          */
774         return flags & HAL_SOCK_FLAG_ENCRYPT ? BT_IO_SEC_MEDIUM :
775                                                         BT_IO_SEC_LOW;
776 }
777
778 static uint8_t rfcomm_listen(int chan, const uint8_t *name, const uint8_t *uuid,
779                                                 uint8_t flags, int *hal_sock)
780 {
781         const struct profile_info *profile;
782         struct rfcomm_sock *rfsock = NULL;
783         BtIOSecLevel sec_level;
784         GIOChannel *io, *jv_io;
785         GIOCondition cond;
786         GError *err = NULL;
787         guint id;
788         uuid_t uu;
789         char uuid_str[32];
790
791         sdp_uuid128_create(&uu, uuid);
792         sdp_uuid2strn(&uu, uuid_str, sizeof(uuid_str));
793
794         DBG("chan %d flags 0x%02x uuid %s name %s", chan, flags, uuid_str,
795                                                                         name);
796
797         if ((!memcmp(uuid, zero_uuid, sizeof(zero_uuid)) && chan <= 0) ||
798                         (chan > RFCOMM_CHANNEL_MAX)) {
799                 error("Invalid rfcomm listen params");
800                 return HAL_STATUS_INVALID;
801         }
802
803         profile = get_profile_by_uuid(uuid);
804         if (!profile) {
805                 sec_level = get_sec_level(flags);
806         } else {
807                 if (!profile->create_record)
808                         return HAL_STATUS_INVALID;
809
810                 chan = profile->channel;
811                 sec_level = profile->sec_level;
812         }
813
814         if (chan <= 0)
815                 chan = find_free_channel();
816
817         if (!chan) {
818                 error("No free channels");
819                 return HAL_STATUS_BUSY;
820         }
821
822         if (servers[chan].rfsock != NULL) {
823                 error("Channel already registered (%d)", chan);
824                 return HAL_STATUS_BUSY;
825         }
826
827         DBG("chan %d sec_level %d", chan, sec_level);
828
829         rfsock = create_rfsock(-1, hal_sock);
830         if (!rfsock)
831                 return HAL_STATUS_FAILED;
832
833         rfsock->channel = chan;
834
835         io = bt_io_listen(accept_cb, NULL, rfsock, NULL, &err,
836                                 BT_IO_OPT_SOURCE_BDADDR, &adapter_addr,
837                                 BT_IO_OPT_CHANNEL, chan,
838                                 BT_IO_OPT_SEC_LEVEL, sec_level,
839                                 BT_IO_OPT_INVALID);
840         if (!io) {
841                 error("Failed listen: %s", err->message);
842                 g_error_free(err);
843                 goto failed;
844         }
845
846         rfsock->bt_sock = g_io_channel_unix_get_fd(io);
847
848         g_io_channel_set_close_on_unref(io, FALSE);
849         g_io_channel_unref(io);
850
851         /* Handle events from Android */
852         cond = G_IO_HUP | G_IO_ERR | G_IO_NVAL;
853         jv_io = g_io_channel_unix_new(rfsock->jv_sock);
854         id = g_io_add_watch_full(jv_io, G_PRIORITY_HIGH, cond,
855                                         jv_sock_server_event_cb, rfsock,
856                                         NULL);
857         g_io_channel_unref(jv_io);
858
859         rfsock->jv_watch = id;
860
861         DBG("rfsock %p bt_sock %d jv_sock %d hal_sock %d", rfsock,
862                                                                 rfsock->bt_sock,
863                                                                 rfsock->jv_sock,
864                                                                 *hal_sock);
865
866         if (write(rfsock->jv_sock, &chan, sizeof(chan)) != sizeof(chan)) {
867                 error("Error sending RFCOMM channel");
868                 goto failed;
869         }
870
871         rfsock->service_handle = sdp_service_register(chan, uuid, profile,
872                                                                         name);
873
874         servers[chan].rfsock = rfsock;
875
876         return HAL_STATUS_SUCCESS;
877
878 failed:
879
880         cleanup_rfsock(rfsock);
881         close(*hal_sock);
882         return HAL_STATUS_FAILED;
883 }
884
885 static uint32_t add_test_record(uuid_t *uuid)
886 {
887         sdp_record_t *record;
888         sdp_list_t *svclass_id;
889         sdp_list_t *seq, *pbg_seq, *proto_seq, *ap_seq;
890         sdp_list_t *proto, *proto1, *aproto;
891         uuid_t l2cap_uuid, pbg_uuid, ap_uuid;
892
893         record = sdp_record_alloc();
894         if (!record)
895                 return 0;
896
897         record->handle =  sdp_next_handle();
898
899         svclass_id = sdp_list_append(NULL, uuid);
900         sdp_set_service_classes(record, svclass_id);
901
902         sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
903         proto = sdp_list_append(NULL, &l2cap_uuid);
904         seq = sdp_list_append(NULL, proto);
905
906         proto_seq = sdp_list_append(NULL, seq);
907         sdp_set_access_protos(record, proto_seq);
908
909         sdp_uuid16_create(&pbg_uuid, PUBLIC_BROWSE_GROUP);
910         pbg_seq = sdp_list_append(NULL, &pbg_uuid);
911         sdp_set_browse_groups(record, pbg_seq);
912
913         /* Additional Protocol Descriptor List */
914         sdp_uuid16_create(&ap_uuid, L2CAP_UUID);
915         proto1 = sdp_list_append(NULL, &ap_uuid);
916         ap_seq = sdp_list_append(NULL, proto1);
917         aproto = sdp_list_append(NULL, ap_seq);
918         sdp_set_add_access_protos(record, aproto);
919
920         sdp_set_service_id(record, *uuid);
921         sdp_set_record_state(record, 0);
922         sdp_set_service_ttl(record, 0);
923         sdp_set_service_avail(record, 0);
924         sdp_set_url_attr(record, "http://www.bluez.org",
925                                 "http://www.bluez.org", "http://www.bluez.org");
926
927         sdp_list_free(proto, NULL);
928         sdp_list_free(seq, NULL);
929         sdp_list_free(proto_seq, NULL);
930         sdp_list_free(pbg_seq, NULL);
931         sdp_list_free(svclass_id, NULL);
932
933         if (bt_adapter_add_record(record, 0) < 0) {
934                 sdp_record_free(record);
935                 return 0;
936         }
937
938         return record->handle;
939 }
940
941 static void test_sdp_cleanup(void)
942 {
943         if (test_sdp_record_uuid16) {
944                 bt_adapter_remove_record(test_sdp_record_uuid16);
945                 test_sdp_record_uuid16 = 0;
946         }
947
948         if (test_sdp_record_uuid32) {
949                 bt_adapter_remove_record(test_sdp_record_uuid32);
950                 test_sdp_record_uuid32 = 0;
951         }
952
953         if (test_sdp_record_uuid128) {
954                 bt_adapter_remove_record(test_sdp_record_uuid128);
955                 test_sdp_record_uuid128 = 0;
956         }
957 }
958
959 static void test_sdp_init(void)
960 {
961         char uuid128[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
962                                 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
963         uuid_t u;
964
965         sdp_uuid16_create(&u, 0xffff);
966         test_sdp_record_uuid16 = add_test_record(&u);
967
968         sdp_uuid32_create(&u, 0xffffffff);
969         test_sdp_record_uuid32 = add_test_record(&u);
970
971         sdp_uuid128_create(&u, uuid128);
972         test_sdp_record_uuid128 = add_test_record(&u);
973 }
974
975 static uint8_t l2cap_listen(int chan, const uint8_t *name, const uint8_t *uuid,
976                                                 uint8_t flags, int *hal_sock)
977 {
978         /* TODO be more strict here? */
979         if (strcmp("BlueZ", (const char *) name)) {
980                 error("socket: Only SDP test supported on L2CAP");
981                 return HAL_STATUS_UNSUPPORTED;
982         }
983
984         test_sdp_cleanup();
985         test_sdp_init();
986
987         *hal_sock = -1;
988
989         return HAL_STATUS_SUCCESS;
990 }
991
992 static void handle_listen(const void *buf, uint16_t len)
993 {
994         const struct hal_cmd_socket_listen *cmd = buf;
995         uint8_t status;
996         int hal_sock;
997
998         switch (cmd->type) {
999         case HAL_SOCK_RFCOMM:
1000                 status = rfcomm_listen(cmd->channel, cmd->name, cmd->uuid,
1001                                                         cmd->flags, &hal_sock);
1002                 break;
1003         case HAL_SOCK_L2CAP:
1004                 status = l2cap_listen(cmd->channel, cmd->name, cmd->uuid,
1005                                                         cmd->flags, &hal_sock);
1006                 break;
1007         case HAL_SOCK_SCO:
1008                 status = HAL_STATUS_UNSUPPORTED;
1009                 break;
1010         default:
1011                 status = HAL_STATUS_INVALID;
1012                 break;
1013         }
1014
1015         if (status != HAL_STATUS_SUCCESS)
1016                 goto failed;
1017
1018         ipc_send_rsp_full(hal_ipc, HAL_SERVICE_ID_SOCKET, HAL_OP_SOCKET_LISTEN,
1019                                                         0, NULL, hal_sock);
1020         close(hal_sock);
1021         return;
1022
1023 failed:
1024         ipc_send_rsp(hal_ipc, HAL_SERVICE_ID_SOCKET, HAL_OP_SOCKET_LISTEN,
1025                                                                         status);
1026 }
1027
1028 static bool sock_send_connect(struct rfcomm_sock *rfsock, bdaddr_t *bdaddr)
1029 {
1030         struct hal_sock_connect_signal cmd;
1031         int len;
1032
1033         DBG("");
1034
1035         memset(&cmd, 0, sizeof(cmd));
1036         cmd.size = sizeof(cmd);
1037         bdaddr2android(bdaddr, cmd.bdaddr);
1038         cmd.channel = rfsock->channel;
1039         cmd.status = 0;
1040
1041         len = write(rfsock->jv_sock, &cmd, sizeof(cmd));
1042         if (len < 0) {
1043                 error("%s", strerror(errno));
1044                 return false;
1045         }
1046
1047         if (len != sizeof(cmd)) {
1048                 error("Error sending connect signal");
1049                 return false;
1050         }
1051
1052         return true;
1053 }
1054
1055 static void connect_cb(GIOChannel *io, GError *err, gpointer user_data)
1056 {
1057         struct rfcomm_sock *rfsock = user_data;
1058         bdaddr_t *dst = &rfsock->dst;
1059         GIOChannel *jv_io;
1060         char address[18];
1061         guint id;
1062         GIOCondition cond;
1063
1064         if (err) {
1065                 error("%s", err->message);
1066                 goto fail;
1067         }
1068
1069         ba2str(dst, address);
1070         DBG("Connected to %s on channel %d (rfsock %p)", address,
1071                                                 rfsock->channel, rfsock);
1072
1073         if (!sock_send_connect(rfsock, dst))
1074                 goto fail;
1075
1076         /* Handle events from Android */
1077         cond = G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL;
1078         jv_io = g_io_channel_unix_new(rfsock->jv_sock);
1079         id = g_io_add_watch(jv_io, cond, jv_sock_client_event_cb, rfsock);
1080         g_io_channel_unref(jv_io);
1081
1082         rfsock->jv_watch = id;
1083
1084         /* Handle rfcomm events */
1085         cond = G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL;
1086         id = g_io_add_watch(io, cond, bt_sock_event_cb, rfsock);
1087         g_io_channel_set_close_on_unref(io, FALSE);
1088
1089         rfsock->bt_watch = id;
1090
1091         return;
1092 fail:
1093         connections = g_list_remove(connections, rfsock);
1094         cleanup_rfsock(rfsock);
1095 }
1096
1097 static bool do_rfcomm_connect(struct rfcomm_sock *rfsock, int chan)
1098 {
1099         GIOChannel *io;
1100         GError *gerr = NULL;
1101
1102         DBG("rfsock %p sec_level %d chan %d", rfsock, rfsock->sec_level, chan);
1103
1104         io = bt_io_connect(connect_cb, rfsock, NULL, &gerr,
1105                                 BT_IO_OPT_SOURCE_BDADDR, &adapter_addr,
1106                                 BT_IO_OPT_DEST_BDADDR, &rfsock->dst,
1107                                 BT_IO_OPT_CHANNEL, chan,
1108                                 BT_IO_OPT_SEC_LEVEL, rfsock->sec_level,
1109                                 BT_IO_OPT_INVALID);
1110         if (!io) {
1111                 error("Failed connect: %s", gerr->message);
1112                 g_error_free(gerr);
1113                 return false;
1114         }
1115
1116         g_io_channel_set_close_on_unref(io, FALSE);
1117         g_io_channel_unref(io);
1118
1119         if (write(rfsock->jv_sock, &chan, sizeof(chan)) != sizeof(chan)) {
1120                 error("Error sending RFCOMM channel");
1121                 return false;
1122         }
1123
1124         rfsock->bt_sock = g_io_channel_unix_get_fd(io);
1125         rfsock_set_buffer(rfsock);
1126         rfsock->channel = chan;
1127         connections = g_list_append(connections, rfsock);
1128
1129         return true;
1130 }
1131
1132 static void sdp_search_cb(sdp_list_t *recs, int err, gpointer data)
1133 {
1134         struct rfcomm_sock *rfsock = data;
1135         sdp_list_t *list;
1136         int chan;
1137
1138         DBG("");
1139
1140         if (err < 0) {
1141                 error("Unable to get SDP record: %s", strerror(-err));
1142                 goto fail;
1143         }
1144
1145         if (!recs || !recs->data) {
1146                 error("No SDP records found");
1147                 goto fail;
1148         }
1149
1150         for (list = recs; list != NULL; list = list->next) {
1151                 sdp_record_t *rec = list->data;
1152                 sdp_list_t *protos;
1153
1154                 if (sdp_get_access_protos(rec, &protos) < 0) {
1155                         error("Unable to get proto list");
1156                         goto fail;
1157                 }
1158
1159                 chan = sdp_get_proto_port(protos, RFCOMM_UUID);
1160
1161                 sdp_list_foreach(protos, (sdp_list_func_t) sdp_list_free,
1162                                                                         NULL);
1163                 sdp_list_free(protos, NULL);
1164
1165                 if (chan)
1166                         break;
1167         }
1168
1169         if (chan <= 0) {
1170                 error("Could not get RFCOMM channel %d", chan);
1171                 goto fail;
1172         }
1173
1174         DBG("Got RFCOMM channel %d", chan);
1175
1176         if (do_rfcomm_connect(rfsock, chan))
1177                 return;
1178 fail:
1179         cleanup_rfsock(rfsock);
1180 }
1181
1182 static uint8_t connect_rfcomm(const bdaddr_t *addr, int chan,
1183                                         const uint8_t *uuid, uint8_t flags,
1184                                         int *hal_sock)
1185 {
1186         struct rfcomm_sock *rfsock;
1187         char address[18];
1188         uuid_t uu;
1189         char uuid_str[32];
1190
1191         sdp_uuid128_create(&uu, uuid);
1192         sdp_uuid2strn(&uu, uuid_str, sizeof(uuid_str));
1193         ba2str(addr, address);
1194
1195         DBG("addr %s chan %d flags 0x%02x uuid %s", address, chan, flags,
1196                                                                 uuid_str);
1197
1198         if ((!memcmp(uuid, zero_uuid, sizeof(zero_uuid)) && chan <= 0) ||
1199                                                 !bacmp(addr, BDADDR_ANY)) {
1200                 error("Invalid rfcomm connect params");
1201                 return HAL_STATUS_INVALID;
1202         }
1203
1204         rfsock = create_rfsock(-1, hal_sock);
1205         if (!rfsock)
1206                 return HAL_STATUS_FAILED;
1207
1208         DBG("rfsock %p jv_sock %d hal_sock %d", rfsock, rfsock->jv_sock,
1209                                                         *hal_sock);
1210
1211         rfsock->sec_level = get_sec_level(flags);
1212
1213         bacpy(&rfsock->dst, addr);
1214
1215         if (!memcmp(uuid, zero_uuid, sizeof(zero_uuid))) {
1216                 if (!do_rfcomm_connect(rfsock, chan))
1217                         goto failed;
1218         } else {
1219
1220                 if (bt_search_service(&adapter_addr, &rfsock->dst, &uu,
1221                                         sdp_search_cb, rfsock, NULL, 0) < 0) {
1222                         error("Failed to search SDP records");
1223                         goto failed;
1224                 }
1225         }
1226
1227         return HAL_STATUS_SUCCESS;
1228
1229 failed:
1230         cleanup_rfsock(rfsock);
1231         close(*hal_sock);
1232         return HAL_STATUS_FAILED;
1233 }
1234
1235 static void handle_connect(const void *buf, uint16_t len)
1236 {
1237         const struct hal_cmd_socket_connect *cmd = buf;
1238         bdaddr_t bdaddr;
1239         uint8_t status;
1240         int hal_sock;
1241
1242         DBG("");
1243
1244         android2bdaddr(cmd->bdaddr, &bdaddr);
1245
1246         switch (cmd->type) {
1247         case HAL_SOCK_RFCOMM:
1248                 status = connect_rfcomm(&bdaddr, cmd->channel, cmd->uuid,
1249                                                         cmd->flags, &hal_sock);
1250                 break;
1251         case HAL_SOCK_SCO:
1252         case HAL_SOCK_L2CAP:
1253                 status = HAL_STATUS_UNSUPPORTED;
1254                 break;
1255         default:
1256                 status = HAL_STATUS_INVALID;
1257                 break;
1258         }
1259
1260         if (status != HAL_STATUS_SUCCESS)
1261                 goto failed;
1262
1263         ipc_send_rsp_full(hal_ipc, HAL_SERVICE_ID_SOCKET, HAL_OP_SOCKET_CONNECT,
1264                                                         0, NULL, hal_sock);
1265         close(hal_sock);
1266         return;
1267
1268 failed:
1269         ipc_send_rsp(hal_ipc, HAL_SERVICE_ID_SOCKET, HAL_OP_SOCKET_CONNECT,
1270                                                                         status);
1271
1272 }
1273
1274 static const struct ipc_handler cmd_handlers[] = {
1275         /* HAL_OP_SOCKET_LISTEN */
1276         { handle_listen, false, sizeof(struct hal_cmd_socket_listen) },
1277         /* HAL_OP_SOCKET_CONNECT */
1278         { handle_connect, false, sizeof(struct hal_cmd_socket_connect) },
1279 };
1280
1281 void bt_socket_register(struct ipc *ipc, const bdaddr_t *addr, uint8_t mode)
1282 {
1283         size_t i;
1284
1285         DBG("");
1286
1287         hal_mode = mode;
1288
1289         /*
1290          * make sure channels assigned for profiles are reserved and not used
1291          * for app services
1292          */
1293         for (i = 0; i < G_N_ELEMENTS(profiles); i++)
1294                 if (profiles[i].channel)
1295                         servers[profiles[i].channel].reserved = true;
1296
1297         bacpy(&adapter_addr, addr);
1298
1299         hal_ipc = ipc;
1300         ipc_register(hal_ipc, HAL_SERVICE_ID_SOCKET, cmd_handlers,
1301                                                 G_N_ELEMENTS(cmd_handlers));
1302 }
1303
1304 void bt_socket_unregister(void)
1305 {
1306         int ch;
1307
1308         DBG("");
1309
1310         test_sdp_cleanup();
1311
1312         g_list_free_full(connections, cleanup_rfsock);
1313
1314         for (ch = 0; ch <= RFCOMM_CHANNEL_MAX; ch++)
1315                 if (servers[ch].rfsock)
1316                         cleanup_rfsock(servers[ch].rfsock);
1317
1318         memset(servers, 0, sizeof(servers));
1319
1320         ipc_unregister(hal_ipc, HAL_SERVICE_ID_SOCKET);
1321         hal_ipc = NULL;
1322 }