Tizen 2.4 SDK Rev6 Release
[framework/connectivity/bluez.git] / src / device.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2006-2010  Nokia Corporation
6  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel@holtmann.org>
7  *
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22  *
23  */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <stdbool.h>
34 #include <errno.h>
35 #include <dirent.h>
36 #include <time.h>
37
38 #include <glib.h>
39 #include <dbus/dbus.h>
40
41 #include "lib/bluetooth.h"
42 #include "lib/sdp.h"
43 #include "lib/sdp_lib.h"
44 #include "lib/uuid.h"
45
46 #include "gdbus/gdbus.h"
47
48 #include "log.h"
49 #include "src/shared/util.h"
50 #include "src/shared/att.h"
51 #include "src/shared/queue.h"
52 #include "src/shared/gatt-db.h"
53 #include "src/shared/gatt-client.h"
54 #include "src/shared/gatt-server.h"
55 #include "btio/btio.h"
56 #include "lib/mgmt.h"
57 #include "attrib/att.h"
58 #include "hcid.h"
59 #include "adapter.h"
60 #include "gatt-database.h"
61 #include "attrib/gattrib.h"
62 #include "attio.h"
63 #ifdef __TIZEN_PATCH__
64 #include "eir.h"
65 #endif
66 #include "device.h"
67 #include "gatt-client.h"
68 #include "profile.h"
69 #include "service.h"
70 #include "dbus-common.h"
71 #include "error.h"
72 #include "uuid-helper.h"
73 #include "sdp-client.h"
74 #include "attrib/gatt.h"
75 #include "agent.h"
76 #include "textfile.h"
77 #include "storage.h"
78 #include "attrib-server.h"
79 #ifdef __TIZEN_PATCH__
80 #include "sdp-xml.h"
81 #endif
82
83 #define IO_CAPABILITY_NOINPUTNOOUTPUT   0x03
84
85 #define DISCONNECT_TIMER        2
86 #define DISCOVERY_TIMER         1
87
88 #ifndef MIN
89 #define MIN(a, b) ((a) < (b) ? (a) : (b))
90 #endif
91
92 #ifdef __TIZEN_PATCH__
93 #define DEV_SIMUL_CONTROLLER 0x08 /* Simultaneous LE and BR/EDR to Same
94                                                 Device Capable (Controller) */
95 #define DEV_SIMUL_HOST 0x10 /* Simultaneous LE and BR/EDR to Same
96                                                 Device Capable (Host) */
97 #define DEV_MAX_MANUFACTURER_DATA_LEN 248
98
99 /* Added for compilation*/
100 #define BT_ADDRESS_STRING_SIZE 18
101 #endif
102
103 static DBusConnection *dbus_conn = NULL;
104 static unsigned service_state_cb_id;
105
106 struct btd_disconnect_data {
107         guint id;
108         disconnect_watch watch;
109         void *user_data;
110         GDestroyNotify destroy;
111 };
112
113 struct bonding_req {
114         DBusMessage *msg;
115         guint listener_id;
116         struct btd_device *device;
117         uint8_t bdaddr_type;
118         struct agent *agent;
119         struct btd_adapter_pin_cb_iter *cb_iter;
120         uint8_t status;
121         guint retry_timer;
122         struct timespec attempt_start_time;
123         long last_attempt_duration_ms;
124 };
125
126 typedef enum {
127         AUTH_TYPE_PINCODE,
128         AUTH_TYPE_PASSKEY,
129         AUTH_TYPE_CONFIRM,
130         AUTH_TYPE_NOTIFY_PASSKEY,
131         AUTH_TYPE_NOTIFY_PINCODE,
132 } auth_type_t;
133
134 struct authentication_req {
135         auth_type_t type;
136         struct agent *agent;
137         struct btd_device *device;
138         uint32_t passkey;
139         char *pincode;
140         gboolean secure;
141 };
142
143 struct browse_req {
144         DBusMessage *msg;
145         struct btd_device *device;
146         GSList *match_uuids;
147         GSList *profiles_added;
148         sdp_list_t *records;
149         int search_uuid;
150         int reconnect_attempt;
151         guint listener_id;
152         uint16_t sdp_flags;
153 };
154
155 struct included_search {
156         struct browse_req *req;
157         GSList *services;
158         GSList *current;
159 };
160
161 struct attio_data {
162         guint id;
163         attio_connect_cb cfunc;
164         attio_disconnect_cb dcfunc;
165         gpointer user_data;
166 };
167
168 struct svc_callback {
169         unsigned int id;
170         guint idle_id;
171         struct btd_device *dev;
172         device_svc_cb_t func;
173         void *user_data;
174 };
175
176 #ifdef __TIZEN_PATCH__
177 struct le_adv_report_info {
178         uint8_t flags;
179         char manufacturer_data[DEV_MAX_MANUFACTURER_DATA_LEN];
180         uint8_t manufacturer_data_len;
181 };
182 #endif
183
184 typedef void (*attio_error_cb) (const GError *gerr, gpointer user_data);
185 typedef void (*attio_success_cb) (gpointer user_data);
186
187 struct att_callbacks {
188         attio_error_cb err;             /* Callback for error */
189         attio_success_cb success;       /* Callback for success */
190         gpointer user_data;
191 };
192
193 /* Per-bearer (LE or BR/EDR) device state */
194 struct bearer_state {
195         bool paired;
196         bool bonded;
197         bool connected;
198         bool svc_resolved;
199 };
200
201 struct csrk_info {
202         uint8_t key[16];
203         uint32_t counter;
204 };
205
206 #ifdef __TIZEN_PATCH__
207 typedef enum {
208         DEV_PAIRED_NONE = 0,
209         DEV_PAIRED_BREDR = 1,
210         DEV_PAIRED_LE,
211         DEV_PAIRED_BREDR_LE,
212 } dev_paired_state;
213
214 typedef enum {
215         DEV_CONNECTED_NONE = 0,
216         DEV_CONNECTED_BREDR = 1,
217         DEV_CONNECTED_LE,
218         DEV_CONNECTED_BREDR_LE,
219 } dev_connected_state;
220 #endif
221
222 struct btd_device {
223         int ref_count;
224
225         bdaddr_t        bdaddr;
226         uint8_t         bdaddr_type;
227         char            *path;
228         bool            bredr;
229         bool            le;
230         bool            pending_paired;         /* "Paired" waiting for SDP */
231         bool            svc_refreshed;
232         GSList          *svc_callbacks;
233         GSList          *eir_uuids;
234         char            name[MAX_NAME_LENGTH + 1];
235         char            *alias;
236         uint32_t        class;
237         uint16_t        vendor_src;
238         uint16_t        vendor;
239         uint16_t        product;
240         uint16_t        version;
241         uint16_t        appearance;
242         char            *modalias;
243         struct btd_adapter      *adapter;
244         GSList          *uuids;
245         GSList          *primaries;             /* List of primary services */
246         GSList          *services;              /* List of btd_service */
247         GSList          *pending;               /* Pending services */
248         GSList          *watches;               /* List of disconnect_data */
249         gboolean        temporary;
250         guint           disconn_timer;
251         guint           discov_timer;
252         struct browse_req *browse;              /* service discover request */
253         struct bonding_req *bonding;
254         struct authentication_req *authr;       /* authentication request */
255         GSList          *disconnects;           /* disconnects message */
256         DBusMessage     *connect;               /* connect message */
257         DBusMessage     *disconnect;            /* disconnect message */
258         GAttrib         *attrib;
259         GSList          *attios;
260         GSList          *attios_offline;
261
262         struct bt_att *att;                     /* The new ATT transport */
263         uint16_t att_mtu;                       /* The ATT MTU */
264         unsigned int att_disconn_id;
265
266         /*
267          * TODO: For now, device creates and owns the client-role gatt_db, but
268          * this needs to be persisted in a more central place so that proper
269          * attribute cache support can be built.
270          */
271         struct gatt_db *db;                     /* GATT db cache */
272         struct bt_gatt_client *client;          /* GATT client instance */
273         struct bt_gatt_server *server;          /* GATT server instance */
274
275         struct btd_gatt_client *client_dbus;
276
277         struct bearer_state bredr_state;
278         struct bearer_state le_state;
279
280         struct csrk_info *local_csrk;
281         struct csrk_info *remote_csrk;
282
283         sdp_list_t      *tmp_records;
284
285         time_t          bredr_seen;
286         time_t          le_seen;
287
288         gboolean        trusted;
289         gboolean        blocked;
290         gboolean        auto_connect;
291         gboolean        disable_auto_connect;
292         gboolean        general_connect;
293
294         bool            legacy;
295         int8_t          rssi;
296
297         GIOChannel      *att_io;
298         guint           store_id;
299 #ifdef __TIZEN_PATCH__
300         guint           attachid;               /* Attrib server attach */
301         bool    legacy_pairing;
302         char            *manufacturer_data;
303         int             manufacturer_data_len;
304         struct le_adv_report_info le_adv_data;
305         int     remote_feature_flags;
306         guint   attio_id;
307         gboolean        gatt_connected;
308         uint16_t        auth_payload_timeout;
309         uint8_t disc_reason;
310         uint8_t         last_bdaddr_type;
311         gboolean                le_auto_connect;
312         guint           auto_id;
313         gboolean        ipsp_connected; /* IPSP Connection state */
314         uint8_t         rpa_res_support; /* RPA Resolution capability of device */
315         uint16_t                max_tx_octets;
316         uint16_t                max_tx_time;
317         uint16_t                max_rx_octets;
318         uint16_t                max_rx_time;
319 #endif
320 };
321
322 static const uint16_t uuid_list[] = {
323         L2CAP_UUID,
324         PNP_INFO_SVCLASS_ID,
325         PUBLIC_BROWSE_GROUP,
326         0
327 };
328
329 static int device_browse_gatt(struct btd_device *device, DBusMessage *msg);
330 static int device_browse_sdp(struct btd_device *device, DBusMessage *msg);
331 #ifdef __TIZEN_PATCH__
332 static int device_custom_browse_sdp(struct btd_device *device,
333                                                                 DBusMessage *msg, uuid_t *search);
334 #endif
335
336
337 static struct bearer_state *get_state(struct btd_device *dev,
338                                                         uint8_t bdaddr_type)
339 {
340         if (bdaddr_type == BDADDR_BREDR)
341                 return &dev->bredr_state;
342         else
343                 return &dev->le_state;
344 }
345
346 static GSList *find_service_with_profile(GSList *list, struct btd_profile *p)
347 {
348         GSList *l;
349
350         for (l = list; l != NULL; l = g_slist_next(l)) {
351                 struct btd_service *service = l->data;
352
353                 if (btd_service_get_profile(service) == p)
354                         return l;
355         }
356
357         return NULL;
358 }
359
360 static GSList *find_service_with_state(GSList *list,
361                                                 btd_service_state_t state)
362 {
363         GSList *l;
364
365         for (l = list; l != NULL; l = g_slist_next(l)) {
366                 struct btd_service *service = l->data;
367
368                 if (btd_service_get_state(service) == state)
369                         return l;
370         }
371
372         return NULL;
373 }
374
375 static GSList *find_service_with_uuid(GSList *list, char *uuid)
376 {
377         GSList *l;
378
379         for (l = list; l != NULL; l = g_slist_next(l)) {
380                 struct btd_service *service = l->data;
381                 struct btd_profile *profile = btd_service_get_profile(service);
382
383                 if (bt_uuid_strcmp(profile->remote_uuid, uuid) == 0)
384                         return l;
385         }
386
387         return NULL;
388 }
389
390 static void update_technologies(GKeyFile *file, struct btd_device *dev)
391 {
392         const char *list[2];
393         size_t len = 0;
394
395         if (dev->bredr)
396                 list[len++] = "BR/EDR";
397
398         if (dev->le) {
399                 const char *type;
400
401                 if (dev->bdaddr_type == BDADDR_LE_PUBLIC)
402                         type = "public";
403                 else
404                         type = "static";
405
406                 g_key_file_set_string(file, "General", "AddressType", type);
407
408                 list[len++] = "LE";
409         }
410
411         g_key_file_set_string_list(file, "General", "SupportedTechnologies",
412                                                                 list, len);
413 }
414
415 static void store_csrk(struct csrk_info *csrk, GKeyFile *key_file,
416                                                         const char *group)
417 {
418         char key[33];
419         int i;
420
421         for (i = 0; i < 16; i++)
422                 sprintf(key + (i * 2), "%2.2X", csrk->key[i]);
423
424         g_key_file_set_string(key_file, group, "Key", key);
425         g_key_file_set_integer(key_file, group, "Counter", csrk->counter);
426 }
427
428 #ifdef __TIZEN_PATCH__
429 static char *manufacturer_data2str(char *data, int size)
430 {
431         char str[DEV_MAX_MANUFACTURER_DATA_LEN * 3 + 1];
432         char tmp[5];
433         int i;
434
435         str[0] = '\0';
436         for(i = 0; i < size; i++) {
437                 snprintf(tmp, sizeof(tmp), "%d ", data[i]);
438                 g_strlcat(str, tmp, sizeof(str));
439         }
440
441         return g_strdup(str);
442 }
443
444 static void load_manufacturer_data_2digit(char *data, int len, char *buf)
445 {
446         int i;
447         char **split;
448
449         split = g_strsplit(data, " ", 0);
450
451         for (i = 0; i < len; i++) {
452                 if (split[i] == NULL)
453                         break;
454
455                 buf[i] = (char)g_ascii_strtoull(split[i], NULL, 10);
456         }
457
458         g_strfreev(split);
459
460         return;
461 }
462 #endif
463
464 static gboolean store_device_info_cb(gpointer user_data)
465 {
466         struct btd_device *device = user_data;
467         GKeyFile *key_file;
468         char filename[PATH_MAX];
469         char adapter_addr[18];
470         char device_addr[18];
471         char *str;
472         char class[9];
473         char **uuids = NULL;
474         gsize length = 0;
475
476         device->store_id = 0;
477
478         ba2str(btd_adapter_get_address(device->adapter), adapter_addr);
479         ba2str(&device->bdaddr, device_addr);
480         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/%s/info", adapter_addr,
481                         device_addr);
482
483         key_file = g_key_file_new();
484         g_key_file_load_from_file(key_file, filename, 0, NULL);
485
486         g_key_file_set_string(key_file, "General", "Name", device->name);
487
488         if (device->alias != NULL)
489                 g_key_file_set_string(key_file, "General", "Alias",
490                                                                 device->alias);
491         else
492                 g_key_file_remove_key(key_file, "General", "Alias", NULL);
493
494         if (device->class) {
495                 sprintf(class, "0x%6.6x", device->class);
496                 g_key_file_set_string(key_file, "General", "Class", class);
497         } else {
498                 g_key_file_remove_key(key_file, "General", "Class", NULL);
499         }
500
501         if (device->appearance) {
502                 sprintf(class, "0x%4.4x", device->appearance);
503                 g_key_file_set_string(key_file, "General", "Appearance", class);
504         } else {
505                 g_key_file_remove_key(key_file, "General", "Appearance", NULL);
506         }
507
508 #ifdef __TIZEN_PATCH__
509         if (device->rpa_res_support) {
510                 g_key_file_set_integer(key_file, "General", "RPAResSupport",
511                                         device->rpa_res_support);
512         } else {
513                 g_key_file_remove_key(key_file, "General", "RPAResSupport", NULL);
514         }
515 #endif
516
517         update_technologies(key_file, device);
518
519         g_key_file_set_boolean(key_file, "General", "Trusted",
520                                                         device->trusted);
521
522         g_key_file_set_boolean(key_file, "General", "Blocked",
523                                                         device->blocked);
524
525         if (device->uuids) {
526                 GSList *l;
527                 int i;
528
529                 uuids = g_new0(char *, g_slist_length(device->uuids) + 1);
530                 for (i = 0, l = device->uuids; l; l = g_slist_next(l), i++)
531                         uuids[i] = l->data;
532                 g_key_file_set_string_list(key_file, "General", "Services",
533                                                 (const char **)uuids, i);
534         } else {
535                 g_key_file_remove_key(key_file, "General", "Services", NULL);
536         }
537
538 #ifdef __TIZEN_PATCH__
539         if (device->le_adv_data.flags) {
540                 g_key_file_set_integer(key_file, "General", "Flags",
541                                         device->le_adv_data.flags);
542         } else {
543                 g_key_file_remove_key(key_file, "General", "Flags", NULL);
544         }
545
546         if (device->manufacturer_data) {
547                 str = manufacturer_data2str(device->manufacturer_data,
548                                         device->manufacturer_data_len);
549                 g_key_file_set_string(key_file, "General",
550                                 "ManufacturerData",
551                                 str);
552                 g_free(str);
553                 g_key_file_set_integer(key_file, "General",
554                                 "ManufacturerDataLen",
555                                 device->manufacturer_data_len);
556         } else {
557                 g_key_file_remove_key(key_file, "General",
558                                                 "ManufacturerData", NULL);
559                 g_key_file_remove_key(key_file, "General",
560                                                 "ManufacturerDataLen", NULL);
561         }
562 #endif
563
564         if (device->vendor_src) {
565                 g_key_file_set_integer(key_file, "DeviceID", "Source",
566                                         device->vendor_src);
567                 g_key_file_set_integer(key_file, "DeviceID", "Vendor",
568                                         device->vendor);
569                 g_key_file_set_integer(key_file, "DeviceID", "Product",
570                                         device->product);
571                 g_key_file_set_integer(key_file, "DeviceID", "Version",
572                                         device->version);
573         } else {
574                 g_key_file_remove_group(key_file, "DeviceID", NULL);
575         }
576
577         if (device->local_csrk)
578                 store_csrk(device->local_csrk, key_file, "LocalSignatureKey");
579
580         if (device->remote_csrk)
581                 store_csrk(device->remote_csrk, key_file, "RemoteSignatureKey");
582
583         create_file(filename, S_IRUSR | S_IWUSR);
584
585         str = g_key_file_to_data(key_file, &length, NULL);
586         g_file_set_contents(filename, str, length, NULL);
587         g_free(str);
588
589         g_key_file_free(key_file);
590         g_free(uuids);
591
592         return FALSE;
593 }
594
595 static bool device_address_is_private(struct btd_device *dev)
596 {
597         if (dev->bdaddr_type != BDADDR_LE_RANDOM)
598                 return false;
599
600         switch (dev->bdaddr.b[5] >> 6) {
601         case 0x00:      /* Private non-resolvable */
602         case 0x01:      /* Private resolvable */
603                 return true;
604         default:
605                 return false;
606         }
607 }
608
609 static void store_device_info(struct btd_device *device)
610 {
611         if (device->temporary || device->store_id > 0)
612                 return;
613
614         if (device_address_is_private(device)) {
615                 warn("Can't store info for private addressed device %s",
616                                                                 device->path);
617                 return;
618         }
619
620         device->store_id = g_idle_add(store_device_info_cb, device);
621 }
622
623 void device_store_cached_name(struct btd_device *dev, const char *name)
624 {
625         char filename[PATH_MAX];
626         char s_addr[18], d_addr[18];
627         GKeyFile *key_file;
628         char *data;
629         gsize length = 0;
630
631         if (device_address_is_private(dev)) {
632                 warn("Can't store name for private addressed device %s",
633                                                                 dev->path);
634                 return;
635         }
636
637         ba2str(btd_adapter_get_address(dev->adapter), s_addr);
638         ba2str(&dev->bdaddr, d_addr);
639         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s", s_addr, d_addr);
640         create_file(filename, S_IRUSR | S_IWUSR);
641
642         key_file = g_key_file_new();
643         g_key_file_load_from_file(key_file, filename, 0, NULL);
644         g_key_file_set_string(key_file, "General", "Name", name);
645
646         data = g_key_file_to_data(key_file, &length, NULL);
647         g_file_set_contents(filename, data, length, NULL);
648         g_free(data);
649
650         g_key_file_free(key_file);
651 }
652
653 static void browse_request_free(struct browse_req *req)
654 {
655         if (req->listener_id)
656                 g_dbus_remove_watch(dbus_conn, req->listener_id);
657         if (req->msg)
658                 dbus_message_unref(req->msg);
659         g_slist_free_full(req->profiles_added, g_free);
660         if (req->records)
661                 sdp_list_free(req->records, (sdp_free_func_t) sdp_record_free);
662
663         g_free(req);
664 }
665
666 static void gatt_client_cleanup(struct btd_device *device)
667 {
668         if (!device->client)
669                 return;
670
671         bt_gatt_client_set_service_changed(device->client, NULL, NULL, NULL);
672         bt_gatt_client_set_ready_handler(device->client, NULL, NULL, NULL);
673         bt_gatt_client_unref(device->client);
674         device->client = NULL;
675
676         /*
677          * TODO: Once GATT over BR/EDR is properly supported, we should check
678          * the bonding state for the correct bearer based on the transport over
679          * which GATT is being done.
680          */
681         if (!device->le_state.bonded)
682                 gatt_db_clear(device->db);
683 }
684
685 static void gatt_server_cleanup(struct btd_device *device)
686 {
687         if (!device->server)
688                 return;
689
690         bt_gatt_server_unref(device->server);
691         device->server = NULL;
692 }
693
694 static void attio_cleanup(struct btd_device *device)
695 {
696 #ifdef __TIZEN_PATCH__
697         if (device->attachid) {
698                 attrib_channel_detach(device->attrib, device->attachid);
699                 device->attachid = 0;
700         }
701 #endif
702
703         if (device->att_disconn_id)
704                 bt_att_unregister_disconnect(device->att,
705                                                         device->att_disconn_id);
706
707         if (device->att_io) {
708                 g_io_channel_shutdown(device->att_io, FALSE, NULL);
709                 g_io_channel_unref(device->att_io);
710                 device->att_io = NULL;
711         }
712
713         gatt_client_cleanup(device);
714         gatt_server_cleanup(device);
715
716         if (device->att) {
717                 bt_att_unref(device->att);
718                 device->att = NULL;
719         }
720
721         if (device->attrib) {
722                 GAttrib *attrib = device->attrib;
723
724                 device->attrib = NULL;
725                 g_attrib_cancel_all(attrib);
726                 g_attrib_unref(attrib);
727         }
728 }
729
730 static void browse_request_cancel(struct browse_req *req)
731 {
732         struct btd_device *device = req->device;
733         struct btd_adapter *adapter = device->adapter;
734
735         DBG("");
736
737         bt_cancel_discovery(btd_adapter_get_address(adapter), &device->bdaddr);
738
739         attio_cleanup(device);
740
741         device->browse = NULL;
742         browse_request_free(req);
743 }
744
745 static void svc_dev_remove(gpointer user_data)
746 {
747         struct svc_callback *cb = user_data;
748
749         if (cb->idle_id > 0)
750                 g_source_remove(cb->idle_id);
751
752         cb->func(cb->dev, -ENODEV, cb->user_data);
753
754         g_free(cb);
755 }
756
757 static void device_free(gpointer user_data)
758 {
759         struct btd_device *device = user_data;
760
761         btd_gatt_client_destroy(device->client_dbus);
762         device->client_dbus = NULL;
763
764         g_slist_free_full(device->uuids, g_free);
765         g_slist_free_full(device->primaries, g_free);
766         g_slist_free_full(device->attios, g_free);
767         g_slist_free_full(device->attios_offline, g_free);
768         g_slist_free_full(device->svc_callbacks, svc_dev_remove);
769
770         attio_cleanup(device);
771
772         gatt_db_unref(device->db);
773
774         if (device->tmp_records)
775                 sdp_list_free(device->tmp_records,
776                                         (sdp_free_func_t) sdp_record_free);
777
778         if (device->disconn_timer)
779                 g_source_remove(device->disconn_timer);
780
781         if (device->discov_timer)
782                 g_source_remove(device->discov_timer);
783
784         if (device->connect)
785                 dbus_message_unref(device->connect);
786
787         if (device->disconnect)
788                 dbus_message_unref(device->disconnect);
789
790 #ifdef __TIZEN_PATCH__
791         if (device->auto_id)
792                 g_source_remove(device->auto_id);
793
794         if (device->le_auto_connect)
795                 btd_adapter_disable_le_auto_connect(device->adapter);
796 #endif
797
798         DBG("%p", device);
799
800         if (device->authr) {
801                 if (device->authr->agent)
802                         agent_unref(device->authr->agent);
803                 g_free(device->authr->pincode);
804                 g_free(device->authr);
805         }
806
807         if (device->eir_uuids)
808                 g_slist_free_full(device->eir_uuids, g_free);
809
810         g_free(device->local_csrk);
811         g_free(device->remote_csrk);
812         g_free(device->path);
813         g_free(device->alias);
814         free(device->modalias);
815         g_free(device);
816 }
817
818 #ifdef __TIZEN_PATCH__
819 void device_set_remote_feature_flag(struct btd_device *device, int flags)
820 {
821         device->remote_feature_flags = flags;
822 }
823
824 gboolean device_is_bredrle(struct btd_device *device)
825 {
826         return (device->remote_feature_flags &
827                 (DEV_SIMUL_CONTROLLER | DEV_SIMUL_HOST));
828 }
829
830 #if 0 /* caller of below function exists but currently commented */
831 static uint8_t device_get_paired_state(struct btd_device *device)
832 {
833         uint8_t paired = DEV_PAIRED_NONE;
834
835         if (device->bredr_state.paired && device->le_state.paired)
836                 paired = DEV_PAIRED_BREDR_LE;
837         else if (device->le_state.paired)
838                 paired = DEV_PAIRED_LE;
839         else if (device->bredr_state.paired)
840                 paired = DEV_PAIRED_BREDR;
841
842         return paired;
843 }
844 #endif
845 #endif
846
847 bool device_is_paired(struct btd_device *device, uint8_t bdaddr_type)
848 {
849         struct bearer_state *state = get_state(device, bdaddr_type);
850
851         return state->paired;
852 }
853
854 bool device_is_bonded(struct btd_device *device, uint8_t bdaddr_type)
855 {
856         struct bearer_state *state = get_state(device, bdaddr_type);
857
858         return state->bonded;
859 }
860
861 gboolean device_is_trusted(struct btd_device *device)
862 {
863         return device->trusted;
864 }
865
866 static gboolean dev_property_get_address(const GDBusPropertyTable *property,
867                                         DBusMessageIter *iter, void *data)
868 {
869         struct btd_device *device = data;
870         char dstaddr[18];
871         const char *ptr = dstaddr;
872
873         ba2str(&device->bdaddr, dstaddr);
874         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &ptr);
875
876         return TRUE;
877 }
878
879 static gboolean dev_property_get_name(const GDBusPropertyTable *property,
880                                         DBusMessageIter *iter, void *data)
881 {
882         struct btd_device *device = data;
883         const char *ptr = device->name;
884
885         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &ptr);
886
887         return TRUE;
888 }
889
890 static gboolean dev_property_exists_name(const GDBusPropertyTable *property,
891                                                                 void *data)
892 {
893         struct btd_device *dev = data;
894
895         return device_name_known(dev);
896 }
897
898 static gboolean dev_property_get_alias(const GDBusPropertyTable *property,
899                                         DBusMessageIter *iter, void *data)
900 {
901         struct btd_device *device = data;
902         char dstaddr[18];
903         const char *ptr;
904
905         /* Alias (fallback to name or address) */
906         if (device->alias != NULL)
907                 ptr = device->alias;
908         else if (strlen(device->name) > 0) {
909                 ptr = device->name;
910         } else {
911                 ba2str(&device->bdaddr, dstaddr);
912 #ifndef __TIZEN_PATCH__
913                 g_strdelimit(dstaddr, ":", '-');
914 #endif
915                 ptr = dstaddr;
916         }
917
918         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &ptr);
919
920         return TRUE;
921 }
922
923 static void set_alias(GDBusPendingPropertySet id, const char *alias,
924                                                                 void *data)
925 {
926         struct btd_device *device = data;
927
928         /* No change */
929         if ((device->alias == NULL && g_str_equal(alias, "")) ||
930                                         g_strcmp0(device->alias, alias) == 0) {
931                 g_dbus_pending_property_success(id);
932                 return;
933         }
934
935         g_free(device->alias);
936         device->alias = g_str_equal(alias, "") ? NULL : g_strdup(alias);
937
938         store_device_info(device);
939
940         g_dbus_emit_property_changed(dbus_conn, device->path,
941                                                 DEVICE_INTERFACE, "Alias");
942
943         g_dbus_pending_property_success(id);
944 }
945
946 static void dev_property_set_alias(const GDBusPropertyTable *property,
947                                         DBusMessageIter *value,
948                                         GDBusPendingPropertySet id, void *data)
949 {
950         const char *alias;
951
952         if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_STRING) {
953                 g_dbus_pending_property_error(id,
954                                         ERROR_INTERFACE ".InvalidArguments",
955                                         "Invalid arguments in method call");
956                 return;
957         }
958
959         dbus_message_iter_get_basic(value, &alias);
960
961         set_alias(id, alias, data);
962 }
963
964 static gboolean dev_property_exists_class(const GDBusPropertyTable *property,
965                                                                 void *data)
966 {
967         struct btd_device *device = data;
968
969         return device->class != 0;
970 }
971
972 static gboolean dev_property_get_class(const GDBusPropertyTable *property,
973                                         DBusMessageIter *iter, void *data)
974 {
975         struct btd_device *device = data;
976
977         if (device->class == 0)
978                 return FALSE;
979
980         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT32, &device->class);
981
982         return TRUE;
983 }
984
985 static gboolean get_appearance(const GDBusPropertyTable *property, void *data,
986                                                         uint16_t *appearance)
987 {
988         struct btd_device *device = data;
989
990         if (dev_property_exists_class(property, data))
991                 return FALSE;
992
993         if (device->appearance) {
994                 *appearance = device->appearance;
995                 return TRUE;
996         }
997
998         return FALSE;
999 }
1000
1001 static gboolean dev_property_exists_appearance(
1002                         const GDBusPropertyTable *property, void *data)
1003 {
1004         uint16_t appearance;
1005
1006         return get_appearance(property, data, &appearance);
1007 }
1008
1009 static gboolean dev_property_get_appearance(const GDBusPropertyTable *property,
1010                                         DBusMessageIter *iter, void *data)
1011 {
1012         uint16_t appearance;
1013
1014         if (!get_appearance(property, data, &appearance))
1015                 return FALSE;
1016
1017         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &appearance);
1018
1019         return TRUE;
1020 }
1021
1022 static const char *get_icon(const GDBusPropertyTable *property, void *data)
1023 {
1024         struct btd_device *device = data;
1025         const char *icon = NULL;
1026         uint16_t appearance;
1027
1028         if (device->class != 0)
1029                 icon = class_to_icon(device->class);
1030         else if (get_appearance(property, data, &appearance))
1031                 icon = gap_appearance_to_icon(appearance);
1032
1033         return icon;
1034 }
1035
1036 static gboolean dev_property_exists_icon(
1037                         const GDBusPropertyTable *property, void *data)
1038 {
1039         return get_icon(property, data) != NULL;
1040 }
1041
1042 static gboolean dev_property_get_icon(const GDBusPropertyTable *property,
1043                                         DBusMessageIter *iter, void *data)
1044 {
1045         const char *icon;
1046
1047         icon = get_icon(property, data);
1048         if (icon == NULL)
1049                 return FALSE;
1050
1051         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &icon);
1052
1053         return TRUE;
1054 }
1055
1056 static gboolean dev_property_get_paired(const GDBusPropertyTable *property,
1057                                         DBusMessageIter *iter, void *data)
1058 {
1059         struct btd_device *dev = data;
1060
1061 #if 0 /* Need to discuss with SLP team */
1062 /* #ifdef __TIZEN_PATCH__ */
1063         uint8_t val = device_get_paired_state(dev);
1064
1065         dbus_message_iter_append_basic(iter, DBUS_TYPE_BYTE, &val);
1066 #else
1067         dbus_bool_t val;
1068
1069         if (dev->bredr_state.paired || dev->le_state.paired)
1070                 val = TRUE;
1071         else
1072                 val = FALSE;
1073
1074         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
1075 #endif
1076
1077         return TRUE;
1078 }
1079
1080 static gboolean dev_property_get_legacy(const GDBusPropertyTable *property,
1081                                         DBusMessageIter *iter, void *data)
1082 {
1083         struct btd_device *device = data;
1084         dbus_bool_t val = device->legacy;
1085
1086         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
1087
1088         return TRUE;
1089 }
1090
1091 static gboolean dev_property_get_rssi(const GDBusPropertyTable *property,
1092                                         DBusMessageIter *iter, void *data)
1093 {
1094         struct btd_device *dev = data;
1095         dbus_int16_t val = dev->rssi;
1096
1097         dbus_message_iter_append_basic(iter, DBUS_TYPE_INT16, &val);
1098
1099         return TRUE;
1100 }
1101
1102 static gboolean dev_property_exists_rssi(const GDBusPropertyTable *property,
1103                                                                 void *data)
1104 {
1105         struct btd_device *dev = data;
1106
1107         if (dev->rssi == 0)
1108                 return FALSE;
1109
1110         return TRUE;
1111 }
1112
1113 static gboolean dev_property_get_trusted(const GDBusPropertyTable *property,
1114                                         DBusMessageIter *iter, void *data)
1115 {
1116         struct btd_device *device = data;
1117         gboolean val = device_is_trusted(device);
1118
1119         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
1120
1121         return TRUE;
1122 }
1123
1124 static void set_trust(GDBusPendingPropertySet id, gboolean value, void *data)
1125 {
1126         struct btd_device *device = data;
1127
1128         btd_device_set_trusted(device, value);
1129
1130         g_dbus_pending_property_success(id);
1131 }
1132
1133 static void dev_property_set_trusted(const GDBusPropertyTable *property,
1134                                         DBusMessageIter *value,
1135                                         GDBusPendingPropertySet id, void *data)
1136 {
1137         dbus_bool_t b;
1138
1139         if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_BOOLEAN) {
1140                 g_dbus_pending_property_error(id,
1141                                         ERROR_INTERFACE ".InvalidArguments",
1142                                         "Invalid arguments in method call");
1143                 return;
1144         }
1145
1146         dbus_message_iter_get_basic(value, &b);
1147
1148         set_trust(id, b, data);
1149 }
1150
1151 static gboolean dev_property_get_blocked(const GDBusPropertyTable *property,
1152                                         DBusMessageIter *iter, void *data)
1153 {
1154         struct btd_device *device = data;
1155
1156         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN,
1157                                                         &device->blocked);
1158
1159         return TRUE;
1160 }
1161
1162 static void set_blocked(GDBusPendingPropertySet id, gboolean value, void *data)
1163 {
1164         struct btd_device *device = data;
1165         int err;
1166
1167         if (value)
1168                 err = device_block(device, FALSE);
1169         else
1170                 err = device_unblock(device, FALSE, FALSE);
1171
1172         switch (-err) {
1173         case 0:
1174                 g_dbus_pending_property_success(id);
1175                 break;
1176         case EINVAL:
1177                 g_dbus_pending_property_error(id, ERROR_INTERFACE ".Failed",
1178                                         "Kernel lacks blacklist support");
1179                 break;
1180         default:
1181                 g_dbus_pending_property_error(id, ERROR_INTERFACE ".Failed",
1182                                                         strerror(-err));
1183                 break;
1184         }
1185 }
1186
1187
1188 static void dev_property_set_blocked(const GDBusPropertyTable *property,
1189                                         DBusMessageIter *value,
1190                                         GDBusPendingPropertySet id, void *data)
1191 {
1192         dbus_bool_t b;
1193
1194         if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_BOOLEAN) {
1195                 g_dbus_pending_property_error(id,
1196                                         ERROR_INTERFACE ".InvalidArguments",
1197                                         "Invalid arguments in method call");
1198                 return;
1199         }
1200
1201         dbus_message_iter_get_basic(value, &b);
1202
1203         set_blocked(id, b, data);
1204 }
1205
1206 #ifdef __TIZEN_PATCH__
1207 static uint8_t device_get_connected_state(struct btd_device *device)
1208 {
1209         if (device->bredr_state.connected && device->le_state.connected)
1210                 return DEV_CONNECTED_BREDR_LE;
1211         else if (device->bredr_state.connected)
1212                 return DEV_CONNECTED_BREDR;
1213         else if (device->le_state.connected)
1214                 return DEV_CONNECTED_LE;
1215         else
1216                 return DEV_CONNECTED_NONE;
1217 }
1218
1219 static gboolean dev_property_get_payload(const GDBusPropertyTable *property,
1220                                         DBusMessageIter *iter, void *data)
1221 {
1222         struct btd_device *dev = data;
1223         dbus_uint16_t payload_timeout = dev->auth_payload_timeout;
1224
1225         dbus_message_iter_append_basic(iter,
1226                         DBUS_TYPE_UINT16, &payload_timeout);
1227
1228         return TRUE;
1229 }
1230
1231 static gboolean dev_property_get_last_addr_type(const GDBusPropertyTable *property,
1232                                         DBusMessageIter *iter, void *data)
1233 {
1234         struct btd_device *dev = data;
1235         uint8_t last_addr_type = dev->last_bdaddr_type;
1236
1237         dbus_message_iter_append_basic(iter,
1238                         DBUS_TYPE_BYTE, &last_addr_type);
1239
1240         return TRUE;
1241 }
1242
1243 static gboolean dev_property_get_ipsp_conn_state(const GDBusPropertyTable *property,
1244                                         DBusMessageIter *iter, void *data)
1245 {
1246         struct btd_device *dev = data;
1247         dbus_bool_t ipsp_connected;
1248
1249         if (dev->ipsp_connected)
1250                 ipsp_connected = TRUE;
1251         else
1252                 ipsp_connected = FALSE;
1253
1254         dbus_message_iter_append_basic(iter,
1255                         DBUS_TYPE_BOOLEAN, &ipsp_connected);
1256
1257         return TRUE;
1258 }
1259 #endif
1260
1261 static gboolean dev_property_get_connected(const GDBusPropertyTable *property,
1262                                         DBusMessageIter *iter, void *data)
1263 {
1264         struct btd_device *dev = data;
1265
1266 #ifdef __TIZEN_PATCH__
1267         uint8_t connected = device_get_connected_state(dev);
1268
1269         dbus_message_iter_append_basic(iter, DBUS_TYPE_BYTE, &connected);
1270 #else
1271         dbus_bool_t connected;
1272
1273         if (dev->bredr_state.connected || dev->le_state.connected)
1274                 connected = TRUE;
1275         else
1276                 connected = FALSE;
1277
1278         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &connected);
1279 #endif
1280
1281         return TRUE;
1282 }
1283
1284 #ifdef __TIZEN_PATCH__
1285 static gboolean dev_property_get_gatt_connected(const GDBusPropertyTable *property,
1286                                         DBusMessageIter *iter, void *data)
1287 {
1288         struct btd_device *device = data;
1289         dbus_bool_t gatt_connected;
1290
1291         if (device->gatt_connected)
1292                 gatt_connected = TRUE;
1293         else
1294                 gatt_connected = FALSE;
1295
1296         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN,
1297                                         &gatt_connected);
1298
1299         return TRUE;
1300 }
1301 #endif
1302
1303 static gboolean dev_property_get_uuids(const GDBusPropertyTable *property,
1304                                         DBusMessageIter *iter, void *data)
1305 {
1306         struct btd_device *dev = data;
1307         DBusMessageIter entry;
1308         GSList *l;
1309
1310         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
1311                                 DBUS_TYPE_STRING_AS_STRING, &entry);
1312
1313         if (dev->bredr_state.svc_resolved || dev->le_state.svc_resolved)
1314                 l = dev->uuids;
1315         else if (dev->eir_uuids)
1316                 l = dev->eir_uuids;
1317         else
1318                 l = dev->uuids;
1319
1320         for (; l != NULL; l = l->next)
1321                 dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
1322                                                         &l->data);
1323
1324         dbus_message_iter_close_container(iter, &entry);
1325
1326         return TRUE;
1327 }
1328
1329 static gboolean dev_property_get_modalias(const GDBusPropertyTable *property,
1330                                         DBusMessageIter *iter, void *data)
1331 {
1332         struct btd_device *device = data;
1333
1334         if (!device->modalias)
1335                 return FALSE;
1336
1337         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING,
1338                                                         &device->modalias);
1339
1340         return TRUE;
1341 }
1342
1343 static gboolean dev_property_exists_modalias(const GDBusPropertyTable *property,
1344                                                                 void *data)
1345 {
1346         struct btd_device *device = data;
1347
1348         return device->modalias ? TRUE : FALSE;
1349 }
1350
1351 static gboolean dev_property_get_adapter(const GDBusPropertyTable *property,
1352                                         DBusMessageIter *iter, void *data)
1353 {
1354         struct btd_device *device = data;
1355         const char *str = adapter_get_path(device->adapter);
1356
1357         dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &str);
1358
1359         return TRUE;
1360 }
1361
1362 #ifdef __TIZEN_PATCH__
1363
1364 static gboolean property_get_flag(const GDBusPropertyTable *property,
1365                                         DBusMessageIter *iter, void *user_data)
1366 {
1367         struct btd_device *device = user_data;
1368         dbus_uint16_t val = device->le_adv_data.flags;
1369
1370         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &val);
1371
1372         return TRUE;
1373 }
1374
1375 static gboolean property_get_manufacturer_data_len(const GDBusPropertyTable *property,
1376                                         DBusMessageIter *iter, void *user_data)
1377 {
1378         struct btd_device *device = user_data;
1379         dbus_uint16_t val = device->manufacturer_data_len;
1380
1381         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &val);
1382
1383         return TRUE;
1384 }
1385
1386 static gboolean property_get_manufacturer_data(const GDBusPropertyTable *property,
1387                                         DBusMessageIter *iter, void *user_data)
1388 {
1389         struct btd_device *device = user_data;
1390         char str[DEV_MAX_MANUFACTURER_DATA_LEN] = {0};
1391         DBusMessageIter array;
1392
1393         memset(str, 0, DEV_MAX_MANUFACTURER_DATA_LEN);
1394         if (device->manufacturer_data_len)
1395                 memcpy(str, device->manufacturer_data,
1396                                         device->manufacturer_data_len);
1397
1398         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
1399                                         DBUS_TYPE_BYTE_AS_STRING, &array);
1400
1401         dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE,
1402                                                 &device->manufacturer_data,
1403                                                 device->manufacturer_data_len);
1404
1405         dbus_message_iter_close_container(iter, &array);
1406
1407         return TRUE;
1408 }
1409
1410 gboolean device_get_gatt_connected(const struct btd_device *device)
1411 {
1412         return device->gatt_connected;
1413 }
1414 #endif
1415
1416 static gboolean disconnect_all(gpointer user_data)
1417 {
1418         struct btd_device *device = user_data;
1419
1420         device->disconn_timer = 0;
1421
1422         if (device->bredr_state.connected)
1423                 btd_adapter_disconnect_device(device->adapter, &device->bdaddr,
1424                                                                 BDADDR_BREDR);
1425
1426         if (device->le_state.connected)
1427                 btd_adapter_disconnect_device(device->adapter, &device->bdaddr,
1428                                                         device->bdaddr_type);
1429
1430         return FALSE;
1431 }
1432
1433 int device_block(struct btd_device *device, gboolean update_only)
1434 {
1435         int err = 0;
1436
1437         if (device->blocked)
1438                 return 0;
1439
1440         disconnect_all(device);
1441
1442         while (device->services != NULL) {
1443                 struct btd_service *service = device->services->data;
1444
1445                 device->services = g_slist_remove(device->services, service);
1446                 service_remove(service);
1447         }
1448
1449         if (!update_only) {
1450                 if (device->le)
1451                         err = btd_adapter_block_address(device->adapter,
1452                                                         &device->bdaddr,
1453                                                         device->bdaddr_type);
1454                 if (!err && device->bredr)
1455                         err = btd_adapter_block_address(device->adapter,
1456                                                         &device->bdaddr,
1457                                                         BDADDR_BREDR);
1458         }
1459
1460         if (err < 0)
1461                 return err;
1462
1463         device->blocked = TRUE;
1464
1465         store_device_info(device);
1466
1467         btd_device_set_temporary(device, false);
1468
1469         g_dbus_emit_property_changed(dbus_conn, device->path,
1470                                                 DEVICE_INTERFACE, "Blocked");
1471
1472         return 0;
1473 }
1474
1475 int device_unblock(struct btd_device *device, gboolean silent,
1476                                                         gboolean update_only)
1477 {
1478         int err = 0;
1479
1480         if (!device->blocked)
1481                 return 0;
1482
1483         if (!update_only) {
1484                 if (device->le)
1485                         err = btd_adapter_unblock_address(device->adapter,
1486                                                         &device->bdaddr,
1487                                                         device->bdaddr_type);
1488                 if (!err && device->bredr)
1489                         err = btd_adapter_unblock_address(device->adapter,
1490                                                         &device->bdaddr,
1491                                                         BDADDR_BREDR);
1492         }
1493
1494         if (err < 0)
1495                 return err;
1496
1497         device->blocked = FALSE;
1498
1499         store_device_info(device);
1500
1501         if (!silent) {
1502                 g_dbus_emit_property_changed(dbus_conn, device->path,
1503                                                 DEVICE_INTERFACE, "Blocked");
1504                 device_probe_profiles(device, device->uuids);
1505         }
1506
1507         return 0;
1508 }
1509
1510 static void browse_request_exit(DBusConnection *conn, void *user_data)
1511 {
1512         struct browse_req *req = user_data;
1513
1514         DBG("Requestor exited");
1515
1516         browse_request_cancel(req);
1517 }
1518
1519 static void bonding_request_cancel(struct bonding_req *bonding)
1520 {
1521         struct btd_device *device = bonding->device;
1522         struct btd_adapter *adapter = device->adapter;
1523
1524         adapter_cancel_bonding(adapter, &device->bdaddr, device->bdaddr_type);
1525 }
1526
1527 static void dev_disconn_service(gpointer a, gpointer b)
1528 {
1529         btd_service_disconnect(a);
1530 }
1531
1532 void device_request_disconnect(struct btd_device *device, DBusMessage *msg)
1533 {
1534         if (device->bonding)
1535                 bonding_request_cancel(device->bonding);
1536
1537         if (device->browse)
1538                 browse_request_cancel(device->browse);
1539
1540         if (device->connect) {
1541                 DBusMessage *reply = btd_error_failed(device->connect,
1542                                                                 "Cancelled");
1543                 g_dbus_send_message(dbus_conn, reply);
1544                 dbus_message_unref(device->connect);
1545                 device->connect = NULL;
1546         }
1547
1548         if (btd_device_is_connected(device) && msg)
1549                 device->disconnects = g_slist_append(device->disconnects,
1550                                                 dbus_message_ref(msg));
1551
1552         if (device->disconn_timer)
1553                 return;
1554
1555         g_slist_foreach(device->services, dev_disconn_service, NULL);
1556
1557         g_slist_free(device->pending);
1558         device->pending = NULL;
1559
1560         while (device->watches) {
1561                 struct btd_disconnect_data *data = device->watches->data;
1562
1563                 if (data->watch)
1564                         /* temporary is set if device is going to be removed */
1565                         data->watch(device, device->temporary,
1566                                                         data->user_data);
1567
1568                 /* Check if the watch has been removed by callback function */
1569                 if (!g_slist_find(device->watches, data))
1570                         continue;
1571
1572                 device->watches = g_slist_remove(device->watches, data);
1573                 g_free(data);
1574         }
1575
1576         if (!btd_device_is_connected(device)) {
1577                 if (msg)
1578                         g_dbus_send_reply(dbus_conn, msg, DBUS_TYPE_INVALID);
1579                 return;
1580         }
1581
1582         device->disconn_timer = g_timeout_add_seconds(DISCONNECT_TIMER,
1583                                                         disconnect_all,
1584                                                         device);
1585 }
1586
1587 static void device_set_auto_connect(struct btd_device *device, gboolean enable)
1588 {
1589         char addr[18];
1590
1591         if (!device || !device->le)
1592                 return;
1593
1594         ba2str(&device->bdaddr, addr);
1595
1596         DBG("%s auto connect: %d", addr, enable);
1597
1598         if (device->auto_connect == enable)
1599                 return;
1600
1601         device->auto_connect = enable;
1602
1603         /* Disabling auto connect */
1604         if (enable == FALSE) {
1605                 adapter_connect_list_remove(device->adapter, device);
1606                 adapter_auto_connect_remove(device->adapter, device);
1607                 return;
1608         }
1609
1610         /* Enabling auto connect */
1611         adapter_auto_connect_add(device->adapter, device);
1612
1613         if (device->attrib) {
1614                 DBG("Already connected");
1615                 return;
1616         }
1617
1618         adapter_connect_list_add(device->adapter, device);
1619 }
1620
1621 static DBusMessage *dev_disconnect(DBusConnection *conn, DBusMessage *msg,
1622                                                         void *user_data)
1623 {
1624         struct btd_device *device = user_data;
1625
1626         /*
1627          * Disable connections through passive scanning until
1628          * Device1.Connect is called
1629          */
1630         if (device->auto_connect) {
1631                 device->disable_auto_connect = TRUE;
1632                 device_set_auto_connect(device, FALSE);
1633         }
1634
1635         device_request_disconnect(device, msg);
1636
1637         return NULL;
1638 }
1639
1640 static int connect_next(struct btd_device *dev)
1641 {
1642         struct btd_service *service;
1643         int err = -ENOENT;
1644
1645         while (dev->pending) {
1646                 service = dev->pending->data;
1647
1648                 if (btd_service_connect(service) == 0)
1649                         return 0;
1650
1651                 dev->pending = g_slist_delete_link(dev->pending, dev->pending);
1652         }
1653
1654         return err;
1655 }
1656
1657 static void device_profile_connected(struct btd_device *dev,
1658                                         struct btd_profile *profile, int err)
1659 {
1660         struct btd_service *pending;
1661         GSList *l;
1662
1663         DBG("%s %s (%d)", profile->name, strerror(-err), -err);
1664
1665         if (!err)
1666                 btd_device_set_temporary(dev, false);
1667
1668         if (dev->pending == NULL)
1669                 return;
1670
1671         if (!btd_device_is_connected(dev)) {
1672                 switch (-err) {
1673                 case EHOSTDOWN: /* page timeout */
1674                 case EHOSTUNREACH: /* adapter not powered */
1675                 case ECONNABORTED: /* adapter powered down */
1676                         goto done;
1677                 }
1678         }
1679
1680
1681         pending = dev->pending->data;
1682         l = find_service_with_profile(dev->pending, profile);
1683         if (l != NULL)
1684                 dev->pending = g_slist_delete_link(dev->pending, l);
1685
1686         /* Only continue connecting the next profile if it matches the first
1687          * pending, otherwise it will trigger another connect to the same
1688          * profile
1689          */
1690         if (profile != btd_service_get_profile(pending))
1691                 return;
1692
1693         if (connect_next(dev) == 0)
1694                 return;
1695
1696 done:
1697         g_slist_free(dev->pending);
1698         dev->pending = NULL;
1699
1700         if (!dev->connect)
1701                 return;
1702
1703         if (!err && dbus_message_is_method_call(dev->connect, DEVICE_INTERFACE,
1704                                                                 "Connect"))
1705                 dev->general_connect = TRUE;
1706
1707         DBG("returning response to %s", dbus_message_get_sender(dev->connect));
1708
1709         l = find_service_with_state(dev->services, BTD_SERVICE_STATE_CONNECTED);
1710
1711         if (err && l == NULL)
1712                 g_dbus_send_message(dbus_conn,
1713                                 btd_error_failed(dev->connect, strerror(-err)));
1714         else {
1715                 /* Start passive SDP discovery to update known services */
1716                 if (dev->bredr && !dev->svc_refreshed)
1717                         device_browse_sdp(dev, NULL);
1718 #ifdef __TIZEN_PATCH__
1719                 if (err)
1720                         g_dbus_send_message(dbus_conn,
1721                                         btd_error_failed(dev->connect, strerror(-err)));
1722                 else
1723                         g_dbus_send_reply(dbus_conn, dev->connect, DBUS_TYPE_INVALID);
1724 #else
1725                 g_dbus_send_reply(dbus_conn, dev->connect, DBUS_TYPE_INVALID);
1726 #endif
1727         }
1728
1729         dbus_message_unref(dev->connect);
1730         dev->connect = NULL;
1731 }
1732
1733 void device_add_eir_uuids(struct btd_device *dev, GSList *uuids)
1734 {
1735         GSList *l;
1736         bool added = false;
1737
1738         if (dev->bredr_state.svc_resolved || dev->le_state.svc_resolved)
1739                 return;
1740
1741         for (l = uuids; l != NULL; l = l->next) {
1742                 const char *str = l->data;
1743                 if (g_slist_find_custom(dev->eir_uuids, str, bt_uuid_strcmp))
1744                         continue;
1745                 added = true;
1746                 dev->eir_uuids = g_slist_append(dev->eir_uuids, g_strdup(str));
1747         }
1748
1749         if (added)
1750                 g_dbus_emit_property_changed(dbus_conn, dev->path,
1751                                                 DEVICE_INTERFACE, "UUIDs");
1752 }
1753
1754 static struct btd_service *find_connectable_service(struct btd_device *dev,
1755                                                         const char *uuid)
1756 {
1757         GSList *l;
1758 #ifdef __TIZEN_PATCH__
1759         struct btd_service *s = NULL;
1760 #endif
1761         for (l = dev->services; l != NULL; l = g_slist_next(l)) {
1762                 struct btd_service *service = l->data;
1763                 struct btd_profile *p = btd_service_get_profile(service);
1764
1765                 if (!p->connect || !p->remote_uuid)
1766                         continue;
1767
1768 #ifndef __TIZEN_PATCH__
1769                 if (strcasecmp(uuid, p->remote_uuid) == 0)
1770                         return service;
1771 #else
1772                 if (strcasecmp(uuid, p->remote_uuid) == 0) {
1773                         s = service;
1774                         if (ext_profile_is_registered_as_client_role(p) == TRUE) {
1775                                 return service;
1776                         } else {
1777                                 continue;
1778                         }
1779                 }
1780 #endif
1781         }
1782 #ifdef __TIZEN_PATCH__
1783         if (s)
1784                 return s;
1785 #endif
1786
1787         return NULL;
1788 }
1789
1790 static int service_prio_cmp(gconstpointer a, gconstpointer b)
1791 {
1792         struct btd_profile *p1 = btd_service_get_profile(a);
1793         struct btd_profile *p2 = btd_service_get_profile(b);
1794
1795         return p2->priority - p1->priority;
1796 }
1797
1798 static GSList *create_pending_list(struct btd_device *dev, const char *uuid)
1799 {
1800         struct btd_service *service;
1801         struct btd_profile *p;
1802         GSList *l;
1803 #ifdef __TIZEN_PATCH__
1804         bool hs_hf_verify = FALSE;
1805 #endif
1806
1807         if (uuid) {
1808                 service = find_connectable_service(dev, uuid);
1809                 if (service)
1810                         return g_slist_prepend(dev->pending, service);
1811 #ifdef __TIZEN_PATCH__
1812                 else if ((service == NULL) &&
1813                                         (g_strcmp0(uuid, HFP_HS_UUID) == 0)) {
1814                         DBG("HFP service not found check for HSP service");
1815                         service = find_connectable_service(dev, HSP_HS_UUID);
1816                         if (service)
1817                                 return g_slist_prepend(dev->pending, service);
1818                 }
1819 #endif
1820                 return dev->pending;
1821         }
1822
1823         for (l = dev->services; l != NULL; l = g_slist_next(l)) {
1824                 service = l->data;
1825                 p = btd_service_get_profile(service);
1826
1827 #ifdef __TIZEN_PATCH__
1828                 DBG("profile uuid %s", p->remote_uuid);
1829                 if (g_strcmp0(p->remote_uuid, HSP_HS_UUID) == 0) {
1830                         DBG("HSP service is found check for HFP service");
1831                         struct btd_service *service;
1832                         struct btd_profile *p;
1833                         GSList *h;
1834
1835                         for (h = dev->services; h != NULL; h = g_slist_next(h)) {
1836                                 service = h->data;
1837                                 p = btd_service_get_profile(service);
1838
1839                                 if (g_strcmp0(p->remote_uuid, HFP_HS_UUID) == 0) {
1840                                         DBG("HFP found,ignore HSP ");
1841                                         hs_hf_verify = TRUE;
1842                                         break;
1843                                 }
1844                         }
1845                         if (hs_hf_verify)
1846                                 continue;
1847                 }
1848 #endif
1849                 if (!p->auto_connect)
1850                         continue;
1851
1852                 if (g_slist_find(dev->pending, service))
1853                         continue;
1854
1855                 if (btd_service_get_state(service) !=
1856                                                 BTD_SERVICE_STATE_DISCONNECTED)
1857                         continue;
1858
1859                 dev->pending = g_slist_insert_sorted(dev->pending, service,
1860                                                         service_prio_cmp);
1861         }
1862
1863         return dev->pending;
1864 }
1865
1866 int btd_device_connect_services(struct btd_device *dev, GSList *services)
1867 {
1868         GSList *l;
1869
1870         if (dev->pending || dev->connect || dev->browse)
1871                 return -EBUSY;
1872
1873         if (!btd_adapter_get_powered(dev->adapter))
1874                 return -ENETDOWN;
1875
1876         if (!dev->bredr_state.svc_resolved)
1877                 return -ENOENT;
1878
1879         for (l = services; l; l = g_slist_next(l)) {
1880                 struct btd_service *service = l->data;
1881
1882                 dev->pending = g_slist_append(dev->pending,
1883                                                 btd_service_ref(service));
1884         }
1885
1886         return connect_next(dev);
1887 }
1888
1889 static DBusMessage *connect_profiles(struct btd_device *dev, uint8_t bdaddr_type,
1890                                         DBusMessage *msg, const char *uuid)
1891 {
1892         struct bearer_state *state = get_state(dev, bdaddr_type);
1893         int err;
1894
1895         DBG("%s %s, client %s", dev->path, uuid ? uuid : "(all)",
1896                                                 dbus_message_get_sender(msg));
1897
1898 #ifdef __TIZEN_PATCH__
1899         if (dev->pending || dev->connect)
1900                 return btd_error_in_progress(msg);
1901 #else
1902         if (dev->pending || dev->connect || dev->browse)
1903                 return btd_error_in_progress(msg);
1904 #endif
1905
1906         if (!btd_adapter_get_powered(dev->adapter))
1907                 return btd_error_not_ready(msg);
1908
1909         btd_device_set_temporary(dev, false);
1910
1911         if (!state->svc_resolved)
1912                 goto resolve_services;
1913
1914         dev->pending = create_pending_list(dev, uuid);
1915         if (!dev->pending) {
1916                 if (dev->svc_refreshed) {
1917                         if (find_service_with_state(dev->services,
1918                                                 BTD_SERVICE_STATE_CONNECTED))
1919                                 return dbus_message_new_method_return(msg);
1920                         else
1921                                 return btd_error_not_available(msg);
1922                 }
1923
1924                 goto resolve_services;
1925         }
1926
1927         err = connect_next(dev);
1928         if (err < 0)
1929                 return btd_error_failed(msg, strerror(-err));
1930
1931         dev->connect = dbus_message_ref(msg);
1932
1933         return NULL;
1934
1935 resolve_services:
1936         DBG("Resolving services for %s", dev->path);
1937
1938         if (bdaddr_type == BDADDR_BREDR)
1939                 err = device_browse_sdp(dev, msg);
1940         else
1941                 err = device_browse_gatt(dev, msg);
1942         if (err < 0)
1943                 return btd_error_failed(msg, strerror(-err));
1944
1945         return NULL;
1946 }
1947
1948 #define NVAL_TIME ((time_t) -1)
1949 #define SEEN_TRESHHOLD 300
1950
1951 static uint8_t select_conn_bearer(struct btd_device *dev)
1952 {
1953         time_t bredr_last = NVAL_TIME, le_last = NVAL_TIME;
1954         time_t current = time(NULL);
1955
1956         if (dev->bredr_seen) {
1957                 bredr_last = current - dev->bredr_seen;
1958                 if (bredr_last > SEEN_TRESHHOLD)
1959                         bredr_last = NVAL_TIME;
1960         }
1961
1962         if (dev->le_seen) {
1963                 le_last = current - dev->le_seen;
1964                 if (le_last > SEEN_TRESHHOLD)
1965                         le_last = NVAL_TIME;
1966         }
1967
1968         if (le_last == NVAL_TIME && bredr_last == NVAL_TIME)
1969                 return dev->bdaddr_type;
1970
1971         if (dev->bredr && (!dev->le || le_last == NVAL_TIME))
1972                 return BDADDR_BREDR;
1973
1974         if (dev->le && (!dev->bredr || bredr_last == NVAL_TIME))
1975                 return dev->bdaddr_type;
1976
1977         if (bredr_last < le_last)
1978                 return BDADDR_BREDR;
1979
1980         return dev->bdaddr_type;
1981 }
1982
1983 static DBusMessage *dev_connect(DBusConnection *conn, DBusMessage *msg,
1984                                                         void *user_data)
1985 {
1986         struct btd_device *dev = user_data;
1987         uint8_t bdaddr_type;
1988
1989         if (dev->bredr_state.connected)
1990                 bdaddr_type = dev->bdaddr_type;
1991         else if (dev->le_state.connected && dev->bredr)
1992                 bdaddr_type = BDADDR_BREDR;
1993         else
1994                 bdaddr_type = select_conn_bearer(dev);
1995
1996         if (bdaddr_type != BDADDR_BREDR) {
1997                 int err;
1998
1999                 if (dev->le_state.connected)
2000                         return dbus_message_new_method_return(msg);
2001
2002                 btd_device_set_temporary(dev, false);
2003
2004                 if (dev->disable_auto_connect) {
2005                         dev->disable_auto_connect = FALSE;
2006                         device_set_auto_connect(dev, TRUE);
2007                 }
2008
2009                 err = device_connect_le(dev);
2010                 if (err < 0)
2011                         return btd_error_failed(msg, strerror(-err));
2012
2013                 dev->connect = dbus_message_ref(msg);
2014
2015                 return NULL;
2016         }
2017
2018         return connect_profiles(dev, bdaddr_type, msg, NULL);
2019 }
2020
2021 static DBusMessage *connect_profile(DBusConnection *conn, DBusMessage *msg,
2022                                                         void *user_data)
2023 {
2024         struct btd_device *dev = user_data;
2025         const char *pattern;
2026         char *uuid;
2027         DBusMessage *reply;
2028
2029         if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &pattern,
2030                                                         DBUS_TYPE_INVALID))
2031                 return btd_error_invalid_args(msg);
2032
2033         uuid = bt_name2string(pattern);
2034         reply = connect_profiles(dev, BDADDR_BREDR, msg, uuid);
2035         free(uuid);
2036
2037         return reply;
2038 }
2039
2040 static void device_profile_disconnected(struct btd_device *dev,
2041                                         struct btd_profile *profile, int err)
2042 {
2043         if (!dev->disconnect)
2044                 return;
2045
2046         if (err)
2047                 g_dbus_send_message(dbus_conn,
2048                                         btd_error_failed(dev->disconnect,
2049                                                         strerror(-err)));
2050         else
2051                 g_dbus_send_reply(dbus_conn, dev->disconnect,
2052                                                         DBUS_TYPE_INVALID);
2053
2054         dbus_message_unref(dev->disconnect);
2055         dev->disconnect = NULL;
2056 }
2057
2058 static DBusMessage *disconnect_profile(DBusConnection *conn, DBusMessage *msg,
2059                                                         void *user_data)
2060 {
2061         struct btd_device *dev = user_data;
2062         struct btd_service *service;
2063         const char *pattern;
2064         char *uuid;
2065         int err;
2066
2067         if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &pattern,
2068                                                         DBUS_TYPE_INVALID))
2069                 return btd_error_invalid_args(msg);
2070
2071         uuid = bt_name2string(pattern);
2072         if (uuid == NULL)
2073                 return btd_error_invalid_args(msg);
2074
2075         service = find_connectable_service(dev, uuid);
2076 #ifdef __TIZEN_PATCH__
2077         if ((service == NULL) && (g_strcmp0(uuid, HFP_HS_UUID) == 0)) {
2078                 DBG("HFP service is not found check for HSP service");
2079                 service = find_connectable_service(dev, HSP_HS_UUID);
2080         }
2081 #endif
2082         free(uuid);
2083
2084         if (!service)
2085                 return btd_error_invalid_args(msg);
2086
2087         if (dev->disconnect)
2088                 return btd_error_in_progress(msg);
2089
2090         dev->disconnect = dbus_message_ref(msg);
2091
2092         err = btd_service_disconnect(service);
2093         if (err == 0)
2094                 return NULL;
2095
2096         dbus_message_unref(dev->disconnect);
2097         dev->disconnect = NULL;
2098
2099         if (err == -ENOTSUP)
2100                 return btd_error_not_supported(msg);
2101
2102         return btd_error_failed(msg, strerror(-err));
2103 }
2104
2105 static void store_services(struct btd_device *device)
2106 {
2107         struct btd_adapter *adapter = device->adapter;
2108         char filename[PATH_MAX];
2109         char src_addr[18], dst_addr[18];
2110         uuid_t uuid;
2111         char *prim_uuid;
2112         GKeyFile *key_file;
2113         GSList *l;
2114         char *data;
2115         gsize length = 0;
2116
2117         if (device_address_is_private(device)) {
2118                 warn("Can't store services for private addressed device %s",
2119                                                                 device->path);
2120                 return;
2121         }
2122
2123         sdp_uuid16_create(&uuid, GATT_PRIM_SVC_UUID);
2124         prim_uuid = bt_uuid2string(&uuid);
2125         if (prim_uuid == NULL)
2126                 return;
2127
2128         ba2str(btd_adapter_get_address(adapter), src_addr);
2129         ba2str(&device->bdaddr, dst_addr);
2130
2131         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/%s/attributes", src_addr,
2132                                                                 dst_addr);
2133         key_file = g_key_file_new();
2134
2135         for (l = device->primaries; l; l = l->next) {
2136                 struct gatt_primary *primary = l->data;
2137                 char handle[6], uuid_str[33];
2138                 int i;
2139
2140                 sprintf(handle, "%hu", primary->range.start);
2141
2142                 bt_string2uuid(&uuid, primary->uuid);
2143                 sdp_uuid128_to_uuid(&uuid);
2144
2145                 switch (uuid.type) {
2146                 case SDP_UUID16:
2147                         sprintf(uuid_str, "%4.4X", uuid.value.uuid16);
2148                         break;
2149                 case SDP_UUID32:
2150                         sprintf(uuid_str, "%8.8X", uuid.value.uuid32);
2151                         break;
2152                 case SDP_UUID128:
2153                         for (i = 0; i < 16; i++)
2154                                 sprintf(uuid_str + (i * 2), "%2.2X",
2155                                                 uuid.value.uuid128.data[i]);
2156                         break;
2157                 default:
2158                         uuid_str[0] = '\0';
2159                 }
2160
2161                 g_key_file_set_string(key_file, handle, "UUID", prim_uuid);
2162                 g_key_file_set_string(key_file, handle, "Value", uuid_str);
2163                 g_key_file_set_integer(key_file, handle, "EndGroupHandle",
2164                                         primary->range.end);
2165         }
2166
2167         data = g_key_file_to_data(key_file, &length, NULL);
2168         if (length > 0) {
2169                 create_file(filename, S_IRUSR | S_IWUSR);
2170                 g_file_set_contents(filename, data, length, NULL);
2171         }
2172
2173         free(prim_uuid);
2174         g_free(data);
2175         g_key_file_free(key_file);
2176 }
2177
2178 static void browse_request_complete(struct browse_req *req, uint8_t bdaddr_type,
2179                                                                         int err)
2180 {
2181         struct btd_device *dev = req->device;
2182         DBusMessage *reply = NULL;
2183
2184         if (!req->msg)
2185                 goto done;
2186
2187         if (dbus_message_is_method_call(req->msg, DEVICE_INTERFACE, "Pair")) {
2188                 if (!device_is_paired(dev, bdaddr_type)) {
2189                         reply = btd_error_failed(req->msg, "Not paired");
2190                         goto done;
2191                 }
2192
2193                 if (dev->pending_paired) {
2194                         g_dbus_emit_property_changed(dbus_conn, dev->path,
2195                                                 DEVICE_INTERFACE, "Paired");
2196                         dev->pending_paired = false;
2197                 }
2198
2199                 /* Disregard browse errors in case of Pair */
2200                 reply = g_dbus_create_reply(req->msg, DBUS_TYPE_INVALID);
2201                 goto done;
2202         }
2203
2204         if (err) {
2205                 reply = btd_error_failed(req->msg, strerror(-err));
2206                 goto done;
2207         }
2208
2209         if (dbus_message_is_method_call(req->msg, DEVICE_INTERFACE, "Connect"))
2210                 reply = dev_connect(dbus_conn, req->msg, dev);
2211         else if (dbus_message_is_method_call(req->msg, DEVICE_INTERFACE,
2212                                                         "ConnectProfile"))
2213                 reply = connect_profile(dbus_conn, req->msg, dev);
2214         else
2215                 reply = g_dbus_create_reply(req->msg, DBUS_TYPE_INVALID);
2216
2217 done:
2218         if (reply)
2219                 g_dbus_send_message(dbus_conn, reply);
2220
2221         browse_request_free(req);
2222 }
2223
2224 static void device_svc_resolved(struct btd_device *dev, uint8_t bdaddr_type,
2225                                                                 int err)
2226 {
2227         struct bearer_state *state = get_state(dev, bdaddr_type);
2228         struct browse_req *req = dev->browse;
2229
2230         DBG("%s err %d", dev->path, err);
2231
2232         state->svc_resolved = true;
2233
2234         /* Disconnection notification can happen before this function
2235          * gets called, so don't set svc_refreshed for a disconnected
2236          * device.
2237          */
2238         if (state->connected)
2239                 dev->svc_refreshed = true;
2240
2241         g_slist_free_full(dev->eir_uuids, g_free);
2242         dev->eir_uuids = NULL;
2243
2244         if (dev->pending_paired) {
2245                 g_dbus_emit_property_changed(dbus_conn, dev->path,
2246                                                 DEVICE_INTERFACE, "Paired");
2247                 dev->pending_paired = false;
2248         }
2249
2250         while (dev->svc_callbacks) {
2251                 struct svc_callback *cb = dev->svc_callbacks->data;
2252
2253                 if (cb->idle_id > 0)
2254                         g_source_remove(cb->idle_id);
2255
2256                 cb->func(dev, err, cb->user_data);
2257
2258                 dev->svc_callbacks = g_slist_delete_link(dev->svc_callbacks,
2259                                                         dev->svc_callbacks);
2260                 g_free(cb);
2261         }
2262
2263         if (!dev->temporary)
2264                 store_device_info(dev);
2265
2266         if (bdaddr_type != BDADDR_BREDR && err == 0)
2267                 store_services(dev);
2268
2269         if (!req)
2270                 return;
2271
2272         dev->browse = NULL;
2273         browse_request_complete(req, bdaddr_type, err);
2274 }
2275
2276 static struct bonding_req *bonding_request_new(DBusMessage *msg,
2277                                                 struct btd_device *device,
2278                                                 uint8_t bdaddr_type,
2279                                                 struct agent *agent)
2280 {
2281         struct bonding_req *bonding;
2282         char addr[18];
2283
2284         ba2str(&device->bdaddr, addr);
2285         DBG("Requesting bonding for %s", addr);
2286
2287         bonding = g_new0(struct bonding_req, 1);
2288
2289         bonding->msg = dbus_message_ref(msg);
2290         bonding->bdaddr_type = bdaddr_type;
2291
2292         bonding->cb_iter = btd_adapter_pin_cb_iter_new(device->adapter);
2293
2294         /* Marks the bonding start time for the first attempt on request
2295          * construction. The following attempts will be updated on
2296          * device_bonding_retry. */
2297         clock_gettime(CLOCK_MONOTONIC, &bonding->attempt_start_time);
2298
2299         if (agent)
2300                 bonding->agent = agent_ref(agent);
2301
2302         return bonding;
2303 }
2304
2305 void device_bonding_restart_timer(struct btd_device *device)
2306 {
2307         if (!device || !device->bonding)
2308                 return;
2309
2310         clock_gettime(CLOCK_MONOTONIC, &device->bonding->attempt_start_time);
2311 }
2312
2313 static void bonding_request_stop_timer(struct bonding_req *bonding)
2314 {
2315         struct timespec current;
2316
2317         clock_gettime(CLOCK_MONOTONIC, &current);
2318
2319         /* Compute the time difference in ms. */
2320         bonding->last_attempt_duration_ms =
2321                 (current.tv_sec - bonding->attempt_start_time.tv_sec) * 1000L +
2322                 (current.tv_nsec - bonding->attempt_start_time.tv_nsec)
2323                                                                 / 1000000L;
2324 }
2325
2326 /* Returns the duration of the last bonding attempt in milliseconds. The
2327  * duration is measured starting from the latest of the following three
2328  * events and finishing when the Command complete event is received for the
2329  * authentication request:
2330  *  - MGMT_OP_PAIR_DEVICE is sent,
2331  *  - MGMT_OP_PIN_CODE_REPLY is sent and
2332  *  - Command complete event is received for the sent MGMT_OP_PIN_CODE_REPLY.
2333  */
2334 long device_bonding_last_duration(struct btd_device *device)
2335 {
2336         struct bonding_req *bonding = device->bonding;
2337
2338         if (!bonding)
2339                 return 0;
2340
2341         return bonding->last_attempt_duration_ms;
2342 }
2343
2344 static void create_bond_req_exit(DBusConnection *conn, void *user_data)
2345 {
2346         struct btd_device *device = user_data;
2347         char addr[18];
2348
2349         ba2str(&device->bdaddr, addr);
2350         DBG("%s: requestor exited before bonding was completed", addr);
2351
2352         if (device->authr)
2353                 device_cancel_authentication(device, FALSE);
2354
2355         if (device->bonding) {
2356                 device->bonding->listener_id = 0;
2357                 device_request_disconnect(device, NULL);
2358         }
2359 }
2360
2361 static DBusMessage *pair_device(DBusConnection *conn, DBusMessage *msg,
2362                                                                 void *data)
2363 {
2364         struct btd_device *device = data;
2365         struct btd_adapter *adapter = device->adapter;
2366 #ifndef __TIZEN_PATCH__
2367         struct bearer_state *state;
2368 #endif
2369         uint8_t bdaddr_type;
2370         const char *sender;
2371         struct agent *agent;
2372         struct bonding_req *bonding;
2373         uint8_t io_cap;
2374 #ifdef __TIZEN_PATCH__
2375         uint8_t conn_type;
2376         bool connect_le = FALSE;
2377 #endif
2378         int err;
2379
2380         btd_device_set_temporary(device, false);
2381
2382 #ifdef __TIZEN_PATCH__
2383         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_BYTE, &conn_type,
2384                                         DBUS_TYPE_INVALID) == FALSE)
2385 #else
2386         if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_INVALID))
2387 #endif
2388                 return btd_error_invalid_args(msg);
2389
2390         if (device->bonding)
2391                 return btd_error_in_progress(msg);
2392
2393 #ifdef __TIZEN_PATCH__
2394         if (conn_type == DEV_CONN_DEFAULT) {
2395                 if (device_is_bonded(device, DEV_CONN_BREDR))
2396                         return btd_error_already_exists(msg);
2397                 else if (device_is_bonded(device, DEV_CONN_LE))
2398                         return btd_error_already_exists(msg);
2399         }
2400         else {
2401                 if (device_is_bonded(device, conn_type))
2402                         return btd_error_already_exists(msg);
2403         }
2404         bdaddr_type = device->bdaddr_type;
2405 #else
2406         if (device->bredr_state.bonded)
2407                 bdaddr_type = device->bdaddr_type;
2408         else if (device->le_state.bonded)
2409                 bdaddr_type = BDADDR_BREDR;
2410         else
2411                 bdaddr_type = select_conn_bearer(device);
2412
2413         state = get_state(device, bdaddr_type);
2414
2415         if (state->bonded)
2416                 return btd_error_already_exists(msg);
2417 #endif
2418
2419 #ifdef __TIZEN_PATCH__
2420         if ((device_is_bredrle(device) || bdaddr_type != BDADDR_BREDR) &&
2421                                 conn_type == DEV_CONN_LE) {
2422                 DBG("Le Connect request");
2423                 connect_le = TRUE;
2424         }
2425 #endif
2426
2427         sender = dbus_message_get_sender(msg);
2428
2429         agent = agent_get(sender);
2430         if (agent)
2431                 io_cap = agent_get_io_capability(agent);
2432         else
2433                 io_cap = IO_CAPABILITY_NOINPUTNOOUTPUT;
2434
2435 #ifdef __TIZEN_PATCH__
2436         if (((conn_type == DEV_CONN_DEFAULT  && bdaddr_type != BDADDR_BREDR) ||
2437                 (connect_le)))
2438                 bonding = bonding_request_new(msg, device, bdaddr_type, agent);
2439         else
2440                 bonding = bonding_request_new(msg, device, BDADDR_BREDR, agent);
2441 #else
2442         bonding = bonding_request_new(msg, device, bdaddr_type, agent);
2443 #endif
2444
2445         if (agent)
2446                 agent_unref(agent);
2447
2448         bonding->listener_id = g_dbus_add_disconnect_watch(dbus_conn,
2449                                                 sender, create_bond_req_exit,
2450                                                 device, NULL);
2451
2452         device->bonding = bonding;
2453         bonding->device = device;
2454
2455         /* Due to a bug in the kernel we might loose out on ATT commands
2456          * that arrive during the SMP procedure, so connect the ATT
2457          * channel first and only then start pairing (there's code for
2458          * this in the ATT connect callback)
2459          */
2460 #ifdef __TIZEN_PATCH__
2461         if (((conn_type == DEV_CONN_DEFAULT  && bdaddr_type != BDADDR_BREDR) ||
2462                 (connect_le)) && !device->le_state.connected)
2463                 err = device_connect_le(device);
2464         else if (connect_le) /* Send bonding request if LE is already connected*/
2465                 err = adapter_create_bonding(adapter, &device->bdaddr,
2466                                                         bdaddr_type, io_cap);
2467         else
2468                 err = adapter_create_bonding(adapter, &device->bdaddr,
2469                                                         BDADDR_BREDR, io_cap);
2470 #else
2471         if (bdaddr_type != BDADDR_BREDR) {
2472                 if (!state->connected && btd_le_connect_before_pairing())
2473                         err = device_connect_le(device);
2474                 else
2475                         err = adapter_create_bonding(adapter, &device->bdaddr,
2476                                                         device->bdaddr_type,
2477                                                         io_cap);
2478         } else {
2479                 err = adapter_create_bonding(adapter, &device->bdaddr,
2480                                                         BDADDR_BREDR, io_cap);
2481         }
2482 #endif
2483
2484         if (err < 0)
2485                 return btd_error_failed(msg, strerror(-err));
2486
2487         return NULL;
2488 }
2489
2490 static DBusMessage *new_authentication_return(DBusMessage *msg, uint8_t status)
2491 {
2492         switch (status) {
2493         case MGMT_STATUS_SUCCESS:
2494                 return dbus_message_new_method_return(msg);
2495
2496         case MGMT_STATUS_CONNECT_FAILED:
2497                 return dbus_message_new_error(msg,
2498                                 ERROR_INTERFACE ".ConnectionAttemptFailed",
2499                                 "Page Timeout");
2500         case MGMT_STATUS_TIMEOUT:
2501                 return dbus_message_new_error(msg,
2502                                 ERROR_INTERFACE ".AuthenticationTimeout",
2503                                 "Authentication Timeout");
2504         case MGMT_STATUS_BUSY:
2505         case MGMT_STATUS_REJECTED:
2506                 return dbus_message_new_error(msg,
2507                                 ERROR_INTERFACE ".AuthenticationRejected",
2508                                 "Authentication Rejected");
2509         case MGMT_STATUS_CANCELLED:
2510         case MGMT_STATUS_NO_RESOURCES:
2511         case MGMT_STATUS_DISCONNECTED:
2512                 return dbus_message_new_error(msg,
2513                                 ERROR_INTERFACE ".AuthenticationCanceled",
2514                                 "Authentication Canceled");
2515         case MGMT_STATUS_ALREADY_PAIRED:
2516                 return dbus_message_new_error(msg,
2517                                 ERROR_INTERFACE ".AlreadyExists",
2518                                 "Already Paired");
2519         default:
2520                 return dbus_message_new_error(msg,
2521                                 ERROR_INTERFACE ".AuthenticationFailed",
2522                                 "Authentication Failed");
2523         }
2524 }
2525
2526 static void bonding_request_free(struct bonding_req *bonding)
2527 {
2528         if (!bonding)
2529                 return;
2530
2531         if (bonding->listener_id)
2532                 g_dbus_remove_watch(dbus_conn, bonding->listener_id);
2533
2534         if (bonding->msg)
2535                 dbus_message_unref(bonding->msg);
2536
2537         if (bonding->cb_iter)
2538                 g_free(bonding->cb_iter);
2539
2540         if (bonding->agent) {
2541                 agent_cancel(bonding->agent);
2542                 agent_unref(bonding->agent);
2543                 bonding->agent = NULL;
2544         }
2545
2546         if (bonding->retry_timer)
2547                 g_source_remove(bonding->retry_timer);
2548
2549         if (bonding->device)
2550                 bonding->device->bonding = NULL;
2551
2552         g_free(bonding);
2553 }
2554
2555 static void device_cancel_bonding(struct btd_device *device, uint8_t status)
2556 {
2557         struct bonding_req *bonding = device->bonding;
2558         DBusMessage *reply;
2559         char addr[18];
2560
2561         if (!bonding)
2562                 return;
2563
2564         ba2str(&device->bdaddr, addr);
2565         DBG("Canceling bonding request for %s", addr);
2566
2567         if (device->authr)
2568                 device_cancel_authentication(device, FALSE);
2569
2570         reply = new_authentication_return(bonding->msg, status);
2571         g_dbus_send_message(dbus_conn, reply);
2572
2573         bonding_request_cancel(bonding);
2574         bonding_request_free(bonding);
2575 }
2576
2577 static DBusMessage *cancel_pairing(DBusConnection *conn, DBusMessage *msg,
2578                                                                 void *data)
2579 {
2580         struct btd_device *device = data;
2581         struct bonding_req *req = device->bonding;
2582
2583         DBG("");
2584
2585         if (!req)
2586                 return btd_error_does_not_exist(msg);
2587
2588         device_cancel_bonding(device, MGMT_STATUS_CANCELLED);
2589
2590         return dbus_message_new_method_return(msg);
2591 }
2592
2593 #ifdef __TIZEN_PATCH__
2594 #if 0 // Not used
2595 static DBusMessage *read_rssi(DBusConnection *conn, DBusMessage *msg,
2596                                                         void *user_data)
2597 {
2598         struct btd_device *device = user_data;
2599         DBG("read_rssi");
2600         int status = btd_adapter_read_rssi(device->adapter,
2601                                                 &device->bdaddr, device);
2602         if (status != 0)
2603                 return btd_error_failed(msg, "Unable to read rssi");
2604         else
2605                 return dbus_message_new_method_return(msg);
2606 }
2607
2608 static DBusMessage *l2cap_conn_param_update(DBusConnection *conn,
2609                                         DBusMessage *msg, void *user_data)
2610 {
2611         struct btd_device *device = user_data;
2612         uint32_t interval_min, interval_max, latency, time_out;
2613         int status;
2614
2615         if (!dbus_message_get_args(msg, NULL,
2616                                 DBUS_TYPE_UINT32, &interval_min,
2617                                 DBUS_TYPE_UINT32, &interval_max,
2618                                 DBUS_TYPE_UINT32, &latency,
2619                                 DBUS_TYPE_UINT32, &time_out,
2620                                 DBUS_TYPE_INVALID))
2621                 return btd_error_invalid_args(msg);
2622
2623         status = btd_adapter_l2cap_conn_param_update(device->adapter,
2624                                 &device->bdaddr, interval_min,
2625                                 interval_max, latency, time_out);
2626         if (status != 0)
2627                 return btd_error_failed(msg, "Unable to update L2cap connection parameter");
2628         else
2629                 return dbus_message_new_method_return(msg);
2630 }
2631
2632 static DBusMessage *read_auth_payload_timeout(DBusConnection *conn,
2633                                         DBusMessage *msg, void *user_data)
2634 {
2635         struct btd_device *device = user_data;
2636         DBG("read_auth_payload_timeout");
2637         int status = btd_adapter_read_auth_payload_timeout(device->adapter,
2638                                                 &device->bdaddr, device);
2639         if (status != 0)
2640                 return btd_error_failed(msg,
2641                         "Unable to read auth payload timeout");
2642         else
2643                 return dbus_message_new_method_return(msg);
2644 }
2645 #endif
2646
2647 static DBusMessage *discover_services(DBusConnection *conn,
2648                                         DBusMessage *msg, void *user_data)
2649 {
2650         struct btd_device *device = user_data;
2651         const char *pattern;
2652         int err;
2653
2654         if (device->browse)
2655                 return btd_error_in_progress(msg);
2656
2657         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &pattern,
2658                                                 DBUS_TYPE_INVALID) == FALSE)
2659                 return btd_error_invalid_args(msg);
2660
2661         if (strlen(pattern) == 0) {
2662                 err = device_custom_browse_sdp(device, msg, NULL);
2663                 if (err < 0)
2664                         goto fail;
2665         } else {
2666                 uuid_t uuid;
2667
2668                 if (bt_string2uuid(&uuid, pattern) < 0)
2669                         return btd_error_invalid_args(msg);
2670
2671                 sdp_uuid128_to_uuid(&uuid);
2672
2673                 err = device_custom_browse_sdp(device, msg, &uuid);
2674                 if (err < 0)
2675                         goto fail;
2676         }
2677
2678         return NULL;
2679
2680 fail:
2681         return btd_error_failed(msg,
2682                         "Unable to search the SDP services");
2683 }
2684
2685 static const char *browse_request_get_requestor(struct browse_req *req)
2686 {
2687         if (!req->msg)
2688                 return NULL;
2689
2690         return dbus_message_get_sender(req->msg);
2691 }
2692
2693 static void iter_append_record(DBusMessageIter *dict, uint32_t handle,
2694                                                         const char *record)
2695 {
2696         DBusMessageIter entry;
2697
2698         dbus_message_iter_open_container(dict, DBUS_TYPE_DICT_ENTRY,
2699                                                         NULL, &entry);
2700
2701         dbus_message_iter_append_basic(&entry, DBUS_TYPE_UINT32, &handle);
2702
2703         dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &record);
2704
2705         dbus_message_iter_close_container(dict, &entry);
2706 }
2707
2708 static void discover_services_reply(struct browse_req *req, int err,
2709                                                         sdp_list_t *recs)
2710 {
2711         DBusMessage *reply;
2712         DBusMessageIter iter, dict;
2713         sdp_list_t *seq;
2714
2715         if (!req->msg)
2716                 return;
2717
2718         if (err) {
2719                 const char *err_if;
2720
2721                 if (err == -EHOSTDOWN)
2722                         err_if = ERROR_INTERFACE ".ConnectionAttemptFailed";
2723                 else
2724                         err_if = ERROR_INTERFACE ".Failed";
2725
2726                 reply = dbus_message_new_error(req->msg, err_if,
2727                                                         strerror(-err));
2728                 g_dbus_send_message(dbus_conn, reply);
2729                 return;
2730         }
2731
2732         reply = dbus_message_new_method_return(req->msg);
2733         if (!reply)
2734                 return;
2735
2736         dbus_message_iter_init_append(reply, &iter);
2737
2738         dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
2739                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
2740                         DBUS_TYPE_UINT32_AS_STRING DBUS_TYPE_STRING_AS_STRING
2741                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
2742
2743         for (seq = recs; seq; seq = seq->next) {
2744                 sdp_record_t *rec = (sdp_record_t *) seq->data;
2745                 GString *result;
2746
2747                 if (!rec)
2748                         break;
2749
2750                 result = g_string_new(NULL);
2751
2752                 convert_sdp_record_to_xml(rec, result,
2753                                 (void *) g_string_append);
2754
2755                 if (result->len)
2756                         iter_append_record(&dict, rec->handle, result->str);
2757
2758                 g_string_free(result, TRUE);
2759         }
2760
2761         dbus_message_iter_close_container(&iter, &dict);
2762
2763         g_dbus_send_message(dbus_conn, reply);
2764 }
2765
2766 static DBusMessage *cancel_discover(DBusConnection *conn,
2767                                         DBusMessage *msg, void *user_data)
2768 {
2769         struct btd_device *device = user_data;
2770         const char *sender = dbus_message_get_sender(msg);
2771         const char *requestor;
2772
2773         if (!device->browse)
2774                 return btd_error_does_not_exist(msg);
2775
2776         if (!dbus_message_is_method_call(device->browse->msg, DEVICE_INTERFACE,
2777                                         "DiscoverServices"))
2778                 return btd_error_not_authorized(msg);
2779
2780         requestor = browse_request_get_requestor(device->browse);
2781
2782         /* only the discover requestor can cancel the inquiry process */
2783         if (!requestor || !g_str_equal(requestor, sender))
2784                 return btd_error_not_authorized(msg);
2785
2786         discover_services_reply(device->browse, -ECANCELED, NULL);
2787
2788         if (device->browse)
2789                 browse_request_cancel(device->browse);
2790
2791         return dbus_message_new_method_return(msg);
2792 }
2793 #ifndef __TIZEN_PATCH__
2794 /* Its not used */
2795 static DBusMessage *write_auth_payload_timeout(DBusConnection *conn,
2796                                 DBusMessage *msg, void *user_data)
2797 {
2798         struct btd_device *device = user_data;
2799         dbus_uint32_t payload_timeout;
2800
2801         DBG("write_auth_payload_timeout");
2802
2803         if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT32,
2804                         &payload_timeout, DBUS_TYPE_INVALID))
2805                 return btd_error_invalid_args(msg);
2806
2807         int status = btd_adapter_write_auth_payload_timeout(device->adapter,
2808                                    &device->bdaddr, payload_timeout, device);
2809
2810         if (status != 0)
2811                 return btd_error_failed(msg,
2812                         "Unable to write auth payload timeout");
2813         else
2814                 return dbus_message_new_method_return(msg);
2815 }
2816 #endif
2817 void device_set_attrib(struct btd_device *device, guint attachid, GAttrib *attrib)
2818 {
2819         if (device == NULL) {
2820                 error("device is NULL");
2821                 return;
2822         }
2823
2824         device->attachid = attachid;
2825         device->attrib = g_attrib_ref(attrib);
2826 }
2827
2828 void device_unset_attrib(struct btd_device *device)
2829 {
2830         if (device == NULL) {
2831                 error("device is NULL");
2832                 return;
2833         }
2834
2835         if (device->attrib == NULL) {
2836                 error("attrib is NULL");
2837                 return;
2838         }
2839
2840         device->attachid = 0;
2841
2842         g_attrib_unref(device->attrib);
2843         device->attrib = NULL;
2844 }
2845
2846 void device_set_gatt_connected(struct btd_device *device, gboolean connected)
2847 {
2848         if (device == NULL) {
2849                 error("device is NULL");
2850                 return;
2851         }
2852
2853         if (device->gatt_connected != connected)
2854                 device->gatt_connected = connected;
2855
2856         DBG("GattConnected %d", connected);
2857
2858         g_dbus_emit_property_changed(dbus_conn, device->path,
2859                         DEVICE_INTERFACE, "GattConnected");
2860 }
2861
2862 static gboolean att_connect(gpointer user_data)
2863 {
2864         struct btd_device *device = user_data;
2865
2866         device->auto_id = 0;
2867
2868         device_connect_le(device);
2869
2870         return FALSE;
2871 }
2872
2873 static DBusMessage *connect_le(DBusConnection *conn, DBusMessage *msg,
2874                                                         void *user_data)
2875 {
2876         struct btd_device *device = user_data;
2877         dbus_bool_t auto_connect = FALSE;
2878
2879         DBG("bdaddr_type  %d", device->bdaddr_type);
2880
2881         /*
2882          * Current bt_adapter_start_device_discovery() cannot scan BREDR and LE
2883          * simultaneously. And bdaddr_type is not supporting both BREDR and LE
2884          * type. So, device for LE is created when connect_le() called.
2885          */
2886         if (device->bdaddr_type == BDADDR_BREDR) {
2887                 if(device->le)
2888                         device->bdaddr_type = BDADDR_LE_PUBLIC;
2889                 else {
2890                         device = btd_adapter_get_device(device->adapter,
2891                                                 &device->bdaddr, BDADDR_LE_PUBLIC);
2892                         if (device == NULL)
2893                                 return btd_error_no_such_adapter(msg);
2894                 }
2895         }
2896
2897         if (device->gatt_connected)
2898                 return btd_error_already_connected(msg);
2899
2900         device->auto_connect = FALSE;
2901
2902         if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_BOOLEAN,
2903                                                                 &auto_connect, DBUS_TYPE_INVALID))
2904                 return btd_error_invalid_args(msg);
2905
2906         if (auto_connect) {
2907                 DBG("Start LE auto connection");
2908
2909                 if (device->le_auto_connect) {
2910                         DBG("Already auto connection is started...");
2911                         return btd_error_already_connected(msg);
2912                 }
2913
2914                 if (btd_adapter_is_le_auto_connect(device->adapter)) {
2915                         DBG("Already auto connection is started");
2916                         return btd_error_already_connected(msg);
2917                 }
2918                 device->le_auto_connect = TRUE;
2919
2920                 /* Clear White list */
2921                 adapter_clear_le_white_list(device->adapter);
2922
2923                 /* Add device to White list */
2924                 adapter_add_le_white_list(device->adapter, device);
2925         }
2926
2927         if (device->att_io == NULL)
2928                 device->attio_id = btd_device_add_attio_callback(device,
2929                                         NULL, NULL, device);
2930
2931         if (device->auto_id == 0)
2932                 device->auto_id = g_timeout_add(200, att_connect, device);
2933
2934         device->connect = dbus_message_ref(msg);
2935         return NULL;
2936 }
2937
2938 static DBusMessage *disconnect_le(DBusConnection *conn, DBusMessage *msg,
2939                                                         void *user_data)
2940 {
2941         struct btd_device *device = user_data;
2942
2943         if (device->bdaddr_type == BDADDR_BREDR)
2944                 return btd_error_not_supported(msg);
2945
2946         if (device->le_auto_connect && !device->le_state.connected) {
2947                 DBG("le_auto_connect : %d, le_connected : %d, attrib : %p",
2948                                 device->le_auto_connect,
2949                                 device->le_state.connected,
2950                                 device->attrib);
2951
2952                 DBG("Cancel LE auto connection");
2953
2954                 btd_adapter_disable_le_auto_connect(device->adapter);
2955                 device->le_auto_connect = FALSE;
2956
2957                 return dbus_message_new_method_return(msg);
2958         }
2959
2960         if (!device->le_state.connected)
2961                 return btd_error_not_connected(msg);
2962
2963         if (device->connect) {
2964                 DBusMessage *reply = btd_error_failed(device->connect,
2965                                                 "Cancelled");
2966                 g_dbus_send_message(dbus_conn, reply);
2967                 dbus_message_unref(device->connect);
2968                 device->connect = NULL;
2969         }
2970
2971         if (device->le_state.connected)
2972                 device->disconnects = g_slist_append(device->disconnects,
2973                                                 dbus_message_ref(msg));
2974
2975         disconnect_all(device);
2976
2977         /*
2978          * Current bt_adapter_start_device_discovery() cannot scan BREDR and LE
2979          * simultaneously. And bdaddr_type is not supporting both BREDR and LE
2980          * type. So, bdaddr_type is returned to bredr after disconnect le.
2981          */
2982         if(device->bredr)
2983                 device->bdaddr_type = BDADDR_BREDR;
2984
2985         return NULL;
2986 }
2987
2988 static DBusMessage *connect_ipsp(DBusConnection *conn, DBusMessage *msg,
2989                                                         void *user_data)
2990 {
2991         struct btd_device *device = user_data;
2992
2993         DBG("bdaddr_type  %d", device->bdaddr_type);
2994
2995         if (device->bdaddr_type == BDADDR_BREDR) {
2996                 if(device->le)
2997                         device->bdaddr_type = BDADDR_LE_PUBLIC;
2998                 else {
2999                         device = btd_adapter_get_device(device->adapter,
3000                                         &device->bdaddr, BDADDR_LE_PUBLIC);
3001                         if (device == NULL)
3002                                 return btd_error_no_such_adapter(msg);
3003                 }
3004         }
3005
3006         if (device->ipsp_connected)
3007                 return btd_error_already_connected(msg);
3008
3009         /* Initiate Connection for 6Lowan*/
3010         if (btd_adapter_connect_ipsp(device->adapter, &device->bdaddr,
3011                                         device->bdaddr_type) != 0)
3012                 return btd_error_failed(msg, "ConnectFailed");
3013
3014         return dbus_message_new_method_return(msg);;
3015 }
3016
3017 static DBusMessage *disconnect_ipsp(DBusConnection *conn, DBusMessage *msg,
3018                                                         void *user_data)
3019 {
3020         struct btd_device *device = user_data;
3021         DBG("bdaddr_type  %d", device->bdaddr_type);
3022
3023         if (device->bdaddr_type == BDADDR_BREDR)
3024                 return btd_error_not_supported(msg);
3025
3026         if (!device->ipsp_connected)
3027                 return btd_error_not_connected(msg);
3028
3029         /* Disconnect the 6Lowpan connection */
3030         if (btd_adapter_disconnect_ipsp(device->adapter, &device->bdaddr,
3031                                         device->bdaddr_type) != 0)
3032                 return btd_error_failed(msg, "DisconnectFailed");
3033
3034         /* TODO: Handle disconnection of GATT connection, If the connection
3035          * is established as part of IPSP connection. */
3036
3037         return dbus_message_new_method_return(msg);;
3038 }
3039
3040 static DBusMessage *le_set_data_length(
3041                         DBusConnection *conn, DBusMessage *msg,
3042                         void *user_data)
3043 {
3044         dbus_uint16_t max_tx_octets;
3045         dbus_uint16_t max_tx_time;
3046         const gchar *address;
3047         bdaddr_t bdaddr;
3048         struct btd_device *device = user_data;
3049         int status;
3050         char addr[BT_ADDRESS_STRING_SIZE];
3051
3052         if (!dbus_message_get_args(msg, NULL,
3053                                 DBUS_TYPE_UINT16, &max_tx_octets,
3054                                 DBUS_TYPE_UINT16, &max_tx_time,
3055                                 DBUS_TYPE_INVALID)) {
3056                 DBG("error in retrieving values");
3057                 return btd_error_invalid_args(msg);
3058         }
3059
3060         if (device->bdaddr_type == BDADDR_BREDR)
3061                 return btd_error_not_supported(msg);
3062
3063         ba2str(&device->bdaddr, addr);
3064
3065         DBG("Remote device address: %s", addr);
3066         DBG("Max tx octets: %u, Max tx time: %u",
3067                                 max_tx_octets, max_tx_time);
3068
3069         status = btd_adapter_le_set_data_length(device->adapter,
3070                                 &device->bdaddr, max_tx_octets,
3071                                 max_tx_time);
3072
3073         if (status != 0)
3074                 return btd_error_failed(msg, "Unable to set le data length values");
3075         else
3076                 return dbus_message_new_method_return(msg);
3077 }
3078
3079 static DBusMessage *is_connected_profile(DBusConnection *conn, DBusMessage *msg,
3080                                                                         void *user_data)
3081 {
3082         struct btd_device *dev = user_data;
3083         struct btd_service *service;
3084 #ifndef __TIZEN_PATCH__
3085         struct btd_profile *profile;
3086 #endif
3087         btd_service_state_t state;
3088         const char *pattern;
3089         char *uuid;
3090         DBusMessage *reply;
3091         dbus_bool_t val;
3092
3093         if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &pattern,
3094                                                         DBUS_TYPE_INVALID))
3095                 return btd_error_invalid_args(msg);
3096
3097         reply = dbus_message_new_method_return(msg);
3098         if (!reply)
3099                 return btd_error_invalid_args(reply);
3100
3101         uuid = bt_name2string(pattern);
3102         DBG("is_connected_profile_uuid : %s", uuid);
3103         service = btd_device_get_service(dev, uuid);
3104 #ifdef __TIZEN_PATCH__
3105         if ((service == NULL) && (g_strcmp0(uuid, HFP_HS_UUID) == 0)) {
3106                 DBG("HFP  service is not found check for HSP service");
3107                 service = btd_device_get_service(dev, HSP_HS_UUID);
3108         }
3109         if (uuid)
3110                 free(uuid);
3111 #endif
3112         if (!service)
3113                 return btd_error_not_supported(msg);
3114
3115         state = btd_service_get_state(service);
3116         DBG("Connected State : %d", state);
3117
3118         if (state == BTD_SERVICE_STATE_CONNECTED)
3119                 val = TRUE;
3120         else
3121                 val = FALSE;
3122
3123         dbus_message_append_args(reply,
3124                         DBUS_TYPE_BOOLEAN, &val,
3125                         DBUS_TYPE_INVALID);
3126
3127         return reply;
3128 }
3129
3130 static DBusMessage *le_conn_update(DBusConnection *conn, DBusMessage *msg,
3131                                                 void *user_data)
3132 {
3133         struct btd_device *device = user_data;
3134         uint32_t interval_min, interval_max, latency, time_out;
3135         int status;
3136         char addr[BT_ADDRESS_STRING_SIZE];
3137
3138         if (!dbus_message_get_args(msg, NULL,
3139                                 DBUS_TYPE_UINT32, &interval_min,
3140                                 DBUS_TYPE_UINT32, &interval_max,
3141                                 DBUS_TYPE_UINT32, &latency,
3142                                 DBUS_TYPE_UINT32, &time_out,
3143                                 DBUS_TYPE_INVALID))
3144                 return btd_error_invalid_args(msg);
3145
3146         ba2str(&device->bdaddr, addr);
3147
3148         DBG("Remote device address: %s", addr);
3149         DBG("Interval min: %u, Interval max: %u, Latency: %u, Timeout: %u",
3150                                 interval_min, interval_max, latency, time_out);
3151
3152         status = btd_adapter_le_conn_update(device->adapter,
3153                                 &device->bdaddr, interval_min,
3154                                 interval_max, latency, time_out);
3155
3156         if (status != 0)
3157                 return btd_error_failed(msg, "Unable to update LE connection");
3158         else
3159                 return dbus_message_new_method_return(msg);
3160 }
3161 #endif
3162
3163 static const GDBusMethodTable device_methods[] = {
3164         { GDBUS_ASYNC_METHOD("Disconnect", NULL, NULL, dev_disconnect) },
3165         { GDBUS_ASYNC_METHOD("Connect", NULL, NULL, dev_connect) },
3166         { GDBUS_ASYNC_METHOD("ConnectProfile", GDBUS_ARGS({ "UUID", "s" }),
3167                                                 NULL, connect_profile) },
3168         { GDBUS_ASYNC_METHOD("DisconnectProfile", GDBUS_ARGS({ "UUID", "s" }),
3169                                                 NULL, disconnect_profile) },
3170 #ifdef __TIZEN_PATCH__
3171         { GDBUS_ASYNC_METHOD("Pair",
3172                         GDBUS_ARGS({ "conn_type", "y" }), NULL,
3173                                 pair_device) },
3174 #else
3175         { GDBUS_ASYNC_METHOD("Pair", NULL, NULL, pair_device) },
3176 #endif
3177         { GDBUS_METHOD("CancelPairing", NULL, NULL, cancel_pairing) },
3178 #ifdef __TIZEN_PATCH__
3179 #if 0 // Not used
3180         { GDBUS_METHOD("ReadRSSI", NULL, NULL, read_rssi) },
3181         { GDBUS_METHOD("L2capConnParamUpdate",
3182                         GDBUS_ARGS({ "interval_min", "u" },
3183                                 { "interval_max", "u" }, { "latency", "u" },
3184                                 { "time_out", "u" }), NULL,
3185                                 l2cap_conn_param_update) },
3186         { GDBUS_METHOD("WritePayloadTimeout",
3187                         GDBUS_ARGS({"auth_payload_timeout", "u"}),
3188                         NULL, write_auth_payload_timeout)},
3189         { GDBUS_METHOD("ReadPayloadTimeout", NULL,
3190                         NULL, read_auth_payload_timeout)},
3191 #endif
3192         { GDBUS_ASYNC_METHOD("ConnectLE",
3193                         GDBUS_ARGS({ "auto_connect", "b"}),
3194                         NULL, connect_le) },
3195         { GDBUS_ASYNC_METHOD("DisconnectLE", NULL, NULL, disconnect_le) },
3196         { GDBUS_METHOD("IsConnectedProfile", GDBUS_ARGS({ "UUID", "s" }),
3197                 GDBUS_ARGS({ "IsConnected", "b" }), is_connected_profile)},
3198         { GDBUS_METHOD("LeConnUpdate",
3199                         GDBUS_ARGS({ "interval_min", "u" },
3200                                 { "interval_max", "u" }, { "latency", "u" },
3201                                 { "time_out", "u" }), NULL,
3202                                 le_conn_update) },
3203         { GDBUS_ASYNC_METHOD("DiscoverServices",
3204                         GDBUS_ARGS({ "pattern", "s" }), NULL,
3205                                 discover_services) },
3206         { GDBUS_METHOD("CancelDiscovery", NULL, NULL, cancel_discover) },
3207         { GDBUS_ASYNC_METHOD("ConnectIpsp", NULL, NULL, connect_ipsp) },
3208         { GDBUS_ASYNC_METHOD("DisconnectIpsp", NULL, NULL, disconnect_ipsp) },
3209         { GDBUS_ASYNC_METHOD("LESetDataLength",
3210                         GDBUS_ARGS({"max_tx_octets", "q" },
3211                         { "max_tx_time", "q" }), NULL,
3212                         le_set_data_length)},
3213 #endif
3214         { }
3215 };
3216
3217 static const GDBusPropertyTable device_properties[] = {
3218         { "Address", "s", dev_property_get_address },
3219         { "Name", "s", dev_property_get_name, NULL, dev_property_exists_name },
3220         { "Alias", "s", dev_property_get_alias, dev_property_set_alias },
3221         { "Class", "u", dev_property_get_class, NULL,
3222                                         dev_property_exists_class },
3223         { "Appearance", "q", dev_property_get_appearance, NULL,
3224                                         dev_property_exists_appearance },
3225         { "Icon", "s", dev_property_get_icon, NULL,
3226                                         dev_property_exists_icon },
3227 #if 0 /* Need to discuss with SLP team */
3228 /* #ifdef __TIZEN_PATCH__ */
3229         { "Paired", "y", dev_property_get_paired },
3230 #else
3231         { "Paired", "b", dev_property_get_paired },
3232 #endif
3233         { "Trusted", "b", dev_property_get_trusted, dev_property_set_trusted },
3234         { "Blocked", "b", dev_property_get_blocked, dev_property_set_blocked },
3235         { "LegacyPairing", "b", dev_property_get_legacy },
3236         { "RSSI", "n", dev_property_get_rssi, NULL, dev_property_exists_rssi },
3237 #ifdef __TIZEN_PATCH__
3238         { "Connected", "y", dev_property_get_connected },
3239 #else
3240         { "Connected", "b", dev_property_get_connected },
3241 #endif
3242         { "UUIDs", "as", dev_property_get_uuids },
3243         { "Modalias", "s", dev_property_get_modalias, NULL,
3244                                                 dev_property_exists_modalias },
3245         { "Adapter", "o", dev_property_get_adapter },
3246 #ifdef __TIZEN_PATCH__
3247          /* To handle Failed Legacy Pairing when initiated from Remote device*/
3248         { "LegacyPaired", "b", dev_property_get_paired },
3249         { "Flag", "q", property_get_flag },
3250         { "ManufacturerDataLen", "q", property_get_manufacturer_data_len },
3251         { "ManufacturerData", "ay", property_get_manufacturer_data },
3252         { "GattConnected", "b", dev_property_get_gatt_connected },
3253         { "PayloadTimeout", "q", dev_property_get_payload},
3254         { "LastAddrType", "y", dev_property_get_last_addr_type},
3255         { "IpspConnected", "b", dev_property_get_ipsp_conn_state },
3256 #endif
3257         { }
3258 };
3259
3260 #ifdef __TIZEN_PATCH__
3261 static const GDBusSignalTable device_signals[] = {
3262         { GDBUS_SIGNAL("Disconnected",
3263                         GDBUS_ARGS({ "bdaddr_type", "y" }, { "reason", "y" })) },
3264         { GDBUS_SIGNAL("DeviceConnected",
3265                         GDBUS_ARGS({ "bdaddr_type", "y"})) },
3266         { GDBUS_SIGNAL("ProfileStateChanged",
3267                         GDBUS_ARGS({ "profile", "s"}, {"state", "i"})) },
3268         { GDBUS_SIGNAL("AdvReport",
3269                         GDBUS_ARGS({"Address","s"},
3270                                         { "Address Type", "y" },
3271                                         { "Adv Type", "y"},
3272                                         { "RSSI", "i"},
3273                                         { "AdvDataLen", "i"},
3274                                         { "AdvData", "ay"})) },
3275         { GDBUS_SIGNAL("LEDataLengthChanged",
3276                         GDBUS_ARGS({"max_tx_octets","q"},
3277                                 { "max_tx_time", "q" },
3278                                 { "max_rx_octets", "q"},
3279                                 { "max_rx_time", "q"})) },
3280 };
3281 #endif
3282
3283 uint8_t btd_device_get_bdaddr_type(struct btd_device *dev)
3284 {
3285         return dev->bdaddr_type;
3286 }
3287
3288 bool btd_device_is_connected(struct btd_device *dev)
3289 {
3290         return dev->bredr_state.connected || dev->le_state.connected;
3291 }
3292
3293 void device_add_connection(struct btd_device *dev, uint8_t bdaddr_type)
3294 {
3295         struct bearer_state *state = get_state(dev, bdaddr_type);
3296
3297         device_update_last_seen(dev, bdaddr_type);
3298
3299         if (state->connected) {
3300                 char addr[18];
3301                 ba2str(&dev->bdaddr, addr);
3302                 error("Device %s is already connected", addr);
3303                 return;
3304         }
3305
3306         /* If this is the first connection over this bearer */
3307         if (bdaddr_type == BDADDR_BREDR)
3308                 device_set_bredr_support(dev);
3309         else
3310                 device_set_le_support(dev, bdaddr_type);
3311
3312         state->connected = true;
3313
3314 #ifndef __TIZEN_PATCH__
3315         if (dev->le_state.connected && dev->bredr_state.connected)
3316                 return;
3317
3318         g_dbus_emit_property_changed(dbus_conn, dev->path, DEVICE_INTERFACE,
3319                                                                 "Connected");
3320 #else
3321         g_dbus_emit_signal(dbus_conn, dev->path,
3322                 DEVICE_INTERFACE, "DeviceConnected",
3323                 DBUS_TYPE_BYTE, &bdaddr_type,
3324                 DBUS_TYPE_INVALID);
3325 #endif
3326 }
3327
3328 void device_remove_connection(struct btd_device *device, uint8_t bdaddr_type)
3329 {
3330         struct bearer_state *state = get_state(device, bdaddr_type);
3331
3332         if (!state->connected)
3333                 return;
3334
3335         state->connected = false;
3336         device->svc_refreshed = false;
3337         device->general_connect = FALSE;
3338
3339         if (device->disconn_timer > 0) {
3340                 g_source_remove(device->disconn_timer);
3341                 device->disconn_timer = 0;
3342         }
3343
3344 #ifdef __TIZEN_PATCH__
3345         if (device->browse) {
3346                 /* clear browse info */
3347                 device->browse = NULL;
3348         }
3349 #endif
3350
3351         while (device->disconnects) {
3352                 DBusMessage *msg = device->disconnects->data;
3353
3354                 g_dbus_send_reply(dbus_conn, msg, DBUS_TYPE_INVALID);
3355                 device->disconnects = g_slist_remove(device->disconnects, msg);
3356                 dbus_message_unref(msg);
3357         }
3358
3359         if (state->paired && !state->bonded)
3360                 btd_adapter_remove_bonding(device->adapter, &device->bdaddr,
3361                                                                 bdaddr_type);
3362
3363 #ifndef __TIZEN_PATCH__
3364         if (device->bredr_state.connected || device->le_state.connected)
3365                 return;
3366
3367         g_dbus_emit_property_changed(dbus_conn, device->path,
3368                                                 DEVICE_INTERFACE, "Connected");
3369 #else
3370         g_dbus_emit_signal(dbus_conn, device->path,
3371                 DEVICE_INTERFACE, "Disconnected",
3372                 DBUS_TYPE_BYTE, &bdaddr_type,
3373                 DBUS_TYPE_BYTE, &device->disc_reason,
3374                 DBUS_TYPE_INVALID);
3375 #endif
3376 }
3377
3378 guint device_add_disconnect_watch(struct btd_device *device,
3379                                 disconnect_watch watch, void *user_data,
3380                                 GDestroyNotify destroy)
3381 {
3382         struct btd_disconnect_data *data;
3383         static guint id = 0;
3384
3385         data = g_new0(struct btd_disconnect_data, 1);
3386         data->id = ++id;
3387         data->watch = watch;
3388         data->user_data = user_data;
3389         data->destroy = destroy;
3390
3391         device->watches = g_slist_append(device->watches, data);
3392
3393         return data->id;
3394 }
3395
3396 void device_remove_disconnect_watch(struct btd_device *device, guint id)
3397 {
3398         GSList *l;
3399
3400         for (l = device->watches; l; l = l->next) {
3401                 struct btd_disconnect_data *data = l->data;
3402
3403                 if (data->id == id) {
3404                         device->watches = g_slist_remove(device->watches,
3405                                                         data);
3406                         if (data->destroy)
3407                                 data->destroy(data->user_data);
3408                         g_free(data);
3409                         return;
3410                 }
3411         }
3412 }
3413
3414 static char *load_cached_name(struct btd_device *device, const char *local,
3415                                 const char *peer)
3416 {
3417         char filename[PATH_MAX];
3418         GKeyFile *key_file;
3419         char *str = NULL;
3420         int len;
3421
3422         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s", local, peer);
3423
3424         key_file = g_key_file_new();
3425
3426         if (!g_key_file_load_from_file(key_file, filename, 0, NULL))
3427                 goto failed;
3428
3429         str = g_key_file_get_string(key_file, "General", "Name", NULL);
3430         if (str) {
3431                 len = strlen(str);
3432                 if (len > HCI_MAX_NAME_LENGTH)
3433                         str[HCI_MAX_NAME_LENGTH] = '\0';
3434         }
3435
3436 failed:
3437         g_key_file_free(key_file);
3438
3439         return str;
3440 }
3441
3442 static struct csrk_info *load_csrk(GKeyFile *key_file, const char *group)
3443 {
3444         struct csrk_info *csrk;
3445         char *str;
3446         int i;
3447
3448         str = g_key_file_get_string(key_file, group, "Key", NULL);
3449         if (!str)
3450                 return NULL;
3451
3452         csrk = g_new0(struct csrk_info, 1);
3453
3454         for (i = 0; i < 16; i++) {
3455                 if (sscanf(str + (i * 2), "%2hhx", &csrk->key[i]) != 1)
3456                         goto fail;
3457         }
3458
3459         /*
3460          * In case of older storage this will return 0 which is fine since it
3461          * didn't support signing at that point the counter should never have
3462          * been used.
3463          */
3464         csrk->counter = g_key_file_get_integer(key_file, group, "Counter",
3465                                                                         NULL);
3466         g_free(str);
3467
3468         return csrk;
3469
3470 fail:
3471         g_free(str);
3472         g_free(csrk);
3473         return NULL;
3474 }
3475
3476 static void load_info(struct btd_device *device, const char *local,
3477                         const char *peer, GKeyFile *key_file)
3478 {
3479         char *str;
3480         gboolean store_needed = FALSE;
3481         gboolean blocked;
3482         char **uuids;
3483         int source, vendor, product, version;
3484         char **techno, **t;
3485 #ifdef __TIZEN_PATCH__
3486         char buf[DEV_MAX_MANUFACTURER_DATA_LEN] = { 0, };
3487 #endif
3488         /* Load device name from storage info file, if that fails fall back to
3489          * the cache.
3490          */
3491         str = g_key_file_get_string(key_file, "General", "Name", NULL);
3492         if (str == NULL) {
3493                 str = load_cached_name(device, local, peer);
3494                 if (str)
3495                         store_needed = TRUE;
3496         }
3497
3498         if (str) {
3499                 strcpy(device->name, str);
3500                 g_free(str);
3501         }
3502
3503         /* Load alias */
3504         device->alias = g_key_file_get_string(key_file, "General", "Alias",
3505                                                                         NULL);
3506
3507         /* Load class */
3508         str = g_key_file_get_string(key_file, "General", "Class", NULL);
3509         if (str) {
3510                 uint32_t class;
3511
3512                 if (sscanf(str, "%x", &class) == 1)
3513                         device->class = class;
3514                 g_free(str);
3515         }
3516
3517         /* Load appearance */
3518         str = g_key_file_get_string(key_file, "General", "Appearance", NULL);
3519         if (str) {
3520                 device->appearance = strtol(str, NULL, 16);
3521                 g_free(str);
3522         }
3523
3524 #ifdef __TIZEN_PATCH__
3525         /* Load RPA Resolution Support value */
3526         device->rpa_res_support = g_key_file_get_integer(key_file,
3527                                                         "General", "RPAResSupport", NULL);
3528
3529         str = g_key_file_get_string(key_file, "General", "ManufacturerDataLen", NULL);
3530         if (str) {
3531                 device->manufacturer_data_len = strtol(str, NULL, 10);
3532                 g_free(str);
3533
3534                 str = g_key_file_get_string(key_file, "General", "ManufacturerData", NULL);
3535                 if (str) {
3536                         load_manufacturer_data_2digit(str,
3537                                                 device->manufacturer_data_len,  buf);
3538                         device->manufacturer_data = g_memdup(buf,
3539                                                 device->manufacturer_data_len);
3540                         g_free(str);
3541                 }
3542         }
3543 #endif
3544
3545         /* Load device technology */
3546         techno = g_key_file_get_string_list(key_file, "General",
3547                                         "SupportedTechnologies", NULL, NULL);
3548         if (!techno)
3549                 goto next;
3550
3551         for (t = techno; *t; t++) {
3552                 if (g_str_equal(*t, "BR/EDR"))
3553                         device->bredr = true;
3554                 else if (g_str_equal(*t, "LE"))
3555                         device->le = true;
3556                 else
3557                         error("Unknown device technology");
3558         }
3559
3560         if (!device->le) {
3561                 device->bdaddr_type = BDADDR_BREDR;
3562         } else {
3563                 str = g_key_file_get_string(key_file, "General",
3564                                                 "AddressType", NULL);
3565
3566                 if (str && g_str_equal(str, "public"))
3567                         device->bdaddr_type = BDADDR_LE_PUBLIC;
3568                 else if (str && g_str_equal(str, "static"))
3569                         device->bdaddr_type = BDADDR_LE_RANDOM;
3570                 else
3571                         error("Unknown LE device technology");
3572
3573                 g_free(str);
3574
3575                 device->local_csrk = load_csrk(key_file, "LocalSignatureKey");
3576                 device->remote_csrk = load_csrk(key_file, "RemoteSignatureKey");
3577         }
3578
3579         g_strfreev(techno);
3580
3581 next:
3582         /* Load trust */
3583         device->trusted = g_key_file_get_boolean(key_file, "General",
3584                                                         "Trusted", NULL);
3585
3586         /* Load device blocked */
3587         blocked = g_key_file_get_boolean(key_file, "General", "Blocked", NULL);
3588         if (blocked)
3589                 device_block(device, FALSE);
3590
3591         /* Load device profile list */
3592         uuids = g_key_file_get_string_list(key_file, "General", "Services",
3593                                                 NULL, NULL);
3594         if (uuids) {
3595                 char **uuid;
3596
3597                 for (uuid = uuids; *uuid; uuid++) {
3598                         GSList *match;
3599
3600                         match = g_slist_find_custom(device->uuids, *uuid,
3601                                                         bt_uuid_strcmp);
3602                         if (match)
3603                                 continue;
3604
3605                         device->uuids = g_slist_insert_sorted(device->uuids,
3606                                                                 g_strdup(*uuid),
3607                                                                 bt_uuid_strcmp);
3608                 }
3609                 g_strfreev(uuids);
3610
3611                 /* Discovered services restored from storage */
3612                 device->bredr_state.svc_resolved = true;
3613         }
3614
3615         /* Load device id */
3616         source = g_key_file_get_integer(key_file, "DeviceID", "Source", NULL);
3617         if (source) {
3618                 vendor = g_key_file_get_integer(key_file, "DeviceID",
3619                                                         "Vendor", NULL);
3620
3621                 product = g_key_file_get_integer(key_file, "DeviceID",
3622                                                         "Product", NULL);
3623
3624                 version = g_key_file_get_integer(key_file, "DeviceID",
3625                                                         "Version", NULL);
3626
3627                 btd_device_set_pnpid(device, source, vendor, product, version);
3628         }
3629
3630         if (store_needed)
3631                 store_device_info(device);
3632 }
3633
3634 static void load_att_info(struct btd_device *device, const char *local,
3635                                 const char *peer)
3636 {
3637         char filename[PATH_MAX];
3638         GKeyFile *key_file;
3639         char *prim_uuid, *str;
3640         char **groups, **handle, *service_uuid;
3641         struct gatt_primary *prim;
3642         uuid_t uuid;
3643         char tmp[3];
3644         int i;
3645
3646         sdp_uuid16_create(&uuid, GATT_PRIM_SVC_UUID);
3647         prim_uuid = bt_uuid2string(&uuid);
3648
3649         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/%s/attributes", local,
3650                         peer);
3651
3652         key_file = g_key_file_new();
3653         g_key_file_load_from_file(key_file, filename, 0, NULL);
3654         groups = g_key_file_get_groups(key_file, NULL);
3655
3656         for (handle = groups; *handle; handle++) {
3657                 gboolean uuid_ok;
3658                 int end;
3659
3660                 str = g_key_file_get_string(key_file, *handle, "UUID", NULL);
3661                 if (!str)
3662                         continue;
3663
3664                 uuid_ok = g_str_equal(str, prim_uuid);
3665                 g_free(str);
3666
3667                 if (!uuid_ok)
3668                         continue;
3669
3670                 str = g_key_file_get_string(key_file, *handle, "Value", NULL);
3671                 if (!str)
3672                         continue;
3673
3674                 end = g_key_file_get_integer(key_file, *handle,
3675                                                 "EndGroupHandle", NULL);
3676                 if (end == 0) {
3677                         g_free(str);
3678                         continue;
3679                 }
3680
3681                 prim = g_new0(struct gatt_primary, 1);
3682                 prim->range.start = atoi(*handle);
3683                 prim->range.end = end;
3684
3685                 switch (strlen(str)) {
3686                 case 4:
3687                         uuid.type = SDP_UUID16;
3688                         sscanf(str, "%04hx", &uuid.value.uuid16);
3689                 break;
3690                 case 8:
3691                         uuid.type = SDP_UUID32;
3692                         sscanf(str, "%08x", &uuid.value.uuid32);
3693                         break;
3694                 case 32:
3695                         uuid.type = SDP_UUID128;
3696                         memset(tmp, 0, sizeof(tmp));
3697                         for (i = 0; i < 16; i++) {
3698                                 memcpy(tmp, str + (i * 2), 2);
3699                                 uuid.value.uuid128.data[i] =
3700                                                 (uint8_t) strtol(tmp, NULL, 16);
3701                         }
3702                         break;
3703                 default:
3704                         g_free(str);
3705                         g_free(prim);
3706                         continue;
3707                 }
3708
3709                 service_uuid = bt_uuid2string(&uuid);
3710                 memcpy(prim->uuid, service_uuid, MAX_LEN_UUID_STR);
3711                 free(service_uuid);
3712                 g_free(str);
3713
3714                 device->primaries = g_slist_append(device->primaries, prim);
3715         }
3716
3717         g_strfreev(groups);
3718         g_key_file_free(key_file);
3719         free(prim_uuid);
3720 }
3721
3722 static void device_register_primaries(struct btd_device *device,
3723                                                 GSList *prim_list, int psm)
3724 {
3725         device->primaries = g_slist_concat(device->primaries, prim_list);
3726 }
3727
3728 static void add_primary(struct gatt_db_attribute *attr, void *user_data)
3729 {
3730         GSList **new_services = user_data;
3731         struct gatt_primary *prim;
3732         bt_uuid_t uuid;
3733
3734         prim = g_new0(struct gatt_primary, 1);
3735         if (!prim) {
3736                 DBG("Failed to allocate gatt_primary structure");
3737                 return;
3738         }
3739
3740         gatt_db_attribute_get_service_handles(attr, &prim->range.start,
3741                                                         &prim->range.end);
3742         gatt_db_attribute_get_service_uuid(attr, &uuid);
3743         bt_uuid_to_string(&uuid, prim->uuid, sizeof(prim->uuid));
3744
3745         *new_services = g_slist_append(*new_services, prim);
3746 }
3747
3748 static void device_add_uuids(struct btd_device *device, GSList *uuids)
3749 {
3750         GSList *l;
3751         bool changed = false;
3752
3753         for (l = uuids; l != NULL; l = g_slist_next(l)) {
3754                 GSList *match = g_slist_find_custom(device->uuids, l->data,
3755                                                         bt_uuid_strcmp);
3756                 if (match)
3757                         continue;
3758
3759                 changed = true;
3760                 device->uuids = g_slist_insert_sorted(device->uuids,
3761                                                 g_strdup(l->data),
3762                                                 bt_uuid_strcmp);
3763         }
3764
3765         if (changed)
3766                 g_dbus_emit_property_changed(dbus_conn, device->path,
3767                                                 DEVICE_INTERFACE, "UUIDs");
3768 }
3769
3770 struct gatt_probe_data {
3771         struct btd_device *dev;
3772         bool all_services;
3773         GSList *uuids;
3774         struct gatt_db_attribute *cur_attr;
3775         char cur_uuid[MAX_LEN_UUID_STR];
3776 };
3777
3778 static bool device_match_profile(struct btd_device *device,
3779                                         struct btd_profile *profile,
3780                                         GSList *uuids)
3781 {
3782         if (profile->remote_uuid == NULL)
3783                 return false;
3784
3785         if (g_slist_find_custom(uuids, profile->remote_uuid,
3786                                                         bt_uuid_strcmp) == NULL)
3787                 return false;
3788
3789         return true;
3790 }
3791
3792 static void dev_probe_gatt(struct btd_profile *p, void *user_data)
3793 {
3794         struct gatt_probe_data *data = user_data;
3795         struct btd_service *service;
3796
3797         if (p->device_probe == NULL)
3798                 return;
3799
3800         if (!p->remote_uuid || bt_uuid_strcmp(p->remote_uuid, data->cur_uuid))
3801                 return;
3802
3803         service = service_create(data->dev, p);
3804         if (!service)
3805                 return;
3806
3807         if (service_probe(service) < 0) {
3808                 btd_service_unref(service);
3809                 return;
3810         }
3811
3812         /* Mark service as claimed */
3813         gatt_db_service_set_claimed(data->cur_attr, true);
3814
3815         data->dev->services = g_slist_append(data->dev->services, service);
3816 }
3817
3818 static void dev_probe_gatt_profile(struct gatt_db_attribute *attr,
3819                                                         void *user_data)
3820 {
3821         struct gatt_probe_data *data = user_data;
3822         bt_uuid_t uuid;
3823         GSList *l = NULL;
3824
3825         gatt_db_attribute_get_service_uuid(attr, &uuid);
3826         bt_uuid_to_string(&uuid, data->cur_uuid, sizeof(data->cur_uuid));
3827
3828         data->cur_attr = attr;
3829
3830         /*
3831          * If we're probing for all services, store the UUID since device->uuids
3832          * was cleared.
3833          */
3834         if (data->all_services)
3835                 data->uuids = g_slist_append(data->uuids,
3836                                                 g_strdup(data->cur_uuid));
3837
3838         /* Don't probe the profiles if a matching service already exists. */
3839         if (find_service_with_uuid(data->dev->services, data->cur_uuid)) {
3840                 /* Mark the service as claimed by the existing profile. */
3841                 gatt_db_service_set_claimed(data->cur_attr, true);
3842                 return;
3843         }
3844
3845         btd_profile_foreach(dev_probe_gatt, data);
3846
3847         if (data->all_services)
3848                 return;
3849
3850         l = g_slist_append(l, g_strdup(data->cur_uuid));
3851         device_add_uuids(data->dev, l);
3852 }
3853
3854 static void device_probe_gatt_profile(struct btd_device *device,
3855                                                 struct gatt_db_attribute *attr)
3856 {
3857         struct gatt_probe_data data;
3858
3859         memset(&data, 0, sizeof(data));
3860
3861         data.dev = device;
3862
3863         dev_probe_gatt_profile(attr, &data);
3864         g_slist_free_full(data.uuids, g_free);
3865 }
3866
3867 static void device_probe_gatt_profiles(struct btd_device *device)
3868 {
3869         struct gatt_probe_data data;
3870         char addr[18];
3871
3872         ba2str(&device->bdaddr, addr);
3873
3874         if (device->blocked) {
3875                 DBG("Skipping profiles for blocked device %s", addr);
3876                 return;
3877         }
3878
3879         memset(&data, 0, sizeof(data));
3880
3881         data.dev = device;
3882         data.all_services = true;
3883
3884         gatt_db_foreach_service(device->db, NULL, dev_probe_gatt_profile,
3885                                                                         &data);
3886
3887         device_add_uuids(device, data.uuids);
3888         g_slist_free_full(data.uuids, g_free);
3889 }
3890
3891 static void device_accept_gatt_profiles(struct btd_device *device)
3892 {
3893         GSList *l;
3894
3895         for (l = device->services; l != NULL; l = g_slist_next(l))
3896                 service_accept(l->data);
3897 }
3898
3899 static void device_remove_gatt_profile(struct btd_device *device,
3900                                                 struct gatt_db_attribute *attr)
3901 {
3902         struct btd_service *service;
3903         bt_uuid_t uuid;
3904         char uuid_str[MAX_LEN_UUID_STR];
3905         GSList *l;
3906
3907         gatt_db_attribute_get_service_uuid(attr, &uuid);
3908         bt_uuid_to_string(&uuid, uuid_str, sizeof(uuid_str));
3909
3910         l = find_service_with_uuid(device->services, uuid_str);
3911         if (!l)
3912                 return;
3913
3914         service = l->data;
3915         device->services = g_slist_delete_link(device->services, l);
3916         device->pending = g_slist_remove(device->pending, service);
3917         service_remove(service);
3918 }
3919
3920 static void gatt_service_added(struct gatt_db_attribute *attr, void *user_data)
3921 {
3922         struct btd_device *device = user_data;
3923         GSList *new_service = NULL;
3924         bt_uuid_t uuid;
3925         char uuid_str[MAX_LEN_UUID_STR];
3926         uint16_t start, end;
3927         GSList *l;
3928
3929         if (!bt_gatt_client_is_ready(device->client))
3930                 return;
3931
3932         gatt_db_attribute_get_service_data(attr, &start, &end, NULL, &uuid);
3933         bt_uuid_to_string(&uuid, uuid_str, sizeof(uuid_str));
3934
3935         DBG("start: 0x%04x, end: 0x%04x", start, end);
3936
3937         /*
3938          * TODO: Remove the primaries list entirely once all profiles use
3939          * shared/gatt.
3940          */
3941         add_primary(attr, &new_service);
3942         if (!new_service)
3943                 return;
3944
3945         l = find_service_with_uuid(device->services, uuid_str);
3946
3947         device_register_primaries(device, new_service, -1);
3948
3949         /*
3950          * If the profile was probed for the first time then call accept on
3951          * the service.
3952          */
3953         if (!l) {
3954                 l = find_service_with_uuid(device->services, uuid_str);
3955                 if (l)
3956                         service_accept(l->data);
3957         }
3958
3959         device_probe_gatt_profile(device, attr);
3960
3961         store_device_info(device);
3962
3963         btd_gatt_client_service_added(device->client_dbus, attr);
3964 }
3965
3966 static gint prim_attr_cmp(gconstpointer a, gconstpointer b)
3967 {
3968         const struct gatt_primary *prim = a;
3969         const struct gatt_db_attribute *attr = b;
3970         uint16_t start, end;
3971
3972         gatt_db_attribute_get_service_handles(attr, &start, &end);
3973
3974         return !(prim->range.start == start && prim->range.end == end);
3975 }
3976
3977 static gint prim_uuid_cmp(gconstpointer a, gconstpointer b)
3978 {
3979         const struct gatt_primary *prim = a;
3980         const char *uuid = b;
3981
3982         return bt_uuid_strcmp(prim->uuid, uuid);
3983 }
3984
3985 static void gatt_service_removed(struct gatt_db_attribute *attr,
3986                                                                 void *user_data)
3987 {
3988         struct btd_device *device = user_data;
3989         GSList *l;
3990         struct gatt_primary *prim;
3991         uint16_t start, end;
3992
3993         /*
3994          * NOTE: shared/gatt-client clears the database in case of failure. This
3995          * triggers the service_removed callback for all affected services.
3996          * Hence, this function will be called in the following cases:
3997          *
3998          *    1. When a GATT service gets removed due to "Service Changed".
3999          *
4000          *    2. When a GATT service gets removed when the database get cleared
4001          *       upon disconnection with a non-bonded device.
4002          *
4003          *    3. When a GATT service gets removed when the database get cleared
4004          *       by shared/gatt-client when its initialization procedure fails,
4005          *       e.g. due to an ATT protocol error or an unexpected disconnect.
4006          *       In this case the gatt-client will not be ready.
4007          */
4008
4009         gatt_db_attribute_get_service_handles(attr, &start, &end);
4010
4011         DBG("start: 0x%04x, end: 0x%04x", start, end);
4012
4013         /* Remove the corresponding gatt_primary */
4014         l = g_slist_find_custom(device->primaries, attr, prim_attr_cmp);
4015         if (!l)
4016                 return;
4017
4018         prim = l->data;
4019         device->primaries = g_slist_delete_link(device->primaries, l);
4020
4021         /*
4022          * Remove the corresponding UUIDs entry and profile, only if this is
4023          * the last service with this UUID.
4024          */
4025         l = g_slist_find_custom(device->uuids, prim->uuid, bt_uuid_strcmp);
4026
4027         if (l && !g_slist_find_custom(device->primaries, prim->uuid,
4028                                                         prim_uuid_cmp)) {
4029                 /*
4030                  * If this happend since the db was cleared for a non-bonded
4031                  * device, then don't remove the btd_service just yet. We do
4032                  * this so that we can avoid re-probing the profile if the same
4033                  * GATT service is found on the device on re-connection.
4034                  * However, if the device is marked as temporary, then we
4035                  * remove it anyway.
4036                  */
4037                 if (device->client || device->temporary == TRUE)
4038                         device_remove_gatt_profile(device, attr);
4039
4040                 g_free(l->data);
4041                 device->uuids = g_slist_delete_link(device->uuids, l);
4042                 g_dbus_emit_property_changed(dbus_conn, device->path,
4043                                                 DEVICE_INTERFACE, "UUIDs");
4044         }
4045
4046         g_free(prim);
4047
4048         store_device_info(device);
4049
4050         btd_gatt_client_service_removed(device->client_dbus, attr);
4051 }
4052
4053 static struct btd_device *device_new(struct btd_adapter *adapter,
4054                                 const char *address)
4055 {
4056         char *address_up;
4057         struct btd_device *device;
4058         const char *adapter_path = adapter_get_path(adapter);
4059
4060         DBG("address %s", address);
4061
4062         device = g_try_malloc0(sizeof(struct btd_device));
4063         if (device == NULL)
4064                 return NULL;
4065
4066         device->db = gatt_db_new();
4067         if (!device->db) {
4068                 g_free(device);
4069                 return NULL;
4070         }
4071
4072         address_up = g_ascii_strup(address, -1);
4073         device->path = g_strdup_printf("%s/dev_%s", adapter_path, address_up);
4074         g_strdelimit(device->path, ":", '_');
4075         g_free(address_up);
4076
4077         str2ba(address, &device->bdaddr);
4078
4079         device->client_dbus = btd_gatt_client_new(device);
4080         if (!device->client_dbus) {
4081                 error("Failed to create btd_gatt_client");
4082                 device_free(device);
4083                 return NULL;
4084         }
4085
4086         DBG("Creating device %s", device->path);
4087
4088         if (g_dbus_register_interface(dbus_conn,
4089                                         device->path, DEVICE_INTERFACE,
4090 #ifdef __TIZEN_PATCH__
4091                                         device_methods, device_signals,
4092 #else
4093                                         device_methods, NULL,
4094 #endif
4095                                         device_properties, device,
4096                                         device_free) == FALSE) {
4097                 error("Unable to register device interface for %s", address);
4098                 device_free(device);
4099                 return NULL;
4100         }
4101
4102         device->adapter = adapter;
4103         device->temporary = true;
4104
4105         gatt_db_register(device->db, gatt_service_added, gatt_service_removed,
4106                                                                 device, NULL);
4107
4108         return btd_device_ref(device);
4109 }
4110
4111 struct btd_device *device_create_from_storage(struct btd_adapter *adapter,
4112                                 const char *address, GKeyFile *key_file)
4113 {
4114         struct btd_device *device;
4115         const bdaddr_t *src;
4116         char srcaddr[18];
4117
4118         DBG("address %s", address);
4119
4120         device = device_new(adapter, address);
4121         if (device == NULL)
4122                 return NULL;
4123
4124         src = btd_adapter_get_address(adapter);
4125         ba2str(src, srcaddr);
4126
4127         load_info(device, srcaddr, address, key_file);
4128         load_att_info(device, srcaddr, address);
4129
4130         return device;
4131 }
4132
4133 struct btd_device *device_create(struct btd_adapter *adapter,
4134                                 const bdaddr_t *bdaddr, uint8_t bdaddr_type)
4135 {
4136         struct btd_device *device;
4137         const bdaddr_t *sba;
4138         char src[18], dst[18];
4139         char *str;
4140
4141         ba2str(bdaddr, dst);
4142         DBG("dst %s", dst);
4143
4144         device = device_new(adapter, dst);
4145         if (device == NULL)
4146                 return NULL;
4147
4148         device->bdaddr_type = bdaddr_type;
4149
4150         if (bdaddr_type == BDADDR_BREDR)
4151                 device->bredr = true;
4152         else
4153                 device->le = true;
4154
4155         sba = btd_adapter_get_address(adapter);
4156         ba2str(sba, src);
4157
4158         str = load_cached_name(device, src, dst);
4159         if (str) {
4160                 strcpy(device->name, str);
4161                 g_free(str);
4162         }
4163
4164         return device;
4165 }
4166
4167 char *btd_device_get_storage_path(struct btd_device *device,
4168                                 const char *filename)
4169 {
4170         char srcaddr[18], dstaddr[18];
4171
4172         if (device_address_is_private(device)) {
4173                 warn("Refusing storage path for private addressed device %s",
4174                                                                 device->path);
4175                 return NULL;
4176         }
4177
4178         ba2str(btd_adapter_get_address(device->adapter), srcaddr);
4179         ba2str(&device->bdaddr, dstaddr);
4180
4181         if (!filename)
4182                 return g_strdup_printf(STORAGEDIR "/%s/%s", srcaddr, dstaddr);
4183
4184         return g_strdup_printf(STORAGEDIR "/%s/%s/%s", srcaddr, dstaddr,
4185                                                         filename);
4186 }
4187
4188 void btd_device_device_set_name(struct btd_device *device, const char *name)
4189 {
4190         if (strncmp(name, device->name, MAX_NAME_LENGTH) == 0)
4191                 return;
4192
4193         DBG("%s %s", device->path, name);
4194
4195         strncpy(device->name, name, MAX_NAME_LENGTH);
4196
4197         store_device_info(device);
4198
4199         g_dbus_emit_property_changed(dbus_conn, device->path,
4200                                                 DEVICE_INTERFACE, "Name");
4201
4202         if (device->alias != NULL)
4203                 return;
4204
4205         g_dbus_emit_property_changed(dbus_conn, device->path,
4206                                                 DEVICE_INTERFACE, "Alias");
4207 }
4208
4209 void device_get_name(struct btd_device *device, char *name, size_t len)
4210 {
4211         if (name != NULL && len > 0) {
4212                 strncpy(name, device->name, len - 1);
4213                 name[len - 1] = '\0';
4214         }
4215 }
4216
4217 bool device_name_known(struct btd_device *device)
4218 {
4219         return device->name[0] != '\0';
4220 }
4221
4222 void device_set_class(struct btd_device *device, uint32_t class)
4223 {
4224         if (device->class == class)
4225                 return;
4226
4227         DBG("%s 0x%06X", device->path, class);
4228
4229         device->class = class;
4230
4231         store_device_info(device);
4232
4233         g_dbus_emit_property_changed(dbus_conn, device->path,
4234                                                 DEVICE_INTERFACE, "Class");
4235         g_dbus_emit_property_changed(dbus_conn, device->path,
4236                                                 DEVICE_INTERFACE, "Icon");
4237 }
4238
4239 void device_update_addr(struct btd_device *device, const bdaddr_t *bdaddr,
4240                                                         uint8_t bdaddr_type)
4241 {
4242         if (!bacmp(bdaddr, &device->bdaddr) &&
4243                                         bdaddr_type == device->bdaddr_type)
4244                 return;
4245
4246         /* Since this function is only used for LE SMP Identity
4247          * Resolving purposes we can now assume LE is supported.
4248          */
4249         device->le = true;
4250
4251         bacpy(&device->bdaddr, bdaddr);
4252         device->bdaddr_type = bdaddr_type;
4253
4254         store_device_info(device);
4255
4256         g_dbus_emit_property_changed(dbus_conn, device->path,
4257                                                 DEVICE_INTERFACE, "Address");
4258 }
4259
4260 void device_set_bredr_support(struct btd_device *device)
4261 {
4262         if (device->bredr)
4263                 return;
4264
4265         device->bredr = true;
4266         store_device_info(device);
4267 }
4268
4269 void device_set_le_support(struct btd_device *device, uint8_t bdaddr_type)
4270 {
4271         if (device->le)
4272                 return;
4273
4274         device->le = true;
4275         device->bdaddr_type = bdaddr_type;
4276
4277         store_device_info(device);
4278 }
4279
4280 void device_update_last_seen(struct btd_device *device, uint8_t bdaddr_type)
4281 {
4282         if (bdaddr_type == BDADDR_BREDR)
4283                 device->bredr_seen = time(NULL);
4284         else
4285                 device->le_seen = time(NULL);
4286 }
4287
4288 /* It is possible that we have two device objects for the same device in
4289  * case it has first been discovered over BR/EDR and has a private
4290  * address when discovered over LE for the first time. In such a case we
4291  * need to inherit critical values from the duplicate so that we don't
4292  * ovewrite them when writing to storage. The next time bluetoothd
4293  * starts the device will show up as a single instance.
4294  */
4295 void device_merge_duplicate(struct btd_device *dev, struct btd_device *dup)
4296 {
4297         GSList *l;
4298
4299         DBG("");
4300
4301         dev->bredr = dup->bredr;
4302
4303         dev->trusted = dup->trusted;
4304         dev->blocked = dup->blocked;
4305
4306         for (l = dup->uuids; l; l = g_slist_next(l))
4307                 dev->uuids = g_slist_append(dev->uuids, g_strdup(l->data));
4308
4309         if (dev->name[0] == '\0')
4310                 strcpy(dev->name, dup->name);
4311
4312         if (!dev->alias)
4313                 dev->alias = g_strdup(dup->alias);
4314
4315         dev->class = dup->class;
4316
4317         dev->vendor_src = dup->vendor_src;
4318         dev->vendor = dup->vendor;
4319         dev->product = dup->product;
4320         dev->version = dup->version;
4321 }
4322
4323 uint32_t btd_device_get_class(struct btd_device *device)
4324 {
4325         return device->class;
4326 }
4327
4328 uint16_t btd_device_get_vendor(struct btd_device *device)
4329 {
4330         return device->vendor;
4331 }
4332
4333 uint16_t btd_device_get_vendor_src(struct btd_device *device)
4334 {
4335         return device->vendor_src;
4336 }
4337
4338 uint16_t btd_device_get_product(struct btd_device *device)
4339 {
4340         return device->product;
4341 }
4342
4343 uint16_t btd_device_get_version(struct btd_device *device)
4344 {
4345         return device->version;
4346 }
4347
4348 static void delete_folder_tree(const char *dirname)
4349 {
4350         DIR *dir;
4351         struct dirent *entry;
4352         char filename[PATH_MAX];
4353
4354         dir = opendir(dirname);
4355         if (dir == NULL)
4356                 return;
4357
4358         while ((entry = readdir(dir)) != NULL) {
4359                 if (g_str_equal(entry->d_name, ".") ||
4360                                 g_str_equal(entry->d_name, ".."))
4361                         continue;
4362
4363                 if (entry->d_type == DT_UNKNOWN)
4364                         entry->d_type = util_get_dt(dirname, entry->d_name);
4365
4366                 snprintf(filename, PATH_MAX, "%s/%s", dirname, entry->d_name);
4367
4368                 if (entry->d_type == DT_DIR)
4369                         delete_folder_tree(filename);
4370                 else
4371                         unlink(filename);
4372         }
4373         closedir(dir);
4374
4375         rmdir(dirname);
4376 }
4377
4378 static void device_remove_stored(struct btd_device *device)
4379 {
4380         const bdaddr_t *src = btd_adapter_get_address(device->adapter);
4381         char adapter_addr[18];
4382         char device_addr[18];
4383         char filename[PATH_MAX];
4384         GKeyFile *key_file;
4385         char *data;
4386         gsize length = 0;
4387
4388         if (device->bredr_state.bonded) {
4389                 device->bredr_state.bonded = false;
4390                 btd_adapter_remove_bonding(device->adapter, &device->bdaddr,
4391                                                                 BDADDR_BREDR);
4392         }
4393
4394         if (device->le_state.bonded) {
4395                 device->le_state.bonded = false;
4396                 btd_adapter_remove_bonding(device->adapter, &device->bdaddr,
4397                                                         device->bdaddr_type);
4398         }
4399
4400         device->bredr_state.paired = false;
4401         device->le_state.paired = false;
4402
4403         if (device->blocked)
4404                 device_unblock(device, TRUE, FALSE);
4405
4406         ba2str(src, adapter_addr);
4407         ba2str(&device->bdaddr, device_addr);
4408
4409         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/%s", adapter_addr,
4410                         device_addr);
4411         delete_folder_tree(filename);
4412
4413         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s", adapter_addr,
4414                         device_addr);
4415
4416         key_file = g_key_file_new();
4417         g_key_file_load_from_file(key_file, filename, 0, NULL);
4418         g_key_file_remove_group(key_file, "ServiceRecords", NULL);
4419
4420         data = g_key_file_to_data(key_file, &length, NULL);
4421         if (length > 0) {
4422                 create_file(filename, S_IRUSR | S_IWUSR);
4423                 g_file_set_contents(filename, data, length, NULL);
4424         }
4425
4426         g_free(data);
4427         g_key_file_free(key_file);
4428 }
4429
4430 #ifdef __TIZEN_PATCH__
4431 void device_unpair(struct btd_device *device, gboolean remove_stored)
4432 {
4433         DBG("+");
4434         DBG("Unpairing device %s", device->path);
4435
4436         if (device->bonding) {
4437                 uint8_t status;
4438
4439                 if (device->bredr_state.connected)
4440                         status = MGMT_STATUS_DISCONNECTED;
4441                 else
4442                         status = MGMT_STATUS_CONNECT_FAILED;
4443
4444                 device_cancel_bonding(device, status);
4445         }
4446
4447         if (device->browse)
4448                 browse_request_cancel(device->browse);
4449
4450
4451 //      while (device->services != NULL) {
4452 //              struct btd_service *service = device->services->data;
4453 //
4454 //              device->services = g_slist_remove(device->services, service);
4455 //              service_remove(service);
4456 //      }
4457
4458         g_slist_free(device->pending);
4459         device->pending = NULL;
4460
4461         if (btd_device_is_connected(device))
4462                 disconnect_all(device);
4463
4464         if (device->store_id > 0) {
4465                 g_source_remove(device->store_id);
4466                 device->store_id = 0;
4467
4468                 if (!remove_stored)
4469                         store_device_info_cb(device);
4470         }
4471
4472         if (remove_stored)
4473                 device_remove_stored(device);
4474
4475         device->bredr_state.paired = 0;
4476         device->le_state.paired = 0;
4477         device->bredr_state.svc_resolved = false;
4478         device->trusted = false;
4479         if (device->alias != NULL) {
4480                 /* Remove alias name because
4481                  * In UG if we rename and then unpair device and
4482                  * initiates connection without scanning then paired
4483                  * list will have alias name as first preference is
4484                  * given to alias name.
4485                  */
4486                 DBG("Freeing device alias name");
4487                 g_free(device->alias);
4488                 device->alias = NULL;
4489         }
4490         g_dbus_emit_property_changed(dbus_conn, device->path,
4491                                         DEVICE_INTERFACE, "Paired");
4492 //      btd_device_unref(device);
4493         DBG("-");
4494  }
4495 #endif
4496
4497 void device_remove(struct btd_device *device, gboolean remove_stored)
4498 {
4499         DBG("Removing device %s", device->path);
4500
4501         if (device->bonding) {
4502                 uint8_t status;
4503
4504                 if (device->bredr_state.connected)
4505                         status = MGMT_STATUS_DISCONNECTED;
4506                 else
4507                         status = MGMT_STATUS_CONNECT_FAILED;
4508
4509                 device_cancel_bonding(device, status);
4510         }
4511
4512         if (device->browse)
4513                 browse_request_cancel(device->browse);
4514
4515         while (device->services != NULL) {
4516                 struct btd_service *service = device->services->data;
4517
4518                 device->services = g_slist_remove(device->services, service);
4519                 service_remove(service);
4520         }
4521
4522         g_slist_free(device->pending);
4523         device->pending = NULL;
4524
4525         if (btd_device_is_connected(device))
4526                 disconnect_all(device);
4527
4528         if (device->store_id > 0) {
4529                 g_source_remove(device->store_id);
4530                 device->store_id = 0;
4531
4532                 if (!remove_stored)
4533                         store_device_info_cb(device);
4534         }
4535
4536         if (remove_stored)
4537                 device_remove_stored(device);
4538
4539         btd_device_unref(device);
4540 }
4541
4542 int device_address_cmp(gconstpointer a, gconstpointer b)
4543 {
4544         const struct btd_device *device = a;
4545         const char *address = b;
4546         char addr[18];
4547
4548         ba2str(&device->bdaddr, addr);
4549         return strcasecmp(addr, address);
4550 }
4551
4552 int device_bdaddr_cmp(gconstpointer a, gconstpointer b)
4553 {
4554         const struct btd_device *device = a;
4555         const bdaddr_t *bdaddr = b;
4556
4557         return bacmp(&device->bdaddr, bdaddr);
4558 }
4559
4560 static bool addr_is_public(uint8_t addr_type)
4561 {
4562         if (addr_type == BDADDR_BREDR || addr_type == BDADDR_LE_PUBLIC)
4563                 return true;
4564
4565         return false;
4566 }
4567
4568 int device_addr_type_cmp(gconstpointer a, gconstpointer b)
4569 {
4570         const struct btd_device *dev = a;
4571         const struct device_addr_type *addr = b;
4572         int cmp;
4573
4574         cmp = bacmp(&dev->bdaddr, &addr->bdaddr);
4575
4576         /*
4577          * Address matches and both old and new are public addresses
4578          * (doesn't matter whether LE or BR/EDR, then consider this a
4579          * match.
4580          */
4581         if (!cmp && addr_is_public(addr->bdaddr_type) &&
4582                                         addr_is_public(dev->bdaddr_type))
4583                 return 0;
4584
4585         if (addr->bdaddr_type == BDADDR_BREDR) {
4586                 if (!dev->bredr)
4587                         return -1;
4588
4589                 return cmp;
4590         }
4591
4592         if (!dev->le)
4593                 return -1;
4594
4595         if (addr->bdaddr_type != dev->bdaddr_type)
4596                 return -1;
4597
4598         return cmp;
4599 }
4600
4601 static gboolean record_has_uuid(const sdp_record_t *rec,
4602                                 const char *profile_uuid)
4603 {
4604         sdp_list_t *pat;
4605
4606         for (pat = rec->pattern; pat != NULL; pat = pat->next) {
4607                 char *uuid;
4608                 int ret;
4609
4610                 uuid = bt_uuid2string(pat->data);
4611                 if (!uuid)
4612                         continue;
4613
4614                 ret = strcasecmp(uuid, profile_uuid);
4615
4616                 free(uuid);
4617
4618                 if (ret == 0)
4619                         return TRUE;
4620         }
4621
4622         return FALSE;
4623 }
4624
4625 GSList *btd_device_get_uuids(struct btd_device *device)
4626 {
4627         return device->uuids;
4628 }
4629
4630 struct probe_data {
4631         struct btd_device *dev;
4632         GSList *uuids;
4633 };
4634
4635 static void dev_probe(struct btd_profile *p, void *user_data)
4636 {
4637         struct probe_data *d = user_data;
4638         struct btd_service *service;
4639
4640         if (p->device_probe == NULL)
4641                 return;
4642
4643         if (!device_match_profile(d->dev, p, d->uuids))
4644                 return;
4645
4646         service = service_create(d->dev, p);
4647
4648         if (service_probe(service) < 0) {
4649                 btd_service_unref(service);
4650                 return;
4651         }
4652
4653         d->dev->services = g_slist_append(d->dev->services, service);
4654 }
4655
4656 void device_probe_profile(gpointer a, gpointer b)
4657 {
4658         struct btd_device *device = a;
4659         struct btd_profile *profile = b;
4660         struct btd_service *service;
4661
4662         if (profile->device_probe == NULL)
4663                 return;
4664
4665         if (!device_match_profile(device, profile, device->uuids))
4666                 return;
4667
4668         service = service_create(device, profile);
4669
4670         if (service_probe(service) < 0) {
4671                 btd_service_unref(service);
4672                 return;
4673         }
4674
4675         device->services = g_slist_append(device->services, service);
4676
4677         if (!profile->auto_connect || !device->general_connect)
4678                 return;
4679
4680         device->pending = g_slist_append(device->pending, service);
4681
4682         if (g_slist_length(device->pending) == 1)
4683                 connect_next(device);
4684 }
4685
4686 void device_remove_profile(gpointer a, gpointer b)
4687 {
4688         struct btd_device *device = a;
4689         struct btd_profile *profile = b;
4690         struct btd_service *service;
4691         GSList *l;
4692
4693         l = find_service_with_profile(device->services, profile);
4694         if (l == NULL)
4695                 return;
4696
4697         service = l->data;
4698         device->services = g_slist_delete_link(device->services, l);
4699         device->pending = g_slist_remove(device->pending, service);
4700         service_remove(service);
4701 }
4702
4703 void device_probe_profiles(struct btd_device *device, GSList *uuids)
4704 {
4705         struct probe_data d = { device, uuids };
4706         char addr[18];
4707
4708         ba2str(&device->bdaddr, addr);
4709
4710         if (device->blocked) {
4711                 DBG("Skipping profiles for blocked device %s", addr);
4712                 goto add_uuids;
4713         }
4714
4715         DBG("Probing profiles for device %s", addr);
4716
4717         btd_profile_foreach(dev_probe, &d);
4718
4719 add_uuids:
4720         device_add_uuids(device, uuids);
4721 }
4722
4723 static void store_sdp_record(GKeyFile *key_file, sdp_record_t *rec)
4724 {
4725         char handle_str[11];
4726         sdp_buf_t buf;
4727         int size, i;
4728         char *str;
4729
4730         sprintf(handle_str, "0x%8.8X", rec->handle);
4731
4732         if (sdp_gen_record_pdu(rec, &buf) < 0)
4733                 return;
4734
4735         size = buf.data_size;
4736
4737         str = g_malloc0(size*2+1);
4738
4739         for (i = 0; i < size; i++)
4740                 sprintf(str + (i * 2), "%02X", buf.data[i]);
4741
4742         g_key_file_set_string(key_file, "ServiceRecords", handle_str, str);
4743
4744         free(buf.data);
4745         g_free(str);
4746 }
4747
4748 static void store_primaries_from_sdp_record(GKeyFile *key_file,
4749                                                 sdp_record_t *rec)
4750 {
4751         uuid_t uuid;
4752         char *att_uuid, *prim_uuid;
4753         uint16_t start = 0, end = 0, psm = 0;
4754         char handle[6], uuid_str[33];
4755         int i;
4756
4757         sdp_uuid16_create(&uuid, ATT_UUID);
4758         att_uuid = bt_uuid2string(&uuid);
4759
4760         sdp_uuid16_create(&uuid, GATT_PRIM_SVC_UUID);
4761         prim_uuid = bt_uuid2string(&uuid);
4762
4763         if (!record_has_uuid(rec, att_uuid))
4764                 goto done;
4765
4766         if (!gatt_parse_record(rec, &uuid, &psm, &start, &end))
4767                 goto done;
4768
4769         sprintf(handle, "%hu", start);
4770         switch (uuid.type) {
4771         case SDP_UUID16:
4772                 sprintf(uuid_str, "%4.4X", uuid.value.uuid16);
4773                 break;
4774         case SDP_UUID32:
4775                 sprintf(uuid_str, "%8.8X", uuid.value.uuid32);
4776                 break;
4777         case SDP_UUID128:
4778                 for (i = 0; i < 16; i++)
4779                         sprintf(uuid_str + (i * 2), "%2.2X",
4780                                         uuid.value.uuid128.data[i]);
4781                 break;
4782         default:
4783                 uuid_str[0] = '\0';
4784         }
4785
4786         g_key_file_set_string(key_file, handle, "UUID", prim_uuid);
4787         g_key_file_set_string(key_file, handle, "Value", uuid_str);
4788         g_key_file_set_integer(key_file, handle, "EndGroupHandle", end);
4789
4790 done:
4791         free(prim_uuid);
4792         free(att_uuid);
4793 }
4794
4795 static int rec_cmp(const void *a, const void *b)
4796 {
4797         const sdp_record_t *r1 = a;
4798         const sdp_record_t *r2 = b;
4799
4800         return r1->handle - r2->handle;
4801 }
4802
4803 static int update_record(struct browse_req *req, const char *uuid,
4804                                                         sdp_record_t *rec)
4805 {
4806         GSList *l;
4807
4808         /* Check for duplicates */
4809         if (sdp_list_find(req->records, rec, rec_cmp))
4810                 return -EALREADY;
4811
4812         /* Copy record */
4813         req->records = sdp_list_append(req->records, sdp_copy_record(rec));
4814
4815         /* Check if UUID is duplicated */
4816         l = g_slist_find_custom(req->device->uuids, uuid, bt_uuid_strcmp);
4817         if (l == NULL) {
4818                 l = g_slist_find_custom(req->profiles_added, uuid,
4819                                                         bt_uuid_strcmp);
4820                 if (l != NULL)
4821                         return 0;
4822                 req->profiles_added = g_slist_append(req->profiles_added,
4823                                                         g_strdup(uuid));
4824         }
4825
4826         return 0;
4827 }
4828
4829 static void update_bredr_services(struct browse_req *req, sdp_list_t *recs)
4830 {
4831         struct btd_device *device = req->device;
4832         sdp_list_t *seq;
4833         char srcaddr[18], dstaddr[18];
4834         char sdp_file[PATH_MAX];
4835         char att_file[PATH_MAX];
4836         GKeyFile *sdp_key_file = NULL;
4837         GKeyFile *att_key_file = NULL;
4838         char *data;
4839         gsize length = 0;
4840
4841         ba2str(btd_adapter_get_address(device->adapter), srcaddr);
4842         ba2str(&device->bdaddr, dstaddr);
4843
4844         if (!device->temporary) {
4845                 snprintf(sdp_file, PATH_MAX, STORAGEDIR "/%s/cache/%s",
4846                                                         srcaddr, dstaddr);
4847
4848                 sdp_key_file = g_key_file_new();
4849                 g_key_file_load_from_file(sdp_key_file, sdp_file, 0, NULL);
4850
4851                 snprintf(att_file, PATH_MAX, STORAGEDIR "/%s/%s/attributes",
4852                                                         srcaddr, dstaddr);
4853
4854                 att_key_file = g_key_file_new();
4855                 g_key_file_load_from_file(att_key_file, att_file, 0, NULL);
4856         }
4857
4858         for (seq = recs; seq; seq = seq->next) {
4859                 sdp_record_t *rec = (sdp_record_t *) seq->data;
4860                 sdp_list_t *svcclass = NULL;
4861                 char *profile_uuid;
4862
4863                 if (!rec)
4864                         break;
4865
4866                 if (sdp_get_service_classes(rec, &svcclass) < 0)
4867                         continue;
4868
4869                 /* Check for empty service classes list */
4870                 if (svcclass == NULL) {
4871                         DBG("Skipping record with no service classes");
4872                         continue;
4873                 }
4874
4875                 /* Extract the first element and skip the remainning */
4876                 profile_uuid = bt_uuid2string(svcclass->data);
4877                 if (!profile_uuid) {
4878                         sdp_list_free(svcclass, free);
4879                         continue;
4880                 }
4881
4882                 if (bt_uuid_strcmp(profile_uuid, PNP_UUID) == 0) {
4883                         uint16_t source, vendor, product, version;
4884                         sdp_data_t *pdlist;
4885
4886                         pdlist = sdp_data_get(rec, SDP_ATTR_VENDOR_ID_SOURCE);
4887                         source = pdlist ? pdlist->val.uint16 : 0x0000;
4888
4889                         pdlist = sdp_data_get(rec, SDP_ATTR_VENDOR_ID);
4890                         vendor = pdlist ? pdlist->val.uint16 : 0x0000;
4891
4892                         pdlist = sdp_data_get(rec, SDP_ATTR_PRODUCT_ID);
4893                         product = pdlist ? pdlist->val.uint16 : 0x0000;
4894
4895                         pdlist = sdp_data_get(rec, SDP_ATTR_VERSION);
4896                         version = pdlist ? pdlist->val.uint16 : 0x0000;
4897
4898                         if (source || vendor || product || version)
4899                                 btd_device_set_pnpid(device, source, vendor,
4900                                                         product, version);
4901                 }
4902
4903                 if (update_record(req, profile_uuid, rec) < 0)
4904                         goto next;
4905
4906                 if (sdp_key_file)
4907                         store_sdp_record(sdp_key_file, rec);
4908
4909                 if (att_key_file)
4910                         store_primaries_from_sdp_record(att_key_file, rec);
4911
4912 next:
4913                 free(profile_uuid);
4914                 sdp_list_free(svcclass, free);
4915         }
4916
4917         if (sdp_key_file) {
4918                 data = g_key_file_to_data(sdp_key_file, &length, NULL);
4919                 if (length > 0) {
4920                         create_file(sdp_file, S_IRUSR | S_IWUSR);
4921                         g_file_set_contents(sdp_file, data, length, NULL);
4922                 }
4923
4924                 g_free(data);
4925                 g_key_file_free(sdp_key_file);
4926         }
4927
4928         if (att_key_file) {
4929                 data = g_key_file_to_data(att_key_file, &length, NULL);
4930                 if (length > 0) {
4931                         create_file(att_file, S_IRUSR | S_IWUSR);
4932                         g_file_set_contents(att_file, data, length, NULL);
4933                 }
4934
4935                 g_free(data);
4936                 g_key_file_free(att_key_file);
4937         }
4938 }
4939
4940 static int primary_cmp(gconstpointer a, gconstpointer b)
4941 {
4942         return memcmp(a, b, sizeof(struct gatt_primary));
4943 }
4944
4945 static void update_gatt_uuids(struct browse_req *req, GSList *current,
4946                                                                 GSList *found)
4947 {
4948         GSList *l, *lmatch;
4949
4950         /* Added Profiles */
4951         for (l = found; l; l = g_slist_next(l)) {
4952                 struct gatt_primary *prim = l->data;
4953
4954                 /* Entry found ? */
4955                 lmatch = g_slist_find_custom(current, prim, primary_cmp);
4956                 if (lmatch)
4957                         continue;
4958
4959                 /* New entry */
4960                 req->profiles_added = g_slist_append(req->profiles_added,
4961                                                         g_strdup(prim->uuid));
4962
4963                 DBG("UUID Added: %s", prim->uuid);
4964         }
4965 }
4966
4967 static GSList *device_services_from_record(struct btd_device *device,
4968                                                         GSList *profiles)
4969 {
4970         GSList *l, *prim_list = NULL;
4971         char *att_uuid;
4972         uuid_t proto_uuid;
4973
4974         sdp_uuid16_create(&proto_uuid, ATT_UUID);
4975         att_uuid = bt_uuid2string(&proto_uuid);
4976
4977         for (l = profiles; l; l = l->next) {
4978                 const char *profile_uuid = l->data;
4979                 const sdp_record_t *rec;
4980                 struct gatt_primary *prim;
4981                 uint16_t start = 0, end = 0, psm = 0;
4982                 uuid_t prim_uuid;
4983
4984                 rec = btd_device_get_record(device, profile_uuid);
4985                 if (!rec)
4986                         continue;
4987
4988                 if (!record_has_uuid(rec, att_uuid))
4989                         continue;
4990
4991                 if (!gatt_parse_record(rec, &prim_uuid, &psm, &start, &end))
4992                         continue;
4993
4994                 prim = g_new0(struct gatt_primary, 1);
4995                 prim->range.start = start;
4996                 prim->range.end = end;
4997                 sdp_uuid2strn(&prim_uuid, prim->uuid, sizeof(prim->uuid));
4998
4999                 prim_list = g_slist_append(prim_list, prim);
5000         }
5001
5002         free(att_uuid);
5003
5004         return prim_list;
5005 }
5006
5007 static void search_cb(sdp_list_t *recs, int err, gpointer user_data)
5008 {
5009         struct browse_req *req = user_data;
5010         struct btd_device *device = req->device;
5011         GSList *primaries;
5012         char addr[18];
5013
5014         ba2str(&device->bdaddr, addr);
5015
5016         if (err < 0) {
5017                 error("%s: error updating services: %s (%d)",
5018                                 addr, strerror(-err), -err);
5019                 goto send_reply;
5020         }
5021
5022         update_bredr_services(req, recs);
5023
5024         if (device->tmp_records)
5025                 sdp_list_free(device->tmp_records,
5026                                         (sdp_free_func_t) sdp_record_free);
5027
5028         device->tmp_records = req->records;
5029         req->records = NULL;
5030
5031         if (!req->profiles_added) {
5032                 DBG("%s: No service update", addr);
5033                 goto send_reply;
5034         }
5035
5036         primaries = device_services_from_record(device, req->profiles_added);
5037         if (primaries)
5038                 device_register_primaries(device, primaries, ATT_PSM);
5039
5040         /*
5041          * TODO: The btd_service instances for GATT services need to be
5042          * initialized with the service handles. Eventually this code should
5043          * perform ATT protocol service discovery over the ATT PSM to obtain
5044          * the full list of services and populate a client-role gatt_db over
5045          * BR/EDR.
5046          */
5047         device_probe_profiles(device, req->profiles_added);
5048
5049         /* Propagate services changes */
5050         g_dbus_emit_property_changed(dbus_conn, req->device->path,
5051                                                 DEVICE_INTERFACE, "UUIDs");
5052
5053 send_reply:
5054 #ifdef __TIZEN_PATCH__
5055         if (!req->msg)
5056                 goto done;
5057
5058         /* since no new services are found, UUID signal is not emitted,
5059         ** so send a reply to the framework with the existing services */
5060         if (dbus_message_is_method_call(req->msg, DEVICE_INTERFACE,
5061                                 "DiscoverServices"))
5062                 discover_services_reply(req, err, device->tmp_records);
5063
5064 done:
5065 #endif
5066
5067         device_svc_resolved(device, BDADDR_BREDR, err);
5068 }
5069
5070 static void browse_cb(sdp_list_t *recs, int err, gpointer user_data)
5071 {
5072         struct browse_req *req = user_data;
5073         struct btd_device *device = req->device;
5074         struct btd_adapter *adapter = device->adapter;
5075         uuid_t uuid;
5076
5077         /* If we have a valid response and req->search_uuid == 2, then L2CAP
5078          * UUID & PNP searching was successful -- we are done */
5079         if (err < 0 || (req->search_uuid == 2 && req->records)) {
5080                 if (err == -ECONNRESET && req->reconnect_attempt < 1) {
5081                         req->search_uuid--;
5082                         req->reconnect_attempt++;
5083                 } else
5084                         goto done;
5085         }
5086
5087         update_bredr_services(req, recs);
5088
5089         /* Search for mandatory uuids */
5090         if (uuid_list[req->search_uuid]) {
5091                 sdp_uuid16_create(&uuid, uuid_list[req->search_uuid++]);
5092                 bt_search_service(btd_adapter_get_address(adapter),
5093                                                 &device->bdaddr, &uuid,
5094                                                 browse_cb, user_data, NULL,
5095                                                 req->sdp_flags);
5096                 return;
5097         }
5098
5099 done:
5100         search_cb(recs, err, user_data);
5101 }
5102
5103 static bool device_get_auto_connect(struct btd_device *device)
5104 {
5105         if (device->disable_auto_connect)
5106                 return false;
5107
5108         return device->auto_connect;
5109 }
5110
5111 static void attio_connected(gpointer data, gpointer user_data)
5112 {
5113         struct attio_data *attio = data;
5114         GAttrib *attrib = user_data;
5115
5116         DBG("");
5117
5118         if (attio->cfunc)
5119                 attio->cfunc(attrib, attio->user_data);
5120 }
5121
5122 static void attio_disconnected(gpointer data, gpointer user_data)
5123 {
5124         struct attio_data *attio = data;
5125
5126         DBG("");
5127
5128         if (attio->dcfunc)
5129                 attio->dcfunc(attio->user_data);
5130 }
5131
5132 static void att_disconnected_cb(int err, void *user_data)
5133 {
5134         struct btd_device *device = user_data;
5135
5136         DBG("");
5137
5138         if (device->browse)
5139                 goto done;
5140
5141         DBG("%s (%d)", strerror(err), err);
5142
5143         g_slist_foreach(device->attios, attio_disconnected, NULL);
5144
5145         btd_gatt_client_disconnected(device->client_dbus);
5146
5147         if (!device_get_auto_connect(device)) {
5148                 DBG("Automatic connection disabled");
5149                 goto done;
5150         }
5151
5152         /*
5153          * Keep scanning/re-connection active if disconnection reason
5154          * is connection timeout, remote user terminated connection or local
5155          * initiated disconnection.
5156          */
5157         if (err == ETIMEDOUT || err == ECONNRESET || err == ECONNABORTED)
5158                 adapter_connect_list_add(device->adapter, device);
5159
5160 done:
5161 #ifdef __TIZEN_PATCH__
5162         device_set_gatt_connected(device, FALSE);
5163 #endif
5164         attio_cleanup(device);
5165 }
5166
5167 static void register_gatt_services(struct btd_device *device)
5168 {
5169         struct browse_req *req = device->browse;
5170         GSList *services = NULL;
5171
5172         if (!bt_gatt_client_is_ready(device->client))
5173                 return;
5174
5175         /*
5176          * TODO: Remove the primaries list entirely once all profiles use
5177          * shared/gatt.
5178          */
5179         gatt_db_foreach_service(device->db, NULL, add_primary, &services);
5180
5181         btd_device_set_temporary(device, false);
5182
5183         if (req)
5184                 update_gatt_uuids(req, device->primaries, services);
5185
5186         g_slist_free_full(device->primaries, g_free);
5187         device->primaries = NULL;
5188
5189         device_register_primaries(device, services, -1);
5190
5191         device_probe_gatt_profiles(device);
5192
5193         device_svc_resolved(device, device->bdaddr_type, 0);
5194 }
5195
5196 #ifdef __TIZEN_PATCH__
5197 static void gatt_client_debug_func(const char *str, void *user_data)
5198 {
5199         DBG("%s", str);
5200 }
5201 #endif
5202
5203 static void gatt_client_ready_cb(bool success, uint8_t att_ecode,
5204                                                                 void *user_data)
5205 {
5206         struct btd_device *device = user_data;
5207
5208         DBG("status: %s, error: %u", success ? "success" : "failed", att_ecode);
5209
5210         if (!success) {
5211                 if (device->browse) {
5212                         struct browse_req *req = device->browse;
5213
5214                         device->browse = NULL;
5215                         browse_request_complete(req, device->bdaddr_type, -EIO);
5216                 }
5217
5218 #ifdef __TIZEN_PATCH__
5219                 if (device->attachid == 0) {
5220                         error("GATT client / server both are not connected");
5221                         return;
5222                 }
5223
5224                 error("Even though GATT client's connection is failed, "
5225                                 "because GATT server's connection is made, "
5226                                 "update GATT connection state.");
5227                 device_set_gatt_connected(device, TRUE);
5228 #endif
5229
5230                 return;
5231         }
5232
5233         register_gatt_services(device);
5234
5235         device_accept_gatt_profiles(device);
5236
5237         btd_gatt_client_ready(device->client_dbus);
5238 }
5239
5240 static void gatt_client_service_changed(uint16_t start_handle,
5241                                                         uint16_t end_handle,
5242                                                         void *user_data)
5243 {
5244         DBG("start 0x%04x, end: 0x%04x", start_handle, end_handle);
5245 }
5246
5247 static void gatt_debug(const char *str, void *user_data)
5248 {
5249         DBG("%s", str);
5250 }
5251
5252 static void gatt_client_init(struct btd_device *device)
5253 {
5254         gatt_client_cleanup(device);
5255
5256         device->client = bt_gatt_client_new(device->db, device->att,
5257                                                         device->att_mtu);
5258         if (!device->client) {
5259                 DBG("Failed to initialize");
5260                 return;
5261         }
5262
5263
5264 #ifdef __TIZEN_PATCH__
5265         if (!bt_gatt_client_set_debug(device->client, gatt_client_debug_func,
5266                                 NULL, NULL)) {
5267                 error("Failed to set debug function");
5268         }
5269 #else
5270         bt_gatt_client_set_debug(device->client, gatt_debug, NULL, NULL);
5271 #endif
5272         /* Notify attio so it can react to notifications */
5273         g_slist_foreach(device->attios, attio_connected, device->attrib);
5274
5275         if (!bt_gatt_client_set_ready_handler(device->client,
5276                                                         gatt_client_ready_cb,
5277                                                         device, NULL)) {
5278                 DBG("Failed to set ready handler");
5279                 gatt_client_cleanup(device);
5280                 return;
5281         }
5282
5283         if (!bt_gatt_client_set_service_changed(device->client,
5284                                                 gatt_client_service_changed,
5285                                                 device, NULL)) {
5286                 DBG("Failed to set service changed handler");
5287                 gatt_client_cleanup(device);
5288                 return;
5289         }
5290 }
5291
5292 static void gatt_server_init(struct btd_device *device, struct gatt_db *db)
5293 {
5294         if (!db) {
5295                 error("No local GATT database exists for this adapter");
5296                 return;
5297         }
5298
5299         gatt_server_cleanup(device);
5300
5301         device->server = bt_gatt_server_new(db, device->att, device->att_mtu);
5302         if (!device->server)
5303                 error("Failed to initialize bt_gatt_server");
5304
5305         bt_gatt_server_set_debug(device->server, gatt_debug, NULL, NULL);
5306 }
5307
5308 static bool local_counter(uint32_t *sign_cnt, void *user_data)
5309 {
5310         struct btd_device *dev = user_data;
5311
5312         if (!dev->local_csrk)
5313                 return false;
5314
5315         *sign_cnt = dev->local_csrk->counter++;
5316
5317         store_device_info(dev);
5318
5319         return true;
5320 }
5321
5322 static bool remote_counter(uint32_t *sign_cnt, void *user_data)
5323 {
5324         struct btd_device *dev = user_data;
5325
5326         if (!dev->remote_csrk || *sign_cnt < dev->remote_csrk->counter)
5327                 return false;
5328
5329         dev->remote_csrk->counter = *sign_cnt;
5330
5331         store_device_info(dev);
5332
5333         return true;
5334 }
5335
5336 bool device_attach_att(struct btd_device *dev, GIOChannel *io)
5337 {
5338         GError *gerr = NULL;
5339         GAttrib *attrib;
5340         BtIOSecLevel sec_level;
5341         uint16_t mtu;
5342         uint16_t cid;
5343         struct btd_gatt_database *database;
5344
5345         bt_io_get(io, &gerr, BT_IO_OPT_SEC_LEVEL, &sec_level,
5346                                                 BT_IO_OPT_IMTU, &mtu,
5347                                                 BT_IO_OPT_CID, &cid,
5348                                                 BT_IO_OPT_INVALID);
5349
5350         if (gerr) {
5351                 error("bt_io_get: %s", gerr->message);
5352                 g_error_free(gerr);
5353                 return false;
5354         }
5355
5356 #if 0
5357         if (sec_level == BT_IO_SEC_LOW && dev->le_state.paired) {
5358                 DBG("Elevating security level since LTK is available");
5359
5360                 sec_level = BT_IO_SEC_MEDIUM;
5361                 bt_io_set(io, &gerr, BT_IO_OPT_SEC_LEVEL, sec_level,
5362                                                         BT_IO_OPT_INVALID);
5363                 if (gerr) {
5364                         error("bt_io_set: %s", gerr->message);
5365                         g_error_free(gerr);
5366                         return false;
5367                 }
5368         }
5369 #endif
5370
5371         dev->att_mtu = MIN(mtu, BT_ATT_MAX_LE_MTU);
5372         attrib = g_attrib_new(io, dev->att_mtu);
5373         if (!attrib) {
5374                 error("Unable to create new GAttrib instance");
5375                 return false;
5376         }
5377
5378 #if 0
5379         dev->attachid = attrib_channel_attach(attrib);
5380         if (dev->attachid == 0) {
5381                 g_attrib_unref(attrib);
5382                 error("Attribute server attach failure!");
5383                 return false;
5384         }
5385 #endif
5386
5387         dev->attrib = attrib;
5388         dev->att = g_attrib_get_att(attrib);
5389
5390         bt_att_ref(dev->att);
5391
5392         dev->att_disconn_id = bt_att_register_disconnect(dev->att,
5393                                                 att_disconnected_cb, dev, NULL);
5394         bt_att_set_close_on_unref(dev->att, true);
5395
5396         if (dev->local_csrk)
5397                 bt_att_set_local_key(dev->att, dev->local_csrk->key,
5398                                                         local_counter, dev);
5399
5400         if (dev->remote_csrk)
5401                 bt_att_set_remote_key(dev->att, dev->remote_csrk->key,
5402                                                         remote_counter, dev);
5403
5404         database = btd_adapter_get_database(dev->adapter);
5405
5406         gatt_client_init(dev);
5407         gatt_server_init(dev, btd_gatt_database_get_db(database));
5408
5409         /*
5410          * Remove the device from the connect_list and give the passive
5411          * scanning another chance to be restarted in case there are
5412          * other devices in the connect_list.
5413          */
5414         adapter_connect_list_remove(dev->adapter, dev);
5415
5416         return true;
5417 }
5418
5419 static void att_connect_cb(GIOChannel *io, GError *gerr, gpointer user_data)
5420 {
5421         struct att_callbacks *attcb = user_data;
5422         struct btd_device *device = attcb->user_data;
5423         DBusMessage *reply;
5424         uint8_t io_cap;
5425         int err = 0;
5426
5427         g_io_channel_unref(device->att_io);
5428         device->att_io = NULL;
5429
5430 #ifdef __TIZEN_PATCH__
5431         if (btd_adapter_is_le_auto_connect(device->adapter)) {
5432                 DBG("LE auto connection is done");
5433                 btd_adapter_set_le_auto_connect(device->adapter, FALSE);
5434                 device->le_auto_connect = FALSE;
5435         }
5436 #endif
5437
5438         if (gerr) {
5439                 DBG("%s", gerr->message);
5440
5441                 if (attcb->err)
5442                         attcb->err(gerr, user_data);
5443
5444                 err = -ECONNABORTED;
5445                 goto done;
5446         }
5447
5448         if (!device_attach_att(device, io))
5449                 goto done;
5450
5451         if (attcb->success)
5452                 attcb->success(user_data);
5453
5454         if (!device->bonding)
5455                 goto done;
5456
5457         if (device->bonding->agent)
5458                 io_cap = agent_get_io_capability(device->bonding->agent);
5459         else
5460                 io_cap = IO_CAPABILITY_NOINPUTNOOUTPUT;
5461
5462         err = adapter_create_bonding(device->adapter, &device->bdaddr,
5463                                         device->bdaddr_type, io_cap);
5464 done:
5465         if (device->bonding && err < 0) {
5466                 reply = btd_error_failed(device->bonding->msg, strerror(-err));
5467                 g_dbus_send_message(dbus_conn, reply);
5468                 bonding_request_cancel(device->bonding);
5469                 bonding_request_free(device->bonding);
5470         }
5471
5472         if (device->connect) {
5473                 if (!device->le_state.svc_resolved)
5474                         device_browse_gatt(device, NULL);
5475
5476                 if (err < 0)
5477                         reply = btd_error_failed(device->connect,
5478                                                         strerror(-err));
5479                 else
5480                         reply = dbus_message_new_method_return(device->connect);
5481
5482                 g_dbus_send_message(dbus_conn, reply);
5483                 dbus_message_unref(device->connect);
5484                 device->connect = NULL;
5485         }
5486
5487         g_free(attcb);
5488 }
5489
5490 static void att_error_cb(const GError *gerr, gpointer user_data)
5491 {
5492         struct att_callbacks *attcb = user_data;
5493         struct btd_device *device = attcb->user_data;
5494
5495         if (g_error_matches(gerr, BT_IO_ERROR, ECONNABORTED))
5496                 return;
5497
5498         if (device_get_auto_connect(device)) {
5499                 DBG("Enabling automatic connections");
5500                 adapter_connect_list_add(device->adapter, device);
5501         }
5502 }
5503
5504 int device_connect_le(struct btd_device *dev)
5505 {
5506         struct btd_adapter *adapter = dev->adapter;
5507         struct att_callbacks *attcb;
5508         BtIOSecLevel sec_level;
5509         GIOChannel *io;
5510         GError *gerr = NULL;
5511         char addr[18];
5512 #ifdef __TIZEN_PATCH__
5513         bdaddr_t *dba;
5514         bdaddr_t le_auto_connect_ba = { {0, } };
5515 #endif
5516
5517         /* There is one connection attempt going on */
5518         if (dev->att_io)
5519                 return -EALREADY;
5520
5521         ba2str(&dev->bdaddr, addr);
5522
5523         DBG("Connection attempt to: %s", addr);
5524
5525         attcb = g_new0(struct att_callbacks, 1);
5526         attcb->err = att_error_cb;
5527         attcb->user_data = dev;
5528
5529         if (dev->le_state.paired)
5530                 sec_level = BT_IO_SEC_MEDIUM;
5531         else
5532                 sec_level = BT_IO_SEC_LOW;
5533
5534         /*
5535          * This connection will help us catch any PDUs that comes before
5536          * pairing finishes
5537          */
5538 #ifndef __TIZEN_PATCH__
5539         io = bt_io_connect(att_connect_cb, attcb, NULL, &gerr,
5540                         BT_IO_OPT_SOURCE_BDADDR,
5541                         btd_adapter_get_address(adapter),
5542                         BT_IO_OPT_SOURCE_TYPE, BDADDR_LE_PUBLIC,
5543                         BT_IO_OPT_DEST_BDADDR, &dev->bdaddr,
5544                         BT_IO_OPT_DEST_TYPE, dev->bdaddr_type,
5545                         BT_IO_OPT_CID, ATT_CID,
5546                         BT_IO_OPT_SEC_LEVEL, sec_level,
5547                         BT_IO_OPT_INVALID);
5548 #else
5549         if (dev->le_auto_connect)
5550                 dba = &le_auto_connect_ba;
5551         else
5552                 dba = &dev->bdaddr;
5553
5554         io = bt_io_connect(att_connect_cb, attcb, NULL, &gerr,
5555                         BT_IO_OPT_SOURCE_BDADDR,
5556                         btd_adapter_get_address(adapter),
5557                         BT_IO_OPT_SOURCE_TYPE, BDADDR_LE_PUBLIC,
5558                         BT_IO_OPT_DEST_BDADDR, dba,
5559                         BT_IO_OPT_DEST_TYPE, dev->bdaddr_type,
5560                         BT_IO_OPT_CID, ATT_CID,
5561                         BT_IO_OPT_SEC_LEVEL, sec_level,
5562                         BT_IO_OPT_INVALID);
5563
5564         if (dev->le_auto_connect) {
5565                 if (io)
5566                         btd_adapter_set_le_auto_connect(adapter, TRUE);
5567                 else {
5568                         btd_adapter_set_le_auto_connect(dev->adapter, FALSE);
5569                         dev->le_auto_connect = FALSE;
5570                 }
5571         }
5572 #endif
5573
5574         if (io == NULL) {
5575                 if (dev->bonding) {
5576                         DBusMessage *reply = btd_error_failed(
5577                                         dev->bonding->msg, gerr->message);
5578
5579                         g_dbus_send_message(dbus_conn, reply);
5580                         bonding_request_cancel(dev->bonding);
5581                         bonding_request_free(dev->bonding);
5582                 }
5583
5584                 error("ATT bt_io_connect(%s): %s", addr, gerr->message);
5585                 g_error_free(gerr);
5586                 g_free(attcb);
5587                 return -EIO;
5588         }
5589
5590         /* Keep this, so we can cancel the connection */
5591         dev->att_io = io;
5592
5593         return 0;
5594 }
5595
5596 static void att_browse_error_cb(const GError *gerr, gpointer user_data)
5597 {
5598         struct att_callbacks *attcb = user_data;
5599         struct btd_device *device = attcb->user_data;
5600         struct browse_req *req = device->browse;
5601
5602         device->browse = NULL;
5603         browse_request_complete(req, device->bdaddr_type, -ECONNABORTED);
5604 }
5605
5606 static void att_browse_cb(gpointer user_data)
5607 {
5608         DBG("ATT connection successful");
5609 }
5610
5611 static struct browse_req *browse_request_new(struct btd_device *device,
5612                                                         DBusMessage *msg)
5613 {
5614         struct browse_req *req;
5615
5616         if (device->browse)
5617                 return NULL;
5618
5619         req = g_new0(struct browse_req, 1);
5620         req->device = device;
5621
5622         device->browse = req;
5623
5624         if (!msg)
5625                 return req;
5626
5627         req->msg = dbus_message_ref(msg);
5628
5629         /*
5630          * Track the request owner to cancel it automatically if the owner
5631          * exits
5632          */
5633         req->listener_id = g_dbus_add_disconnect_watch(dbus_conn,
5634                                                 dbus_message_get_sender(msg),
5635                                                 browse_request_exit,
5636                                                 req, NULL);
5637
5638         return req;
5639 }
5640
5641 static int device_browse_gatt(struct btd_device *device, DBusMessage *msg)
5642 {
5643         struct btd_adapter *adapter = device->adapter;
5644         struct att_callbacks *attcb;
5645         struct browse_req *req;
5646
5647         req = browse_request_new(device, msg);
5648         if (!req)
5649                 return -EBUSY;
5650
5651         if (device->attrib) {
5652                 /*
5653                  * If discovery has not yet completed, then wait for gatt-client
5654                  * to become ready.
5655                  */
5656                 if (!device->le_state.svc_resolved)
5657                         return 0;
5658
5659                 /*
5660                  * Services have already been discovered, so signal this browse
5661                  * request as resolved.
5662                  */
5663                 device_svc_resolved(device, device->bdaddr_type, 0);
5664                 return 0;
5665         }
5666
5667         attcb = g_new0(struct att_callbacks, 1);
5668         attcb->err = att_browse_error_cb;
5669         attcb->success = att_browse_cb;
5670         attcb->user_data = device;
5671
5672         device->att_io = bt_io_connect(att_connect_cb,
5673                                 attcb, NULL, NULL,
5674                                 BT_IO_OPT_SOURCE_BDADDR,
5675                                 btd_adapter_get_address(adapter),
5676                                 BT_IO_OPT_SOURCE_TYPE, BDADDR_LE_PUBLIC,
5677                                 BT_IO_OPT_DEST_BDADDR, &device->bdaddr,
5678                                 BT_IO_OPT_DEST_TYPE, device->bdaddr_type,
5679                                 BT_IO_OPT_CID, ATT_CID,
5680                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_LOW,
5681                                 BT_IO_OPT_INVALID);
5682
5683         if (device->att_io == NULL) {
5684                 device->browse = NULL;
5685                 browse_request_free(req);
5686                 g_free(attcb);
5687                 return -EIO;
5688         }
5689
5690         return 0;
5691 }
5692
5693 static uint16_t get_sdp_flags(struct btd_device *device)
5694 {
5695         uint16_t vid, pid;
5696
5697         vid = btd_device_get_vendor(device);
5698         pid = btd_device_get_product(device);
5699
5700         /* Sony DualShock 4 is not respecting negotiated L2CAP MTU. This might
5701          * results in SDP response being dropped by kernel. Workaround this by
5702          * forcing SDP code to use bigger MTU while connecting.
5703          */
5704         if (vid == 0x054c && pid == 0x05c4)
5705                 return SDP_LARGE_MTU;
5706
5707         if (btd_adapter_ssp_enabled(device->adapter))
5708                 return 0;
5709
5710         /* if no EIR try matching Sony DualShock 4 with name and class */
5711         if (!strncmp(device->name, "Wireless Controller", MAX_NAME_LENGTH) &&
5712                         device->class == 0x2508)
5713                 return SDP_LARGE_MTU;
5714
5715         return 0;
5716 }
5717
5718 static int device_browse_sdp(struct btd_device *device, DBusMessage *msg)
5719 {
5720         struct btd_adapter *adapter = device->adapter;
5721         struct browse_req *req;
5722         uuid_t uuid;
5723         int err;
5724
5725         req = browse_request_new(device, msg);
5726         if (!req)
5727                 return -EBUSY;
5728
5729         sdp_uuid16_create(&uuid, uuid_list[req->search_uuid++]);
5730
5731         req->sdp_flags = get_sdp_flags(device);
5732
5733         err = bt_search_service(btd_adapter_get_address(adapter),
5734                                 &device->bdaddr, &uuid, browse_cb, req, NULL,
5735                                 req->sdp_flags);
5736         if (err < 0) {
5737                 browse_request_free(req);
5738                 return err;
5739         }
5740
5741         return err;
5742 }
5743
5744 #ifdef __TIZEN_PATCH__
5745 static int device_custom_browse_sdp(struct btd_device *device,
5746                                                                 DBusMessage *msg, uuid_t *search)
5747 {
5748         struct btd_adapter *adapter = device->adapter;
5749         struct browse_req *req;
5750         uuid_t uuid;
5751         int err;
5752
5753         if (device->browse)
5754                 return -EBUSY;
5755
5756         req = g_new0(struct browse_req, 1);
5757         req->device = device;
5758         if (search) {
5759                 memcpy(&uuid, search, sizeof(uuid_t));
5760         } else {
5761                 sdp_uuid16_create(&uuid, uuid_list[req->search_uuid++]);
5762         }
5763
5764         req->sdp_flags = get_sdp_flags(device);
5765
5766         err = bt_search_service(btd_adapter_get_address(adapter),
5767                                 &device->bdaddr, &uuid, browse_cb, req, NULL,
5768                                 req->sdp_flags);
5769         if (err < 0) {
5770                 browse_request_free(req);
5771                 return err;
5772         }
5773
5774         device->browse = req;
5775
5776         if (msg) {
5777                 const char *sender = dbus_message_get_sender(msg);
5778
5779                 req->msg = dbus_message_ref(msg);
5780                 /* Track the request owner to cancel it
5781                  * automatically if the owner exits */
5782                 req->listener_id = g_dbus_add_disconnect_watch(dbus_conn,
5783                                                 sender,
5784                                                 browse_request_exit,
5785                                                 req, NULL);
5786         }
5787         return err;
5788 }
5789
5790 void device_set_last_addr_type(struct btd_device *device, uint8_t type)
5791 {
5792         if (!device)
5793                 return;
5794
5795         DBG("Last addr type %d", type);
5796
5797         device->last_bdaddr_type = type;
5798 }
5799
5800 gboolean device_is_ipsp_connected(struct btd_device * device)
5801 {
5802         return device->ipsp_connected;
5803 }
5804
5805 void device_set_ipsp_connected(struct btd_device *device, gboolean connected)
5806 {
5807         if (device == NULL) {
5808                 error("device is NULL");
5809                 return;
5810         }
5811
5812         if (device->ipsp_connected == connected)
5813                 return;
5814
5815         device->ipsp_connected = connected;
5816
5817         DBG("ipsp_connected %d", connected);
5818
5819         g_dbus_emit_property_changed(dbus_conn, device->path,
5820                         DEVICE_INTERFACE, "IpspConnected");
5821 }
5822 void device_le_data_length_changed(struct btd_device *device, uint16_t max_tx_octets,
5823                 uint16_t max_tx_time, uint16_t max_rx_octets, uint16_t max_rx_time)
5824 {
5825         if (device == NULL) {
5826                 error("device is NULL");
5827                 return;
5828         }
5829
5830         device->max_tx_octets = max_tx_octets;
5831         device->max_tx_time = max_tx_time;
5832         device->max_rx_octets = max_rx_octets;
5833         device->max_rx_time = max_rx_time;
5834
5835         DBG("data length changed values :max_tx_octets: %d  max_tx_time: %d  max_rx_octets: %d  max_rx_time: %d",
5836                 max_tx_octets, max_tx_time, max_rx_octets, max_rx_time);
5837
5838         g_dbus_emit_signal(dbus_conn, device->path,
5839                 DEVICE_INTERFACE, "LEDataLengthChanged",
5840                 DBUS_TYPE_UINT16, &max_tx_octets,
5841                 DBUS_TYPE_UINT16, &max_tx_time,
5842                 DBUS_TYPE_UINT16, &max_rx_octets,
5843                 DBUS_TYPE_UINT16, &max_rx_time,
5844                 DBUS_TYPE_INVALID);
5845 }
5846 #endif
5847
5848 int device_discover_services(struct btd_device *device)
5849 {
5850         int err;
5851
5852         if (device->bredr)
5853                 err = device_browse_sdp(device, NULL);
5854         else
5855                 err = device_browse_gatt(device, NULL);
5856
5857         if (err == 0 && device->discov_timer) {
5858                 g_source_remove(device->discov_timer);
5859                 device->discov_timer = 0;
5860         }
5861
5862         return err;
5863 }
5864
5865 struct btd_adapter *device_get_adapter(struct btd_device *device)
5866 {
5867         if (!device)
5868                 return NULL;
5869
5870         return device->adapter;
5871 }
5872
5873 const bdaddr_t *device_get_address(struct btd_device *device)
5874 {
5875         return &device->bdaddr;
5876 }
5877
5878 const char *device_get_path(const struct btd_device *device)
5879 {
5880         if (!device)
5881                 return NULL;
5882
5883         return device->path;
5884 }
5885
5886 gboolean device_is_temporary(struct btd_device *device)
5887 {
5888         return device->temporary;
5889 }
5890
5891 void btd_device_set_temporary(struct btd_device *device, bool temporary)
5892 {
5893         if (!device)
5894                 return;
5895
5896         if (device->temporary == temporary)
5897                 return;
5898
5899         DBG("temporary %d", temporary);
5900
5901         device->temporary = temporary;
5902
5903         if (temporary) {
5904                 if (device->bredr)
5905                         adapter_whitelist_remove(device->adapter, device);
5906                 adapter_connect_list_remove(device->adapter, device);
5907                 return;
5908         }
5909
5910         if (device->bredr)
5911                 adapter_whitelist_add(device->adapter, device);
5912
5913         store_device_info(device);
5914 }
5915
5916 void btd_device_set_trusted(struct btd_device *device, gboolean trusted)
5917 {
5918         if (!device)
5919                 return;
5920
5921         if (device->trusted == trusted)
5922                 return;
5923
5924         DBG("trusted %d", trusted);
5925
5926         device->trusted = trusted;
5927
5928         store_device_info(device);
5929
5930         g_dbus_emit_property_changed(dbus_conn, device->path,
5931                                         DEVICE_INTERFACE, "Trusted");
5932 }
5933
5934 void device_set_bonded(struct btd_device *device, uint8_t bdaddr_type)
5935 {
5936         if (!device)
5937                 return;
5938
5939         DBG("");
5940
5941         if (bdaddr_type == BDADDR_BREDR)
5942                 device->bredr_state.bonded = true;
5943         else
5944                 device->le_state.bonded = true;
5945
5946         btd_device_set_temporary(device, false);
5947 }
5948
5949 void device_set_legacy(struct btd_device *device, bool legacy)
5950 {
5951         if (!device)
5952                 return;
5953
5954         DBG("legacy %d", legacy);
5955
5956         if (device->legacy == legacy)
5957                 return;
5958
5959         device->legacy = legacy;
5960
5961         g_dbus_emit_property_changed(dbus_conn, device->path,
5962                                         DEVICE_INTERFACE, "LegacyPairing");
5963 }
5964
5965 void device_set_rssi(struct btd_device *device, int8_t rssi)
5966 {
5967         if (!device)
5968                 return;
5969
5970 #ifdef __TIZEN_PATCH__
5971         if (rssi == 0 || device->rssi == 0) {
5972                 if (device->rssi == rssi)
5973                         return;
5974         }
5975
5976         device->rssi = rssi;
5977         DBG("rssi %d", rssi);
5978 #else
5979         if (rssi == 0 || device->rssi == 0) {
5980                 if (device->rssi == rssi)
5981                         return;
5982
5983                 DBG("rssi %d", rssi);
5984
5985                 device->rssi = rssi;
5986         } else {
5987                 int delta;
5988
5989                 if (device->rssi > rssi)
5990                         delta = device->rssi - rssi;
5991                 else
5992                         delta = rssi - device->rssi;
5993
5994                 /* only report changes of 8 dBm or more */
5995                 if (delta < 8)
5996                         return;
5997
5998                 DBG("rssi %d delta %d", rssi, delta);
5999
6000                 device->rssi = rssi;
6001         }
6002 #endif
6003
6004         g_dbus_emit_property_changed(dbus_conn, device->path,
6005                                                 DEVICE_INTERFACE, "RSSI");
6006 }
6007
6008 static gboolean start_discovery(gpointer user_data)
6009 {
6010         struct btd_device *device = user_data;
6011
6012         if (device->bredr)
6013                 device_browse_sdp(device, NULL);
6014         else
6015                 device_browse_gatt(device, NULL);
6016
6017         device->discov_timer = 0;
6018
6019         return FALSE;
6020 }
6021
6022 void device_set_paired(struct btd_device *dev, uint8_t bdaddr_type)
6023 {
6024         struct bearer_state *state = get_state(dev, bdaddr_type);
6025
6026         if (state->paired)
6027                 return;
6028
6029         state->paired = true;
6030
6031         /* If the other bearer state was alraedy true we don't need to
6032          * send any property signals.
6033          */
6034         if (dev->bredr_state.paired == dev->le_state.paired)
6035                 return;
6036
6037         if (!state->svc_resolved) {
6038                 dev->pending_paired = true;
6039                 return;
6040         }
6041
6042         g_dbus_emit_property_changed(dbus_conn, dev->path,
6043                                                 DEVICE_INTERFACE, "Paired");
6044 }
6045
6046 void device_set_unpaired(struct btd_device *dev, uint8_t bdaddr_type)
6047 {
6048         struct bearer_state *state = get_state(dev, bdaddr_type);
6049
6050         if (!state->paired)
6051                 return;
6052
6053         state->paired = false;
6054
6055         /*
6056          * If the other bearer state is still true we don't need to
6057          * send any property signals or remove device.
6058          */
6059         if (dev->bredr_state.paired != dev->le_state.paired) {
6060                 /* TODO disconnect only unpaired bearer */
6061                 if (state->connected)
6062                         device_request_disconnect(dev, NULL);
6063
6064                 return;
6065         }
6066
6067         g_dbus_emit_property_changed(dbus_conn, dev->path,
6068                                                 DEVICE_INTERFACE, "Paired");
6069
6070         btd_device_set_temporary(dev, true);
6071
6072         if (btd_device_is_connected(dev))
6073                 device_request_disconnect(dev, NULL);
6074         else
6075                 btd_adapter_remove_device(dev->adapter, dev);
6076 }
6077
6078 static void device_auth_req_free(struct btd_device *device)
6079 {
6080         struct authentication_req *authr = device->authr;
6081
6082         if (!authr)
6083                 return;
6084
6085         if (authr->agent)
6086                 agent_unref(authr->agent);
6087
6088         g_free(authr->pincode);
6089         g_free(authr);
6090
6091         device->authr = NULL;
6092 }
6093
6094 bool device_is_retrying(struct btd_device *device)
6095 {
6096         struct bonding_req *bonding = device->bonding;
6097
6098         return bonding && bonding->retry_timer > 0;
6099 }
6100
6101 void device_bonding_complete(struct btd_device *device, uint8_t bdaddr_type,
6102                                                                 uint8_t status)
6103 {
6104         struct bonding_req *bonding = device->bonding;
6105         struct authentication_req *auth = device->authr;
6106         struct bearer_state *state = get_state(device, bdaddr_type);
6107
6108         DBG("bonding %p status 0x%02x", bonding, status);
6109
6110         if (auth && auth->agent)
6111                 agent_cancel(auth->agent);
6112
6113         if (status) {
6114                 device_cancel_authentication(device, TRUE);
6115                 device_bonding_failed(device, status);
6116 #ifdef __TIZEN_PATCH__
6117                 device->legacy_pairing = false;
6118 #endif
6119                 return;
6120         }
6121 #ifdef __TIZEN_PATCH__
6122                 device->legacy_pairing = false;
6123 #endif
6124         device_auth_req_free(device);
6125
6126         /* If we're already paired nothing more is needed */
6127         if (state->paired) {
6128 #ifdef __TIZEN_PATCH__
6129 #ifdef TIZEN_WEARABLE
6130                 DBG("Already paired. Send Paired Signal for Wearble syspopup termn");
6131                 DBG("state->svc_resolved [%d]", state->svc_resolved);
6132                 if (state->svc_resolved)
6133                         g_dbus_emit_property_changed(dbus_conn, device->path,
6134                                         DEVICE_INTERFACE, "Paired");
6135 #endif  /* TIZEN_WEARABLE */
6136 #endif  /* __TIZEN_PATCH__ */
6137                 return;
6138         }
6139
6140         device_set_paired(device, bdaddr_type);
6141
6142         /* If services are already resolved just reply to the pairing
6143          * request
6144          */
6145         if (state->svc_resolved && bonding) {
6146                 g_dbus_send_reply(dbus_conn, bonding->msg, DBUS_TYPE_INVALID);
6147                 bonding_request_free(bonding);
6148                 return;
6149         }
6150
6151         /* If we were initiators start service discovery immediately.
6152          * However if the other end was the initator wait a few seconds
6153          * before SDP. This is due to potential IOP issues if the other
6154          * end starts doing SDP at the same time as us */
6155         if (bonding) {
6156                 DBG("Proceeding with service discovery");
6157                 /* If we are initiators remove any discovery timer and just
6158                  * start discovering services directly */
6159                 if (device->discov_timer) {
6160                         g_source_remove(device->discov_timer);
6161                         device->discov_timer = 0;
6162                 }
6163
6164                 if (bdaddr_type == BDADDR_BREDR)
6165                         device_browse_sdp(device, bonding->msg);
6166                 else
6167                         device_browse_gatt(device, bonding->msg);
6168
6169                 bonding_request_free(bonding);
6170         } else if (!state->svc_resolved) {
6171                 if (!device->browse && !device->discov_timer &&
6172                                 main_opts.reverse_sdp) {
6173                         /* If we are not initiators and there is no currently
6174                          * active discovery or discovery timer, set discovery
6175                          * timer */
6176                         DBG("setting timer for reverse service discovery");
6177                         device->discov_timer = g_timeout_add_seconds(
6178                                                         DISCOVERY_TIMER,
6179                                                         start_discovery,
6180                                                         device);
6181                 }
6182         }
6183 }
6184
6185 static gboolean svc_idle_cb(gpointer user_data)
6186 {
6187         struct svc_callback *cb = user_data;
6188         struct btd_device *dev = cb->dev;
6189
6190         dev->svc_callbacks = g_slist_remove(dev->svc_callbacks, cb);
6191
6192         cb->func(cb->dev, 0, cb->user_data);
6193
6194         g_free(cb);
6195
6196         return FALSE;
6197 }
6198
6199 unsigned int device_wait_for_svc_complete(struct btd_device *dev,
6200                                                         device_svc_cb_t func,
6201                                                         void *user_data)
6202 {
6203         /* This API is only used for BR/EDR (for now) */
6204         struct bearer_state *state = &dev->bredr_state;
6205         static unsigned int id = 0;
6206         struct svc_callback *cb;
6207
6208         cb = g_new0(struct svc_callback, 1);
6209         cb->func = func;
6210         cb->user_data = user_data;
6211         cb->dev = dev;
6212         cb->id = ++id;
6213
6214         dev->svc_callbacks = g_slist_prepend(dev->svc_callbacks, cb);
6215
6216         if (state->svc_resolved || !main_opts.reverse_sdp)
6217                 cb->idle_id = g_idle_add(svc_idle_cb, cb);
6218         else if (dev->discov_timer > 0) {
6219                 g_source_remove(dev->discov_timer);
6220                 dev->discov_timer = g_idle_add(start_discovery, dev);
6221         }
6222
6223         return cb->id;
6224 }
6225
6226 bool device_remove_svc_complete_callback(struct btd_device *dev,
6227                                                         unsigned int id)
6228 {
6229         GSList *l;
6230
6231         for (l = dev->svc_callbacks; l != NULL; l = g_slist_next(l)) {
6232                 struct svc_callback *cb = l->data;
6233
6234                 if (cb->id != id)
6235                         continue;
6236
6237                 if (cb->idle_id > 0)
6238                         g_source_remove(cb->idle_id);
6239
6240                 dev->svc_callbacks = g_slist_remove(dev->svc_callbacks, cb);
6241                 g_free(cb);
6242
6243                 return true;
6244         }
6245
6246         return false;
6247 }
6248
6249 gboolean device_is_bonding(struct btd_device *device, const char *sender)
6250 {
6251         struct bonding_req *bonding = device->bonding;
6252
6253         if (!device->bonding)
6254                 return FALSE;
6255
6256         if (!sender)
6257                 return TRUE;
6258
6259         return g_str_equal(sender, dbus_message_get_sender(bonding->msg));
6260 }
6261
6262 static gboolean device_bonding_retry(gpointer data)
6263 {
6264         struct btd_device *device = data;
6265         struct btd_adapter *adapter = device_get_adapter(device);
6266         struct bonding_req *bonding = device->bonding;
6267         uint8_t io_cap;
6268         int err;
6269
6270         if (!bonding)
6271                 return FALSE;
6272
6273         DBG("retrying bonding");
6274         bonding->retry_timer = 0;
6275
6276         /* Restart the bonding timer to the begining of the pairing. If not
6277          * pincode request/reply occurs during this retry,
6278          * device_bonding_last_duration() will return a consistent value from
6279          * this point. */
6280         device_bonding_restart_timer(device);
6281
6282         if (bonding->agent)
6283                 io_cap = agent_get_io_capability(bonding->agent);
6284         else
6285                 io_cap = IO_CAPABILITY_NOINPUTNOOUTPUT;
6286
6287         err = adapter_bonding_attempt(adapter, &device->bdaddr,
6288                                 device->bdaddr_type, io_cap);
6289         if (err < 0)
6290                 device_bonding_complete(device, bonding->bdaddr_type,
6291                                                         bonding->status);
6292
6293         return FALSE;
6294 }
6295
6296 int device_bonding_attempt_retry(struct btd_device *device)
6297 {
6298         struct bonding_req *bonding = device->bonding;
6299
6300         /* Ignore other failure events while retrying */
6301         if (device_is_retrying(device))
6302                 return 0;
6303
6304         if (!bonding)
6305                 return -EINVAL;
6306
6307         /* Mark the end of a bonding attempt to compute the delta for the
6308          * retry. */
6309         bonding_request_stop_timer(bonding);
6310
6311         if (btd_adapter_pin_cb_iter_end(bonding->cb_iter))
6312                 return -EINVAL;
6313
6314         DBG("scheduling retry");
6315         bonding->retry_timer = g_timeout_add(3000,
6316                                                 device_bonding_retry, device);
6317         return 0;
6318 }
6319
6320 void device_bonding_failed(struct btd_device *device, uint8_t status)
6321 {
6322         struct bonding_req *bonding = device->bonding;
6323         DBusMessage *reply;
6324
6325         DBG("status %u", status);
6326
6327         if (!bonding) {
6328 #ifdef __TIZEN_PATCH__
6329                 if (device->legacy_pairing) {
6330                         DBG("Emit LegacyPaired");
6331                         g_dbus_emit_property_changed(dbus_conn, device->path,
6332                                         DEVICE_INTERFACE, "LegacyPaired");
6333                 }
6334 #endif
6335                 return;
6336         }
6337 #ifdef __TIZEN_PATCH__
6338         btd_device_set_temporary(device, TRUE);
6339 #endif
6340
6341         if (device->authr)
6342                 device_cancel_authentication(device, FALSE);
6343
6344         reply = new_authentication_return(bonding->msg, status);
6345         g_dbus_send_message(dbus_conn, reply);
6346
6347         bonding_request_free(bonding);
6348 }
6349
6350 struct btd_adapter_pin_cb_iter *device_bonding_iter(struct btd_device *device)
6351 {
6352         if (device->bonding == NULL)
6353                 return NULL;
6354
6355         return device->bonding->cb_iter;
6356 }
6357
6358 static void pincode_cb(struct agent *agent, DBusError *err, const char *pin,
6359                                                                 void *data)
6360 {
6361         struct authentication_req *auth = data;
6362         struct btd_device *device = auth->device;
6363
6364         /* No need to reply anything if the authentication already failed */
6365         if (auth->agent == NULL)
6366                 return;
6367
6368         btd_adapter_pincode_reply(device->adapter, &device->bdaddr,
6369                                                 pin, pin ? strlen(pin) : 0);
6370
6371         agent_unref(device->authr->agent);
6372         device->authr->agent = NULL;
6373 }
6374
6375 static void confirm_cb(struct agent *agent, DBusError *err, void *data)
6376 {
6377         struct authentication_req *auth = data;
6378         struct btd_device *device = auth->device;
6379
6380         /* No need to reply anything if the authentication already failed */
6381         if (auth->agent == NULL)
6382                 return;
6383
6384 #ifdef __TIZEN_PATCH__
6385         if (device->bredr == TRUE)
6386                 btd_adapter_confirm_reply(device->adapter, &device->bdaddr,
6387                                                         BDADDR_BREDR,
6388                                                         err ? FALSE : TRUE);
6389         else
6390 #endif
6391         btd_adapter_confirm_reply(device->adapter, &device->bdaddr,
6392                                                 device->bdaddr_type,
6393                                                 err ? FALSE : TRUE);
6394
6395         agent_unref(device->authr->agent);
6396         device->authr->agent = NULL;
6397 }
6398
6399 static void passkey_cb(struct agent *agent, DBusError *err,
6400                                                 uint32_t passkey, void *data)
6401 {
6402         struct authentication_req *auth = data;
6403         struct btd_device *device = auth->device;
6404
6405         /* No need to reply anything if the authentication already failed */
6406         if (auth->agent == NULL)
6407                 return;
6408
6409         if (err)
6410                 passkey = INVALID_PASSKEY;
6411
6412         btd_adapter_passkey_reply(device->adapter, &device->bdaddr,
6413                                                 device->bdaddr_type, passkey);
6414
6415         agent_unref(device->authr->agent);
6416         device->authr->agent = NULL;
6417 }
6418
6419 static void display_pincode_cb(struct agent *agent, DBusError *err, void *data)
6420 {
6421         struct authentication_req *auth = data;
6422         struct btd_device *device = auth->device;
6423
6424         pincode_cb(agent, err, auth->pincode, auth);
6425
6426         g_free(device->authr->pincode);
6427         device->authr->pincode = NULL;
6428 }
6429
6430 static struct authentication_req *new_auth(struct btd_device *device,
6431                                         auth_type_t type, gboolean secure)
6432 {
6433         struct authentication_req *auth;
6434         struct agent *agent;
6435         char addr[18];
6436
6437         ba2str(&device->bdaddr, addr);
6438         DBG("Requesting agent authentication for %s", addr);
6439
6440         if (device->authr) {
6441                 error("Authentication already requested for %s", addr);
6442                 return NULL;
6443         }
6444
6445         if (device->bonding && device->bonding->agent)
6446                 agent = agent_ref(device->bonding->agent);
6447         else
6448                 agent = agent_get(NULL);
6449
6450         if (!agent) {
6451                 error("No agent available for request type %d", type);
6452                 return NULL;
6453         }
6454
6455         auth = g_new0(struct authentication_req, 1);
6456         auth->agent = agent;
6457         auth->device = device;
6458         auth->type = type;
6459         auth->secure = secure;
6460         device->authr = auth;
6461
6462         return auth;
6463 }
6464
6465 int device_request_pincode(struct btd_device *device, gboolean secure)
6466 {
6467         struct authentication_req *auth;
6468         int err;
6469
6470         auth = new_auth(device, AUTH_TYPE_PINCODE, secure);
6471         if (!auth)
6472                 return -EPERM;
6473
6474         err = agent_request_pincode(auth->agent, device, pincode_cb, secure,
6475                                                                 auth, NULL);
6476         if (err < 0) {
6477                 error("Failed requesting authentication");
6478                 device_auth_req_free(device);
6479         }
6480
6481         return err;
6482 }
6483
6484 int device_request_passkey(struct btd_device *device)
6485 {
6486         struct authentication_req *auth;
6487         int err;
6488
6489         auth = new_auth(device, AUTH_TYPE_PASSKEY, FALSE);
6490         if (!auth)
6491                 return -EPERM;
6492
6493         err = agent_request_passkey(auth->agent, device, passkey_cb, auth,
6494                                                                         NULL);
6495         if (err < 0) {
6496                 error("Failed requesting authentication");
6497                 device_auth_req_free(device);
6498         }
6499
6500         return err;
6501 }
6502
6503 int device_confirm_passkey(struct btd_device *device, uint32_t passkey,
6504                                                         uint8_t confirm_hint)
6505
6506 {
6507         struct authentication_req *auth;
6508         int err;
6509
6510         auth = new_auth(device, AUTH_TYPE_CONFIRM, FALSE);
6511         if (!auth)
6512                 return -EPERM;
6513
6514         auth->passkey = passkey;
6515
6516 #ifndef TIZEN_WEARABLE
6517         if (confirm_hint)
6518                 err = agent_request_authorization(auth->agent, device,
6519                                                 confirm_cb, auth, NULL);
6520         else
6521 #endif
6522                 err = agent_request_confirmation(auth->agent, device, passkey,
6523                                                 confirm_cb, auth, NULL);
6524
6525         if (err < 0) {
6526                 error("Failed requesting authentication");
6527                 device_auth_req_free(device);
6528         }
6529
6530         return err;
6531 }
6532
6533 int device_notify_passkey(struct btd_device *device, uint32_t passkey,
6534                                                         uint8_t entered)
6535 {
6536         struct authentication_req *auth;
6537         int err;
6538
6539         if (device->authr) {
6540                 auth = device->authr;
6541                 if (auth->type != AUTH_TYPE_NOTIFY_PASSKEY)
6542                         return -EPERM;
6543         } else {
6544                 auth = new_auth(device, AUTH_TYPE_NOTIFY_PASSKEY, FALSE);
6545                 if (!auth)
6546                         return -EPERM;
6547         }
6548
6549         err = agent_display_passkey(auth->agent, device, passkey, entered);
6550         if (err < 0) {
6551                 error("Failed requesting authentication");
6552                 device_auth_req_free(device);
6553         }
6554
6555         return err;
6556 }
6557
6558 int device_notify_pincode(struct btd_device *device, gboolean secure,
6559                                                         const char *pincode)
6560 {
6561         struct authentication_req *auth;
6562         int err;
6563
6564         auth = new_auth(device, AUTH_TYPE_NOTIFY_PINCODE, secure);
6565         if (!auth)
6566                 return -EPERM;
6567
6568         auth->pincode = g_strdup(pincode);
6569
6570         err = agent_display_pincode(auth->agent, device, pincode,
6571                                         display_pincode_cb, auth, NULL);
6572         if (err < 0) {
6573                 error("Failed requesting authentication");
6574                 device_auth_req_free(device);
6575         }
6576
6577         return err;
6578 }
6579
6580 static void cancel_authentication(struct authentication_req *auth)
6581 {
6582         struct agent *agent;
6583         DBusError err;
6584
6585         if (!auth || !auth->agent)
6586                 return;
6587
6588         agent = auth->agent;
6589         auth->agent = NULL;
6590
6591         dbus_error_init(&err);
6592         dbus_set_error_const(&err, ERROR_INTERFACE ".Canceled", NULL);
6593
6594         switch (auth->type) {
6595         case AUTH_TYPE_PINCODE:
6596                 pincode_cb(agent, &err, NULL, auth);
6597                 break;
6598         case AUTH_TYPE_CONFIRM:
6599                 confirm_cb(agent, &err, auth);
6600                 break;
6601         case AUTH_TYPE_PASSKEY:
6602                 passkey_cb(agent, &err, 0, auth);
6603                 break;
6604         case AUTH_TYPE_NOTIFY_PASSKEY:
6605                 /* User Notify doesn't require any reply */
6606                 break;
6607         case AUTH_TYPE_NOTIFY_PINCODE:
6608                 pincode_cb(agent, &err, NULL, auth);
6609                 break;
6610         }
6611
6612         dbus_error_free(&err);
6613 }
6614
6615 void device_cancel_authentication(struct btd_device *device, gboolean aborted)
6616 {
6617         struct authentication_req *auth = device->authr;
6618         char addr[18];
6619
6620         if (!auth)
6621                 return;
6622
6623         ba2str(&device->bdaddr, addr);
6624         DBG("Canceling authentication request for %s", addr);
6625
6626         if (auth->agent)
6627                 agent_cancel(auth->agent);
6628
6629         if (!aborted)
6630                 cancel_authentication(auth);
6631
6632         device_auth_req_free(device);
6633 }
6634
6635 gboolean device_is_authenticating(struct btd_device *device)
6636 {
6637         return (device->authr != NULL);
6638 }
6639
6640 struct gatt_primary *btd_device_get_primary(struct btd_device *device,
6641                                                         const char *uuid)
6642 {
6643         GSList *match;
6644
6645         match = g_slist_find_custom(device->primaries, uuid, bt_uuid_strcmp);
6646         if (match)
6647                 return match->data;
6648
6649         return NULL;
6650 }
6651
6652 GSList *btd_device_get_primaries(struct btd_device *device)
6653 {
6654         return device->primaries;
6655 }
6656
6657 struct gatt_db *btd_device_get_gatt_db(struct btd_device *device)
6658 {
6659         if (!device)
6660                 return NULL;
6661
6662         return device->db;
6663 }
6664
6665 struct bt_gatt_client *btd_device_get_gatt_client(struct btd_device *device)
6666 {
6667         if (!device)
6668                 return NULL;
6669
6670         return device->client;
6671 }
6672
6673 struct bt_gatt_server *btd_device_get_gatt_server(struct btd_device *device)
6674 {
6675         if (!device)
6676                 return NULL;
6677
6678         return device->server;
6679 }
6680
6681 void btd_device_gatt_set_service_changed(struct btd_device *device,
6682                                                 uint16_t start, uint16_t end)
6683 {
6684         /*
6685          * TODO: Remove this function and handle service changed via
6686          * gatt-client.
6687          */
6688 }
6689
6690 void btd_device_add_uuid(struct btd_device *device, const char *uuid)
6691 {
6692         GSList *uuid_list;
6693         char *new_uuid;
6694
6695         if (g_slist_find_custom(device->uuids, uuid, bt_uuid_strcmp))
6696                 return;
6697
6698         new_uuid = g_strdup(uuid);
6699         uuid_list = g_slist_append(NULL, new_uuid);
6700
6701         device_probe_profiles(device, uuid_list);
6702
6703         g_free(new_uuid);
6704         g_slist_free(uuid_list);
6705
6706         store_device_info(device);
6707
6708         g_dbus_emit_property_changed(dbus_conn, device->path,
6709                                                 DEVICE_INTERFACE, "UUIDs");
6710 }
6711
6712 static sdp_list_t *read_device_records(struct btd_device *device)
6713 {
6714         char local[18], peer[18];
6715         char filename[PATH_MAX];
6716         GKeyFile *key_file;
6717         char **keys, **handle;
6718         char *str;
6719         sdp_list_t *recs = NULL;
6720         sdp_record_t *rec;
6721
6722         ba2str(btd_adapter_get_address(device->adapter), local);
6723         ba2str(&device->bdaddr, peer);
6724
6725         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s", local, peer);
6726
6727         key_file = g_key_file_new();
6728         g_key_file_load_from_file(key_file, filename, 0, NULL);
6729         keys = g_key_file_get_keys(key_file, "ServiceRecords", NULL, NULL);
6730
6731         for (handle = keys; handle && *handle; handle++) {
6732                 str = g_key_file_get_string(key_file, "ServiceRecords",
6733                                                 *handle, NULL);
6734                 if (!str)
6735                         continue;
6736
6737                 rec = record_from_string(str);
6738                 recs = sdp_list_append(recs, rec);
6739                 g_free(str);
6740         }
6741
6742         g_strfreev(keys);
6743         g_key_file_free(key_file);
6744
6745         return recs;
6746 }
6747
6748 const sdp_record_t *btd_device_get_record(struct btd_device *device,
6749                                                         const char *uuid)
6750 {
6751         if (device->tmp_records) {
6752                 const sdp_record_t *record;
6753
6754                 record = find_record_in_list(device->tmp_records, uuid);
6755                 if (record != NULL)
6756                         return record;
6757
6758                 sdp_list_free(device->tmp_records,
6759                                         (sdp_free_func_t) sdp_record_free);
6760                 device->tmp_records = NULL;
6761         }
6762
6763         device->tmp_records = read_device_records(device);
6764         if (!device->tmp_records)
6765                 return NULL;
6766
6767         return find_record_in_list(device->tmp_records, uuid);
6768 }
6769
6770 struct btd_device *btd_device_ref(struct btd_device *device)
6771 {
6772         __sync_fetch_and_add(&device->ref_count, 1);
6773
6774         return device;
6775 }
6776
6777 void btd_device_unref(struct btd_device *device)
6778 {
6779         if (__sync_sub_and_fetch(&device->ref_count, 1))
6780                 return;
6781
6782         if (!device->path) {
6783                 error("freeing device without an object path");
6784                 return;
6785         }
6786
6787         DBG("Freeing device %s", device->path);
6788
6789         g_dbus_unregister_interface(dbus_conn, device->path, DEVICE_INTERFACE);
6790 }
6791
6792 int device_get_appearance(struct btd_device *device, uint16_t *value)
6793 {
6794         if (device->appearance == 0)
6795                 return -1;
6796
6797         if (value)
6798                 *value = device->appearance;
6799
6800         return 0;
6801 }
6802
6803 void device_set_appearance(struct btd_device *device, uint16_t value)
6804 {
6805         const char *icon = gap_appearance_to_icon(value);
6806
6807         if (device->appearance == value)
6808                 return;
6809
6810         g_dbus_emit_property_changed(dbus_conn, device->path,
6811                                         DEVICE_INTERFACE, "Appearance");
6812
6813         if (icon)
6814                 g_dbus_emit_property_changed(dbus_conn, device->path,
6815                                                 DEVICE_INTERFACE, "Icon");
6816
6817         device->appearance = value;
6818         store_device_info(device);
6819 }
6820
6821 #ifdef __TIZEN_PATCH__
6822 /* Store the RPA Resolution Characteristic Value of remote device.
6823  * This value would be checked before start directed advertising using RPA.
6824  */
6825 void device_set_rpa_res_char_value(struct btd_device *device, uint8_t value)
6826 {
6827         if (device->rpa_res_support == value)
6828                 return;
6829
6830         device->rpa_res_support = value;
6831         store_device_info(device);
6832 }
6833
6834 void device_set_manufacturer_info(struct btd_device *device, struct eir_data *eir)
6835 {
6836         if (!device)
6837                 return;
6838
6839         if (eir->manufacturer_data_len == 0)
6840                 return;
6841
6842         device->manufacturer_data = g_memdup(eir->manufacturer_data,
6843                                                                 eir->manufacturer_data_len);
6844         device->manufacturer_data_len = eir->manufacturer_data_len;
6845
6846         store_device_info(device);
6847
6848         g_dbus_emit_property_changed(dbus_conn, device->path,
6849                                         DEVICE_INTERFACE, "ManufacturerDataLen");
6850
6851         g_dbus_emit_property_changed(dbus_conn, device->path,
6852                                         DEVICE_INTERFACE, "ManufacturerData");
6853 }
6854
6855
6856 void device_set_adv_report_info(struct btd_device *device, void *data, uint8_t data_len,
6857                                 uint8_t adv_type)
6858 {
6859         if (!device)
6860                 return;
6861
6862         char peer_addr[18];
6863         const char *paddr = peer_addr;
6864         dbus_int32_t rssi = device->rssi;
6865         int adv_len = data_len;
6866
6867         ba2str(&device->bdaddr, peer_addr);
6868
6869         g_dbus_emit_signal(dbus_conn, device->path,
6870                 DEVICE_INTERFACE, "AdvReport",
6871                 DBUS_TYPE_STRING, &paddr,
6872                 DBUS_TYPE_BYTE, &device->bdaddr_type,
6873                 DBUS_TYPE_BYTE, &adv_type,
6874                 DBUS_TYPE_INT32, &rssi,
6875                 DBUS_TYPE_INT32, &adv_len,
6876                 DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &data, data_len,
6877                 DBUS_TYPE_INVALID);
6878 }
6879
6880 void device_set_payload_timeout(struct btd_device *device,
6881                         uint16_t payload_timeout)
6882 {
6883         if (!device)
6884                 return;
6885         if (device->auth_payload_timeout == payload_timeout)
6886                 return;
6887
6888         DBG("Payload timeout %d", payload_timeout);
6889
6890         device->auth_payload_timeout = payload_timeout;
6891         g_dbus_emit_property_changed(dbus_conn, device->path,
6892                                 DEVICE_INTERFACE, "PayloadTimeout");
6893 }
6894
6895 void device_set_disconnect_reason(struct btd_device *device, uint8_t reason)
6896 {
6897         device->disc_reason = reason;
6898 }
6899
6900 void btd_device_disconnect(struct btd_device *device)
6901 {
6902         char dst[18];
6903         struct btd_service *service;
6904         btd_service_state_t state;
6905
6906         ba2str(&device->bdaddr, dst);
6907
6908         DBG("");
6909         if (device->bredr_state.connected == false)
6910                 return;
6911
6912         service = btd_device_get_service(device, HFP_HS_UUID);
6913         if (!service)
6914                 return;
6915
6916         state = btd_service_get_state(service);
6917         DBG("Connected State : %d", state);
6918
6919         if (state == BTD_SERVICE_STATE_DISCONNECTED) {
6920                 btd_adapter_disconnect_device(device->adapter, &device->bdaddr,
6921                                                                 BDADDR_BREDR);
6922         }
6923
6924         return;
6925 }
6926 #endif
6927
6928 static gboolean notify_attios(gpointer user_data)
6929 {
6930         struct btd_device *device = user_data;
6931
6932         DBG("");
6933
6934         if (device->attrib == NULL)
6935                 return FALSE;
6936
6937         g_slist_foreach(device->attios_offline, attio_connected, device->attrib);
6938         device->attios = g_slist_concat(device->attios, device->attios_offline);
6939         device->attios_offline = NULL;
6940
6941         return FALSE;
6942 }
6943
6944 guint btd_device_add_attio_callback(struct btd_device *device,
6945                                                 attio_connect_cb cfunc,
6946                                                 attio_disconnect_cb dcfunc,
6947                                                 gpointer user_data)
6948 {
6949         struct attio_data *attio;
6950         static guint attio_id = 0;
6951
6952         DBG("%p registered ATT connection callback", device);
6953
6954         attio = g_new0(struct attio_data, 1);
6955         attio->id = ++attio_id;
6956         attio->cfunc = cfunc;
6957         attio->dcfunc = dcfunc;
6958         attio->user_data = user_data;
6959
6960 #ifdef __TIZEN_PATCH__
6961         /*
6962          * User space auto connection is not used.
6963          * Instead of this, BT chip can trigger auto connection
6964          * by adding remote address to white list and
6965          * setting 0x01 to "Initiator_Filter_Policy"
6966          * when LE Create Connection is happened.
6967          */
6968         device_set_auto_connect(device, FALSE);
6969 #else
6970         device_set_auto_connect(device, TRUE);
6971 #endif
6972
6973         /* Check if there is no GAttrib associated to the device created by a
6974          * incoming connection */
6975         if (!device->attrib)
6976                 device->attrib = attrib_from_device(device);
6977
6978         if (device->attrib && cfunc) {
6979                 device->attios_offline = g_slist_append(device->attios_offline,
6980                                                                         attio);
6981                 g_idle_add(notify_attios, device);
6982                 return attio->id;
6983         }
6984
6985         device->attios = g_slist_append(device->attios, attio);
6986
6987         return attio->id;
6988 }
6989
6990 static int attio_id_cmp(gconstpointer a, gconstpointer b)
6991 {
6992         const struct attio_data *attio = a;
6993         guint id = GPOINTER_TO_UINT(b);
6994
6995         return attio->id - id;
6996 }
6997
6998 gboolean btd_device_remove_attio_callback(struct btd_device *device, guint id)
6999 {
7000         struct attio_data *attio;
7001         GSList *l;
7002
7003         l = g_slist_find_custom(device->attios, GUINT_TO_POINTER(id),
7004                                                                 attio_id_cmp);
7005         if (l) {
7006                 attio = l->data;
7007                 device->attios = g_slist_remove(device->attios, attio);
7008         } else {
7009                 l = g_slist_find_custom(device->attios_offline,
7010                                         GUINT_TO_POINTER(id), attio_id_cmp);
7011                 if (!l)
7012                         return FALSE;
7013
7014                 attio = l->data;
7015                 device->attios_offline = g_slist_remove(device->attios_offline,
7016                                                                         attio);
7017         }
7018
7019         g_free(attio);
7020
7021 #ifdef __TIZEN_PATCH__
7022         if (device->auto_id) {
7023                 g_source_remove(device->auto_id);
7024                 device->auto_id = 0;
7025         }
7026
7027         if (device->le_auto_connect) {
7028                 device->le_auto_connect = FALSE;
7029                 btd_adapter_disable_le_auto_connect(device->adapter);
7030                 DBG("remove attio callback");
7031         }
7032 #endif
7033
7034         return TRUE;
7035 }
7036
7037 void btd_device_set_pnpid(struct btd_device *device, uint16_t source,
7038                         uint16_t vendor, uint16_t product, uint16_t version)
7039 {
7040         if (device->vendor_src == source && device->version == version &&
7041                         device->vendor == vendor && device->product == product)
7042                 return;
7043
7044         device->vendor_src = source;
7045         device->vendor = vendor;
7046         device->product = product;
7047         device->version = version;
7048
7049         free(device->modalias);
7050         device->modalias = bt_modalias(source, vendor, product, version);
7051
7052         g_dbus_emit_property_changed(dbus_conn, device->path,
7053                                                 DEVICE_INTERFACE, "Modalias");
7054
7055         store_device_info(device);
7056 }
7057
7058 static void service_state_changed(struct btd_service *service,
7059                                                 btd_service_state_t old_state,
7060                                                 btd_service_state_t new_state,
7061                                                 void *user_data)
7062 {
7063         struct btd_profile *profile = btd_service_get_profile(service);
7064         struct btd_device *device = btd_service_get_device(service);
7065         int err = btd_service_get_error(service);
7066
7067 #ifdef __TIZEN_PATCH__
7068         if (!err) {
7069                 g_dbus_emit_signal(dbus_conn, device->path,
7070                                 DEVICE_INTERFACE, "ProfileStateChanged",
7071                                 DBUS_TYPE_STRING, &profile->remote_uuid,
7072                                 DBUS_TYPE_INT32, &new_state,
7073                                 DBUS_TYPE_INVALID);
7074         }
7075
7076         if (new_state == BTD_SERVICE_STATE_CONNECTING ||
7077                         new_state == BTD_SERVICE_STATE_DISCONNECTING ||
7078                         new_state == BTD_SERVICE_STATE_UNAVAILABLE)
7079 #else
7080         if (new_state == BTD_SERVICE_STATE_CONNECTING ||
7081                                 new_state == BTD_SERVICE_STATE_DISCONNECTING)
7082 #endif
7083                 return;
7084
7085         if (old_state == BTD_SERVICE_STATE_CONNECTING)
7086                 device_profile_connected(device, profile, err);
7087         else if (old_state == BTD_SERVICE_STATE_DISCONNECTING)
7088                 device_profile_disconnected(device, profile, err);
7089 }
7090
7091 struct btd_service *btd_device_get_service(struct btd_device *dev,
7092                                                 const char *remote_uuid)
7093 {
7094         GSList *l;
7095
7096         for (l = dev->services; l != NULL; l = g_slist_next(l)) {
7097                 struct btd_service *service = l->data;
7098                 struct btd_profile *p = btd_service_get_profile(service);
7099
7100                 if (g_str_equal(p->remote_uuid, remote_uuid))
7101                         return service;
7102         }
7103
7104         return NULL;
7105 }
7106
7107 void btd_device_init(void)
7108 {
7109         dbus_conn = btd_get_dbus_connection();
7110         service_state_cb_id = btd_service_add_state_cb(
7111                                                 service_state_changed, NULL);
7112 }
7113
7114 void btd_device_cleanup(void)
7115 {
7116         btd_service_remove_state_cb(service_state_cb_id);
7117 }
7118
7119 #ifdef __TIZEN_PATCH__
7120 void btd_device_set_legacy_pairing(struct btd_device *dev, bool legacy_pairing)
7121 {
7122         dev->legacy_pairing = legacy_pairing;
7123 }
7124 #endif