c1d959579dbd6b706858dc8758dc1382852db73f
[platform/core/connectivity/bluetooth-agent.git] / ag-agent / bluetooth-ag-agent.c
1 /*
2  * Bluetooth-ag-agent
3  *
4  * Copyright (c) 2014 - 2015 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Contact:     Hocheol Seo <hocheol.seo@samsung.com>
7  *              Chethan T N <chethan.tn@samsung.com>
8  *              Chanyeol Park <chanyeol.park@samsung.com>
9  *              Rakesh MK <rakesh.mk@samsung.com>
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *              http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  */
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <signal.h>
27 #include <sys/poll.h>
28 #include <gio/gunixfdlist.h>
29 #include <bundle_internal.h>
30 #include "bluetooth-ag-agent.h"
31 #include "bluetooth-ag-handler.h"
32 #include "bluetooth-agent-profile.h"
33
34 #include <TapiUtility.h>
35 #include <ITapiSim.h>
36 #include <ITapiModem.h>
37 #include <TelNetwork.h>
38 #include <app.h>
39 #include <aul.h>
40 #include <system_info.h>
41
42 #include "contacts.h"
43 #include "appsvc.h"
44
45 static GMainLoop *gmain_loop = NULL;
46 static GDBusProxy *service_gproxy;
47 static guint interface_added_sig_id = 0;
48 static guint interface_removed_sig_id = 0;
49 static guint name_owner_sig_id = 0;
50 GDBusConnection *ag_dbus_conn = NULL;
51 gchar *remote_dev_path = NULL;
52 gboolean wbs_en;
53 uint16_t hfp_ver;
54 uint16_t hsp_ver;
55 static TapiHandle *tapi_handle;
56 extern wbs_options wbs_opts;
57 GSList *active_devices = NULL;
58 static gchar *local_addr = NULL;
59 static GDBusProxy *app_gproxy;
60 static gboolean call_launch_requested = FALSE;
61 static gchar* sco_owner = NULL;
62 static guint sco_open_timer_id = 0;
63 static gboolean sco_open_request = FALSE;
64 static guint hf_bluez_id;
65 static guint hs_bluez_id;
66 static guint app_id;
67 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
68 static guint media_sig_id = 0;
69 static guint media_state_sig_id = 0;
70 static bt_ag_media_transport_state_t transport_state;
71 #endif
72
73 #define HSP_AG_UUID "00001112-0000-1000-8000-00805f9b34fb"
74 #define HFP_AG_UUID "0000111f-0000-1000-8000-00805f9b34fb"
75 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
76 #define A2DP_SINK_UUID "0000110b-0000-1000-8000-00805f9b34fb"
77 #endif
78 #define DEFAULT_ADAPTER_OBJECT_PATH "/org/bluez/hci0"
79 #define VCONF_KEY_BT_LUNAR_ENABLED "db/wms/bt_loop_device_hfp_connected"
80
81 #if defined(TIZEN_PROFILE_WEARABLE) && defined(TIZEN_FEATURE_BT_HFP_AG)
82 #define CALL_APP_ID "org.tizen.call-ui"
83 #endif
84
85 #if defined(TIZEN_SUPPORT_DUAL_HF)
86 #define VCONF_KEY_BT_HOST_BT_MAC_ADDR "db/wms/host_bt_mac"
87 #define MAX_CONNECTED_DEVICES 2
88 #else
89 #define MAX_CONNECTED_DEVICES 1
90 #endif
91
92 #define BT_AG_SIG_NUM 3
93 static struct sigaction bt_ag_sigoldact[BT_AG_SIG_NUM];
94 static int bt_ag_sig_to_handle[] = { SIGABRT, SIGSEGV, SIGTERM };
95
96 /*Below Inrospection data is exposed to bluez from agent*/
97 static const gchar ag_agent_bluez_introspection_xml[] =
98 "<node name='/'>"
99 " <interface name='org.bluez.Profile1'>"
100 "     <method name='NewConnection'>"
101 "          <arg type='o' name='device' direction='in'/>"
102 "          <arg type='h' name='fd' direction='in'/>"
103 "          <arg type='a{sv}' name='options' direction='in'/>"
104 "     </method>"
105 "     <method name='RequestDisconnection'>"
106 "          <arg type='o' name='device' direction='in'/>"
107 "     </method>"
108 " </interface>"
109 "</node>";
110
111 /*Below Introspection data is exposed to application from agent*/
112 static const gchar ag_agent_app_introspection_xml[] =
113 "<node name='/'>"
114 "  <interface name='Org.Hfp.App.Interface'>"
115 "     <method name='RegisterApplication'>"
116 "          <arg type='s' name='path' direction='in'/>"
117 "          <arg type='s' name='address' direction='in'/>"
118 "     </method>"
119 "     <method name='UnregisterApplication'>"
120 "          <arg type='s' name='path' direction='in'/>"
121 "     </method>"
122 "     <method name='IncomingCall'>"
123 "          <arg type='s' name='path' direction='in'/>"
124 "          <arg type='s' name='number' direction='in'/>"
125 "          <arg type='i' name='id' direction='in'/>"
126 "     </method>"
127 "     <method name='OutgoingCall'>"
128 "          <arg type='s' name='path' direction='in'/>"
129 "          <arg type='s' name='number' direction='in'/>"
130 "          <arg type='i' name='id' direction='in'/>"
131 "     </method>"
132 "     <method name='ChangeCallStatus'>"
133 "          <arg type='s' name='path' direction='in'/>"
134 "          <arg type='s' name='number' direction='in'/>"
135 "          <arg type='i' name='status' direction='in'/>"
136 "          <arg type='i' name='id' direction='in'/>"
137 "     </method>"
138 "     <method name='GetProperties'>"
139 "               <arg type='a{sv}' name='properties' direction='out'/>"
140 "     </method>"
141 "       <method name='Disconnect'>"
142 "       </method>"
143 "       <method name='IsConnected'>"
144 "               <arg type='b' name='connected' direction='out'/>"
145 "       </method>"
146 "       <method name='IndicateCall'>"
147 "       </method>"
148 "       <method name='CancelCall'>"
149 "       </method>"
150 "       <method name='Play'>"
151 "       </method>"
152 "       <method name='Stop'>"
153 "       </method>"
154 "       <method name='IsPlaying'>"
155 "       <arg type='b' name='playing' direction='out'/>"
156 "       </method>"
157 "       <method name='GetSpeakerGain'>"
158 "               <arg type='q' name='gain' direction='out'/>"
159 "       </method>"
160 "       <method name='GetMicrophoneGain'>"
161 "               <arg type='q' name='gain' direction='out'/>"
162 "       </method>"
163 "       <method name='SetSpeakerGain'>"
164 "               <arg type='q' name='gain' direction='in'/>"
165 "       </method>"
166 "       <method name='SetMicrophoneGain'>"
167 "               <arg type='q' name='gain' direction='in'/>"
168 "       </method>"
169 "       <method name='SetVoiceDial'>"
170 "               <arg type='b' name='enable' direction='in'/>"
171 "       </method>"
172 "       <method name='CheckPrivilege'>"
173 "       </method>"
174 "     <method name='SwapHeadset'>"
175 "          <arg type='s' name='remote_addr' direction='in'/>"
176 "     </method>"
177 "  </interface>"
178 "</node>";
179
180 struct event {
181         const char *cmd;
182         int (*callback)(bt_ag_info_t *hs, const char *buf);
183 };
184
185 struct sco_socket_addr {
186         sa_family_t     sco_family;
187         bt_addr         sco_bdaddr;
188 };
189
190 typedef struct {
191         uint16_t setting;
192 } bt_voice;
193
194 struct ag_codec {
195         bt_ag_info_t *bt_ag_info;
196         char *codec_status;
197 };
198
199 bt_ag_status_t ag = {
200         .telephony_ready = FALSE,
201         .features = 0,
202         .er_mode = 3,
203         .er_ind = 0,
204         .rh = BT_RSP_HOLD_NOT_SUPPORTED,
205         .number = NULL,
206         .number_type = 0,
207         .ring_timer = 0,
208         .sdp_features = 0,
209 };
210 static void __bt_ag_agent_sigterm_handler(int signo);
211 static gboolean __bt_ag_agent_connection(gint32 fd, const gchar *device_path,
212                                                 const gchar *object_path);
213 static gboolean __bt_ag_agent_connection_release(bt_ag_info_t *hs);
214 static gboolean __bt_ag_event_handler(GIOChannel *channel, GIOCondition cond,
215         void *user_data);
216 static int __bt_ag_sco_connect(bt_ag_info_t *hs);
217 void _bt_ag_set_headset_state(bt_ag_info_t *hs, hs_state_t state);
218 static void __bt_ag_agent_reg_sim_event(TapiHandle *handle, void *user_data);
219 static void __bt_ag_agent_dereg_sim_event(TapiHandle *handle);
220 static void __bt_ag_name_owner_changed_cb(GDBusConnection *connection,
221                                         const gchar *sender_name,
222                                         const gchar *object_path,
223                                         const gchar *interface_name,
224                                         const gchar *signal_name,
225                                         GVariant *parameters,
226                                         gpointer user_data);
227
228 static void __bt_convert_addr_type_to_rev_string(char *address,
229                                 unsigned char *addr)
230 {
231         ret_if(address == NULL);
232         ret_if(addr == NULL);
233
234         g_snprintf(address, BT_ADDRESS_STRING_SIZE,
235                         "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X",
236                         addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]);
237 }
238
239 static GDBusProxy *__bt_ag_gdbus_init_service_proxy(const gchar *service,
240                                 const gchar *path, const gchar *interface)
241 {
242         FN_START;
243
244         GDBusProxy *proxy;
245         GError *err = NULL;
246
247         if (ag_dbus_conn == NULL)
248                 ag_dbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
249
250         if (!ag_dbus_conn) {
251                 if (err) {
252                         ERR("Unable to connect to gdbus: %s", err->message);
253                         g_clear_error(&err);
254                 }
255                 return NULL;
256         }
257
258         proxy =  g_dbus_proxy_new_sync(ag_dbus_conn,
259                         G_DBUS_PROXY_FLAGS_NONE, NULL,
260                         service, path,
261                         interface, NULL, &err);
262
263         if (!proxy) {
264                 if (err) {
265                         ERR("Unable to create proxy: %s", err->message);
266                         g_clear_error(&err);
267                 }
268                 return NULL;
269         }
270
271         FN_END;
272         return proxy;
273 }
274
275 static GDBusProxy *__bt_ag_gdbus_get_app_proxy(const gchar *service,
276                                 const gchar *path, const gchar *interface)
277 {
278         return (app_gproxy) ? app_gproxy :
279                         __bt_ag_gdbus_init_service_proxy(service,
280                                         path, interface);
281 }
282
283 static int __bt_ag_agent_gdbus_method_send(const char *service,
284                                 const gchar *path, const char *interface,
285                                 const char *method, gboolean response,
286                                 GVariant *parameters)
287 {
288         FN_START;
289
290         GVariant *ret;
291         GDBusProxy *proxy;
292         GError *error = NULL;
293
294         proxy = __bt_ag_gdbus_get_app_proxy(service, path, interface);
295         if (!proxy)
296                 return BT_HFP_AGENT_ERROR_INTERNAL;
297
298         if (response) {
299                 ret = g_dbus_proxy_call_sync(proxy,
300                                         method, parameters,
301                                         G_DBUS_CALL_FLAGS_NONE, -1,
302                                         NULL, &error);
303                 if (ret == NULL) {
304                         /* dBUS-RPC is failed */
305                         ERR("dBUS-RPC is failed");
306                         if (error != NULL) {
307                                 /* dBUS gives error cause */
308                                 ERR("D-Bus API failure: errCode[%x], message[%s]",
309                                         error->code, error->message);
310
311                                 g_clear_error(&error);
312                         }
313                         return BT_HFP_AGENT_ERROR_INTERNAL;
314                 }
315
316                 g_variant_unref(ret);
317         } else {
318                 g_dbus_proxy_call(proxy,
319                                         method, parameters,
320                                         G_DBUS_CALL_FLAGS_NONE, 2000,
321                                         NULL, NULL, NULL);
322         }
323         return BT_HFP_AGENT_ERROR_NONE;
324 }
325
326 gboolean _bt_ag_agent_emit_signal(
327                                 GDBusConnection *connection,
328                                 const char *path,
329                                 const char *interface,
330                                 const char *name,
331                                 GVariant *property)
332 {
333         FN_START;
334
335         GError *error = NULL;
336         gboolean ret;
337         ret =  g_dbus_connection_emit_signal(connection,
338                                 NULL, path, interface,
339                                 name, property,
340                                 &error);
341         if (!ret) {
342                 if (error != NULL) {
343                         /* dBUS gives error cause */
344                         ERR("D-Bus API failure: errCode[%x], message[%s]",
345                                 error->code, error->message);
346                         g_clear_error(&error);
347                 }
348         }
349         INFO_C("Emit Signal done = [%s]", name);
350
351         FN_END;
352         return ret;
353 }
354
355 gboolean _bt_ag_agent_emit_property_changed(
356                                 GDBusConnection *connection,
357                                 const char *path,
358                                 const char *interface,
359                                 const char *name,
360                                 GVariant *property)
361 {
362         FN_START;
363
364         gboolean ret;
365         GVariant *var_data;
366
367         var_data = g_variant_new("(sv)",        name, property);
368
369         ret =  _bt_ag_agent_emit_signal(connection,
370                                 path, interface,
371                                 "PropertyChanged", var_data);
372         FN_END;
373         return ret;
374 }
375
376 static void __bt_ag_agent_start_watch(bt_ag_info_t *bt_ag_info)
377 {
378         bt_ag_info->watch_id = g_io_add_watch(bt_ag_info->io_chan,
379                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
380                         (GIOFunc) __bt_ag_event_handler, bt_ag_info);
381 }
382
383 static void __bt_ag_agent_remove_watch(guint *watch_id)
384 {
385         DBG("Remove IO watch ID %d", *watch_id);
386         if (*watch_id > 0) {
387                 g_source_remove(*watch_id);
388                 *watch_id = 0;
389         }
390 }
391
392 #if defined(TIZEN_SUPPORT_DUAL_HF)
393 gboolean __bt_ag_agent_is_companion_device(const char *addr)
394 {
395 #if defined(TIZEN_PROFILE_WEARABLE)
396         char *host_device_address = NULL;
397         host_device_address = vconf_get_str(VCONF_KEY_BT_HOST_BT_MAC_ADDR);
398
399         if (!host_device_address) {
400                 INFO("Failed to get a companion device address");
401                 return FALSE;
402         }
403
404         if (g_strcmp0(host_device_address, addr) == 0) {
405                 INFO("addr[%s] is companion device", addr);
406                 return TRUE;
407         }
408
409         return FALSE;
410 #else
411         /* TODO : Need to add companion device check condition for Phone models */
412         return FALSE;
413 #endif
414 }
415
416 void __bt_convert_device_path_to_address(const gchar *device_path,
417                                                 char *device_address)
418 {
419         char address[BT_ADDRESS_STRING_SIZE] = { 0 };
420         char *dev_addr;
421
422         ret_if(device_path == NULL);
423         ret_if(device_address == NULL);
424
425         dev_addr = strstr(device_path, "dev_");
426         if (dev_addr != NULL) {
427                 char *pos = NULL;
428                 dev_addr += 4;
429                 g_strlcpy(address, dev_addr, sizeof(address));
430
431                 while ((pos = strchr(address, '_')) != NULL)
432                         *pos = ':';
433
434                 g_strlcpy(device_address, address, BT_ADDRESS_STRING_SIZE);
435         }
436 }
437
438 static gboolean  __bt_ag_agent_is_companion_device_connected(void)
439 {
440         GSList *l;
441
442         for (l = active_devices ; l; l = l->next) {
443                 bt_ag_info_t *data = l->data;
444
445                 if (data->is_companion_device) {
446                         DBG("Companion device found");
447                         return TRUE;
448                 }
449         }
450
451         return FALSE;
452 }
453
454 gboolean __bt_ag_agent_check_dual_hf_condition(const gchar *device_path)
455 {
456         char device_address[BT_ADDRESS_STRING_SIZE] = { 0 };
457         gboolean is_companion_device;
458
459         __bt_convert_device_path_to_address(device_path, device_address);
460         is_companion_device = __bt_ag_agent_is_companion_device(device_address);
461
462         DBG(" device_address[%s]", device_address);
463         DBG(" is_companion_device[%d]", is_companion_device);
464
465         if (__bt_ag_agent_is_companion_device_connected()) {
466                 if (is_companion_device)
467                         return FALSE;
468         } else {
469                 if (!is_companion_device)
470                         return FALSE;
471         }
472         return TRUE;
473 }
474 #endif /* TIZEN_SUPPORT_DUAL_HF */
475
476 static gboolean __bt_is_phone_locked(int *phone_lock_state)
477 {
478         FN_START;
479         int ret;
480
481         if (NULL == phone_lock_state)
482                 return FALSE;
483
484         ret = vconf_get_int(VCONFKEY_IDLE_LOCK_STATE, phone_lock_state);
485         if (ret != 0) {
486                 ERR("Failed to read  [%s]\n", VCONFKEY_IDLE_LOCK_STATE);
487                 return FALSE;
488         }
489
490         FN_END;
491         return TRUE;
492 }
493
494 static gboolean __bt_get_outgoing_callapp_type(int *callapp_type)
495 {
496         FN_START;
497
498         if (NULL == callapp_type)
499                 return FALSE;
500
501 #if defined(TIZEN_PROFILE_WEARABLE) && defined(TIZEN_FEATURE_BT_HFP_AG)
502         *callapp_type = BT_VOICE_CALL;
503         FN_END;
504         return TRUE;
505 #else
506 #if 0
507         int ret;
508         ret = vconf_get_int(
509                         VCONFKEY_CISSAPPL_OUTGOING_CALL_TYPE_INT,
510                         callapp_type);
511         if (ret != 0) {
512                 ERR("Failed to read  [%s]\n",
513                         VCONFKEY_CISSAPPL_OUTGOING_CALL_TYPE_INT);
514                 return FALSE;
515         }
516
517         INFO(" [%s] = [%d]\n",
518                 VCONFKEY_CISSAPPL_OUTGOING_CALL_TYPE_INT, *callapp_type);
519 #endif
520         /* The vconf value does not include in platform. */
521         *callapp_type = BT_VOICE_CALL;
522         FN_END;
523         return TRUE;
524 #endif
525 }
526
527 static gboolean __bt_get_outgoing_call_condition(int *condition)
528 {
529         FN_START;
530
531         if (NULL == condition)
532                 return FALSE;
533
534 #if defined(TIZEN_PROFILE_WEARABLE) && defined(TIZEN_FEATURE_BT_HFP_AG)
535         *condition = BT_MO_ONLY_UNLOCKED;
536         FN_END;
537         return TRUE;
538 #else
539 #if 0
540         int ret;
541         ret = vconf_get_int(
542                         VCONFKEY_CISSAPPL_OUTGOING_CALL_CONDITIONS_INT,
543                         condition);
544         if (ret != 0) {
545                 ERR("Failed to read  [%s]\n",
546                         VCONFKEY_CISSAPPL_OUTGOING_CALL_CONDITIONS_INT);
547                 return FALSE;
548         }
549 #endif
550         /* The vconf value does not include in platform. */
551         *condition = BT_MO_ONLY_UNLOCKED;
552         FN_END;
553         return TRUE;
554 #endif
555 }
556
557 static gboolean  __bt_ag_agent_launch_call_app(const char *number)
558 {
559         FN_START;
560         bundle *b;
561
562         DBG_SECURE("number(%s)", number);
563
564         b = bundle_create();
565         if (NULL == b) {
566                 ERR("bundle_create() Failed");
567                 return FALSE;
568         }
569
570         bundle_add(b, "launch-type", "MO");
571         bundle_add(b, "dial-type", "HEADSET");
572
573         if (strlen(number) != 0)
574                 bundle_add(b, "number", number);
575
576         aul_launch_app_async(CALL_APP_ID, b);
577         bundle_free(b);
578
579         FN_END;
580         return TRUE;
581 }
582
583 static void *__bt_ag_agent_launch_call_req(void *arg)
584 {
585         FN_START;
586         bundle *b = (bundle *)arg;
587         if (appsvc_run_service(b, 0, NULL, NULL) < 0)
588                 ERR("Unable to run app svc");
589         bundle_free(b);
590         call_launch_requested = FALSE;
591         FN_END;
592         return NULL;
593 }
594
595 static gboolean __bt_ag_agent_make_call(const char *number)
596 {
597         FN_START;
598
599         char telnum[BT_MAX_TEL_NUM_STRING];
600         bundle *b;
601         pthread_t thread_id;
602
603         if (TIZEN_PROFILE_WEARABLE)
604                 return __bt_ag_agent_launch_call_app(number);
605
606         if (call_launch_requested == TRUE) {
607                 DBG("Launch request is in progress");
608                 return TRUE;
609         }
610
611         b = bundle_create();
612         if (NULL == b)
613                 return FALSE;
614
615         appsvc_set_operation(b, APPSVC_OPERATION_CALL);
616         snprintf(telnum, sizeof(telnum), "tel:%s", number);
617         appsvc_set_uri(b, telnum);
618         appsvc_add_data(b, "ctindex", "-1");
619
620         call_launch_requested = TRUE;
621         if (pthread_create(&thread_id, NULL,
622                         (void *)&__bt_ag_agent_launch_call_req,
623                                         (void *)b) < 0) {
624                 ERR("pthread_create() is failed");
625                 call_launch_requested = FALSE;
626                 return FALSE;
627         }
628         if (pthread_detach(thread_id) < 0)
629                 ERR("pthread_detach() is failed");
630
631         FN_END;
632         return TRUE;
633 }
634
635 static gboolean __bt_ag_agent_make_video_call(const char *mo_number)
636 {
637         FN_START;
638         bundle *kb;
639
640         kb = bundle_create();
641         if (NULL == kb)
642                 return FALSE;
643
644         bundle_add(kb, "KEY_CALL_TYPE", "MO");
645         bundle_add(kb, "number", mo_number);
646         aul_launch_app("org.tizen.vtmain", kb);
647         bundle_free(kb);
648
649         FN_END;
650         return TRUE;
651 }
652
653 gboolean _bt_ag_agent_answer_call(unsigned int call_id,
654                                 const gchar *path, const gchar *sender)
655 {
656         FN_START;
657
658         if (path == NULL || sender == NULL) {
659                 DBG("Invalid Arguments");
660                 return FALSE;
661         }
662
663         DBG("Application path = %s", path);
664         DBG("Call Id = %d", call_id);
665         DBG("Sender = %s", sender);
666
667         _bt_ag_agent_emit_signal(ag_dbus_conn, path,
668                                         BT_AG_SERVICE_NAME, "Answer",
669                                         g_variant_new("(u)", call_id));
670         FN_END;
671         return TRUE;
672 }
673
674 gboolean _bt_ag_agent_reject_call(unsigned int call_id,
675                                 const gchar *path, const gchar *sender)
676 {
677         FN_START;
678
679         if (path == NULL || sender == NULL) {
680                 DBG("Invalid Arguments");
681                 return FALSE;
682         }
683
684         DBG("Application path = %s", path);
685         DBG("Call Id = %d", call_id);
686         DBG("Sender = %s", sender);
687
688         _bt_ag_agent_emit_signal(ag_dbus_conn, path,
689                                         BT_AG_SERVICE_NAME, "Reject",
690                                         g_variant_new("(u)", call_id));
691         FN_END;
692         return TRUE;
693 }
694
695 gboolean _bt_ag_agent_release_call(unsigned int call_id,
696                                 const gchar *path, const gchar *sender)
697 {
698         FN_START;
699
700         if (path == NULL || sender == NULL) {
701                 DBG("Invalid Arguments");
702                 return FALSE;
703         }
704
705         DBG("Application path = %s", path);
706         DBG("Call Id = %d", call_id);
707         DBG("Sender = %s", sender);
708
709         _bt_ag_agent_emit_signal(ag_dbus_conn, path,
710                                         BT_AG_SERVICE_NAME, "Release",
711                                         g_variant_new("(u)", call_id));
712
713         FN_END;
714         return TRUE;
715 }
716
717 bt_hfp_agent_error_t _bt_ag_agent_dial_num(const gchar *number, guint flags)
718 {
719         bt_hfp_agent_error_t error_code = BT_HFP_AGENT_ERROR_NONE;
720         int callapp_type;
721         int phone_lock_state;
722         int condition;
723
724         FN_START;
725
726         if (number == NULL) {
727                 ERR("Invalid Argument");
728                 error_code = BT_HFP_AGENT_ERROR_INVALID_PARAM;
729                 goto fail;
730         }
731
732         DBG("Number = %s", number);
733         DBG("flags = %d", flags);
734
735         if (!__bt_is_phone_locked(&phone_lock_state)) {
736                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
737                 goto fail;
738         }
739
740         if (!__bt_get_outgoing_callapp_type(&callapp_type)) {
741                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
742                 goto fail;
743         }
744
745         if (!__bt_get_outgoing_call_condition(&condition)) {
746                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
747                 goto fail;
748         }
749
750         if (condition == BT_MO_ONLY_UNLOCKED && phone_lock_state ==
751                 VCONFKEY_IDLE_LOCK) {
752                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
753                 goto fail;
754         }
755
756         if (callapp_type == BT_VIDEO_CALL) {
757                 if (!__bt_ag_agent_make_video_call(number)) {
758                         ERR("Problem launching application");
759                         error_code = BT_HFP_AGENT_ERROR_INTERNAL;
760                         goto fail;
761                 }
762         } else {
763                 if (!__bt_ag_agent_make_call(number)) {
764                         ERR("Problem launching application");
765                         error_code = BT_HFP_AGENT_ERROR_INTERNAL;
766                         goto fail;
767                 }
768         }
769
770 fail:
771         FN_END;
772         return error_code;
773 }
774
775 bt_hfp_agent_error_t _bt_ag_agent_dial_memory(unsigned int location)
776 {
777         bt_hfp_agent_error_t error_code = BT_HFP_AGENT_ERROR_NONE;
778         char *number = NULL;
779         contacts_filter_h filter = NULL;
780         contacts_query_h query = NULL;
781         contacts_list_h list = NULL;
782         contacts_record_h record = NULL;
783         unsigned int projections[] = {
784                 _contacts_speeddial.number,
785         };
786
787         FN_START;
788
789         DBG("location = %d", location);
790
791         /*Get number from contacts location*/
792         if (contacts_connect() != CONTACTS_ERROR_NONE) {
793                 ERR(" contacts_connect failed");
794                 return BT_HFP_AGENT_ERROR_INTERNAL;
795         }
796
797         contacts_filter_create(_contacts_speeddial._uri, &filter);
798
799         if (filter == NULL)
800                 goto done;
801
802         if (contacts_filter_add_int(filter,
803                 _contacts_speeddial.speeddial_number,
804                 CONTACTS_MATCH_EQUAL, location) !=
805                 CONTACTS_ERROR_NONE) {
806                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
807                 goto done;
808         }
809
810         contacts_query_create(_contacts_speeddial._uri, &query);
811
812         if (query == NULL)
813                 goto done;
814
815         contacts_query_set_filter(query, filter);
816
817         if (contacts_query_set_projection(query, projections,
818                                 sizeof(projections)/sizeof(unsigned int)) !=
819                                 CONTACTS_ERROR_NONE) {
820                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
821                 goto done;
822         }
823
824         if (contacts_db_get_records_with_query(query, 0, 1, &list) !=
825                                 CONTACTS_ERROR_NONE) {
826                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
827                 goto done;
828         }
829
830         if (contacts_list_first(list) != CONTACTS_ERROR_NONE) {
831                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
832                 goto done;
833         }
834
835         if (contacts_list_get_current_record_p(list, &record) !=
836                                 CONTACTS_ERROR_NONE) {
837                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
838                 goto done;
839         }
840
841         if (record == NULL)
842                 goto done;
843
844         if (contacts_record_get_str(record, _contacts_speeddial.number, &number)
845                 != CONTACTS_ERROR_NONE) {
846                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
847                 goto done;
848         }
849
850         if (number == NULL) {
851                 ERR("No number at the location");
852                 error_code = BT_HFP_AGENT_ERROR_INVALID_MEMORY_INDEX;
853                 goto done;
854         }
855
856         DBG("number %s", number);
857
858         /*Make Voice call*/
859         if (!__bt_ag_agent_make_call(number)) {
860                 ERR("Problem launching application");
861                 error_code = BT_HFP_AGENT_ERROR_INTERNAL;
862         }
863
864         g_free(number);
865 done:
866         if (list != NULL)
867                 contacts_list_destroy(list, TRUE);
868
869         if (filter != NULL)
870                 contacts_filter_destroy(filter);
871
872         if (query != NULL)
873                 contacts_query_destroy(query);
874
875         contacts_disconnect();
876
877         FN_END;
878
879         return error_code;
880 }
881
882 bt_hfp_agent_error_t _bt_ag_agent_send_dtmf(const gchar *dtmf,
883                                 const gchar *path, const gchar *sender)
884 {
885         bt_hfp_agent_error_t ret;
886
887         FN_START;
888
889         if (dtmf == NULL || path == NULL || sender == NULL) {
890                 ERR("Invalid Argument");
891                 return BT_HFP_AGENT_ERROR_INVALID_PARAM;
892         }
893
894         DBG("Dtmf = %s", dtmf);
895         DBG("Application path = %s", path);
896         DBG("Sender = %s", sender);
897
898         ret = __bt_ag_agent_gdbus_method_send(sender,
899                                 path, TELEPHONY_APP_INTERFACE,
900                                 "SendDtmf", FALSE,
901                                 g_variant_new("(s)", dtmf));
902
903         return ret;
904 }
905
906 gboolean _bt_ag_agent_threeway_call(unsigned int chld_value,
907                                 const gchar *path, const gchar *sender)
908 {
909         FN_START;
910
911         if (path == NULL || sender == NULL) {
912                 DBG("Invalid Arguments");
913                 return FALSE;
914         }
915
916         DBG("Application path = %s", path);
917         DBG("Value = %d", chld_value);
918         DBG("Sender = %s", sender);
919
920 #if defined(TIZEN_PROFILE_WEARABLE) && defined(TIZEN_FEATURE_BT_HFP_AG)
921         /* Check if AG supports (i.e. ag_chld_str = "0,1,2") the requested CHLD;
922         if not return FALSE */
923         if (chld_value != 0 && chld_value != 1 && chld_value != 2)
924                 return FALSE;
925 #else
926         if (chld_value != 0 && chld_value != 1 && chld_value != 2 &&
927                                 chld_value != 3)
928                 return FALSE;
929 #endif
930         _bt_ag_agent_emit_signal(ag_dbus_conn, path,
931                                         BT_AG_SERVICE_NAME, "Threeway",
932                                         g_variant_new("(u)", chld_value));
933         FN_END;
934         return TRUE;
935 }
936
937 bt_hfp_agent_error_t _bt_ag_agent_dial_last_num(void *device)
938 {
939         bt_hfp_agent_error_t err_code = BT_HFP_AGENT_ERROR_NONE;
940         char *last_num = NULL;
941         int type;
942         int callapp_type;
943         int phone_lock_state;
944         int condition;
945         contacts_list_h list = NULL;
946         contacts_query_h query = NULL;
947         contacts_filter_h filter = NULL;
948         contacts_record_h record = NULL;
949         unsigned int projections[] = {
950                 _contacts_phone_log.address,
951                 _contacts_phone_log.log_type,
952         };
953
954         FN_START;
955
956         if (contacts_connect() != CONTACTS_ERROR_NONE) {
957                 ERR(" contacts_connect failed");
958                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
959                 return err_code;
960         }
961
962         contacts_filter_create(_contacts_phone_log._uri, &filter);
963
964         if (filter == NULL)
965                 goto done;
966
967         if (contacts_filter_add_int(filter, _contacts_phone_log.log_type,
968                                 CONTACTS_MATCH_EQUAL,
969                                 CONTACTS_PLOG_TYPE_VOICE_OUTGOING) !=
970                                 CONTACTS_ERROR_NONE) {
971                 ERR(" contacts_filter_add_int failed");
972                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
973                 goto done;
974         }
975
976         if (contacts_filter_add_operator(filter, CONTACTS_FILTER_OPERATOR_OR) !=
977                                 CONTACTS_ERROR_NONE) {
978                 ERR(" contacts_filter_add_operator failed");
979                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
980                 goto done;
981         }
982
983         if (contacts_filter_add_int(filter, _contacts_phone_log.log_type,
984                                 CONTACTS_MATCH_EQUAL,
985                                 CONTACTS_PLOG_TYPE_VIDEO_OUTGOING) !=
986                                 CONTACTS_ERROR_NONE) {
987                 ERR(" contacts_filter_add_int failed");
988                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
989                 goto done;
990         }
991
992         contacts_query_create(_contacts_phone_log._uri, &query);
993
994         if (query == NULL)
995                 goto done;
996
997         contacts_query_set_filter(query, filter);
998
999         if (contacts_query_set_projection(query, projections,
1000                                 sizeof(projections)/sizeof(unsigned int)) !=
1001                                 CONTACTS_ERROR_NONE) {
1002                 ERR(" contacts_query_set_projection failed");
1003                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1004                 goto done;
1005         }
1006
1007         if (contacts_query_set_sort(query, _contacts_phone_log.log_time, false)
1008                 != CONTACTS_ERROR_NONE) {
1009                 ERR(" contacts_query_set_sort failed");
1010                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1011                 goto done;
1012         }
1013
1014         if (contacts_db_get_records_with_query(query, 0, 1, &list)  !=
1015                                 CONTACTS_ERROR_NONE) {
1016                 ERR(" contacts_db_get_records_with_query failed");
1017                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1018                 goto done;
1019         }
1020
1021         if (contacts_list_first(list)  != CONTACTS_ERROR_NONE) {
1022                 ERR(" contacts_list_first failed");
1023                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1024                 goto done;
1025         }
1026
1027         if (contacts_list_get_current_record_p(list, &record)  !=
1028                                 CONTACTS_ERROR_NONE) {
1029                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1030                 goto done;
1031         }
1032
1033         if (record == NULL)
1034                 goto done;
1035
1036         if (contacts_record_get_str(record, _contacts_phone_log.address,
1037                                 &last_num) != CONTACTS_ERROR_NONE) {
1038                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1039                 goto done;
1040         }
1041
1042         if (last_num == NULL) {
1043                 ERR("No last number");
1044                 err_code = BT_HFP_AGENT_ERROR_NO_CALL_LOGS;
1045                 goto done;
1046         }
1047
1048         if (!__bt_is_phone_locked(&phone_lock_state)) {
1049                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1050                 goto done;
1051         }
1052
1053         if (!__bt_get_outgoing_callapp_type(&callapp_type)) {
1054                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1055                 goto done;
1056         }
1057
1058         if (!__bt_get_outgoing_call_condition(&condition)) {
1059                 ERR(" Failed to get the call condition");
1060                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1061                 goto done;
1062         }
1063
1064         if (condition == BT_MO_ONLY_UNLOCKED &&
1065                 phone_lock_state == VCONFKEY_IDLE_LOCK) {
1066                 ERR(" call condition and phone lock state check fail");
1067                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1068                 goto done;
1069         }
1070
1071         switch (callapp_type) {
1072         case BT_VOICE_CALL:
1073                 if (!__bt_ag_agent_make_call(last_num)) {
1074                         ERR("Problem launching application");
1075                         err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1076                 }
1077                 break;
1078         case BT_VIDEO_CALL:
1079                 if (!__bt_ag_agent_make_video_call(last_num)) {
1080                         ERR("Problem launching application");
1081                         err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1082                 }
1083                 break;
1084         case BT_FOLLOW_CALL_LOG:
1085                 if (contacts_record_get_int(record,
1086                         _contacts_phone_log.log_type,
1087                         &type) != CONTACTS_ERROR_NONE) {
1088                         err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1089                         break;
1090                 }
1091                 if (type == CONTACTS_PLOG_TYPE_VOICE_OUTGOING) {
1092                         if (!__bt_ag_agent_make_call(last_num)) {
1093                                 ERR("Problem launching application");
1094                                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1095                         }
1096                 } else if (type == CONTACTS_PLOG_TYPE_VIDEO_OUTGOING) {
1097                         if (!__bt_ag_agent_make_video_call(last_num)) {
1098                                 ERR("Problem launching application");
1099                                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1100                         }
1101                 } else {
1102                                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1103                 }
1104                 break;
1105         default:
1106                 err_code = BT_HFP_AGENT_ERROR_INTERNAL;
1107                 break;
1108         }
1109
1110 done:
1111
1112         if (list != NULL)
1113                 contacts_list_destroy(list, TRUE);
1114
1115         if (filter != NULL)
1116                 contacts_filter_destroy(filter);
1117
1118         if (query != NULL)
1119                 contacts_query_destroy(query);
1120
1121         contacts_disconnect();
1122
1123         if (last_num != NULL)
1124                 g_free(last_num);
1125
1126         FN_END;
1127
1128         return err_code;
1129 }
1130
1131 bt_hfp_agent_error_t _bt_ag_agent_vendor_cmd(const gchar *cmd,
1132                 const gchar *path, const gchar *sender)
1133 {
1134         bt_hfp_agent_error_t ret;
1135
1136         FN_START;
1137
1138         if (cmd == NULL || path == NULL || sender == NULL) {
1139                 ERR("Invalid Argument");
1140                 return BT_HFP_AGENT_ERROR_INVALID_PARAM;
1141         }
1142
1143         DBG("cmd = %s", cmd);
1144         DBG("Application path = %s", path);
1145         DBG("Sender = %s", sender);
1146
1147         ret = __bt_ag_agent_gdbus_method_send(sender,
1148                                 path, TELEPHONY_APP_INTERFACE,
1149                                 "VendorCmd", FALSE,
1150                                 g_variant_new("(s)", cmd));
1151         FN_END;
1152         return ret;
1153 }
1154
1155 gboolean _bt_ag_agent_get_signal_quality(void *device)
1156 {
1157         gint rssi;
1158
1159         FN_START;
1160
1161         if (vconf_get_int(VCONFKEY_TELEPHONY_RSSI, &rssi)) {
1162                 DBG("VCONFKEY_TELEPHONY_RSSI failed\n");
1163                 goto fail;
1164         }
1165
1166         DBG("RSSI : %d", rssi);
1167
1168         _bt_hfp_signal_quality_reply(rssi, BT_SIGNAL_QUALITY_BER,
1169                 device);
1170
1171         FN_END;
1172         return TRUE;
1173 fail:
1174         FN_END;
1175         _bt_hfp_signal_quality_reply(-1, -1, device);
1176         return FALSE;
1177 }
1178
1179 gboolean _bt_ag_agent_get_battery_status(void *device)
1180 {
1181         gint battery_chrg_status;
1182         gint battery_capacity;
1183
1184         FN_START;
1185
1186         if (vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW,
1187                                                 &battery_chrg_status)) {
1188                 DBG("VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW failed\n");
1189                 goto fail;
1190         }
1191
1192         DBG("Status : %d\n", battery_chrg_status);
1193
1194         if (vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CAPACITY,
1195                                                 &battery_capacity)) {
1196                 DBG("VCONFKEY_SYSMAN_BATTERY_CAPACITY failed\n");
1197                 goto fail;
1198         }
1199
1200         DBG("Capacity : %d\n", battery_capacity);
1201
1202         _bt_hfp_battery_property_reply(device,
1203                 battery_chrg_status, battery_capacity);
1204         FN_END;
1205         return TRUE;
1206
1207 fail:
1208         _bt_hfp_battery_property_reply(device, -1, -1);
1209         FN_END;
1210         return FALSE;
1211 }
1212
1213 gboolean _bt_ag_agent_get_operator_name(void *device)
1214 {
1215         char *operator_name;
1216         FN_START;
1217
1218         operator_name = vconf_get_str(VCONFKEY_TELEPHONY_NWNAME);
1219         if (NULL == operator_name) {
1220                 DBG("vconf_get_str failed");
1221                 _bt_hfp_operator_reply(NULL, device);
1222                 return FALSE;
1223         }
1224
1225         DBG("operator_name  = [%s]", operator_name);
1226
1227         _bt_hfp_operator_reply(operator_name, device);
1228
1229         free(operator_name);
1230
1231         FN_END;
1232         return TRUE;
1233 }
1234
1235 gboolean _bt_hfp_agent_nrec_status(gboolean status,
1236                         void *t_device)
1237 {
1238         FN_START;
1239         bt_ag_info_t *hs = (bt_ag_info_t *)t_device;
1240
1241         DBG("NREC status = %d", status);
1242         if (status)
1243                 hs->nrec_status = FALSE;
1244         else
1245                 hs->nrec_status = TRUE;
1246
1247         _bt_ag_agent_emit_signal(ag_dbus_conn, hs->path,
1248                                         BT_AG_SERVICE_NAME, "NrecStatusChanged",
1249                                         g_variant_new("(b)", status));
1250         FN_END;
1251         return TRUE;
1252 }
1253
1254 gboolean _bt_ag_agent_get_imei_number(void *device)
1255 {
1256         FN_START;
1257         char *imei_number;
1258
1259         imei_number = tel_get_misc_me_imei_sync(tapi_handle);
1260         if (NULL == imei_number) {
1261                 ERR("tel_get_misc_me_imei_sync for imei_number failed");
1262                 goto fail;
1263         }
1264
1265         if (!g_utf8_validate(imei_number, -1, NULL)) {
1266                 free(imei_number);
1267                 ERR("get_imei_number : invalid UTF8");
1268                 goto fail;
1269         }
1270
1271         DBG_SECURE("imei_number  = [%s]", imei_number);
1272         _bt_hfp_get_imei_number_reply(imei_number, device);
1273         free(imei_number);
1274         FN_END;
1275         return TRUE;
1276
1277 fail:
1278         _bt_hfp_get_imei_number_reply(NULL, device);
1279         FN_END;
1280         return FALSE;
1281 }
1282
1283 void _bt_ag_agent_get_manufacturer_name(void *device)
1284 {
1285         FN_START;
1286         char *manufacturer_name;
1287         int ret;
1288
1289         ret = system_info_get_platform_string("http://tizen.org/system/manufacturer",
1290                                                 &manufacturer_name);
1291         if (SYSTEM_INFO_ERROR_NONE != ret) {
1292                 ERR("Get manufacturer_name failed : %d", ret);
1293                 if (NULL != manufacturer_name)
1294                         free(manufacturer_name);
1295
1296                 manufacturer_name = g_strdup("Unknown");
1297         } else if (!g_utf8_validate(manufacturer_name, -1, NULL)) {
1298                 free(manufacturer_name);
1299                 manufacturer_name = g_strdup("Unknown");
1300                 ERR("get_manufacturer_name : invalid UTF8");
1301         }
1302
1303         DBG_SECURE("manufacturer_name  = [%s]", manufacturer_name);
1304         _bt_hfp_get_device_manufacturer_reply(manufacturer_name, device);
1305         free(manufacturer_name);
1306         FN_END;
1307 }
1308
1309 void _bt_ag_agent_get_imsi(void *device)
1310 {
1311         FN_START;
1312         TelSimImsiInfo_t imsi;
1313         memset(&imsi, 0, sizeof(TelSimImsiInfo_t));
1314         if (tel_get_sim_imsi(tapi_handle, &imsi) != TAPI_API_SUCCESS) {
1315                 ERR("tel_get_sim_imsi failed");
1316                 goto fail;
1317         }
1318         DBG_SECURE("tapi values %s %s %s", imsi.szMcc, imsi.szMnc, imsi.szMsin);
1319
1320         _bt_hfp_get_imsi_reply(imsi.szMcc, imsi.szMnc, imsi.szMsin, device);
1321         FN_END;
1322         return;
1323 fail:
1324         _bt_hfp_get_imsi_reply(NULL, NULL, NULL, device);
1325         FN_END;
1326 }
1327
1328 int _bt_ag_agent_registration_status_convert(int result)
1329 {
1330         switch (result) {
1331         case TAPI_NETWORK_SERVICE_LEVEL_NO:
1332                 return BT_AGENT_NETWORK_REG_STATUS_NOT_REGISTER;
1333         case TAPI_NETWORK_SERVICE_LEVEL_EMERGENCY:
1334                 return BT_AGENT_NETWORK_REG_STATUS_EMERGENCY;
1335         case TAPI_NETWORK_SERVICE_LEVEL_FULL:
1336                 return BT_AGENT_NETWORK_REG_STATUS_REGISTER_HOME_NETWORK;
1337         case TAPI_NETWORK_SERVICE_LEVEL_SEARCH:
1338                 return BT_AGENT_NETWORK_REG_STATUS_SEARCH;
1339         default:
1340                 return BT_AGENT_NETWORK_REG_STATUS_UNKNOWN;
1341         }
1342         return result;
1343 }
1344
1345 void _bt_ag_agent_get_creg_status(void *device)
1346 {
1347         FN_START;
1348         int result = 0;
1349         int ret = 0;
1350         int n = 1;
1351         int registration_status = 0;
1352         int roam_status = 0;
1353
1354         ret = tel_get_property_int(tapi_handle, TAPI_PROP_NETWORK_CIRCUIT_STATUS,
1355                                 &result);
1356         if (ret != TAPI_API_SUCCESS) {
1357                 ERR("tel_get_property_int failed");
1358                 return;
1359         }
1360         registration_status =
1361                         _bt_ag_agent_registration_status_convert(result);
1362
1363         DBG_SECURE("Registration status %d", result);
1364         DBG_SECURE("Mapped Status %d", registration_status);
1365         if (registration_status ==
1366                         BT_AGENT_NETWORK_REG_STATUS_REGISTER_HOME_NETWORK) {
1367                 ret = vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &roam_status);
1368                 if (ret != 0) {
1369                         ERR("Get roaming status failed err = %d\n", ret);
1370                         return;
1371                 }
1372                 DBG_SECURE("Roam status %d", roam_status);
1373                 if (roam_status == 1) {
1374                         registration_status =
1375                                         BT_AGENT_NETWORK_REG_STATUS_REGISTERED_ROAMING;
1376                 }
1377         }
1378
1379         _bt_hfp_get_creg_status_reply(n, registration_status, device);
1380
1381         FN_END;
1382         return;
1383 }
1384
1385 void _bt_ag_agent_get_model_name(void *device)
1386 {
1387         FN_START;
1388         char *model_name;
1389         int ret;
1390
1391         ret = system_info_get_platform_string("http://tizen.org/system/model_name", &model_name);
1392         if (SYSTEM_INFO_ERROR_NONE != ret) {
1393                 ERR("Get model_name failed: %d", ret);
1394                 if (NULL != model_name)
1395                         free(model_name);
1396
1397                 model_name = g_strdup("Unknown");
1398         } else if (!g_utf8_validate(model_name, -1, NULL)) {
1399                 free(model_name);
1400                 model_name = g_strdup("Unknown");
1401                 ERR("get_model_name : invalid UTF8");
1402         }
1403
1404         DBG_SECURE("model_name  = [%s]", model_name);
1405         _bt_hfp_get_model_info_reply(model_name, device);
1406         free(model_name);
1407         FN_END;
1408 }
1409
1410 void _bt_ag_agent_get_revision_information(void *device)
1411 {
1412         FN_START;
1413         char *revision_info;
1414         int ret;
1415
1416         ret = system_info_get_platform_string("http://tizen.org/system/build.string",
1417                                 &revision_info);
1418         if (SYSTEM_INFO_ERROR_NONE != ret) {
1419                 ERR("Get revision_info failed: %d", ret);
1420                 if (NULL != revision_info)
1421                         free(revision_info);
1422
1423                 revision_info = g_strdup("Unknown");
1424         } else if (!g_utf8_validate(revision_info, -1, NULL)) {
1425                         free(revision_info);
1426                         revision_info = g_strdup("Unknown");
1427                         ERR("get_revision_info: invalid UTF8");
1428                 }
1429
1430         DBG_SECURE("revision_info  = [%s]", revision_info);
1431         _bt_hfp_get_revision_info_reply(revision_info, device);
1432         free(revision_info);
1433         FN_END;
1434 }
1435
1436 #if defined(TIZEN_PROFILE_WEARABLE) && defined(TIZEN_FEATURE_BT_HFP_AG)
1437 static gboolean __bt_ag_agent_launch_voice_dial(gboolean activate)
1438 {
1439         FN_START;
1440         bundle *b;
1441
1442         b = bundle_create();
1443         if (NULL == b) {
1444                 ERR("bundle_create() Failed");
1445                 return FALSE;
1446         }
1447
1448         bundle_add(b, "domain", "bt_headset");
1449         if (!activate)
1450                 bundle_add(b, "action_type", "deactivate");
1451
1452         aul_launch_app_async("org.tizen.svoice", b);
1453         bundle_free(b);
1454         FN_END;
1455         return TRUE;
1456 }
1457 #else
1458 static gboolean __bt_ag_agent_launch_voice_dial(gboolean activate)
1459 {
1460         FN_START;
1461         app_control_h service = NULL;
1462
1463         app_control_create(&service);
1464
1465         if (service == NULL) {
1466                 ERR("Service create failed");
1467                 return FALSE;
1468         }
1469
1470         app_control_set_app_id(service, "org.tizen.svoice");
1471         app_control_set_operation(service, APP_CONTROL_OPERATION_DEFAULT);
1472         if (app_control_add_extra_data(service, "domain", "bt_headset")
1473                                         != APP_CONTROL_ERROR_NONE) {
1474                 ERR("app_control_add_extra_data failed");
1475                 app_control_destroy(service);
1476                 return FALSE;
1477         }
1478
1479         if (!activate)
1480                 if (app_control_add_extra_data(service, "action_type", "deactivate")
1481                                         != APP_CONTROL_ERROR_NONE) {
1482                         ERR("app_control_add_extra_data failed");
1483                         app_control_destroy(service);
1484                         return FALSE;
1485                 }
1486
1487         if (app_control_send_launch_request(service, NULL, NULL) !=
1488                                                 APP_CONTROL_ERROR_NONE) {
1489                 ERR("launch failed");
1490                 app_control_destroy(service);
1491                 return FALSE;
1492         }
1493
1494         app_control_destroy(service);
1495         FN_END;
1496         return TRUE;
1497 }
1498 #endif
1499
1500 gboolean _bt_ag_agent_voice_dial(gboolean activate)
1501 {
1502         DBG("Activate = %d", activate);
1503
1504         return __bt_ag_agent_launch_voice_dial(activate);
1505 }
1506
1507 static void __bt_ag_codec_negotiation_info_reset(bt_ag_info_t *hs,
1508                                         gboolean reset)
1509 {
1510         hs->codec_info.is_negotiating = FALSE;
1511         hs->codec_info.requested_by_hf = FALSE;
1512         hs->codec_info.sending_codec = 0;
1513         if (reset) {
1514                 hs->codec_info.remote_codecs = 0;
1515                 hs->codec_info.final_codec = 0;
1516                 hs->nrec_status = FALSE;
1517         }
1518
1519         if (hs->codec_info.nego_timer) {
1520                 g_source_remove(hs->codec_info.nego_timer);
1521                 hs->codec_info.nego_timer = 0;
1522         }
1523         wbs_opts.wbs_enable = wbs_en;
1524 }
1525
1526 static gboolean __bt_ag_codec_negotiation_finished(gpointer user_data)
1527 {
1528         struct ag_codec *data = (struct ag_codec *)user_data;
1529
1530         if (g_strcmp0(data->codec_status, "finish") == 0) {
1531                 DBG("Codec negotiation finished");
1532                 __bt_ag_sco_connect(data->bt_ag_info);
1533                 __bt_ag_codec_negotiation_info_reset(data->bt_ag_info, FALSE);
1534                 g_free(data->codec_status);
1535                 g_free(data);
1536                 return TRUE;
1537         } else if (g_strcmp0(data->codec_status, "timeout") == 0) {
1538                 DBG("Timeout is occured in codec negotiation");
1539         }
1540
1541         if (data->bt_ag_info->codec_info.requested_by_hf) {
1542                 __bt_ag_codec_negotiation_info_reset(data->bt_ag_info, FALSE);
1543         } else {
1544                 __bt_ag_sco_connect(data->bt_ag_info);
1545                 __bt_ag_codec_negotiation_info_reset(data->bt_ag_info, FALSE);
1546         }
1547         g_free(data->codec_status);
1548         g_free(data);
1549
1550         return FALSE;
1551 }
1552
1553 static bt_hfp_agent_error_t __bt_ag_set_codec(void *device, char *method)
1554 {
1555         GDBusProxy *proxy;
1556         GVariant *ret;
1557         GError *err = NULL;
1558         bt_ag_info_t *bt_ag_info = (bt_ag_info_t *)device;
1559
1560         proxy =  g_dbus_proxy_new_sync(ag_dbus_conn,
1561                         G_DBUS_PROXY_FLAGS_NONE, NULL,
1562                         BLUEZ_SERVICE_NAME, DEFAULT_ADAPTER_OBJECT_PATH,
1563                         BT_ADAPTER_INTERFACE, NULL, &err);
1564
1565         if (!proxy) {
1566                 if (err) {
1567                         ERR("Unable to create proxy: %s", err->message);
1568                         g_clear_error(&err);
1569                 }
1570                 return BT_HFP_AGENT_ERROR_INTERNAL;
1571         }
1572
1573         ret = g_dbus_proxy_call_sync(proxy, method,
1574                         g_variant_new("(ss)", "Gateway", bt_ag_info->remote_addr),
1575                         G_DBUS_CALL_FLAGS_NONE, -1,
1576                         NULL, &err);
1577         if (ret == NULL) {
1578                 /* dBUS-RPC is failed */
1579                 ERR("dBUS-RPC is failed");
1580                 if (err != NULL) {
1581                         /* dBUS gives error cause */
1582                         ERR("D-Bus API failure: errCode[%x], message[%s]",
1583                                err->code, err->message);
1584
1585                         g_clear_error(&err);
1586                 }
1587                 return BT_HFP_AGENT_ERROR_INTERNAL;
1588         }
1589         g_variant_unref(ret);
1590
1591         return BT_HFP_AGENT_ERROR_NONE;
1592 }
1593
1594 static bt_hfp_agent_error_t __bt_ag_codec_selection_setup(bt_ag_info_t *hs,
1595                         uint32_t codec)
1596 {
1597         bt_hfp_agent_error_t err = BT_HFP_AGENT_ERROR_NONE;
1598
1599         DBG("Codec setup [%x]", codec);
1600
1601         /* 1. Compare sending codec & recieved code */
1602         if (hs->codec_info.sending_codec != codec)
1603                 err = BT_HFP_AGENT_ERROR_INTERNAL;
1604
1605         /* 2. Send WB or NB command */
1606         switch (codec) {
1607         case BT_CVSD_CODEC_ID:
1608                 err = __bt_ag_set_codec(hs, "SetNbParameters");
1609                 break;
1610         case BT_MSBC_CODEC_ID:
1611                 err = __bt_ag_set_codec(hs, "SetWbsParameters");
1612                 break;
1613         default:
1614                 err = BT_HFP_AGENT_ERROR_INTERNAL;
1615                 break;
1616         }
1617
1618         /* If the vendor specific calling returns error or codec is not correct,
1619          * we send CVSD Codec parameter to MM module. and also returns
1620          * normal value to HF
1621         */
1622         if (err != BT_HFP_AGENT_ERROR_NONE)
1623                 codec = BT_CVSD_CODEC_ID;
1624
1625         hs->codec_info.final_codec = codec;
1626
1627         return err;
1628 }
1629
1630 static bt_hfp_agent_error_t __bt_hfp_send_bcs_command(bt_ag_info_t *hs,
1631                         gboolean init_by_hf)
1632 {
1633         uint32_t codec;
1634         struct ag_codec *data = NULL;;
1635
1636         if (hs->codec_info.remote_codecs & BT_MSBC_CODEC_MASK)
1637                 codec = BT_MSBC_CODEC_ID;
1638         else
1639                 codec = BT_CVSD_CODEC_ID;
1640
1641         if (wbs_opts.wbs_enable == FALSE)
1642                 codec = BT_CVSD_CODEC_ID;
1643
1644         hs->codec = codec;
1645
1646         if (_bt_ag_send_at(hs, "\r\n+BCS: %d\r\n", codec) < 0)
1647                 return BT_HFP_AGENT_ERROR_INTERNAL;
1648         else
1649                 DBG("Send +BCS:%d\n", codec);
1650
1651         /* Send +BCS command to HF, and wait some times */
1652         hs->codec_info.is_negotiating = TRUE;
1653         hs->codec_info.sending_codec = codec;
1654         hs->codec_info.requested_by_hf = init_by_hf;
1655         hs->codec_info.final_codec = codec;
1656
1657         data = g_new0(struct ag_codec, 1);
1658         if (data == NULL)
1659                 return BT_HFP_AGENT_ERROR_NO_MEMORY;
1660
1661         data->bt_ag_info = hs;
1662         data->codec_status = g_strdup("timeout");
1663
1664         hs->codec_info.nego_timer = g_timeout_add_seconds(
1665                         HFP_CODEC_NEGOTIATION_TIMEOUT,
1666                         (GSourceFunc)__bt_ag_codec_negotiation_finished,
1667                         data);
1668
1669         return BT_HFP_AGENT_ERROR_NONE;
1670 }
1671
1672
1673 static bt_hfp_agent_error_t __bt_hfp_codec_connection_setup(
1674                                 bt_ag_info_t *hs, gboolean init_by_hf)
1675 {
1676         DBG("Request to codec connection by %s", init_by_hf ? "HF" : "AG");
1677
1678         if (hs->state < HEADSET_STATE_CONNECTED)
1679                 return BT_HFP_AGENT_ERROR_NOT_CONNECTED;
1680
1681         if (hs->codec_info.is_negotiating == TRUE) {
1682                 /* In codec negotiation, return and wait */
1683                 ERR("Codec nogotiation is in progress");
1684                 return BT_HFP_AGENT_ERROR_BUSY;
1685         }
1686
1687         /* Not support Codec Negotiation or Not recieved BAC command */
1688         if (!(ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) ||
1689                                 hs->codec_info.remote_codecs == 0) {
1690                 ERR("No support for Codec Negotiation or receive BAC command");
1691                 if (init_by_hf) {
1692                         return BT_HFP_AGENT_ERROR_INTERNAL;
1693                 } else {
1694                         __bt_ag_sco_connect(hs);
1695                         return BT_HFP_AGENT_ERROR_INTERNAL;
1696                 }
1697         }
1698
1699         /* If HF initiated codec connection setup, it should send OK command
1700          * before +BCS command transmission.
1701          */
1702         if (init_by_hf)
1703                 return HFP_STATE_MNGR_ERR_NONE;
1704         else
1705                 return __bt_hfp_send_bcs_command(hs, init_by_hf);
1706 }
1707
1708
1709 static int __hfp_parse_available_codecs(const char *cmd, uint32_t *codecs)
1710 {
1711         char *str = NULL;
1712         *codecs = 0x00000000;
1713
1714         str = strchr(cmd, '=');
1715         if (str == NULL)
1716                 return -EINVAL;
1717
1718         while (str != NULL) {
1719                 str++;
1720
1721                 if (atoi(str) == BT_CVSD_CODEC_ID)
1722                         *codecs |= BT_CVSD_CODEC_MASK;
1723                 else if (atoi(str) == BT_MSBC_CODEC_ID)
1724                         *codecs |= BT_MSBC_CODEC_MASK;
1725
1726                 str = strchr(str, ',');
1727         }
1728
1729         if (*codecs == 0x00000000)
1730                 return -EINVAL;
1731
1732         return 0;
1733 }
1734
1735 /* AT+BAC (Bluetooth Available Codecs) */
1736 static int __bt_hfp_available_codecs(bt_ag_info_t *hs, const char *buf)
1737 {
1738         uint32_t codecs = 0x00000000;
1739         hfp_state_manager_err_t err = HFP_STATE_MNGR_ERR_NONE;
1740
1741         if (!(ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION)) {
1742                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1743         } else if (__hfp_parse_available_codecs(buf, &codecs) < 0) {
1744                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1745         } else {
1746                 DBG("Update remote available codecs [%x]", codecs);
1747                 hs->codec_info.remote_codecs = codecs;
1748         }
1749
1750         _bt_ag_send_response(hs, err);
1751
1752         /* Reset codec information and
1753          * restart codec connection setup by AG
1754          */
1755         hs->codec_info.final_codec = 0;
1756         if (hs->codec_info.nego_timer) {
1757                 hs->codec_info.is_negotiating = FALSE;
1758                 hs->codec_info.requested_by_hf = FALSE;
1759                 hs->codec_info.sending_codec = 0;
1760                 g_source_remove(hs->codec_info.nego_timer);
1761                 __bt_hfp_codec_connection_setup(hs, FALSE);
1762         }
1763
1764         return 0;
1765 }
1766
1767 /* AT+BCC (Bluetooth Codec Connection) */
1768 static int __bt_hfp_codec_connection(bt_ag_info_t *hs, const char *buf)
1769 {
1770         hfp_state_manager_err_t err = HFP_STATE_MNGR_ERR_NONE;
1771
1772         err = __bt_hfp_codec_connection_setup(hs, TRUE);
1773
1774         _bt_ag_send_response(hs, err);
1775
1776         if (err == HFP_STATE_MNGR_ERR_NONE)
1777                 err = __bt_hfp_send_bcs_command(hs, TRUE);
1778
1779         if (err != HFP_STATE_MNGR_ERR_NONE)
1780                 ERR("Fail to request codec connection setup");
1781
1782         return 0;
1783 }
1784
1785 /* AT+BCS (Bluetooth Codec Selection) */
1786 static int __bt_hfp_codec_selection(bt_ag_info_t *hs, const char *buf)
1787 {
1788         uint32_t codec = 0x00000000;
1789         hfp_state_manager_err_t err = HFP_STATE_MNGR_ERR_NONE;
1790         struct ag_codec *data = g_new0(struct ag_codec, 1);
1791
1792         /* Timer reset */
1793         if (hs->codec_info.nego_timer) {
1794                 g_source_remove(hs->codec_info.nego_timer);
1795                 hs->codec_info.nego_timer = 0;
1796         }
1797
1798         if (!(ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION))
1799                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1800         else if (__hfp_parse_available_codecs(buf, &codec) < 0)
1801                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1802         else if (__bt_ag_codec_selection_setup(hs, codec) !=
1803                                         BT_HFP_AGENT_ERROR_NONE)
1804                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1805
1806         data->bt_ag_info = hs;
1807         data->codec_status = g_strdup("finish");
1808         _bt_ag_send_response(hs, err);
1809         __bt_ag_codec_negotiation_finished(data);
1810
1811         return 0;
1812 }
1813
1814 static void __bt_ag_str2ba(const char *str, bt_addr *ba)
1815 {
1816         int i;
1817         for (i = 5; i >= 0; i--, str += 3)
1818                 ba->b[i] = strtol(str, NULL, 16);
1819 }
1820
1821 static const char *__bt_ag_state2str(hs_state_t state)
1822 {
1823         switch (state) {
1824         case HEADSET_STATE_DISCONNECTED:
1825                 return "disconnected";
1826         case HEADSET_STATE_CONNECTING:
1827                 return "connecting";
1828         case HEADSET_STATE_CONNECTED:
1829                 return "connected";
1830         case HEADSET_STATE_PLAY_IN_PROGRESS:
1831                 return "Play In Progress";
1832         case HEADSET_STATE_ON_CALL:
1833                 return "On Call";
1834         }
1835
1836         return NULL;
1837 }
1838
1839 void _bt_convert_addr_string_to_type_rev(unsigned char *addr,
1840                 const char *address)
1841 {
1842         int i;
1843         char *ptr = NULL;
1844
1845         ret_if(address == NULL);
1846         ret_if(addr == NULL);
1847
1848         for (i = 0; i < 6; i++) {
1849                 addr[5 - i] = strtol(address, &ptr, 16);
1850                 if (ptr[0] != '\0') {
1851                         if (ptr[0] != ':')
1852                                 return;
1853
1854                         address = ptr + 1;
1855                 }
1856         }
1857 }
1858
1859 static gboolean __bt_ag_check_nval(GIOChannel *chan)
1860 {
1861         struct pollfd file_desc;
1862
1863         memset(&file_desc, 0, sizeof(file_desc));
1864         file_desc.fd = g_io_channel_unix_get_fd(chan);
1865         file_desc.events = POLLNVAL;
1866
1867         if (poll(&file_desc, 1, 0) > 0 && (POLLNVAL & file_desc.revents))
1868                 return TRUE;
1869
1870         return FALSE;
1871 }
1872
1873 static int __bt_ag_sco_connect(bt_ag_info_t *hs)
1874 {
1875         struct sco_socket_addr sco_addr;
1876         int err;
1877         GIOChannel *io;
1878         int sco_skt;
1879         bt_voice bt_vo;
1880         bt_ag_slconn_t *slconn = hs->slc;
1881         /*guint watch_id;*/
1882
1883         if (hs->state == HEADSET_STATE_ON_CALL)
1884                 return BT_HFP_AGENT_ERROR_ALREADY_CONNECTED;
1885
1886         if (hs->state != HEADSET_STATE_CONNECTED)
1887                 return BT_HFP_AGENT_ERROR_NOT_CONNECTED;
1888 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
1889         _bt_ag_agent_check_transport_state();
1890 #endif
1891
1892         /* Create Sco socket */
1893         sco_skt = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BT_SCO_PRTCL);
1894         if (sco_skt < 0) {
1895                 ERR("ERROR: Create socket failed.\n");
1896                 return BT_HFP_AGENT_ERROR_INTERNAL;
1897         }
1898
1899         /* Bind Sco Socket to Local BD addr */
1900         memset(&sco_addr, 0, sizeof(sco_addr));
1901         sco_addr.sco_family = AF_BLUETOOTH;
1902
1903         __bt_ag_str2ba(local_addr, &sco_addr.sco_bdaddr);
1904         DBG("Local BD address: %s", local_addr);
1905
1906         err = bind(sco_skt, (struct sockaddr *) &sco_addr, sizeof(sco_addr));
1907         if (err < 0) {
1908                 ERR("ERROR: sco socket binding failed");
1909                 ERR("Close SCO skt");
1910                 close(sco_skt);
1911                 return BT_HFP_AGENT_ERROR_INTERNAL;
1912         }
1913
1914         DBG("Socket FD : %d", sco_skt);
1915
1916         io = g_io_channel_unix_new(sco_skt);
1917         g_io_channel_set_close_on_unref(io, TRUE);
1918         /*g_io_channel_set_flags(io, G_IO_FLAG_NONBLOCK, NULL);
1919         g_io_channel_set_buffered(io, FALSE);
1920         g_io_channel_set_encoding(io, NULL, NULL);*/
1921
1922         if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
1923                 (slconn && (slconn->hs_features &
1924                         BT_HF_FEATURE_CODEC_NEGOTIATION)) &&
1925                         wbs_opts.wbs_enable == TRUE) {
1926                 bt_vo.setting = (hs->codec == BT_MSBC_CODEC_ID) ?
1927                                 BT_HFP_MSBC_VOICE : BT_HFP_CVSD_VOICE;
1928
1929                 DBG("set Bluetooth voice: %d", bt_vo.setting);
1930                 err = setsockopt(sco_skt, BT_SOCKET_LEVEL,
1931                                         BT_VOICE_NUM, &bt_vo, sizeof(bt_vo));
1932                 if (err < 0) {
1933                         ERR("ERROR: sco socket set socket option failed");
1934                         ERR("Close SCO skt");
1935                         g_io_channel_unref(io);
1936                         close(sco_skt);
1937                         return BT_HFP_AGENT_ERROR_INTERNAL;
1938                 }
1939         } else {
1940                 DBG("Set NB codec parameter");
1941                 __bt_ag_set_codec(hs, "SetNbParameters");
1942         }
1943
1944         memset(&sco_addr, 0, sizeof(sco_addr));
1945         sco_addr.sco_family = AF_BLUETOOTH;
1946         __bt_ag_str2ba(hs->remote_addr, &sco_addr.sco_bdaddr);
1947         DBG("remotel BD address: %s", hs->remote_addr);
1948
1949         err = connect(sco_skt, (struct sockaddr *) &sco_addr, sizeof(sco_addr));
1950         if (err < 0 && !(errno == EINPROGRESS || errno == EAGAIN)) {
1951                 ERR("ERROR: sco socket connect failed : %d", err);
1952                 ERR("Close SCO skt");
1953                 g_io_channel_unref(io);
1954                 close(sco_skt);
1955                 return BT_HFP_AGENT_ERROR_INTERNAL;
1956         }
1957
1958         /* Disabling the watch since SCO is connected */
1959         /*watch_id = __bt_ag_set_watch(io,
1960                         (GIOFunc) __bt_ag_sco_connect_cb, hs);
1961         if (watch_id)
1962                 DBG("SCO watch set Success");*/
1963
1964         hs->sco = io;
1965
1966         _bt_ag_set_headset_state(hs, HEADSET_STATE_ON_CALL);
1967         return BT_HFP_AGENT_ERROR_NONE;
1968 }
1969
1970 static void __bt_ag_close_sco(bt_ag_info_t *hs)
1971 {
1972         DBG("");
1973         if (hs->sco) {
1974                 int sock = g_io_channel_unix_get_fd(hs->sco);
1975                 shutdown(sock, SHUT_RDWR);
1976                 g_io_channel_unref(hs->sco);
1977                 hs->sco = NULL;
1978         }
1979
1980         if (hs->sco_id)
1981                 __bt_ag_agent_remove_watch(&hs->sco_id);
1982
1983         if (hs->sco_incoming_id)
1984                 __bt_ag_agent_remove_watch(&hs->sco_incoming_id);
1985 }
1986
1987 static gboolean __bt_ag_sco_server_conn_cb(GIOChannel *chan,
1988                                 GIOCondition cond, gpointer user_data)
1989 {
1990         bt_ag_info_t *ag_info = user_data;
1991
1992         DBG("");
1993         if (cond & G_IO_NVAL)
1994                 return FALSE;
1995
1996         if (cond & (G_IO_HUP | G_IO_ERR)) {
1997                 ag_info->sco = NULL;
1998                 if (ag_info->sco_id)
1999                         __bt_ag_agent_remove_watch(&ag_info->sco_id);
2000
2001                 if (ag_info->sco_incoming_id)
2002                         __bt_ag_agent_remove_watch(&ag_info->sco_incoming_id);
2003
2004                 if (ag_info->watch_id)
2005                         _bt_ag_set_headset_state(ag_info, HEADSET_STATE_CONNECTED);
2006                 return FALSE;
2007         }
2008         return TRUE;
2009 }
2010
2011 static gboolean __bt_ag_sco_server_cb(GIOChannel *chan,
2012                                 GIOCondition cond, gpointer user_data)
2013 {
2014         bt_ag_info_t *ag_info = user_data;
2015         int sco_skt;
2016         int cli_sco_sock;
2017         GIOChannel *sco_io;
2018         bt_ag_slconn_t *slconn = ag_info->slc;
2019         bt_voice bt_vo;
2020         int err;
2021
2022         if ((cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) ||
2023                                 __bt_ag_check_nval(chan)) {
2024                 ERR("cond or chan is not valid");
2025                 return FALSE;
2026         }
2027
2028         INFO_C("Incoming SCO....");
2029
2030         if (ag_info->state < HEADSET_STATE_CONNECTED)
2031                 return BT_HFP_AGENT_ERROR_NOT_CONNECTED;
2032
2033         sco_skt = g_io_channel_unix_get_fd(chan);
2034
2035         cli_sco_sock = accept(sco_skt, NULL, NULL);
2036         if (cli_sco_sock < 0) {
2037                 ERR("accept is failed");
2038                 return TRUE;
2039         }
2040
2041         sco_io = g_io_channel_unix_new(cli_sco_sock);
2042         g_io_channel_set_close_on_unref(sco_io, TRUE);
2043         g_io_channel_set_encoding(sco_io, NULL, NULL);
2044         g_io_channel_set_flags(sco_io, G_IO_FLAG_NONBLOCK, NULL);
2045         g_io_channel_set_buffered(sco_io, FALSE);
2046
2047         if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
2048                 (slconn && (slconn->hs_features &
2049                         BT_HF_FEATURE_CODEC_NEGOTIATION)) &&
2050                         wbs_opts.wbs_enable == TRUE) {
2051                 bt_vo.setting = (ag_info->codec == BT_MSBC_CODEC_ID) ?
2052                                 BT_HFP_MSBC_VOICE : BT_HFP_CVSD_VOICE;
2053
2054                 DBG("set Bluetooth voice: %d", bt_vo.setting);
2055                 err = setsockopt(cli_sco_sock, BT_SOCKET_LEVEL,
2056                                         BT_VOICE_NUM, &bt_vo, sizeof(bt_vo));
2057                 if (err < 0) {
2058                         ERR("Sco socket set socket option failed");
2059                         close(cli_sco_sock);
2060                         return FALSE;
2061                 }
2062         }
2063
2064         ag_info->sco = sco_io;
2065         ag_info->sco_incoming_id = g_io_add_watch(sco_io, G_IO_HUP | G_IO_ERR | G_IO_NVAL,
2066                                         __bt_ag_sco_server_conn_cb, ag_info);
2067
2068         if (remote_dev_path)
2069                 g_free(remote_dev_path);
2070
2071         remote_dev_path = g_strdup(ag_info->path);
2072
2073         _bt_ag_set_headset_state(ag_info, HEADSET_STATE_ON_CALL);
2074
2075         return TRUE;
2076 }
2077
2078 static int __bt_ag_start_sco_server(bt_ag_info_t *hs)
2079 {
2080         DBG("Start SCO server");
2081         struct sco_socket_addr addr;
2082         GIOChannel *sco_io;
2083         int sco_skt;
2084         bdaddr_t bd_addr = {{0},};
2085
2086         if (hs->sco_server_started) {
2087                 DBG("Already exsist");
2088                 return BT_HFP_AGENT_ERROR_ALREADY_EXSIST;
2089         }
2090
2091         /* Create socket */
2092         sco_skt = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BT_SCO_PRTCL);
2093         if (sco_skt < 0) {
2094                 ERR("Can't create socket:\n");
2095                 return BT_HFP_AGENT_ERROR_INTERNAL;
2096         }
2097
2098         /* Bind to local address */
2099         memset(&addr, 0, sizeof(addr));
2100         addr.sco_family = AF_BLUETOOTH;
2101
2102         _bt_convert_addr_string_to_type_rev(bd_addr.b, hs->remote_addr);
2103         DBG("Bind to address %s", hs->remote_addr);
2104         memcpy(&addr.sco_bdaddr, &bd_addr, sizeof(bdaddr_t));
2105
2106         if (bind(sco_skt, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
2107                 ERR("Can't bind socket:\n");
2108                 goto error;
2109         }
2110
2111         if (listen(sco_skt, 1)) {
2112                 ERR("Can not listen on the socket:\n");
2113                 goto error;
2114         }
2115
2116         sco_io = g_io_channel_unix_new(sco_skt);
2117         g_io_channel_set_close_on_unref(sco_io, TRUE);
2118         g_io_channel_set_encoding(sco_io, NULL, NULL);
2119         g_io_channel_set_flags(sco_io, G_IO_FLAG_NONBLOCK, NULL);
2120         g_io_channel_set_buffered(sco_io, FALSE);
2121
2122         hs->sco_server = sco_io;
2123         hs->sco_watch_id = g_io_add_watch(sco_io,
2124                         G_IO_IN | G_IO_HUP | G_IO_ERR |
2125                         G_IO_NVAL, __bt_ag_sco_server_cb, hs);
2126
2127         hs->sco_server_started = TRUE;
2128         return BT_HFP_AGENT_ERROR_NONE;
2129
2130 error:
2131         close(sco_skt);
2132         return BT_HFP_AGENT_ERROR_INTERNAL;
2133 }
2134
2135 void __bt_ag_stop_sco_server(bt_ag_info_t *hs)
2136 {
2137         DBG("Stop SCO server");
2138         if (hs->sco_server) {
2139                 g_io_channel_shutdown(hs->sco_server, TRUE, NULL);
2140                 g_io_channel_unref(hs->sco_server);
2141                 hs->sco_server = NULL;
2142         }
2143         hs->sco_server_started = FALSE;
2144 }
2145
2146 static int __bt_ag_headset_close_rfcomm(bt_ag_info_t *hs)
2147 {
2148         GIOChannel *rfcomm = hs->rfcomm;
2149
2150         if (rfcomm) {
2151                 g_io_channel_shutdown(rfcomm, TRUE, NULL);
2152                 g_io_channel_unref(rfcomm);
2153                 hs->rfcomm = NULL;
2154         }
2155
2156         g_free(hs->slc);
2157         hs->slc = NULL;
2158
2159         return 0;
2160 }
2161
2162 static gboolean __bt_ag_sco_cb(GIOChannel *chan, GIOCondition cond,
2163                         bt_ag_info_t *hs)
2164 {
2165         if (cond & G_IO_NVAL)
2166                 return FALSE;
2167
2168         if (name_owner_sig_id != -1)
2169                 g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
2170                                         name_owner_sig_id);
2171         name_owner_sig_id = -1;
2172         g_free(sco_owner);
2173         sco_owner = NULL;
2174
2175         DBG("Audio connection disconnected");
2176         _bt_ag_set_headset_state(hs, HEADSET_STATE_CONNECTED);
2177
2178         return FALSE;
2179 }
2180
2181 void _bt_ag_set_headset_state(bt_ag_info_t *hs, hs_state_t state)
2182 {
2183         bt_ag_slconn_t *slconn = hs->slc;
2184         const char *hs_state;
2185         hs_state_t org_state = hs->state;
2186         gboolean val = FALSE;
2187
2188         if (org_state == state)
2189                 return;
2190
2191         hs_state = __bt_ag_state2str(state);
2192
2193         switch (state) {
2194         case HEADSET_STATE_CONNECTING:
2195                 _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2196                                         hs->path,
2197                                         BT_HEADSET_INTERFACE, "State",
2198                                         g_variant_new("s", hs_state));
2199                 hs->state = state;
2200                 break;
2201
2202         case HEADSET_STATE_CONNECTED:
2203                 if (hs->state != HEADSET_STATE_PLAY_IN_PROGRESS)
2204                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2205                                         hs->path,
2206                                         BT_HEADSET_INTERFACE, "State",
2207                                         g_variant_new("s", hs_state));
2208
2209                 if (hs->state < state) {
2210                         val = TRUE;
2211                         active_devices = g_slist_append(active_devices, hs);
2212                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2213                                                 hs->path,
2214                                                 BT_HEADSET_INTERFACE,
2215                                                 "Connected",
2216                                                 g_variant_new("b", val));
2217
2218                         DBG("Device %s connected\n", hs->remote_addr);
2219 #if defined(TIZEN_SUPPORT_DUAL_HF)
2220                          if (!hs->is_companion_device)
2221                                 __bt_ag_start_sco_server(hs);
2222 #else
2223                         __bt_ag_start_sco_server(hs);
2224 #endif
2225
2226                         /* Set default code as Gateway NB */
2227                         __bt_ag_set_codec(hs, "SetNbParameters");
2228                 } else if (hs->state == HEADSET_STATE_ON_CALL) {
2229                         val = FALSE;
2230                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2231                                                 hs->path,
2232                                                 BT_HEADSET_INTERFACE,
2233                                                 "Playing",
2234                                                 g_variant_new("b", val));
2235                 }
2236                 hs->state = state;
2237                 break;
2238
2239         case HEADSET_STATE_DISCONNECTED:
2240                 __bt_ag_close_sco(hs);
2241                 __bt_ag_headset_close_rfcomm(hs);
2242
2243                 if (hs->state == HEADSET_STATE_ON_CALL) {
2244                         val = FALSE;
2245                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2246                                                 hs->path,
2247                                                 BT_HEADSET_INTERFACE,
2248                                                 "Playing",
2249                                                 g_variant_new("b", val));
2250                 }
2251
2252                 val = FALSE;
2253                 _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2254                                 hs->path,
2255                                 BT_HEADSET_INTERFACE,
2256                                 "Connected",
2257                                 g_variant_new("b", val));
2258                 if (hs->state > HEADSET_STATE_CONNECTING)
2259                         _bt_hfp_device_disconnected(hs);
2260
2261                 active_devices = g_slist_remove(active_devices, hs);
2262
2263                 __bt_ag_codec_negotiation_info_reset(hs, TRUE);
2264 #if 0 /* SCO is crashed if below is called when SCO is opened by hf-agent */
2265                 __bt_ag_set_codec(hs, "SetNbParameters");
2266 #endif
2267                 hs->codec = 0;
2268
2269                 /* Since SCO server is binded on remote address */
2270                 /* Need to stop SCO server once heasdet disconencted*/
2271                 if (hs->sco_server_started)
2272                         __bt_ag_stop_sco_server(hs);
2273
2274                 g_free(hs->remote_addr);
2275                 g_free(hs);
2276                 break;
2277
2278         case HEADSET_STATE_PLAY_IN_PROGRESS:
2279         case HEADSET_STATE_ON_CALL:
2280                 val = TRUE;
2281                 _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2282                                         hs->path,
2283                                         BT_HEADSET_INTERFACE, "State",
2284                                         g_variant_new("s", hs_state));
2285
2286                 /*add watch for sco data */
2287                 hs->sco_id = g_io_add_watch(hs->sco,
2288                                         G_IO_ERR | G_IO_NVAL,
2289                                         (GIOFunc) __bt_ag_sco_cb, hs);
2290
2291                 _bt_ag_agent_emit_property_changed(
2292                                 ag_dbus_conn, hs->path,
2293                                 BT_HEADSET_INTERFACE, "Playing",
2294                                 g_variant_new("b", val));
2295
2296                 if (slconn->microphone_gain >= 0)
2297                         _bt_ag_send_at(hs, "\r\n+VGM=%u\r\n",
2298                                 slconn->microphone_gain);
2299
2300                 if (slconn->speaker_gain >= 0)
2301                         _bt_ag_send_at(hs, "\r\n+VGS=%u\r\n",
2302                                 slconn->speaker_gain);
2303
2304                 hs->state = state;
2305                 break;
2306
2307         default:
2308                 hs->state = state;
2309                 break;
2310         }
2311
2312         INFO("STATE CHANGED from [%s(%d)] to [%s(%d)]",
2313                 __bt_ag_state2str(org_state), org_state, __bt_ag_state2str(state), state);
2314 }
2315
2316 static struct event at_event_callbacks[] = {
2317         { "AT+BRSF", _bt_hfp_supported_features },
2318         { "AT+CIND", _bt_hfp_report_indicators },
2319         { "AT+CMER", _bt_hfp_enable_indicators },
2320         { "AT+CHLD", _bt_hfp_call_hold },
2321         { "ATA", _bt_hfp_answer_call },
2322         { "ATD", _bt_hfp_dial_number },
2323         { "AT+VG", _bt_hfp_signal_gain_setting },
2324         { "AT+CHUP", _bt_hfp_terminate_call },
2325         { "AT+CKPD", _bt_hfp_key_press },
2326         { "AT+CLIP", _bt_hfp_cli_notification },
2327         { "AT+BTRH", _bt_hfp_response_and_hold },
2328         { "AT+BLDN", _bt_hfp_last_dialed_number },
2329         { "AT+VTS", _bt_hfp_dtmf_tone },
2330         { "AT+CNUM", _bt_hfp_subscriber_number },
2331         { "AT+CLCC", _bt_hfp_list_current_calls },
2332         { "AT+CMEE", _bt_hfp_extended_errors },
2333         { "AT+CCWA", _bt_hfp_call_waiting_notify },
2334         { "AT+COPS", _bt_hfp_operator_selection },
2335         { "AT+NREC", _bt_hfp_nr_and_ec },
2336         { "AT+BVRA", _bt_hfp_voice_dial },
2337         { "AT+XAPL", _bt_hfp_apl_command },
2338         { "AT+IPHONEACCEV", _bt_hfp_apl_command },
2339         { "AT+BIA", _bt_hfp_indicators_activation },
2340         { "AT+CPBS", _bt_hfp_select_pb_memory },
2341         { "AT+CPBR", _bt_hfp_read_pb_entries},
2342         { "AT+CPBF", _bt_hfp_find_pb_entires },
2343         { "AT+CSCS", _bt_hfp_select_character_set },
2344         { "AT+CSQ", _bt_hfp_get_signal_quality },
2345         { "AT+CBC", _bt_hfp_get_battery_charge_status },
2346         { "AT+CPAS", _bt_hfp_get_activity_status },
2347         { "AT+CGSN", _bt_hfp_get_equipment_identity },
2348         { "AT+CGMM", _bt_hfp_get_model_information },
2349         { "AT+CGMI", _bt_hfp_get_device_manufacturer },
2350         { "AT+CGMR", _bt_hfp_get_revision_information },
2351         { "AT+BAC", __bt_hfp_available_codecs },
2352         { "AT+BCC", __bt_hfp_codec_connection },
2353         { "AT+BCS", __bt_hfp_codec_selection },
2354         { "AT+XSAT", _bt_hfp_vendor_cmd },
2355         { "AT+CIMI", _bt_hfp_get_imsi },
2356         { "AT+CREG", _bt_hfp_get_creg_status },
2357         { 0 }
2358 };
2359
2360 int num_of_secure_command = 4;
2361 static const char* secure_command[] = {"CLCC", "CLIP", "CPBR", "CCWA"};
2362
2363 void __bt_ag_agent_print_at_buffer(char *message, const char *buf)
2364 {
2365
2366         int i = 0;
2367         char s[MAX_BUFFER_SIZE] = {0, };
2368         gboolean hide = FALSE;
2369
2370         gboolean is_security_command = FALSE;
2371         char *xsat_ptr;
2372
2373         strncpy(s, buf, MAX_BUFFER_SIZE - 1);
2374
2375         for (i = 0; i < num_of_secure_command; i++) {
2376                 if (strstr(buf, secure_command[i])) {
2377                         is_security_command = TRUE;
2378                         break;
2379                 }
2380         }
2381
2382         /* +XSAT: 11,DISC */
2383         xsat_ptr =  strstr(s, "11,DISC,");
2384         if (xsat_ptr) {
2385                 xsat_ptr = xsat_ptr + 8;
2386                 int x = 0;
2387                 while (xsat_ptr[x] != '\0' && xsat_ptr[x] != '\r' && xsat_ptr[x] != '\n') {
2388                         xsat_ptr[x] = 'X';
2389                         x++;
2390                 }
2391         }
2392
2393         /* AT+XSAT=11,Q_CT,X,XXXX */
2394         xsat_ptr =  strstr(s, "11,Q_CT,");
2395         if (xsat_ptr) {
2396                 xsat_ptr = xsat_ptr + 8;
2397                 int x = 0;
2398                 while (xsat_ptr[x] != '\0' && xsat_ptr[x] != '\r' && xsat_ptr[x] != '\n') {
2399                         if (x > 1) /* ignore 0 and 1 position */
2400                                 xsat_ptr[x] = 'X';
2401                         x++;
2402                 }
2403         }
2404
2405         i = 0;
2406         while (s[i] != '\0') {
2407                 if (s[i] == '\r' || s[i] == '\n') {
2408                         s[i] = '.';
2409                 } else {
2410                         if (s[i] == '\"')
2411                                 hide = hide ? FALSE : TRUE;
2412                         else if (is_security_command && hide) {
2413                                 if (i % 2)
2414                                         s[i] = 'X';
2415                         }
2416                 }
2417                 i++;
2418         }
2419         if (message)
2420                 INFO("%s Buffer = [%s], Len(%d)", message, s, strlen(s));
2421         else
2422                 INFO("[%s]", s);
2423 }
2424
2425 static int __bt_ag_at_handler(bt_ag_info_t *hs, const char *buf)
2426 {
2427         struct event *ev;
2428
2429         __bt_ag_agent_print_at_buffer("[AG AT CMD][RCVD] :", buf);
2430
2431         for (ev = at_event_callbacks; ev->cmd; ev++) {
2432                 if (!strncmp(buf, ev->cmd, strlen(ev->cmd)))
2433                         return ev->callback(hs, buf);
2434         }
2435
2436         return -EINVAL;
2437 }
2438
2439 static int __bt_ag_send_at_valist(bt_ag_info_t *hdset, va_list list,
2440                         char *list_format)
2441 {
2442         ssize_t final_written, count;
2443         char rsp_buffer[MAX_BUFFER_SIZE];
2444         int fd;
2445         int err;
2446
2447         count = vsnprintf(rsp_buffer, sizeof(rsp_buffer), list_format, list);
2448         if (count < 0) {
2449                 ERR("count is %d", count);
2450                 return -EINVAL;
2451         }
2452
2453         if (!hdset->io_chan) {
2454                 ERR("__bt_ag_send_at_valist: headset not connected");
2455                 return -EIO;
2456         }
2457
2458         final_written = 0;
2459
2460         fd = g_io_channel_unix_get_fd(hdset->io_chan);
2461
2462         if (fd != 0) {
2463                 while (final_written < count) {
2464                         ssize_t written;
2465
2466                         do {
2467                                 written = write(fd, rsp_buffer + final_written,
2468                                                 count - final_written);
2469                         } while (written < 0 && errno == EINTR);
2470
2471                         if (written < 0) {
2472                                 err = -errno;
2473                                 ERR("write failed : %s (%d)", strerror(-err), -err);
2474                                 return -errno;
2475                         }
2476
2477                         final_written += written;
2478                 }
2479
2480                 /* Synchronize the sending buffer */
2481                 sync();
2482                 fsync(fd);
2483         } else {
2484                 ERR("FD is 0. remote_addr : %s", hdset->remote_addr);
2485                 return -1;
2486         }
2487
2488         __bt_ag_agent_print_at_buffer("[AG AT CMD][SENT]", rsp_buffer);
2489
2490         return 0;
2491 }
2492
2493 int __attribute__((format(printf, 2, 3)))
2494                         _bt_ag_send_at(bt_ag_info_t *hs, char *format, ...)
2495 {
2496         va_list ap;
2497         int ret;
2498
2499         va_start(ap, format);
2500         ret = __bt_ag_send_at_valist(hs, ap, format);
2501         va_end(ap);
2502
2503         return ret;
2504 }
2505
2506 void __attribute__((format(printf, 3, 4)))
2507                 _bt_ag_send_foreach_headset(GSList *devices,
2508                                 int (*cmp) (bt_ag_info_t *hs),
2509                                 char *format, ...)
2510 {
2511         GSList *l;
2512         va_list ap;
2513
2514         for (l = devices; l != NULL; l = l->next) {
2515                 bt_ag_info_t *hs = l->data;
2516                 int ret;
2517
2518                 if (cmp && cmp(hs) != 0)
2519                         continue;
2520
2521                 va_start(ap, format);
2522                 ret = __bt_ag_send_at_valist(hs, ap, format);
2523                 if (ret < 0)
2524                         ERR("Failed to send to headset: %s (%d)",
2525                                         strerror(-ret), -ret);
2526                 va_end(ap);
2527         }
2528 }
2529
2530 int _bt_ag_send_response(bt_ag_info_t *hs, hfp_state_manager_err_t err)
2531 {
2532         if ((err != HFP_STATE_MNGR_ERR_NONE) && hs->slc->is_cme_enabled)
2533                 return _bt_ag_send_at(hs, "\r\n+CME ERROR: %d\r\n", err);
2534
2535         switch (err) {
2536         case HFP_STATE_MNGR_ERR_NONE:
2537                 return _bt_ag_send_at(hs, "\r\nOK\r\n");
2538         case HFP_STATE_MNGR_ERR_NO_NETWORK_SERVICE:
2539                 return _bt_ag_send_at(hs, "\r\nNO CARRIER\r\n");
2540         default:
2541                 return _bt_ag_send_at(hs, "\r\nERROR\r\n");
2542         }
2543 }
2544
2545 static gboolean __bt_ag_event_handler(GIOChannel *channel,
2546                                 GIOCondition cond, void *user_data)
2547 {
2548         bt_ag_slconn_t *slconn;
2549         unsigned char event_buf[MAX_BUFFER_SIZE];
2550         ssize_t len;
2551         size_t available_buffer;
2552         int fd;
2553         bt_ag_info_t *bt_ag_info = (bt_ag_info_t *)user_data;
2554         int err_return = 0;
2555
2556
2557         if (cond & G_IO_NVAL)
2558                 return FALSE;
2559
2560         slconn = bt_ag_info->slc;
2561         if (cond & (G_IO_ERR | G_IO_HUP)) {
2562                 if (bt_ag_info->watch_id)
2563                         __bt_ag_agent_remove_watch(&bt_ag_info->watch_id);
2564
2565                 ERR("ERR or HUP on RFCOMM socket");
2566                 INFO_C("Disconnected [AG role] [Terminated by remote dev]");
2567                 goto failed;
2568         }
2569
2570         fd = g_io_channel_unix_get_fd(channel);
2571         len = read(fd, event_buf, sizeof(event_buf) - 1);
2572
2573         if (len < 0)
2574                 return FALSE;
2575         available_buffer = sizeof(slconn->buffer) - (slconn->start) -
2576                                 (slconn->length) - 1;
2577         if (available_buffer < (size_t) len) {
2578                 ERR("Buffer over flow");
2579                 goto failed;
2580         }
2581
2582         memcpy(&slconn->buffer[slconn->start + slconn->length], event_buf, len);
2583         slconn->length += len;
2584
2585         slconn->buffer[slconn->start + slconn->length] = '\0';
2586
2587         while (slconn->length > 0) {
2588                 char *get_cr;
2589                 int err;
2590                 off_t cmd_len;
2591
2592                 get_cr = strchr(&slconn->buffer[slconn->start], '\r');
2593                 if (!get_cr) {
2594                         ERR("Broken AT command received, break");
2595                         break;
2596                 }
2597
2598                 cmd_len = 1 + (off_t) get_cr -
2599                         (off_t) &slconn->buffer[slconn->start];
2600                 *get_cr = '\0';
2601
2602                 if (cmd_len > 1) {
2603                         DBG("Call AT handler");
2604                         err = __bt_ag_at_handler(bt_ag_info,
2605                                         &slconn->buffer[slconn->start]);
2606                 } else {
2607                         ERR("Failed to call AT handler");
2608                         err = 0;
2609                 }
2610
2611                 if (err < 0) {
2612                         switch (err) {
2613                         case -EINVAL:
2614                                 err_return = HFP_STATE_MNGR_ERR_NOT_SUPPORTED;
2615                                 break;
2616                         case -EACCES:
2617                                 err_return = HFP_STATE_MNGR_ERR_NOT_ALLOWED;
2618                                 break;
2619                         default:
2620                                 err_return = HFP_STATE_MNGR_ERR_NOT_SUPPORTED;
2621                                 break;
2622                         }
2623                         ERR("Error handling command %s: %s (%d)",
2624                                                 &slconn->buffer[slconn->start],
2625                                                 strerror(-err), -err);
2626                         err = _bt_ag_send_response(bt_ag_info,
2627                                         err_return);
2628                         if (err < 0)
2629                                 goto failed;
2630                 }
2631
2632                 slconn->start += cmd_len;
2633                 slconn->length -= cmd_len;
2634
2635                 if (slconn->length <= 0)
2636                         slconn->start = 0;
2637         }
2638         return TRUE;
2639 failed:
2640         ERR("Failed in event handler - SLC Disconnect");
2641         _bt_ag_set_headset_state(bt_ag_info,
2642                                         HEADSET_STATE_DISCONNECTED);
2643         return FALSE;
2644 }
2645
2646 static gboolean __bt_ag_agent_connection(gint32 fd, const gchar *device_path,
2647                                                 const gchar *object_path)
2648 {
2649         GIOFlags flags;
2650
2651         bt_ag_info_t *bt_ag_info = g_new0(bt_ag_info_t, 1);
2652         struct sockaddr_remote address;
2653         socklen_t address_len;
2654
2655         INFO_C("Connected [AG role]");
2656         bt_ag_info->rfcomm = NULL;
2657         bt_ag_info->slc = NULL;
2658         bt_ag_info->hfp_active = TRUE;
2659         bt_ag_info->vr_blacklisted = FALSE;
2660         bt_ag_info->state = HEADSET_STATE_DISCONNECTED;
2661         bt_ag_info->sco_server_started = FALSE;
2662         __bt_ag_codec_negotiation_info_reset(bt_ag_info, TRUE);
2663
2664         bt_ag_info->path = device_path;
2665         DBG("device_path = [%s]", device_path);
2666
2667         address_len = sizeof(address);
2668         if (getpeername(fd, (struct sockaddr *) &address, &address_len) != 0)
2669                 ERR("BD_ADDR is NULL");
2670
2671         DBG("RFCOMM connection for HFP/HSP is completed. Fd = [%d]", fd);
2672         bt_ag_info->fd = fd;
2673         bt_ag_info->io_chan = g_io_channel_unix_new(bt_ag_info->fd);
2674         flags = g_io_channel_get_flags(bt_ag_info->io_chan);
2675
2676         flags &= ~G_IO_FLAG_NONBLOCK;
2677         flags &= G_IO_FLAG_MASK;
2678         g_io_channel_set_flags(bt_ag_info->io_chan, flags, NULL);
2679         g_io_channel_set_encoding(bt_ag_info->io_chan, NULL, NULL);
2680         g_io_channel_set_buffered(bt_ag_info->io_chan, FALSE);
2681
2682         bt_ag_info->rfcomm = g_io_channel_ref(bt_ag_info->io_chan);
2683
2684         bt_ag_info->remote_addr = g_malloc0(BT_ADDRESS_STRING_SIZE);
2685         __bt_convert_addr_type_to_rev_string(bt_ag_info->remote_addr,
2686                                                 address.remote_bdaddr.b);
2687
2688 #if defined(TIZEN_SUPPORT_DUAL_HF)
2689         bt_ag_info->is_companion_device =
2690                         __bt_ag_agent_is_companion_device(bt_ag_info->remote_addr);
2691 #endif
2692
2693         DBG("remote Device Address = [%s]", bt_ag_info->remote_addr);
2694
2695         if (g_strcmp0(object_path, BT_HS_AG_AGENT_OBJECT_PATH) == 0) {
2696                 DBG("HSP connection completed");
2697                 _bt_ag_set_headset_state(bt_ag_info,
2698                                                 HEADSET_STATE_CONNECTED);
2699         } else {
2700                 DBG("HFP connection connecting");
2701                 _bt_ag_set_headset_state(bt_ag_info,
2702                                                 HEADSET_STATE_CONNECTING);
2703         }
2704
2705         __bt_ag_agent_start_watch(bt_ag_info);
2706
2707         bt_ag_info->slc = g_new0(bt_ag_slconn_t, 1);
2708         bt_ag_info->slc->speaker_gain = 15;
2709         bt_ag_info->slc->microphone_gain = 15;
2710         bt_ag_info->slc->is_nrec = TRUE;
2711
2712         return TRUE;
2713 }
2714
2715 static gboolean __bt_ag_agent_is_device_vr_blacklisted(const char *lap_addr)
2716 {
2717         char *buffer;
2718         FILE *fp;
2719         long size;
2720         size_t result;
2721         char *token;
2722         char *saveptr;
2723
2724         fp = fopen(AGENT_VR_BLACKLIST_FILE, "r");
2725
2726         if (fp == NULL) {
2727                 ERR("Unable to open VR blacklist file");
2728                 return FALSE;
2729         }
2730
2731         fseek(fp, 0, SEEK_END);
2732         size = ftell(fp);
2733         if (size <= 0) {
2734                 ERR("size is not a positive number");
2735                 fclose(fp);
2736                 return FALSE;
2737         }
2738
2739         rewind(fp);
2740
2741         buffer = g_malloc0(sizeof(char) * size);
2742         if (buffer == NULL) {
2743                 ERR("g_malloc0 is failed");
2744                 fclose(fp);
2745                 return FALSE;
2746         }
2747         result = fread((char *)buffer, 1, size, fp);
2748         fclose(fp);
2749         if (result != size) {
2750                 ERR("Read Error");
2751                 g_free(buffer);
2752                 return FALSE;
2753         }
2754
2755         token = strtok_r(buffer, "=", &saveptr);
2756         if (token == NULL) {
2757                 g_free(buffer);
2758                 return FALSE;
2759         }
2760
2761         while ((token = strtok_r(NULL, ",", &saveptr))) {
2762                 if (strlen(token) > 8)
2763                         token[8] = '\0';
2764                 if (0 == g_strcmp0(token, lap_addr)) {
2765                         INFO("Voice Recognition blacklisted");
2766                         g_free(buffer);
2767                         return TRUE;
2768                 }
2769         }
2770         g_free(buffer);
2771         return FALSE;
2772 }
2773
2774 static gboolean __bt_sco_open_delay_timeout_cb(gpointer user_data)
2775 {
2776         bt_ag_info_t *bt_ag_info = (bt_ag_info_t *)user_data;
2777         sco_open_timer_id = 0;
2778         DBG("sco_open_request (%d)", sco_open_request);
2779
2780         if (sco_open_request && bt_ag_info->state == HEADSET_STATE_CONNECTED) {
2781                 bt_ag_slconn_t *slconn = bt_ag_info->slc;
2782
2783                 INFO("try to open SCO");
2784                 sco_open_request = FALSE;
2785
2786                 if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
2787                                 (slconn && (slconn->hs_features &
2788                                         BT_HF_FEATURE_CODEC_NEGOTIATION))) {
2789                         switch (bt_ag_info->codec_info.final_codec) {
2790                         case BT_CVSD_CODEC_ID:
2791                                 __bt_ag_set_codec(bt_ag_info, "SetNbParameters");
2792                                 __bt_ag_sco_connect(bt_ag_info);
2793                                 break;
2794                         case BT_MSBC_CODEC_ID:
2795                                 __bt_ag_set_codec(bt_ag_info, "SetWbsParameters");
2796                                 __bt_ag_sco_connect(bt_ag_info);
2797                                 break;
2798                         default:
2799                                 __bt_hfp_codec_connection_setup(bt_ag_info, FALSE);
2800                                 break;
2801                         }
2802                 } else
2803                         __bt_ag_sco_connect(bt_ag_info);
2804         }
2805
2806         return FALSE;
2807 }
2808
2809 /*
2810 * Service level connection complete
2811 * indication and state management
2812 */
2813 void _bt_ag_slconn_complete(bt_ag_info_t *hs)
2814 {
2815         char lap_address[BT_LOWER_ADDRESS_LENGTH];
2816
2817         DBG("HFP Service Level Connection established\n");
2818
2819         /* Check device Voice Recognition blacklist status */
2820         g_strlcpy(lap_address, hs->remote_addr, sizeof(lap_address));
2821         hs->vr_blacklisted =
2822                 __bt_ag_agent_is_device_vr_blacklisted(lap_address);
2823
2824         if (sco_open_timer_id > 0) {
2825                 g_source_remove(sco_open_timer_id);
2826                 sco_open_timer_id = 0;
2827         }
2828
2829         sco_open_request = FALSE;
2830         sco_open_timer_id = g_timeout_add(BT_SCO_OPEN_DELAY_TIMER,
2831                                                 __bt_sco_open_delay_timeout_cb, hs);
2832
2833         _bt_ag_set_headset_state(hs, HEADSET_STATE_CONNECTED);
2834 }
2835
2836 static gboolean __bt_ag_agent_connection_release(bt_ag_info_t *hs)
2837 {
2838
2839         g_io_channel_shutdown(hs->io_chan, TRUE, NULL);
2840         g_io_channel_unref(hs->io_chan);
2841         hs->io_chan = NULL;
2842
2843         if (hs->sco) {
2844                 __bt_ag_close_sco(hs);
2845                 _bt_ag_set_headset_state(hs, HEADSET_STATE_CONNECTED);
2846         }
2847         __bt_ag_agent_remove_watch(&hs->watch_id);
2848
2849         _bt_ag_set_headset_state(hs, HEADSET_STATE_DISCONNECTED);
2850         return TRUE;
2851 }
2852
2853 static GQuark __bt_ag_agent_error_quark(void)
2854 {
2855         FN_START;
2856
2857         static GQuark quark = 0;
2858         if (!quark)
2859                 quark = g_quark_from_static_string("ag-agent");
2860
2861         FN_END;
2862         return quark;
2863 }
2864
2865 static GError *__bt_ag_agent_set_error(bt_hfp_agent_error_t error)
2866 {
2867         FN_START;
2868         ERR("error[%d]\n", error);
2869
2870         switch (error) {
2871         case BT_HFP_AGENT_ERROR_NOT_AVAILABLE:
2872                 return g_error_new(BT_AG_AGENT_ERROR, error,
2873                                         BT_ERROR_NOT_AVAILABLE);
2874         case BT_HFP_AGENT_ERROR_NOT_CONNECTED:
2875         return g_error_new(BT_AG_AGENT_ERROR, error,
2876                                         BT_ERROR_NOT_CONNECTED);
2877         case BT_HFP_AGENT_ERROR_BUSY:
2878                 return g_error_new(BT_AG_AGENT_ERROR, error,
2879                                                 BT_ERROR_BUSY);
2880         case BT_HFP_AGENT_ERROR_INVALID_PARAM:
2881                 return g_error_new(BT_AG_AGENT_ERROR, error,
2882                                                 BT_ERROR_INVALID_PARAM);
2883         case BT_HFP_AGENT_ERROR_ALREADY_EXSIST:
2884                 return g_error_new(BT_AG_AGENT_ERROR, error,
2885                                                 BT_ERROR_ALREADY_EXSIST);
2886         case BT_HFP_AGENT_ERROR_ALREADY_CONNECTED:
2887                 return g_error_new(BT_AG_AGENT_ERROR, error,
2888                                                 BT_ERROR_ALREADY_CONNECTED);
2889         case BT_HFP_AGENT_ERROR_NO_MEMORY:
2890                 return g_error_new(BT_AG_AGENT_ERROR, error,
2891                                                 BT_ERROR_NO_MEMORY);
2892         case BT_HFP_AGENT_ERROR_I_O_ERROR:
2893                 return g_error_new(BT_AG_AGENT_ERROR, error,
2894                                                 BT_ERROR_I_O_ERROR);
2895         case BT_HFP_AGENT_ERROR_OPERATION_NOT_AVAILABLE:
2896                 return g_error_new(BT_AG_AGENT_ERROR, error,
2897                                         BT_ERROR_OPERATION_NOT_AVAILABLE);
2898         case BT_HFP_AGENT_ERROR_BATTERY_STATUS:
2899                 return g_error_new(BT_AG_AGENT_ERROR, error,
2900                                         BT_ERROR_BATTERY);
2901         case BT_HFP_AGENT_ERROR_SIGNAL_STATUS:
2902                 return g_error_new(BT_AG_AGENT_ERROR, error,
2903                                         BT_ERROR_SIGNAL);
2904         case BT_HFP_AGENT_ERROR_NO_CALL_LOGS:
2905                 return g_error_new(BT_AG_AGENT_ERROR, error,
2906                                         BT_ERROR_NO_CALL_LOG);
2907         case BT_HFP_AGENT_ERROR_INTERNAL:
2908         default:
2909                 return g_error_new(BT_AG_AGENT_ERROR, error,
2910                                                 BT_ERROR_INTERNAL);
2911         }
2912         FN_END;
2913 }
2914
2915 static bt_ag_info_t *__bt_get_active_headset(const gchar *device_path)
2916 {
2917         GSList *l;
2918
2919         for (l = active_devices ; l; l = l->next) {
2920                 bt_ag_info_t *data = l->data;
2921                 if (device_path == NULL) /*just to avoid crash incase of "play" when dailed from device[NEEDS TO BE CHANGED]*/
2922                         return data;
2923                 if (g_strcmp0(data->path, device_path) == 0) {
2924                         INFO("Active device found");
2925                         return data;
2926                 }
2927         }
2928
2929         INFO("Active device not found");
2930         return NULL;
2931 }
2932
2933 static void __bt_ag_agent_method(GDBusConnection *connection,
2934                         const gchar *sender,
2935                         const gchar *object_path,
2936                         const gchar *interface_name,
2937                         const gchar *method_name,
2938                         GVariant *parameters,
2939                         GDBusMethodInvocation *invocation,
2940                         gpointer user_data)
2941 {
2942         FN_START;
2943
2944         INFO("method %s", method_name);
2945         INFO("object_path %s", object_path);
2946         int ret = BT_HFP_AGENT_ERROR_NONE;
2947         GError *err = NULL;
2948         const gchar *device_path = NULL;
2949
2950         if (g_strcmp0(method_name, "NewConnection") == 0) {
2951                 gint32 fd;
2952                 int index = 0;
2953                 GDBusMessage *msg;
2954                 GUnixFDList *fd_list;
2955                 GVariant *options = NULL;
2956                 int device_count = 0;
2957
2958                 device_count = g_slist_length(active_devices);
2959
2960                 INFO("device_count %d", device_count);
2961
2962                 if (device_count >= MAX_CONNECTED_DEVICES) {
2963                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2964                         goto fail;
2965                 }
2966
2967                 g_variant_get(parameters, "(oha{sv})",
2968                                                 &device_path, &index, &options);
2969
2970 #if defined(TIZEN_SUPPORT_DUAL_HF) && defined(TIZEN_PROFILE_WEARABLE)
2971                 /*
2972                  * Below code is not required for dual HF support for
2973                  * mobile devices
2974                  */
2975                 if (device_count &&
2976                         __bt_ag_agent_check_dual_hf_condition(device_path) == FALSE) {
2977                         INFO("not allow to connect 2nd HF connection");
2978                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2979                         goto fail;
2980                 }
2981 #endif
2982                 msg = g_dbus_method_invocation_get_message(invocation);
2983                 fd_list = g_dbus_message_get_unix_fd_list(msg);
2984                 if (fd_list == NULL) {
2985                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2986                         goto fail;
2987                 }
2988
2989                 fd = g_unix_fd_list_get(fd_list, index, NULL);
2990                 if (fd == -1) {
2991                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2992                         goto fail;
2993                 }
2994
2995                 DBG("FD is = [%d], device_path = [%s]\n", fd, device_path);
2996
2997                 if (!__bt_ag_agent_connection(fd, device_path, object_path)) {
2998                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2999                         goto fail;
3000                 }
3001
3002                 g_dbus_method_invocation_return_value(invocation, NULL);
3003         } else if (g_strcmp0(method_name, "RequestDisconnection") == 0) {
3004                 GSList *l;
3005
3006                 g_variant_get(parameters, "(o)", &device_path);
3007                 INFO("device_path %s", device_path);
3008
3009                 for (l = active_devices; l; l = l->next) {
3010                         bt_ag_info_t *data = l->data;
3011
3012                         INFO("data->path %s", data->path);
3013                         if (g_strcmp0(data->path, device_path) == 0) {
3014                                 if (!__bt_ag_agent_connection_release(data)) {
3015                                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3016                                         goto fail;
3017                                 }
3018                                 INFO_C("Disconnected [AG role] [Terminated by local host]");
3019                                 g_dbus_method_invocation_return_value(invocation, NULL);
3020                         }
3021                 }
3022         } else if (g_strcmp0(method_name, "RegisterApplication") == 0) {
3023                 gchar *path = NULL;
3024                 gchar *address = NULL;
3025                 g_variant_get(parameters, "(&s&s)", &path, &address);
3026                 /*local_addr = malloc(strlen(address));
3027                 memcpy(local_addr, address, strlen(address));*/
3028
3029                 DBG("Sender = %s, Application path = %s\n", sender, path);
3030                 ret = _bt_hfp_register_telephony_agent(TRUE, path, sender);
3031                 if (ret)
3032                         goto fail;
3033
3034                 g_free(local_addr);
3035                 local_addr = g_strdup(address);
3036                 DBG("Address = %s\n", local_addr);
3037                 g_dbus_method_invocation_return_value(invocation, NULL);
3038         } else if (g_strcmp0(method_name, "UnregisterApplication") == 0) {
3039                 gchar *path = NULL;
3040                 g_variant_get(parameters, "(&s)", &path);
3041
3042                 DBG("Application path = %s\n", path);
3043                 DBG("Sender = %s\n", sender);
3044
3045                 ret = _bt_hfp_register_telephony_agent(FALSE, path, sender);
3046                 if (ret)
3047                         goto fail;
3048
3049                 g_dbus_method_invocation_return_value(invocation, NULL);
3050         } else if (g_strcmp0(method_name, "IncomingCall") == 0) {
3051                 gchar *path = NULL;
3052                 gchar *number = NULL;
3053                 gint call_id = 0;
3054
3055                 g_variant_get(parameters, "(&s&si)", &path, &number, &call_id);
3056
3057                 DBG("Application path = %s", path);
3058                 DBG_SECURE("Phone number = %s", number);
3059                 DBG("Call id = %d", call_id);
3060
3061                 DBG("Sender = %s", sender);
3062
3063                 ret = _bt_hfp_incoming_call(path, number, call_id, sender);
3064                 if (ret)
3065                         goto fail;
3066                 g_dbus_method_invocation_return_value(invocation, NULL);
3067         } else if (g_strcmp0(method_name, "OutgoingCall") == 0) {
3068                 gchar *path = NULL;
3069                 gchar *number = NULL;
3070                 gint call_id = 0;
3071
3072                 g_variant_get(parameters, "(&s&si)", &path, &number, &call_id);
3073
3074                 DBG("Application path = %s", path);
3075                 DBG_SECURE("Phone number = %s", number);
3076                 DBG("Call id = %d", call_id);
3077
3078                 DBG("Sender = %s", sender);
3079
3080                 ret = _bt_hfp_outgoing_call(path, number, call_id, sender);
3081                 if (ret)
3082                         goto fail;
3083                 g_dbus_method_invocation_return_value(invocation, NULL);
3084         } else if (g_strcmp0(method_name, "ChangeCallStatus") == 0) {
3085                 gchar *path = NULL;
3086                 gchar *number = NULL;
3087                 gint status = 0;
3088                 gint call_id = 0;
3089                 GSList *l;
3090
3091                 g_variant_get(parameters, "(&s&sii)",
3092                                         &path, &number, &status, &call_id);
3093                 DBG("Application path = %s\n", path);
3094                 DBG_SECURE("Number = %s\n", number);
3095                 DBG("Status = %d\n", status);
3096                 DBG("Call id = %d\n", call_id);
3097                 DBG("Sender = %s\n", sender);
3098
3099                 ret = _bt_hfp_change_call_status(path,
3100                                         number, status, call_id, sender);
3101
3102                 if (_bt_hfp_is_call_exist() == FALSE) {
3103                         for (l = active_devices; l; l = l->next) {
3104                                 bt_ag_info_t *data = l->data;
3105
3106                                 if (data->state == HEADSET_STATE_ON_CALL) {
3107                                         __bt_ag_close_sco(data);
3108                                         _bt_ag_set_headset_state(data,
3109                                                 HEADSET_STATE_CONNECTED);
3110                                 }
3111                         }
3112                 }
3113
3114                 if (ret)
3115                         goto fail;
3116                 g_dbus_method_invocation_return_value(invocation, NULL);
3117         } else if (g_strcmp0(method_name, "GetProperties") == 0) {
3118                 GVariantBuilder *builder;
3119                 GVariant *var_data;
3120                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3121
3122                 if (bt_ag_info) {
3123                         gchar *codec = g_strdup("codec");
3124                         gchar *nrec = g_strdup("nrec");
3125
3126                         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
3127
3128                         g_variant_builder_add(builder, "{sv}",
3129                                         codec, g_variant_new("u", bt_ag_info->codec_info.final_codec));
3130                         g_variant_builder_add(builder, "{sv}",
3131                                         nrec, g_variant_new("b", bt_ag_info->nrec_status));
3132
3133                         var_data = g_variant_new("(a{sv})", builder);
3134                         g_variant_builder_unref(builder);
3135                         g_dbus_method_invocation_return_value(invocation, var_data);
3136
3137                         g_free(codec);
3138                         g_free(nrec);
3139                 } else {
3140                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3141                         goto fail;
3142                 }
3143         } else if (g_strcmp0(method_name, "Disconnect") == 0) {
3144                 char hdset_address[18] = { 0, };
3145                 GSList *l;
3146
3147                 for (l = active_devices; l; l = l->next) {
3148                         bt_ag_info_t *data = l->data;
3149
3150                         __bt_convert_addr_type_to_rev_string(hdset_address,
3151                                         (unsigned char *)data->remote_addr);
3152
3153                         DBG("Disconnect Headset %s, %s\n",
3154                                                 hdset_address, data->path);
3155                         _bt_ag_set_headset_state(data,
3156                                                 HEADSET_STATE_DISCONNECTED);
3157                 }
3158                 g_dbus_method_invocation_return_value(invocation, NULL);
3159         } else if (g_strcmp0(method_name, "IsConnected") == 0) {
3160                 gboolean is_connected = FALSE;
3161                 GSList *l;
3162
3163                 for (l = active_devices; l; l = l->next) {
3164                         bt_ag_info_t *data = l->data;
3165
3166                         if (data->state == HEADSET_STATE_CONNECTED)
3167                                 is_connected = TRUE;
3168                 }
3169                 DBG("is_connected : %s",
3170                                 is_connected ? "Connected" : "Disconnected");
3171
3172                 g_dbus_method_invocation_return_value(invocation,
3173                                 g_variant_new("(b)", is_connected));
3174         } else if (g_strcmp0(method_name, "IndicateCall") == 0) {
3175                 GSList *l;
3176
3177                 if (0 == g_slist_length(active_devices)) {
3178                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3179                         goto fail;
3180                 }
3181
3182                 if (ag.ring_timer) {
3183                         DBG("IndicateCall received when already indicating");
3184                         g_dbus_method_invocation_return_value(invocation, NULL);
3185                 }
3186
3187                 for (l = active_devices; l; l = l->next) {
3188                         bt_ag_info_t *data = l->data;
3189
3190                         if (data->state >= HEADSET_STATE_CONNECTED)
3191                                 _bt_ag_send_at(data, "\r\nRING\r\n");
3192                 }
3193
3194                 __bt_ring_timer_cb(NULL);
3195                 ag.ring_timer = g_timeout_add(AG_RING_INTERVAL,
3196                                 __bt_ring_timer_cb, NULL);
3197                 g_dbus_method_invocation_return_value(invocation, NULL);
3198         } else if (g_strcmp0(method_name, "CancelCall") == 0) {
3199                 if (0 == g_slist_length(active_devices)) {
3200                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3201                         goto fail;
3202                 }
3203
3204                 if (ag.ring_timer) {
3205                         g_source_remove(ag.ring_timer);
3206                         ag.ring_timer = 0;
3207                 } else
3208                         DBG("Got CancelCall method call but no call is active");
3209
3210                 g_dbus_method_invocation_return_value(invocation, NULL);
3211         } else if (g_strcmp0(method_name, "Play") == 0) {
3212                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3213                 bt_ag_slconn_t *slconn = NULL;
3214
3215                 if (bt_ag_info) {
3216                         slconn = bt_ag_info->slc;
3217                 } else {
3218                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3219                         goto fail;
3220                 }
3221
3222 #ifndef __TIZEN_OPEN__
3223 #ifdef MDM_PHASE_2
3224                 int mode;
3225                 if (slconn && FALSE == slconn->is_voice_recognition_running &&
3226                                 mdm_get_service() == MDM_RESULT_SUCCESS) {
3227                         mode = mdm_get_allow_bluetooth_outgoing_call();
3228                         mdm_release_service();
3229
3230                         if (mode == MDM_RESTRICTED) {
3231                                 ERR("[MDM] Not allow the outgoing call");
3232                                 ret = BT_HFP_AGENT_ERROR_OPERATION_NOT_AVAILABLE;
3233                                 goto fail;
3234                         }
3235                 }
3236 #endif
3237 #endif
3238
3239                 switch (bt_ag_info->state) {
3240                 case HEADSET_STATE_CONNECTING:
3241                 case HEADSET_STATE_DISCONNECTED:
3242                         ERR("HEADSET_STATE  ERROR");
3243                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3244                         break;
3245                 case HEADSET_STATE_CONNECTED:
3246                         break;
3247                 case HEADSET_STATE_PLAY_IN_PROGRESS:
3248                         ERR("Play In Progress");
3249                         ret = BT_HFP_AGENT_ERROR_BUSY;
3250                         break;
3251                 default:
3252                         break;
3253                 }
3254                 if (ret)
3255                         goto fail;
3256
3257                 if (sco_open_timer_id > 0) {
3258                         INFO("SCO open delay");
3259                         sco_open_request = TRUE;
3260                         g_dbus_method_invocation_return_value(invocation, NULL);
3261                         return;
3262                 }
3263
3264                 if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
3265                                 (slconn && (slconn->hs_features &
3266                                         BT_HF_FEATURE_CODEC_NEGOTIATION))) {
3267                         switch (bt_ag_info->codec_info.final_codec) {
3268                         case BT_CVSD_CODEC_ID:
3269                                 __bt_ag_set_codec(bt_ag_info, "SetNbParameters");
3270                                 ret = __bt_ag_sco_connect(bt_ag_info);
3271                                 break;
3272                         case BT_MSBC_CODEC_ID:
3273                                 __bt_ag_set_codec(bt_ag_info, "SetWbsParameters");
3274                                 ret = __bt_ag_sco_connect(bt_ag_info);
3275                                 break;
3276                         default:
3277                                 ret = __bt_hfp_codec_connection_setup(bt_ag_info, FALSE);
3278                                 break;
3279                         }
3280                 } else
3281                         ret = __bt_ag_sco_connect(bt_ag_info);
3282
3283                 if (ret)
3284                         goto fail;
3285
3286                 g_free(sco_owner);
3287                 sco_owner = g_strdup(sender);
3288
3289                 g_dbus_method_invocation_return_value(invocation, NULL);
3290
3291                 name_owner_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
3292                                         NULL, NULL, "NameOwnerChanged", NULL, NULL, 0,
3293                                         __bt_ag_name_owner_changed_cb, NULL, NULL);
3294         } else if (g_strcmp0(method_name, "Stop") == 0) {
3295                 GSList *l;
3296
3297                 for (l = active_devices; l; l = l->next) {
3298                         bt_ag_info_t *data = l->data;
3299
3300                         if (data->state > HEADSET_STATE_CONNECTED) {
3301                                 __bt_ag_close_sco(data);
3302                                 _bt_ag_set_headset_state(data,
3303                                         HEADSET_STATE_CONNECTED);
3304                         }
3305                 }
3306
3307                 g_dbus_method_invocation_return_value(invocation, NULL);
3308         } else if (g_strcmp0(method_name, "IsPlaying") == 0) {
3309                 gboolean is_playing = FALSE;
3310                 GSList *l;
3311
3312                 for (l = active_devices; l; l = l->next) {
3313                         bt_ag_info_t *data = l->data;
3314
3315                         if (data->state == HEADSET_STATE_ON_CALL)
3316                                 is_playing = TRUE;
3317                 }
3318                 DBG("is_playing : %s", is_playing ? "Playing" : "Not Playing");
3319
3320                 g_dbus_method_invocation_return_value(invocation,
3321                                 g_variant_new("(b)", is_playing));
3322         } else if (g_strcmp0(method_name, "GetSpeakerGain") == 0) {
3323                 bt_ag_slconn_t *slconn = NULL;
3324                 guint16 gain_value = 0;
3325                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3326
3327                 if (bt_ag_info == NULL) {
3328                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3329                         goto fail;
3330                 }
3331
3332                 if (bt_ag_info->state < HEADSET_STATE_CONNECTED) {
3333                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3334                         goto fail;
3335                 }
3336
3337                 slconn = bt_ag_info->slc;
3338                 if (slconn)
3339                         gain_value = (guint16) slconn->speaker_gain;
3340
3341                 g_dbus_method_invocation_return_value(invocation,
3342                                 g_variant_new("(q)", gain_value));
3343         } else if (g_strcmp0(method_name, "SetSpeakerGain") == 0) {
3344                 guint16 gain = 0;
3345                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3346
3347                 g_variant_get(parameters, "(q)", &gain);
3348                 DBG("Speaker gain = %d\n", gain);
3349
3350                 if (bt_ag_info == NULL) {
3351                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3352                         goto fail;
3353                 }
3354
3355                 ret = _bt_hfp_set_speaker_gain(bt_ag_info, gain);
3356                 if (ret)
3357                         goto fail;
3358                 g_dbus_method_invocation_return_value(invocation, NULL);
3359         } else if (g_strcmp0(method_name, "GetMicrophoneGain") == 0) {
3360                 bt_ag_slconn_t *slconn = NULL;
3361                 guint16 gain_value = 0;
3362                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3363
3364                 if (bt_ag_info == NULL) {
3365                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3366                         goto fail;
3367                 }
3368
3369                 if (bt_ag_info->state < HEADSET_STATE_CONNECTED) {
3370                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3371                         goto fail;
3372                 }
3373
3374                 slconn = bt_ag_info->slc;
3375                 if (slconn)
3376                         gain_value = (guint16) slconn->microphone_gain;
3377
3378                 g_dbus_method_invocation_return_value(invocation,
3379                                 g_variant_new("(q)", gain_value));
3380         } else if (g_strcmp0(method_name, "SetMicrophoneGain") == 0) {
3381                 guint16 gain = 0;
3382                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3383
3384                 g_variant_get(parameters, "(q)", &gain);
3385                 DBG("Microphone gain = %d\n", gain);
3386
3387                 if (bt_ag_info == NULL) {
3388                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3389                         goto fail;
3390                 }
3391
3392                 ret = _bt_hfp_set_microphone_gain(bt_ag_info, gain);
3393                 if (ret)
3394                         goto fail;
3395                 g_dbus_method_invocation_return_value(invocation, NULL);
3396         } else if (g_strcmp0(method_name, "SetVoiceDial") == 0) {
3397                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3398                 if (bt_ag_info == NULL) {
3399                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3400                         goto fail;
3401                 }
3402
3403                 bt_ag_slconn_t *slconn = bt_ag_info->slc;
3404                 gboolean enable;
3405
3406                 g_variant_get(parameters, "(b)", &enable);
3407                 DBG("VoiceDail enable = %d\n", enable);
3408
3409                 if ((slconn && !(slconn->hs_features &
3410                                         BT_HF_FEATURE_VOICE_RECOGNITION)))
3411                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3412                 else if (bt_ag_info->vr_blacklisted)
3413                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3414                 else
3415                         ret = _bt_hfp_set_voice_dial(bt_ag_info, enable);
3416
3417                 if (slconn)
3418                         slconn->is_voice_recognition_running = enable;
3419
3420                 if (ret)
3421                         goto fail;
3422                 g_dbus_method_invocation_return_value(invocation, NULL);
3423         } else if (g_strcmp0(method_name, "SendVendorAtCmd") == 0) {
3424                 gchar *cmd;
3425                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3426                 if (bt_ag_info == NULL) {
3427                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3428                         goto fail;
3429                 }
3430
3431                 g_variant_get(parameters, "(&s)", &cmd);
3432                 if (cmd == NULL) {
3433                         ret = BT_HFP_AGENT_ERROR_INVALID_PARAM;
3434                         goto fail;
3435                 }
3436
3437                 DBG("vendor cmd = %s", cmd);
3438
3439                 ret = _bt_hfp_send_vendor_cmd(bt_ag_info, cmd);
3440                 if (ret)
3441                         goto fail;
3442                 g_dbus_method_invocation_return_value(invocation, NULL);
3443         } else if (g_strcmp0(method_name, "CheckPrivilege") == 0) {
3444                 DBG("Already pass dbus SMACK for bt-service::platform");
3445                 /* Return success */
3446                 g_dbus_method_invocation_return_value(invocation, NULL);
3447         }  else if (g_strcmp0(method_name, "SwapHeadset") == 0) {
3448                 GSList *l;
3449                 gchar *addr = NULL;
3450                 char address[BT_ADDRESS_STRING_SIZE];
3451                 char remote_addr[BT_ADDRESS_STRING_SIZE];
3452                 gboolean device_found = FALSE;
3453
3454                 g_variant_get(parameters, "(s)", &addr);
3455                 g_strlcpy(address, addr, sizeof(address));
3456                 DBG("Sender = %s", sender);
3457
3458                 /* Loop through connected headset list
3459                  * If found, update the remote_dev_path.
3460                  */
3461                 for (l = active_devices ; l; l = l->next) {
3462                         bt_ag_info_t *data = l->data;
3463                         g_strlcpy(remote_addr, data->remote_addr, sizeof(remote_addr));
3464                         if (g_strcmp0(remote_addr, address) == 0) {
3465                                 DBG("Active device found");
3466                                 if (data->path == NULL) {
3467                                         DBG("device path is null");
3468                                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3469                                         goto fail;
3470                                 }
3471                                 remote_dev_path = g_strdup(data->path);
3472                                 DBG("Setting device path %s as active device path", remote_dev_path);
3473                                 device_found = TRUE;
3474                                 break;
3475                         }
3476                 }
3477
3478                 if (!device_found) {
3479                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3480                         goto fail;
3481                 }
3482
3483                 g_dbus_method_invocation_return_value(invocation, NULL);
3484         }
3485
3486         INFO("-");
3487         return;
3488
3489 fail:
3490         err = __bt_ag_agent_set_error(ret);
3491         g_dbus_method_invocation_return_gerror(invocation, err);
3492         g_error_free(err);
3493         INFO("-");
3494 }
3495
3496 static const GDBusInterfaceVTable method_table = {
3497         __bt_ag_agent_method,
3498         NULL,
3499         NULL,
3500 };
3501
3502 static GDBusNodeInfo *__bt_ag_create_method_node_info
3503                                         (const gchar *introspection_data)
3504 {
3505         GError *err = NULL;
3506         GDBusNodeInfo *node_info = NULL;
3507
3508         if (introspection_data == NULL)
3509                 return NULL;
3510
3511         node_info = g_dbus_node_info_new_for_xml(introspection_data, &err);
3512
3513         if (err) {
3514                 ERR("Unable to create node: %s", err->message);
3515                 g_clear_error(&err);
3516         }
3517         return node_info;
3518 }
3519
3520 static GDBusConnection *__bt_ag_get_gdbus_connection(void)
3521 {
3522         FN_START;
3523
3524         GError *err = NULL;
3525
3526         if (ag_dbus_conn == NULL)
3527                 ag_dbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
3528
3529         if (!ag_dbus_conn) {
3530                 if (err) {
3531                         ERR("Unable to connect to dbus: %s", err->message);
3532                         g_clear_error(&err);
3533                 }
3534                 return NULL;
3535         }
3536         FN_END;
3537
3538         return ag_dbus_conn;
3539 }
3540
3541 static gboolean __bt_ag_register_profile_methods(void)
3542 {
3543         FN_START;
3544         GError *error = NULL;
3545         guint owner_id;
3546         GDBusNodeInfo *node_info = NULL;
3547         gchar *path;
3548
3549         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
3550                                 BT_AG_SERVICE_NAME,
3551                                 G_BUS_NAME_OWNER_FLAGS_NONE,
3552                                 NULL, NULL, NULL,
3553                                 NULL, NULL);
3554
3555         DBG("owner_id is [%d]", owner_id);
3556
3557         node_info = __bt_ag_create_method_node_info(
3558                                 ag_agent_bluez_introspection_xml);
3559         if (node_info == NULL)
3560                 return FALSE;
3561
3562         path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
3563         DBG("path is [%s]", path);
3564
3565         hf_bluez_id = g_dbus_connection_register_object(ag_dbus_conn, path,
3566                                         node_info->interfaces[0],
3567                                         &method_table,
3568                                         NULL, NULL, &error);
3569         if (hf_bluez_id == 0) {
3570                 ERR("Failed to register: %s", error->message);
3571                 g_error_free(error);
3572                 g_free(path);
3573                 g_dbus_node_info_unref(node_info);
3574                 return FALSE;
3575         }
3576         g_free(path);
3577
3578         /* Ag register profile methods for HSP*/
3579
3580         path = g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
3581         DBG("path is [%s]", path);
3582
3583         hs_bluez_id = g_dbus_connection_register_object(ag_dbus_conn, path,
3584                                         node_info->interfaces[0],
3585                                         &method_table,
3586                                         NULL, NULL, &error);
3587         if (hs_bluez_id == 0) {
3588                 ERR("Failed to register: %s", error->message);
3589                 g_error_free(error);
3590                 g_free(path);
3591                 g_dbus_node_info_unref(node_info);
3592                 return FALSE;
3593         }
3594         g_free(path);
3595         g_dbus_node_info_unref(node_info);
3596
3597         node_info = __bt_ag_create_method_node_info
3598                                 (ag_agent_app_introspection_xml);
3599         if (node_info == NULL)
3600                 return FALSE;
3601
3602         path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
3603         DBG("path is [%s]", path);
3604
3605         app_id = g_dbus_connection_register_object(ag_dbus_conn, path,
3606                                                 node_info->interfaces[0],
3607                                                 &method_table,
3608                                                 NULL, NULL, &error);
3609         if (app_id == 0) {
3610                 ERR("Failed to register: %s", error->message);
3611                 g_error_free(error);
3612                 g_free(path);
3613                 g_dbus_node_info_unref(node_info);
3614                 return FALSE;
3615         }
3616         g_free(path);
3617         g_dbus_node_info_unref(node_info);
3618
3619         FN_END;
3620         return TRUE;
3621 }
3622
3623 static void __bt_ag_unregister_profile_methods(void)
3624 {
3625         DBG("");
3626
3627         if (hf_bluez_id > 0) {
3628                 g_dbus_connection_unregister_object(ag_dbus_conn,
3629                                                         hf_bluez_id);
3630                 hf_bluez_id = 0;
3631         }
3632
3633         if (hs_bluez_id > 0) {
3634                 g_dbus_connection_unregister_object(ag_dbus_conn,
3635                                                         hs_bluez_id);
3636                 hs_bluez_id = 0;
3637         }
3638
3639         if (app_id > 0) {
3640                 g_dbus_connection_unregister_object(ag_dbus_conn,
3641                                                         app_id);
3642                 app_id = 0;
3643         }
3644 }
3645
3646 static GDBusProxy *__bt_ag_gdbus_get_service_proxy(const gchar *service,
3647                                 const gchar *path, const gchar *interface)
3648 {
3649         return (service_gproxy) ? service_gproxy :
3650                         __bt_ag_gdbus_init_service_proxy(service,
3651                                         path, interface);
3652 }
3653
3654 static void __bt_ag_agent_register(gchar *path, uint16_t profile_version,
3655                                 char *profile_uuid, const char* profile_name)
3656 {
3657         FN_START;
3658         GDBusProxy *proxy;
3659         GVariant *ret;
3660         GError *error = NULL;
3661         GVariantBuilder *builder;
3662
3663         proxy = __bt_ag_gdbus_get_service_proxy(BLUEZ_SERVICE_NAME,
3664                 "/org/bluez", BLUEZ_PROFILE_MGMT_INTERFACE);
3665         if (proxy == NULL)
3666                 return;
3667
3668
3669         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
3670
3671         g_variant_builder_add(builder, "{sv}",
3672                         "Name", g_variant_new("s",
3673                         profile_name));
3674         g_variant_builder_add(builder, "{sv}",
3675                         "Version", g_variant_new("q", profile_version));
3676         /*g_variant_builder_add(builder, "{sv}",
3677                         "Role", g_variant_new("s","client"));*/
3678         if (g_strcmp0(path, BT_AG_AGENT_OBJECT_PATH) == 0) {
3679                 g_variant_builder_add(builder, "{sv}",
3680                                 "features", g_variant_new("q", ag.sdp_features));
3681         }
3682
3683         ret = g_dbus_proxy_call_sync(proxy, "RegisterProfile",
3684                                         g_variant_new("(osa{sv})", path,
3685                                                         profile_uuid, builder),
3686                                         G_DBUS_CALL_FLAGS_NONE, -1,
3687                                         NULL, &error);
3688         g_variant_builder_unref(builder);
3689         /* set the name and role for the profile*/
3690         if (ret == NULL) {
3691                 /* dBUS-RPC is failed */
3692                 ERR("dBUS-RPC is failed");
3693
3694                 if (error != NULL) {
3695                         /* dBUS gives error cause */
3696                         ERR("D-Bus API failure: errCode[%x], message[%s]",
3697                                         error->code, error->message);
3698
3699                         g_clear_error(&error);
3700                 }
3701                 g_free(path);
3702                 return;
3703         }
3704         g_variant_unref(ret);
3705         g_free(path);
3706
3707         FN_END;
3708         return;
3709 }
3710
3711 static void __bt_ag_agent_unregister(gchar *path)
3712 {
3713         FN_START;
3714         GDBusProxy *proxy;
3715         GVariant *ret;
3716         GError *error = NULL;
3717
3718         proxy = __bt_ag_gdbus_get_service_proxy(BLUEZ_SERVICE_NAME,
3719                 "/org/bluez", BLUEZ_PROFILE_MGMT_INTERFACE);
3720         if (proxy == NULL)
3721                 return;
3722
3723
3724         ret = g_dbus_proxy_call_sync(proxy, "UnregisterProfile",
3725                                         g_variant_new("(o)", path),
3726                                         G_DBUS_CALL_FLAGS_NONE, -1,
3727                                         NULL, &error);
3728         g_free(path);
3729         /* set the name and role for the profile*/
3730         if (ret == NULL) {
3731                 /* dBUS-RPC is failed */
3732                 ERR("dBUS-RPC is failed");
3733
3734                 if (error != NULL) {
3735                         /* dBUS gives error cause */
3736                         ERR("D-Bus API failure: errCode[%x], message[%s]",
3737                                         error->code, error->message);
3738
3739                         g_clear_error(&error);
3740                 }
3741                 return;
3742         }
3743         g_variant_unref(ret);
3744
3745         if (local_addr) {
3746                 g_free(local_addr);
3747                 local_addr = NULL;
3748         }
3749         FN_END;
3750         return;
3751 }
3752
3753 static void __bt_ag_agent_battery_status_cb(keynode_t *node)
3754 {
3755         int batt = vconf_keynode_get_int(node);
3756
3757         _bt_hfp_set_property_value("BatteryBarsChanged", batt);
3758 }
3759
3760 static void __bt_ag_agent_network_signal_status_cb(keynode_t *node)
3761 {
3762         int signal_bar = vconf_keynode_get_int(node);
3763
3764         BT_CHECK_SIGNAL_STRENGTH(signal_bar);
3765         _bt_hfp_set_property_value("SignalBarsChanged", signal_bar);
3766 }
3767
3768 static void __bt_ag_agent_lunar_connection_status_cb(keynode_t *node)
3769 {
3770         gboolean status = vconf_keynode_get_bool(node);
3771         GSList *l;
3772         DBG("status = %d", status);
3773
3774         if (status == TRUE) {
3775                 for (l = active_devices; l; l = l->next) {
3776                         bt_ag_info_t *data = l->data;
3777                         _bt_ag_send_at(data, "\r\n+BSIR:1\r\n");
3778                 }
3779         }
3780 }
3781
3782 static void __bt_ag_agent_network_register_status_cb(keynode_t *node)
3783 {
3784         int service = vconf_keynode_get_int(node);
3785         bt_hfp_agent_network_registration_status_t network_service;
3786         int roam_status;
3787         int ret;
3788
3789         DBG("Current Signal Level = [%d] \n", service);
3790
3791         switch (service) {
3792         case VCONFKEY_TELEPHONY_SVCTYPE_NONE:
3793         case VCONFKEY_TELEPHONY_SVCTYPE_NOSVC:
3794         case VCONFKEY_TELEPHONY_SVCTYPE_SEARCH:
3795                 service = 0;
3796                 break;
3797         default:
3798                 service = 1;
3799                 break;
3800         }
3801
3802         ret = vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &roam_status);
3803         if (ret != 0) {
3804                 ERR("Get roaming status failed err = %d\n", ret);
3805                 return;
3806         }
3807
3808         if (roam_status == 0 && service == 1)
3809                 network_service = BT_AGENT_NETWORK_REG_STATUS_HOME;
3810         else if (roam_status == 1 && service == 1)
3811                 network_service = BT_AGENT_NETWORK_REG_STATUS_ROAMING;
3812         else
3813                 network_service = BT_AGENT_NETWORK_REG_STATUS_UNKOWN;
3814
3815         _bt_hfp_set_property_value("RegistrationChanged", network_service);
3816 }
3817
3818 static void __bt_ag_agent_subscribe_vconf_updates(void)
3819 {
3820         int ret;
3821
3822         DBG("\n");
3823
3824         ret = vconf_notify_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY,
3825                                 (void *)__bt_ag_agent_battery_status_cb, NULL);
3826         if (0 != ret)
3827                 ERR("Subsrciption to battery status failed err =  [%d]\n", ret);
3828
3829         ret = vconf_notify_key_changed(VCONFKEY_TELEPHONY_RSSI,
3830                         (void *)__bt_ag_agent_network_signal_status_cb, NULL);
3831         if (0 != ret)
3832                 ERR("Subsrciption to netowrk signal failed err =  [%d]\n", ret);
3833
3834         ret = vconf_notify_key_changed(VCONFKEY_TELEPHONY_SVCTYPE,
3835                         (void *)__bt_ag_agent_network_register_status_cb, NULL);
3836         if (0 != ret)
3837                 ERR("Subsrciption to network failed err =  [%d]\n", ret);
3838
3839         if (TIZEN_PROFILE_WEARABLE) {
3840                 ret = vconf_notify_key_changed(VCONF_KEY_BT_LUNAR_ENABLED,
3841                                 (void *)__bt_ag_agent_lunar_connection_status_cb, NULL);
3842                 if (0 != ret)
3843                         ERR("Subsrciption to lunar connection failed err =  [%d]\n", ret);
3844         }
3845 }
3846
3847 static void __bt_ag_agent_release_vconf_updates(void)
3848 {
3849         int ret;
3850
3851         DBG("\n");
3852
3853         ret = vconf_ignore_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY,
3854                         (vconf_callback_fn)__bt_ag_agent_battery_status_cb);
3855         if (0 != ret)
3856                 ERR("vconf_ignore_key_changed failed\n");
3857
3858         ret = vconf_ignore_key_changed(VCONFKEY_TELEPHONY_RSSI,
3859                 (vconf_callback_fn)__bt_ag_agent_network_signal_status_cb);
3860         if (0 != ret)
3861                 ERR("vconf_ignore_key_changed failed\n");
3862
3863         ret = vconf_ignore_key_changed(VCONFKEY_TELEPHONY_SVCTYPE,
3864                 (vconf_callback_fn)__bt_ag_agent_network_register_status_cb);
3865         if (0 != ret)
3866                 ERR("vconf_ignore_key_changed failed\n");
3867 }
3868
3869 static gboolean __bt_ag_agent_send_subscriber_number_changed(
3870                                                         const char *number)
3871 {
3872         const char *property = g_strdup("SubscriberNumberChanged");
3873
3874         FN_START;
3875
3876         DBG("Number is %s", number);
3877
3878         if (!_bt_hfp_set_property_name(property, number)) {
3879                 DBG("Error- set property for subscriber no change  - ERROR\n");
3880                 g_free((void *)property);
3881                 return FALSE;
3882         }
3883         g_free((void *)property);
3884         FN_END;
3885         return TRUE;
3886 }
3887 static void __bt_ag_agent_sigterm_handler(int signo)
3888 {
3889         int i;
3890         GSList *l;
3891
3892         ERR_C("***** Signal handler came with signal %d *****", signo);
3893
3894         for (l = active_devices ; l; l = l->next) {
3895                 bt_ag_info_t *data = l->data;
3896                 if (!__bt_ag_agent_connection_release(data))
3897                         ERR("__bt_ag_agent_connection_release failed");
3898         }
3899         if (ag_dbus_conn)
3900                 g_dbus_connection_flush(ag_dbus_conn, NULL, NULL, NULL);
3901
3902         if (gmain_loop) {
3903                 g_main_loop_quit(gmain_loop);
3904                 DBG("Exiting");
3905                 gmain_loop = NULL;
3906         } else {
3907                 INFO("Terminating AG agent");
3908                 exit(0);
3909         }
3910
3911         if (signo == SIGTERM)
3912                 return;
3913
3914         for (i = 0; i < BT_AG_SIG_NUM; i++)
3915                 sigaction(bt_ag_sig_to_handle[i], &(bt_ag_sigoldact[i]), NULL);
3916
3917         raise(signo);
3918 }
3919
3920 static void  __bt_ag_agent_tel_cb(TapiHandle *handle,
3921                                 int result,
3922                                 void *data,
3923                                 void *user_data)
3924 {
3925         TelSimMsisdnList_t *number;
3926         gchar *subscriber_number;
3927
3928         ERR("*********** result = %d", result);
3929
3930         if (result == TAPI_API_SIM_LOCKED ||
3931                 result == TAPI_API_SIM_NOT_INITIALIZED ||
3932                 result == TAPI_API_SERVICE_NOT_READY) {
3933                 DBG("initializing the tapi event for SIM status");
3934                 __bt_ag_agent_reg_sim_event(handle, user_data);
3935                 return;
3936         }
3937
3938         if (data == NULL)
3939                 return;
3940
3941         number = (TelSimMsisdnList_t *)data;
3942         subscriber_number = g_strdup(number->list[0].num);
3943         __bt_ag_agent_send_subscriber_number_changed(subscriber_number);
3944         g_free(subscriber_number);
3945 }
3946
3947 static void __bt_ag_agent_on_noti_sim_status(TapiHandle *handle,
3948                 const char *noti_id, void *data, void *user_data)
3949 {
3950         TelSimCardStatus_t *status = data;
3951         int tapi_result;
3952
3953         DBG("event TAPI_NOTI_SIM_STATUS received!! status[%d]", *status);
3954
3955         if (*status == TAPI_SIM_STATUS_SIM_INIT_COMPLETED) {
3956                 __bt_ag_agent_dereg_sim_event(handle);
3957                 tapi_result = tel_get_sim_msisdn(handle, __bt_ag_agent_tel_cb,
3958                                         user_data);
3959                 if (tapi_result != TAPI_API_SUCCESS)
3960                         ERR("Fail to get sim info: %d", tapi_result);
3961         }
3962 }
3963
3964 static void __bt_ag_agent_reg_sim_event(TapiHandle *handle, void *user_data)
3965 {
3966         int ret;
3967         ret = tel_register_noti_event(handle, TAPI_NOTI_SIM_STATUS,
3968                 __bt_ag_agent_on_noti_sim_status, user_data);
3969
3970         if (ret != TAPI_API_SUCCESS)
3971                 ERR("event register failed(%d)", ret);
3972 }
3973
3974 static void __bt_ag_agent_dereg_sim_event(TapiHandle *handle)
3975 {
3976         int ret;
3977         ret = tel_deregister_noti_event(handle, TAPI_NOTI_SIM_STATUS);
3978
3979         if (ret != TAPI_API_SUCCESS)
3980                 ERR("event deregister failed(%d)", ret);
3981 }
3982
3983 static void __bt_ag_name_owner_changed_cb(GDBusConnection *connection,
3984                                         const gchar *sender_name,
3985                                         const gchar *object_path,
3986                                         const gchar *interface_name,
3987                                         const gchar *signal_name,
3988                                         GVariant *parameters,
3989                                         gpointer user_data)
3990 {
3991         FN_START;
3992         char *name_owner = NULL;
3993         char *old_owner = NULL;
3994         char *new_owner = NULL;
3995
3996         if (strcasecmp(signal_name, "NameOwnerChanged") == 0) {
3997                 GSList *l;
3998
3999                 g_variant_get(parameters, "(sss)", &name_owner, &old_owner, &new_owner);
4000
4001                 _bt_hfp_release_all_calls_by_sender(name_owner);
4002
4003                 if (sco_owner == NULL)
4004                         return;
4005
4006                 if (strcasecmp(name_owner, sco_owner) == 0) {
4007                         if (name_owner_sig_id != -1)
4008                                 g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4009                                                         name_owner_sig_id);
4010                         name_owner_sig_id = -1;
4011                         g_free(sco_owner);
4012                         sco_owner = NULL;
4013
4014                         for (l = active_devices ; l; l = l->next) {
4015                                 bt_ag_info_t *data = l->data;
4016
4017                                 if (data->sco) {
4018                                         __bt_ag_close_sco(data);
4019                                         _bt_ag_set_headset_state(data,
4020                                                 HEADSET_STATE_CONNECTED);
4021                                 }
4022                         }
4023                 }
4024         }
4025 }
4026
4027 static void __bt_ag_agent_filter_cb(GDBusConnection *connection,
4028                                         const gchar *sender_name,
4029                                         const gchar *object_path,
4030                                         const gchar *interface_name,
4031                                         const gchar *signal_name,
4032                                         GVariant *parameters,
4033                                         gpointer user_data)
4034 {
4035         FN_START;
4036         char *path = NULL;
4037         GVariant *optional_param = NULL;
4038
4039         if (strcasecmp(signal_name, "InterfacesAdded") == 0) {
4040
4041                 g_variant_get(parameters, "(&o@a{sa{sv}})",
4042                                                         &path, &optional_param);
4043                 if (!path) {
4044                         if (optional_param)
4045                                 g_variant_unref(optional_param);
4046                         ERR("Invalid adapter path");
4047                         return;
4048                 }
4049
4050                 INFO("Adapter Path = [%s]", path);
4051                 if (strcasecmp(path, DEFAULT_ADAPTER_OBJECT_PATH) == 0) {
4052                         gchar *path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
4053                         __bt_ag_agent_register(path, hfp_ver,
4054                                  HFP_AG_UUID, "Hands-Free Audio Gateway");
4055
4056                         path =  g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
4057                         __bt_ag_agent_register(path, hsp_ver,
4058                                 HSP_AG_UUID, "Headset Audio Gateway");
4059                 }
4060         } else if (strcasecmp(signal_name, "InterfacesRemoved") == 0) {
4061                 g_variant_get(parameters, "(&o@as)", &path, &optional_param);
4062                 if (!path) {
4063                         if (optional_param)
4064                                 g_variant_unref(optional_param);
4065                         ERR("Invalid adapter path");
4066                         return;
4067                 }
4068
4069                 INFO("Adapter Path = [%s]", path);
4070                 if (strcasecmp(path, DEFAULT_ADAPTER_OBJECT_PATH) == 0) {
4071                         gchar *path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
4072                         __bt_ag_agent_unregister(path);
4073
4074                         path =  g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
4075                         __bt_ag_agent_unregister(path);
4076                 }
4077         }
4078
4079         if (optional_param)
4080                 g_variant_unref(optional_param);
4081
4082         FN_END;
4083 }
4084
4085 static void __bt_ag_agent_dbus_deinit(void)
4086 {
4087
4088         if (service_gproxy) {
4089                 g_object_unref(service_gproxy);
4090                 service_gproxy = NULL;
4091         }
4092
4093         if (app_gproxy) {
4094                 g_object_unref(app_gproxy);
4095                 app_gproxy = NULL;
4096         }
4097
4098         if (ag_dbus_conn) {
4099                 __bt_ag_unregister_profile_methods();
4100
4101                 if (interface_added_sig_id)
4102                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4103                                                 interface_added_sig_id);
4104
4105                 if (interface_removed_sig_id)
4106                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4107                                                 interface_removed_sig_id);
4108
4109                 if (name_owner_sig_id)
4110                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4111                                                 name_owner_sig_id);
4112 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
4113                 if (media_sig_id)
4114                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4115                                                 media_sig_id);
4116                 media_sig_id = 0;
4117
4118                 if (media_state_sig_id)
4119                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4120                                                 media_state_sig_id);
4121                 media_state_sig_id = 0;
4122 #endif
4123
4124                 interface_added_sig_id = 0;
4125                 interface_removed_sig_id = 0;
4126                 name_owner_sig_id = 0;
4127                 g_free(sco_owner);
4128                 sco_owner = NULL;
4129
4130                 g_object_unref(ag_dbus_conn);
4131                 ag_dbus_conn = NULL;
4132         }
4133         return;
4134 }
4135
4136 static int __bt_ag_agent_get_adapter_path(GDBusConnection *conn, char *path)
4137 {
4138         GError *err = NULL;
4139         GDBusProxy *manager_proxy = NULL;
4140         GVariant *result = NULL;
4141         char *adapter_path = NULL;
4142
4143         if (conn == NULL)
4144                 return BT_HFP_AGENT_ERROR_INTERNAL;
4145
4146         manager_proxy =  g_dbus_proxy_new_sync(conn,
4147                         G_DBUS_PROXY_FLAGS_NONE, NULL,
4148                         BLUEZ_SERVICE_NAME,
4149                         "/",
4150                         BT_MANAGER_INTERFACE,
4151                         NULL, &err);
4152
4153         if (!manager_proxy) {
4154                 ERR("Unable to create proxy: %s", err->message);
4155                 goto fail;
4156         }
4157
4158         result = g_dbus_proxy_call_sync(manager_proxy, "DefaultAdapter", NULL,
4159                         G_DBUS_CALL_FLAGS_NONE, -1, NULL, &err);
4160         if (!result) {
4161                 if (err != NULL)
4162                         ERR("Fail to get DefaultAdapter (Error: %s)", err->message);
4163                 else
4164                         ERR("Fail to get DefaultAdapter");
4165
4166                 goto fail;
4167         }
4168
4169         if (g_strcmp0(g_variant_get_type_string(result), "(o)")) {
4170                 ERR("Incorrect result\n");
4171                 goto fail;
4172         }
4173
4174         g_variant_get(result, "(&o)", &adapter_path);
4175
4176         if (adapter_path == NULL ||
4177                 strlen(adapter_path) >= BT_ADAPTER_OBJECT_PATH_MAX) {
4178                 ERR("Adapter path is inproper\n");
4179                 goto fail;
4180         }
4181
4182         if (path)
4183                 g_strlcpy(path, adapter_path, BT_ADAPTER_OBJECT_PATH_MAX);
4184
4185         g_variant_unref(result);
4186         g_object_unref(manager_proxy);
4187
4188         return 0;
4189
4190 fail:
4191         g_clear_error(&err);
4192
4193         if (result)
4194                 g_variant_unref(result);
4195
4196         if (manager_proxy)
4197                 g_object_unref(manager_proxy);
4198
4199         return BT_HFP_AGENT_ERROR_INTERNAL;
4200
4201 }
4202
4203 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
4204 void _bt_ag_agent_check_transport_state(void)
4205 {
4206         FN_START;
4207
4208         if (transport_state == MEDIA_TRANSPORT_STATE_PLAYING) {
4209                 GDBusProxy *proxy;
4210                 GError *err = NULL;
4211
4212                 proxy =  g_dbus_proxy_new_sync(ag_dbus_conn,
4213                                 G_DBUS_PROXY_FLAGS_NONE, NULL,
4214                                 "org.PulseAudio2", A2DP_SOURCE_ENDPOINT,
4215                                 BLUEZ_MEDIA_ENDPOINT_INTERFACE, NULL, &err);
4216
4217                 if (!proxy) {
4218                         if (err) {
4219                                 ERR("Unable to create proxy: %s", err->message);
4220                                 g_clear_error(&err);
4221                         }
4222                         return;
4223                 }
4224                 INFO_C("SuspendMedia initiated");
4225
4226                 g_dbus_proxy_call(proxy,
4227                                         "SuspendMedia", NULL,
4228                                         G_DBUS_CALL_FLAGS_NONE, 2000,
4229                                         NULL, NULL, NULL);
4230                 transport_state = MEDIA_TRANSPORT_STATE_IDLE;
4231         }
4232
4233         FN_END;
4234 }
4235
4236 static void __bt_ag_agent_transport_state_update(const char *value)
4237 {
4238
4239         if (!g_strcmp0(value, "idle"))
4240                 transport_state = MEDIA_TRANSPORT_STATE_IDLE;
4241         else if (!g_strcmp0(value, "pending") || !g_strcmp0(value, "active"))
4242                 transport_state = MEDIA_TRANSPORT_STATE_PLAYING;
4243         else
4244                 transport_state =  MEDIA_TRANSPORT_STATE_DISCONNECTED;
4245
4246         INFO_C("transport_state %d", transport_state);
4247 }
4248
4249 static void __bt_ag_agent_media_filter_cb(GDBusConnection *connection,
4250                                         const gchar *sender_name,
4251                                         const gchar *object_path,
4252                                         const gchar *interface_name,
4253                                         const gchar *signal_name,
4254                                         GVariant *parameters,
4255                                         gpointer user_data)
4256 {
4257         FN_START;
4258         char *inter = NULL;
4259         GVariant *dict_param = NULL;
4260         GVariant *optional_param = NULL;
4261
4262         if (strcasecmp(signal_name, "PropertiesChanged") == 0) {
4263                 if (g_strcmp0(g_variant_get_type_string(parameters),
4264                                                         "(sa{sv}as)")) {
4265                         ERR("Incorrect parameters\n");
4266                         return;
4267                 }
4268
4269                 g_variant_get(parameters, "(&s@a{sv}@as)",
4270                                         &inter, &dict_param, &optional_param);
4271                 if (dict_param && (!g_strcmp0(inter,
4272                                 BLUEZ_MEDIA_TRANSPORT_INTERFACE))){
4273                         GVariantIter *iter = NULL;
4274                         const gchar *key = NULL;
4275                         GVariant *value_var = NULL;
4276                         gchar *value = NULL;
4277                         g_variant_get(dict_param, "a{sv}", &iter);
4278                         while (g_variant_iter_loop(
4279                                         iter, "{sv}", &key, &value_var)) {
4280                                 DBG("key %s", key);
4281                                 if (g_strcmp0(key, "State") == 0) {
4282                                         value = (gchar *)g_variant_get_string(
4283                                                                 value_var,
4284                                                                 NULL);
4285                                         DBG("value %s", value);
4286                                         __bt_ag_agent_transport_state_update(value);
4287                                         break;
4288                                 }
4289                         }
4290                         g_variant_iter_free(iter);
4291                 }
4292         } else if (strcasecmp(signal_name, "ProfileStateChanged") == 0) {
4293                 char *profile_uuid = NULL;
4294                 int state = 0;
4295
4296                 g_variant_get(parameters, "(&si)", &profile_uuid, &state);
4297                 if ((g_strcmp0(profile_uuid, A2DP_SINK_UUID) == 0)  &&
4298                         (state == BT_PROFILE_STATE_DISCONNECTED)) {
4299                         DBG("Updating the transport state");
4300                         __bt_ag_agent_transport_state_update("Disconnect");
4301                 }
4302         }
4303
4304         if (dict_param)
4305                 g_variant_unref(dict_param);
4306
4307         if (optional_param)
4308                 g_variant_unref(optional_param);
4309
4310         FN_END;
4311 }
4312 #endif
4313 static void __bt_ag_agent_dbus_init(void)
4314 {
4315         FN_START;
4316
4317         if (__bt_ag_get_gdbus_connection() == NULL) {
4318                 ERR("Error in creating the gdbus connection\n");
4319                 return;
4320         }
4321         if (!__bt_ag_register_profile_methods()) {
4322                 ERR("Error in HFP / HSP register_profile_methods\n");
4323                 return;
4324         }
4325
4326         if (!__bt_ag_agent_get_adapter_path(ag_dbus_conn , NULL)) {
4327
4328                 gchar *path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
4329                 __bt_ag_agent_register(path, hfp_ver,
4330                          HFP_AG_UUID, "Hands-Free Audio Gateway");
4331
4332                 path = g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
4333                 __bt_ag_agent_register(path, hsp_ver,
4334                         HSP_AG_UUID, "Headset Audio Gateway");
4335         }
4336
4337         interface_added_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4338                                 NULL, BT_MANAGER_INTERFACE,
4339                                 BT_INTERFACES_ADDED, NULL, NULL, 0,
4340                                 __bt_ag_agent_filter_cb, NULL, NULL);
4341
4342         interface_removed_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4343                                 NULL, BT_MANAGER_INTERFACE,
4344                                 BT_INTERFACES_REMOVED, NULL, NULL, 0,
4345                                 __bt_ag_agent_filter_cb, NULL, NULL);
4346
4347 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
4348         media_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4349                                 NULL, BT_PROPERTIES_INTERFACE, NULL, NULL,
4350                                 NULL, 0, __bt_ag_agent_media_filter_cb,
4351                                 NULL, NULL);
4352
4353         media_state_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4354                                 NULL, BLUEZ_DEVICE_INTERFACE, NULL, NULL,
4355                                 NULL, 0, __bt_ag_agent_media_filter_cb,
4356                                 NULL, NULL);
4357
4358         transport_state = MEDIA_TRANSPORT_STATE_DISCONNECTED;
4359 #endif
4360         FN_END;
4361         return;
4362 }
4363
4364 static uint32_t __bt_ag_agent_get_ag_features(void)
4365 {
4366
4367         uint32_t ag_features = BT_AG_FEATURE_EC_AND_NR |
4368                                 BT_AG_FEATURE_REJECT_CALL |
4369                                 BT_AG_FEATURE_ENHANCED_CALL_STATUS |
4370                                 BT_AG_FEATURE_THREE_WAY_CALL |
4371                                 BT_AG_FEATURE_VOICE_RECOGNITION |
4372                                 BT_AG_FEATURE_EXTENDED_ERROR_RESULT_CODES;
4373
4374         wbs_en = TRUE;
4375 #if defined(TIZEN_FEATURE_BT_HFP_AG)
4376         hfp_ver = HFP_VERSION_1_7;
4377 #else
4378         hfp_ver = HFP_VERSION_1_5;
4379 #endif
4380         hsp_ver = HSP_VERSION_1_2;
4381
4382         if (hfp_ver > HFP_VERSION_1_5)
4383                 ag_features |= BT_AG_FEATURE_CODEC_NEGOTIATION;
4384         if (hfp_ver == HFP_VERSION_1_7)
4385                 ag_features |= BT_AG_FEATURE_ESCO_S4_T2_SUPPORT;
4386
4387         return ag_features;
4388 }
4389
4390 void *__bt_ag_agent_telephony_init(void *arg)
4391 {
4392
4393         int tapi_result;
4394         uint32_t ag_features = *((uint32_t *)arg);
4395
4396         INFO_C("Initializing the telephony info");
4397
4398         _bt_hfp_initialize_telephony_manager(ag_features);
4399         __bt_ag_agent_subscribe_vconf_updates();
4400
4401         tapi_handle = tel_init(NULL);
4402         tapi_result = tel_get_sim_msisdn(tapi_handle, __bt_ag_agent_tel_cb,
4403                                         NULL);
4404         if (tapi_result != TAPI_API_SUCCESS)
4405                 ERR("Fail to get sim info: %d", tapi_result);
4406         return NULL;
4407 }
4408
4409 int main(void)
4410 {
4411         int i;
4412         uint32_t ag_features;
4413         struct sigaction sa;
4414         pthread_t thread_id;
4415
4416         INFO_C("### Starting Bluetooth AG agent");
4417
4418         ag_features = __bt_ag_agent_get_ag_features();
4419
4420         ag.sdp_features = (uint16_t) ag_features & 0x1F;
4421
4422         if (hfp_ver >= HFP_VERSION_1_6 && wbs_en == TRUE)
4423                 ag.sdp_features |= BT_AG_FEATURE_SDP_WIDEBAND_SPEECH;
4424
4425         memset(&sa, 0, sizeof(sa));
4426         sa.sa_flags = SA_NOCLDSTOP;
4427         sa.sa_handler = __bt_ag_agent_sigterm_handler;
4428
4429         for (i = 0; i < BT_AG_SIG_NUM; i++)
4430                 sigaction(bt_ag_sig_to_handle[i], &sa, &(bt_ag_sigoldact[i]));
4431
4432         gmain_loop = g_main_loop_new(NULL, FALSE);
4433
4434         if (gmain_loop == NULL) {
4435                 ERR("GMainLoop create failed");
4436                 return EXIT_FAILURE;
4437         }
4438
4439         __bt_ag_agent_dbus_init();
4440         if (pthread_create(&thread_id, NULL,
4441                         (void *)&__bt_ag_agent_telephony_init,
4442                                         &ag_features) < 0) {
4443                 ERR("pthread_create() is failed");
4444                 return EXIT_FAILURE;
4445         }
4446
4447         if (pthread_detach(thread_id) < 0)
4448                 ERR("pthread_detach() is failed");
4449
4450         g_main_loop_run(gmain_loop);
4451
4452         DBG("Cleaning up");
4453
4454         tel_deinit(tapi_handle);
4455
4456         __bt_ag_agent_dbus_deinit();
4457         _bt_hfp_deinitialize_telephony_manager();
4458         __bt_ag_agent_release_vconf_updates();
4459
4460         if (remote_dev_path)
4461                 g_free(remote_dev_path);
4462
4463         if (gmain_loop)
4464                 g_main_loop_unref(gmain_loop);
4465
4466         INFO_C("### Terminating Bluetooth AG agent");
4467         return 0;
4468 }