099485cf8000789840021f6f28619c7ba7eb8fac
[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 (TIZEN_MODEL_NAME_TM1) {
1637                 codec = BT_CVSD_CODEC_ID;
1638         } else {
1639                 if (hs->codec_info.remote_codecs & BT_MSBC_CODEC_MASK)
1640                         codec = BT_MSBC_CODEC_ID;
1641                 else
1642                         codec = BT_CVSD_CODEC_ID;
1643         }
1644
1645         if (wbs_opts.wbs_enable == FALSE)
1646                 codec = BT_CVSD_CODEC_ID;
1647
1648         hs->codec = codec;
1649
1650         if (_bt_ag_send_at(hs, "\r\n+BCS: %d\r\n", codec) < 0)
1651                 return BT_HFP_AGENT_ERROR_INTERNAL;
1652         else
1653                 DBG("Send +BCS:%d\n", codec);
1654
1655         /* Send +BCS command to HF, and wait some times */
1656         hs->codec_info.is_negotiating = TRUE;
1657         hs->codec_info.sending_codec = codec;
1658         hs->codec_info.requested_by_hf = init_by_hf;
1659         hs->codec_info.final_codec = codec;
1660
1661         data = g_new0(struct ag_codec, 1);
1662         if (data == NULL)
1663                 return BT_HFP_AGENT_ERROR_NO_MEMORY;
1664
1665         data->bt_ag_info = hs;
1666         data->codec_status = g_strdup("timeout");
1667
1668         hs->codec_info.nego_timer = g_timeout_add_seconds(
1669                         HFP_CODEC_NEGOTIATION_TIMEOUT,
1670                         (GSourceFunc)__bt_ag_codec_negotiation_finished,
1671                         data);
1672
1673         return BT_HFP_AGENT_ERROR_NONE;
1674 }
1675
1676
1677 static bt_hfp_agent_error_t __bt_hfp_codec_connection_setup(
1678                                 bt_ag_info_t *hs, gboolean init_by_hf)
1679 {
1680         DBG("Request to codec connection by %s", init_by_hf ? "HF" : "AG");
1681
1682         if (hs->state < HEADSET_STATE_CONNECTED)
1683                 return BT_HFP_AGENT_ERROR_NOT_CONNECTED;
1684
1685         if (hs->codec_info.is_negotiating == TRUE) {
1686                 /* In codec negotiation, return and wait */
1687                 ERR("Codec nogotiation is in progress");
1688                 return BT_HFP_AGENT_ERROR_BUSY;
1689         }
1690
1691         /* Not support Codec Negotiation or Not recieved BAC command */
1692         if (!(ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) ||
1693                                 hs->codec_info.remote_codecs == 0) {
1694                 ERR("No support for Codec Negotiation or receive BAC command");
1695                 if (init_by_hf) {
1696                         return BT_HFP_AGENT_ERROR_INTERNAL;
1697                 } else {
1698                         __bt_ag_sco_connect(hs);
1699                         return BT_HFP_AGENT_ERROR_INTERNAL;
1700                 }
1701         }
1702
1703         /* If HF initiated codec connection setup, it should send OK command
1704          * before +BCS command transmission.
1705          */
1706         if (init_by_hf)
1707                 return HFP_STATE_MNGR_ERR_NONE;
1708         else
1709                 return __bt_hfp_send_bcs_command(hs, init_by_hf);
1710 }
1711
1712
1713 static int __hfp_parse_available_codecs(const char *cmd, uint32_t *codecs)
1714 {
1715         char *str = NULL;
1716         *codecs = 0x00000000;
1717
1718         str = strchr(cmd, '=');
1719         if (str == NULL)
1720                 return -EINVAL;
1721
1722         while (str != NULL) {
1723                 str++;
1724
1725                 if (atoi(str) == BT_CVSD_CODEC_ID)
1726                         *codecs |= BT_CVSD_CODEC_MASK;
1727                 else if (atoi(str) == BT_MSBC_CODEC_ID)
1728                         *codecs |= BT_MSBC_CODEC_MASK;
1729
1730                 str = strchr(str, ',');
1731         }
1732
1733         if (*codecs == 0x00000000)
1734                 return -EINVAL;
1735
1736         return 0;
1737 }
1738
1739 /* AT+BAC (Bluetooth Available Codecs) */
1740 static int __bt_hfp_available_codecs(bt_ag_info_t *hs, const char *buf)
1741 {
1742         uint32_t codecs = 0x00000000;
1743         hfp_state_manager_err_t err = HFP_STATE_MNGR_ERR_NONE;
1744
1745         if (!(ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION)) {
1746                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1747         } else if (__hfp_parse_available_codecs(buf, &codecs) < 0) {
1748                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1749         } else {
1750                 DBG("Update remote available codecs [%x]", codecs);
1751                 hs->codec_info.remote_codecs = codecs;
1752         }
1753
1754         _bt_ag_send_response(hs, err);
1755
1756         /* Reset codec information and
1757          * restart codec connection setup by AG
1758          */
1759         hs->codec_info.final_codec = 0;
1760         if (hs->codec_info.nego_timer) {
1761                 hs->codec_info.is_negotiating = FALSE;
1762                 hs->codec_info.requested_by_hf = FALSE;
1763                 hs->codec_info.sending_codec = 0;
1764                 g_source_remove(hs->codec_info.nego_timer);
1765                 __bt_hfp_codec_connection_setup(hs, FALSE);
1766         }
1767
1768         return 0;
1769 }
1770
1771 /* AT+BCC (Bluetooth Codec Connection) */
1772 static int __bt_hfp_codec_connection(bt_ag_info_t *hs, const char *buf)
1773 {
1774         hfp_state_manager_err_t err = HFP_STATE_MNGR_ERR_NONE;
1775
1776         err = __bt_hfp_codec_connection_setup(hs, TRUE);
1777
1778         _bt_ag_send_response(hs, err);
1779
1780         if (err == HFP_STATE_MNGR_ERR_NONE)
1781                 err = __bt_hfp_send_bcs_command(hs, TRUE);
1782
1783         if (err != HFP_STATE_MNGR_ERR_NONE)
1784                 ERR("Fail to request codec connection setup");
1785
1786         return 0;
1787 }
1788
1789 /* AT+BCS (Bluetooth Codec Selection) */
1790 static int __bt_hfp_codec_selection(bt_ag_info_t *hs, const char *buf)
1791 {
1792         uint32_t codec = 0x00000000;
1793         hfp_state_manager_err_t err = HFP_STATE_MNGR_ERR_NONE;
1794         struct ag_codec *data = g_new0(struct ag_codec, 1);
1795
1796         /* Timer reset */
1797         if (hs->codec_info.nego_timer) {
1798                 g_source_remove(hs->codec_info.nego_timer);
1799                 hs->codec_info.nego_timer = 0;
1800         }
1801
1802         if (!(ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION))
1803                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1804         else if (__hfp_parse_available_codecs(buf, &codec) < 0)
1805                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1806         else if (__bt_ag_codec_selection_setup(hs, codec) !=
1807                                         BT_HFP_AGENT_ERROR_NONE)
1808                 err = HFP_STATE_MNGR_ERR_AG_FAILURE;
1809
1810         data->bt_ag_info = hs;
1811         data->codec_status = g_strdup("finish");
1812         _bt_ag_send_response(hs, err);
1813         __bt_ag_codec_negotiation_finished(data);
1814
1815         return 0;
1816 }
1817
1818 static void __bt_ag_str2ba(const char *str, bt_addr *ba)
1819 {
1820         int i;
1821         for (i = 5; i >= 0; i--, str += 3)
1822                 ba->b[i] = strtol(str, NULL, 16);
1823 }
1824
1825 static const char *__bt_ag_state2str(hs_state_t state)
1826 {
1827         switch (state) {
1828         case HEADSET_STATE_DISCONNECTED:
1829                 return "disconnected";
1830         case HEADSET_STATE_CONNECTING:
1831                 return "connecting";
1832         case HEADSET_STATE_CONNECTED:
1833                 return "connected";
1834         case HEADSET_STATE_PLAY_IN_PROGRESS:
1835                 return "Play In Progress";
1836         case HEADSET_STATE_ON_CALL:
1837                 return "On Call";
1838         }
1839
1840         return NULL;
1841 }
1842
1843 void _bt_convert_addr_string_to_type_rev(unsigned char *addr,
1844                 const char *address)
1845 {
1846         int i;
1847         char *ptr = NULL;
1848
1849         ret_if(address == NULL);
1850         ret_if(addr == NULL);
1851
1852         for (i = 0; i < 6; i++) {
1853                 addr[5 - i] = strtol(address, &ptr, 16);
1854                 if (ptr[0] != '\0') {
1855                         if (ptr[0] != ':')
1856                                 return;
1857
1858                         address = ptr + 1;
1859                 }
1860         }
1861 }
1862
1863 static gboolean __bt_ag_check_nval(GIOChannel *chan)
1864 {
1865         struct pollfd file_desc;
1866
1867         memset(&file_desc, 0, sizeof(file_desc));
1868         file_desc.fd = g_io_channel_unix_get_fd(chan);
1869         file_desc.events = POLLNVAL;
1870
1871         if (poll(&file_desc, 1, 0) > 0 && (POLLNVAL & file_desc.revents))
1872                 return TRUE;
1873
1874         return FALSE;
1875 }
1876
1877 static int __bt_ag_sco_connect(bt_ag_info_t *hs)
1878 {
1879         struct sco_socket_addr sco_addr;
1880         int err;
1881         GIOChannel *io;
1882         int sco_skt;
1883         bt_voice bt_vo;
1884         bt_ag_slconn_t *slconn = hs->slc;
1885         /*guint watch_id;*/
1886
1887         if (hs->state == HEADSET_STATE_ON_CALL)
1888                 return BT_HFP_AGENT_ERROR_ALREADY_CONNECTED;
1889
1890         if (hs->state != HEADSET_STATE_CONNECTED)
1891                 return BT_HFP_AGENT_ERROR_NOT_CONNECTED;
1892 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
1893         _bt_ag_agent_check_transport_state();
1894 #endif
1895
1896         /* Create Sco socket */
1897         sco_skt = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BT_SCO_PRTCL);
1898         if (sco_skt < 0) {
1899                 ERR("ERROR: Create socket failed.\n");
1900                 return BT_HFP_AGENT_ERROR_INTERNAL;
1901         }
1902
1903         /* Bind Sco Socket to Local BD addr */
1904         memset(&sco_addr, 0, sizeof(sco_addr));
1905         sco_addr.sco_family = AF_BLUETOOTH;
1906
1907         __bt_ag_str2ba(local_addr, &sco_addr.sco_bdaddr);
1908         DBG("Local BD address: %s", local_addr);
1909
1910         err = bind(sco_skt, (struct sockaddr *) &sco_addr, sizeof(sco_addr));
1911         if (err < 0) {
1912                 ERR("ERROR: sco socket binding failed");
1913                 ERR("Close SCO skt");
1914                 close(sco_skt);
1915                 return BT_HFP_AGENT_ERROR_INTERNAL;
1916         }
1917
1918         DBG("Socket FD : %d", sco_skt);
1919
1920         io = g_io_channel_unix_new(sco_skt);
1921         g_io_channel_set_close_on_unref(io, TRUE);
1922         /*g_io_channel_set_flags(io, G_IO_FLAG_NONBLOCK, NULL);
1923         g_io_channel_set_buffered(io, FALSE);
1924         g_io_channel_set_encoding(io, NULL, NULL);*/
1925
1926         if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
1927                 (slconn && (slconn->hs_features &
1928                         BT_HF_FEATURE_CODEC_NEGOTIATION)) &&
1929                         wbs_opts.wbs_enable == TRUE) {
1930                 bt_vo.setting = (hs->codec == BT_MSBC_CODEC_ID) ?
1931                                 BT_HFP_MSBC_VOICE : BT_HFP_CVSD_VOICE;
1932
1933                 DBG("set Bluetooth voice: %d", bt_vo.setting);
1934                 err = setsockopt(sco_skt, BT_SOCKET_LEVEL,
1935                                         BT_VOICE_NUM, &bt_vo, sizeof(bt_vo));
1936                 if (err < 0) {
1937                         ERR("ERROR: sco socket set socket option failed");
1938                         ERR("Close SCO skt");
1939                         g_io_channel_unref(io);
1940                         close(sco_skt);
1941                         return BT_HFP_AGENT_ERROR_INTERNAL;
1942                 }
1943         } else {
1944                 DBG("Set NB codec parameter");
1945                 __bt_ag_set_codec(hs, "SetNbParameters");
1946         }
1947
1948         memset(&sco_addr, 0, sizeof(sco_addr));
1949         sco_addr.sco_family = AF_BLUETOOTH;
1950         __bt_ag_str2ba(hs->remote_addr, &sco_addr.sco_bdaddr);
1951         DBG("remotel BD address: %s", hs->remote_addr);
1952
1953         err = connect(sco_skt, (struct sockaddr *) &sco_addr, sizeof(sco_addr));
1954         if (err < 0 && !(errno == EINPROGRESS || errno == EAGAIN)) {
1955                 ERR("ERROR: sco socket connect failed : %d", err);
1956                 ERR("Close SCO skt");
1957                 g_io_channel_unref(io);
1958                 close(sco_skt);
1959                 return BT_HFP_AGENT_ERROR_INTERNAL;
1960         }
1961
1962         /* Disabling the watch since SCO is connected */
1963         /*watch_id = __bt_ag_set_watch(io,
1964                         (GIOFunc) __bt_ag_sco_connect_cb, hs);
1965         if (watch_id)
1966                 DBG("SCO watch set Success");*/
1967
1968         hs->sco = io;
1969
1970         _bt_ag_set_headset_state(hs, HEADSET_STATE_ON_CALL);
1971         return BT_HFP_AGENT_ERROR_NONE;
1972 }
1973
1974 static void __bt_ag_close_sco(bt_ag_info_t *hs)
1975 {
1976         DBG("");
1977         if (hs->sco) {
1978                 int sock = g_io_channel_unix_get_fd(hs->sco);
1979                 shutdown(sock, SHUT_RDWR);
1980                 g_io_channel_unref(hs->sco);
1981                 hs->sco = NULL;
1982         }
1983
1984         if (hs->sco_id)
1985                 __bt_ag_agent_remove_watch(&hs->sco_id);
1986
1987         if (hs->sco_incoming_id)
1988                 __bt_ag_agent_remove_watch(&hs->sco_incoming_id);
1989 }
1990
1991 static gboolean __bt_ag_sco_server_conn_cb(GIOChannel *chan,
1992                                 GIOCondition cond, gpointer user_data)
1993 {
1994         bt_ag_info_t *ag_info = user_data;
1995
1996         DBG("");
1997         if (cond & G_IO_NVAL)
1998                 return FALSE;
1999
2000         if (cond & (G_IO_HUP | G_IO_ERR)) {
2001                 ag_info->sco = NULL;
2002                 if (ag_info->sco_id)
2003                         __bt_ag_agent_remove_watch(&ag_info->sco_id);
2004
2005                 if (ag_info->sco_incoming_id)
2006                         __bt_ag_agent_remove_watch(&ag_info->sco_incoming_id);
2007
2008                 if (ag_info->watch_id)
2009                         _bt_ag_set_headset_state(ag_info, HEADSET_STATE_CONNECTED);
2010                 return FALSE;
2011         }
2012         return TRUE;
2013 }
2014
2015 static gboolean __bt_ag_sco_server_cb(GIOChannel *chan,
2016                                 GIOCondition cond, gpointer user_data)
2017 {
2018         bt_ag_info_t *ag_info = user_data;
2019         int sco_skt;
2020         int cli_sco_sock;
2021         GIOChannel *sco_io;
2022         bt_ag_slconn_t *slconn = ag_info->slc;
2023         bt_voice bt_vo;
2024         int err;
2025
2026         if ((cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) ||
2027                                 __bt_ag_check_nval(chan)) {
2028                 ERR("cond or chan is not valid");
2029                 return FALSE;
2030         }
2031
2032         INFO_C("Incoming SCO....");
2033
2034         if (ag_info->state < HEADSET_STATE_CONNECTED)
2035                 return BT_HFP_AGENT_ERROR_NOT_CONNECTED;
2036
2037         sco_skt = g_io_channel_unix_get_fd(chan);
2038
2039         cli_sco_sock = accept(sco_skt, NULL, NULL);
2040         if (cli_sco_sock < 0) {
2041                 ERR("accept is failed");
2042                 return TRUE;
2043         }
2044
2045         sco_io = g_io_channel_unix_new(cli_sco_sock);
2046         g_io_channel_set_close_on_unref(sco_io, TRUE);
2047         g_io_channel_set_encoding(sco_io, NULL, NULL);
2048         g_io_channel_set_flags(sco_io, G_IO_FLAG_NONBLOCK, NULL);
2049         g_io_channel_set_buffered(sco_io, FALSE);
2050
2051         if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
2052                 (slconn && (slconn->hs_features &
2053                         BT_HF_FEATURE_CODEC_NEGOTIATION)) &&
2054                         wbs_opts.wbs_enable == TRUE) {
2055                 bt_vo.setting = (ag_info->codec == BT_MSBC_CODEC_ID) ?
2056                                 BT_HFP_MSBC_VOICE : BT_HFP_CVSD_VOICE;
2057
2058                 DBG("set Bluetooth voice: %d", bt_vo.setting);
2059                 err = setsockopt(cli_sco_sock, BT_SOCKET_LEVEL,
2060                                         BT_VOICE_NUM, &bt_vo, sizeof(bt_vo));
2061                 if (err < 0) {
2062                         ERR("Sco socket set socket option failed");
2063                         close(cli_sco_sock);
2064                         return FALSE;
2065                 }
2066         }
2067
2068         ag_info->sco = sco_io;
2069         ag_info->sco_incoming_id = g_io_add_watch(sco_io, G_IO_HUP | G_IO_ERR | G_IO_NVAL,
2070                                         __bt_ag_sco_server_conn_cb, ag_info);
2071
2072         if (remote_dev_path)
2073                 g_free(remote_dev_path);
2074
2075         remote_dev_path = g_strdup(ag_info->path);
2076
2077         _bt_ag_set_headset_state(ag_info, HEADSET_STATE_ON_CALL);
2078
2079         return TRUE;
2080 }
2081
2082 static int __bt_ag_start_sco_server(bt_ag_info_t *hs)
2083 {
2084         DBG("Start SCO server");
2085         struct sco_socket_addr addr;
2086         GIOChannel *sco_io;
2087         int sco_skt;
2088         bdaddr_t bd_addr = {{0},};
2089
2090         if (hs->sco_server_started) {
2091                 DBG("Already exsist");
2092                 return BT_HFP_AGENT_ERROR_ALREADY_EXSIST;
2093         }
2094
2095         /* Create socket */
2096         sco_skt = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BT_SCO_PRTCL);
2097         if (sco_skt < 0) {
2098                 ERR("Can't create socket:\n");
2099                 return BT_HFP_AGENT_ERROR_INTERNAL;
2100         }
2101
2102         /* Bind to local address */
2103         memset(&addr, 0, sizeof(addr));
2104         addr.sco_family = AF_BLUETOOTH;
2105
2106         _bt_convert_addr_string_to_type_rev(bd_addr.b, hs->remote_addr);
2107         DBG("Bind to address %s", hs->remote_addr);
2108         memcpy(&addr.sco_bdaddr, &bd_addr, sizeof(bdaddr_t));
2109
2110         if (bind(sco_skt, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
2111                 ERR("Can't bind socket:\n");
2112                 goto error;
2113         }
2114
2115         if (listen(sco_skt, 1)) {
2116                 ERR("Can not listen on the socket:\n");
2117                 goto error;
2118         }
2119
2120         sco_io = g_io_channel_unix_new(sco_skt);
2121         g_io_channel_set_close_on_unref(sco_io, TRUE);
2122         g_io_channel_set_encoding(sco_io, NULL, NULL);
2123         g_io_channel_set_flags(sco_io, G_IO_FLAG_NONBLOCK, NULL);
2124         g_io_channel_set_buffered(sco_io, FALSE);
2125
2126         hs->sco_server = sco_io;
2127         hs->sco_watch_id = g_io_add_watch(sco_io,
2128                         G_IO_IN | G_IO_HUP | G_IO_ERR |
2129                         G_IO_NVAL, __bt_ag_sco_server_cb, hs);
2130
2131         hs->sco_server_started = TRUE;
2132         return BT_HFP_AGENT_ERROR_NONE;
2133
2134 error:
2135         close(sco_skt);
2136         return BT_HFP_AGENT_ERROR_INTERNAL;
2137 }
2138
2139 void __bt_ag_stop_sco_server(bt_ag_info_t *hs)
2140 {
2141         DBG("Stop SCO server");
2142         if (hs->sco_server) {
2143                 g_io_channel_shutdown(hs->sco_server, TRUE, NULL);
2144                 g_io_channel_unref(hs->sco_server);
2145                 hs->sco_server = NULL;
2146         }
2147         hs->sco_server_started = FALSE;
2148 }
2149
2150 static int __bt_ag_headset_close_rfcomm(bt_ag_info_t *hs)
2151 {
2152         GIOChannel *rfcomm = hs->rfcomm;
2153
2154         if (rfcomm) {
2155                 g_io_channel_shutdown(rfcomm, TRUE, NULL);
2156                 g_io_channel_unref(rfcomm);
2157                 hs->rfcomm = NULL;
2158         }
2159
2160         g_free(hs->slc);
2161         hs->slc = NULL;
2162
2163         return 0;
2164 }
2165
2166 static gboolean __bt_ag_sco_cb(GIOChannel *chan, GIOCondition cond,
2167                         bt_ag_info_t *hs)
2168 {
2169         if (cond & G_IO_NVAL)
2170                 return FALSE;
2171
2172         if (name_owner_sig_id != -1)
2173                 g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
2174                                         name_owner_sig_id);
2175         name_owner_sig_id = -1;
2176         g_free(sco_owner);
2177         sco_owner = NULL;
2178
2179         DBG("Audio connection disconnected");
2180         _bt_ag_set_headset_state(hs, HEADSET_STATE_CONNECTED);
2181
2182         return FALSE;
2183 }
2184
2185 void _bt_ag_set_headset_state(bt_ag_info_t *hs, hs_state_t state)
2186 {
2187         bt_ag_slconn_t *slconn = hs->slc;
2188         const char *hs_state;
2189         hs_state_t org_state = hs->state;
2190         gboolean val = FALSE;
2191
2192         if (org_state == state)
2193                 return;
2194
2195         hs_state = __bt_ag_state2str(state);
2196
2197         switch (state) {
2198         case HEADSET_STATE_CONNECTING:
2199                 _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2200                                         hs->path,
2201                                         BT_HEADSET_INTERFACE, "State",
2202                                         g_variant_new("s", hs_state));
2203                 hs->state = state;
2204                 break;
2205
2206         case HEADSET_STATE_CONNECTED:
2207                 if (hs->state != HEADSET_STATE_PLAY_IN_PROGRESS)
2208                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2209                                         hs->path,
2210                                         BT_HEADSET_INTERFACE, "State",
2211                                         g_variant_new("s", hs_state));
2212
2213                 if (hs->state < state) {
2214                         val = TRUE;
2215                         active_devices = g_slist_append(active_devices, hs);
2216                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2217                                                 hs->path,
2218                                                 BT_HEADSET_INTERFACE,
2219                                                 "Connected",
2220                                                 g_variant_new("b", val));
2221
2222                         DBG("Device %s connected\n", hs->remote_addr);
2223 #if defined(TIZEN_SUPPORT_DUAL_HF)
2224                          if (!hs->is_companion_device)
2225                                 __bt_ag_start_sco_server(hs);
2226 #else
2227                         __bt_ag_start_sco_server(hs);
2228 #endif
2229
2230                         /* Set default code as Gateway NB */
2231                         __bt_ag_set_codec(hs, "SetNbParameters");
2232                 } else if (hs->state == HEADSET_STATE_ON_CALL) {
2233                         val = FALSE;
2234                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2235                                                 hs->path,
2236                                                 BT_HEADSET_INTERFACE,
2237                                                 "Playing",
2238                                                 g_variant_new("b", val));
2239                 }
2240                 hs->state = state;
2241                 break;
2242
2243         case HEADSET_STATE_DISCONNECTED:
2244                 __bt_ag_close_sco(hs);
2245                 __bt_ag_headset_close_rfcomm(hs);
2246
2247                 if (hs->state == HEADSET_STATE_ON_CALL) {
2248                         val = FALSE;
2249                         _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2250                                                 hs->path,
2251                                                 BT_HEADSET_INTERFACE,
2252                                                 "Playing",
2253                                                 g_variant_new("b", val));
2254                 }
2255
2256                 val = FALSE;
2257                 _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2258                                 hs->path,
2259                                 BT_HEADSET_INTERFACE,
2260                                 "Connected",
2261                                 g_variant_new("b", val));
2262                 if (hs->state > HEADSET_STATE_CONNECTING)
2263                         _bt_hfp_device_disconnected(hs);
2264
2265                 active_devices = g_slist_remove(active_devices, hs);
2266
2267                 __bt_ag_codec_negotiation_info_reset(hs, TRUE);
2268 #if 0 /* SCO is crashed if below is called when SCO is opened by hf-agent */
2269                 __bt_ag_set_codec(hs, "SetNbParameters");
2270 #endif
2271                 hs->codec = 0;
2272
2273                 /* Since SCO server is binded on remote address */
2274                 /* Need to stop SCO server once heasdet disconencted*/
2275                 if (hs->sco_server_started)
2276                         __bt_ag_stop_sco_server(hs);
2277
2278                 g_free(hs->remote_addr);
2279                 g_free(hs);
2280                 break;
2281
2282         case HEADSET_STATE_PLAY_IN_PROGRESS:
2283         case HEADSET_STATE_ON_CALL:
2284                 val = TRUE;
2285                 _bt_ag_agent_emit_property_changed(ag_dbus_conn,
2286                                         hs->path,
2287                                         BT_HEADSET_INTERFACE, "State",
2288                                         g_variant_new("s", hs_state));
2289
2290                 /*add watch for sco data */
2291                 hs->sco_id = g_io_add_watch(hs->sco,
2292                                         G_IO_ERR | G_IO_NVAL,
2293                                         (GIOFunc) __bt_ag_sco_cb, hs);
2294
2295                 _bt_ag_agent_emit_property_changed(
2296                                 ag_dbus_conn, hs->path,
2297                                 BT_HEADSET_INTERFACE, "Playing",
2298                                 g_variant_new("b", val));
2299
2300                 if (slconn->microphone_gain >= 0)
2301                         _bt_ag_send_at(hs, "\r\n+VGM=%u\r\n",
2302                                 slconn->microphone_gain);
2303
2304                 if (slconn->speaker_gain >= 0)
2305                         _bt_ag_send_at(hs, "\r\n+VGS=%u\r\n",
2306                                 slconn->speaker_gain);
2307
2308                 hs->state = state;
2309                 break;
2310
2311         default:
2312                 hs->state = state;
2313                 break;
2314         }
2315
2316         INFO("STATE CHANGED from [%s(%d)] to [%s(%d)]",
2317                 __bt_ag_state2str(org_state), org_state, __bt_ag_state2str(state), state);
2318 }
2319
2320 static struct event at_event_callbacks[] = {
2321         { "AT+BRSF", _bt_hfp_supported_features },
2322         { "AT+CIND", _bt_hfp_report_indicators },
2323         { "AT+CMER", _bt_hfp_enable_indicators },
2324         { "AT+CHLD", _bt_hfp_call_hold },
2325         { "ATA", _bt_hfp_answer_call },
2326         { "ATD", _bt_hfp_dial_number },
2327         { "AT+VG", _bt_hfp_signal_gain_setting },
2328         { "AT+CHUP", _bt_hfp_terminate_call },
2329         { "AT+CKPD", _bt_hfp_key_press },
2330         { "AT+CLIP", _bt_hfp_cli_notification },
2331         { "AT+BTRH", _bt_hfp_response_and_hold },
2332         { "AT+BLDN", _bt_hfp_last_dialed_number },
2333         { "AT+VTS", _bt_hfp_dtmf_tone },
2334         { "AT+CNUM", _bt_hfp_subscriber_number },
2335         { "AT+CLCC", _bt_hfp_list_current_calls },
2336         { "AT+CMEE", _bt_hfp_extended_errors },
2337         { "AT+CCWA", _bt_hfp_call_waiting_notify },
2338         { "AT+COPS", _bt_hfp_operator_selection },
2339         { "AT+NREC", _bt_hfp_nr_and_ec },
2340         { "AT+BVRA", _bt_hfp_voice_dial },
2341         { "AT+XAPL", _bt_hfp_apl_command },
2342         { "AT+IPHONEACCEV", _bt_hfp_apl_command },
2343         { "AT+BIA", _bt_hfp_indicators_activation },
2344         { "AT+CPBS", _bt_hfp_select_pb_memory },
2345         { "AT+CPBR", _bt_hfp_read_pb_entries},
2346         { "AT+CPBF", _bt_hfp_find_pb_entires },
2347         { "AT+CSCS", _bt_hfp_select_character_set },
2348         { "AT+CSQ", _bt_hfp_get_signal_quality },
2349         { "AT+CBC", _bt_hfp_get_battery_charge_status },
2350         { "AT+CPAS", _bt_hfp_get_activity_status },
2351         { "AT+CGSN", _bt_hfp_get_equipment_identity },
2352         { "AT+CGMM", _bt_hfp_get_model_information },
2353         { "AT+CGMI", _bt_hfp_get_device_manufacturer },
2354         { "AT+CGMR", _bt_hfp_get_revision_information },
2355         { "AT+BAC", __bt_hfp_available_codecs },
2356         { "AT+BCC", __bt_hfp_codec_connection },
2357         { "AT+BCS", __bt_hfp_codec_selection },
2358         { "AT+XSAT", _bt_hfp_vendor_cmd },
2359         { "AT+CIMI", _bt_hfp_get_imsi },
2360         { "AT+CREG", _bt_hfp_get_creg_status },
2361         { 0 }
2362 };
2363
2364 int num_of_secure_command = 4;
2365 static const char* secure_command[] = {"CLCC", "CLIP", "CPBR", "CCWA"};
2366
2367 static void __bt_ag_agent_print_at_buffer(char *message, const char *buf)
2368 {
2369
2370         int i = 0;
2371         char s[MAX_BUFFER_SIZE] = {0, };
2372         gboolean hide = FALSE;
2373
2374         gboolean is_security_command = FALSE;
2375         char *xsat_ptr;
2376
2377         strncpy(s, buf, MAX_BUFFER_SIZE - 1);
2378
2379         for (i = 0; i < num_of_secure_command; i++) {
2380                 if (strstr(buf, secure_command[i])) {
2381                         is_security_command = TRUE;
2382                         break;
2383                 }
2384         }
2385
2386         /* +XSAT: 11,DISC */
2387         xsat_ptr =  strstr(s, "11,DISC,");
2388         if (xsat_ptr) {
2389                 xsat_ptr = xsat_ptr + 8;
2390                 int x = 0;
2391                 while (xsat_ptr[x] != '\0' && xsat_ptr[x] != '\r' && xsat_ptr[x] != '\n') {
2392                         xsat_ptr[x] = 'X';
2393                         x++;
2394                 }
2395         }
2396
2397         /* AT+XSAT=11,Q_CT,X,XXXX */
2398         xsat_ptr =  strstr(s, "11,Q_CT,");
2399         if (xsat_ptr) {
2400                 xsat_ptr = xsat_ptr + 8;
2401                 int x = 0;
2402                 while (xsat_ptr[x] != '\0' && xsat_ptr[x] != '\r' && xsat_ptr[x] != '\n') {
2403                         if (x > 1) /* ignore 0 and 1 position */
2404                                 xsat_ptr[x] = 'X';
2405                         x++;
2406                 }
2407         }
2408
2409         i = 0;
2410         while (s[i] != '\0') {
2411                 if (s[i] == '\r' || s[i] == '\n') {
2412                         s[i] = '.';
2413                 } else {
2414                         if (s[i] == '\"')
2415                                 hide = hide ? FALSE : TRUE;
2416                         else if (is_security_command && hide) {
2417                                 if (i % 2)
2418                                         s[i] = 'X';
2419                         }
2420                 }
2421                 i++;
2422         }
2423         if (message)
2424                 INFO("%s Buffer = [%s], Len(%d)", message, s, strlen(s));
2425         else
2426                 INFO("[%s]", s);
2427 }
2428
2429 static int __bt_ag_at_handler(bt_ag_info_t *hs, const char *buf)
2430 {
2431         struct event *ev;
2432
2433         __bt_ag_agent_print_at_buffer("[AG AT CMD][RCVD] :", buf);
2434
2435         for (ev = at_event_callbacks; ev->cmd; ev++) {
2436                 if (!strncmp(buf, ev->cmd, strlen(ev->cmd)))
2437                         return ev->callback(hs, buf);
2438         }
2439
2440         return -EINVAL;
2441 }
2442
2443 static int __bt_ag_send_at_valist(bt_ag_info_t *hdset, va_list list,
2444                         char *list_format)
2445 {
2446         ssize_t final_written, count;
2447         char rsp_buffer[MAX_BUFFER_SIZE];
2448         int fd;
2449         int err;
2450
2451         count = vsnprintf(rsp_buffer, sizeof(rsp_buffer), list_format, list);
2452         if (count < 0) {
2453                 ERR("count is %d", count);
2454                 return -EINVAL;
2455         }
2456
2457         if (!hdset->io_chan) {
2458                 ERR("__bt_ag_send_at_valist: headset not connected");
2459                 return -EIO;
2460         }
2461
2462         final_written = 0;
2463
2464         fd = g_io_channel_unix_get_fd(hdset->io_chan);
2465
2466         if (fd != 0) {
2467                 while (final_written < count) {
2468                         ssize_t written;
2469
2470                         do {
2471                                 written = write(fd, rsp_buffer + final_written,
2472                                                 count - final_written);
2473                         } while (written < 0 && errno == EINTR);
2474
2475                         if (written < 0) {
2476                                 err = -errno;
2477                                 ERR("write failed : %s (%d)", strerror(-err), -err);
2478                                 return -errno;
2479                         }
2480
2481                         final_written += written;
2482                 }
2483
2484                 /* Synchronize the sending buffer */
2485                 sync();
2486                 fsync(fd);
2487         } else {
2488                 ERR("FD is 0. remote_addr : %s", hdset->remote_addr);
2489                 return -1;
2490         }
2491
2492         __bt_ag_agent_print_at_buffer("[AG AT CMD][SENT]", rsp_buffer);
2493
2494         return 0;
2495 }
2496
2497 int __attribute__((format(printf, 2, 3)))
2498                         _bt_ag_send_at(bt_ag_info_t *hs, char *format, ...)
2499 {
2500         va_list ap;
2501         int ret;
2502
2503         va_start(ap, format);
2504         ret = __bt_ag_send_at_valist(hs, ap, format);
2505         va_end(ap);
2506
2507         return ret;
2508 }
2509
2510 void __attribute__((format(printf, 3, 4)))
2511                 _bt_ag_send_foreach_headset(GSList *devices,
2512                                 int (*cmp) (bt_ag_info_t *hs),
2513                                 char *format, ...)
2514 {
2515         GSList *l;
2516         va_list ap;
2517
2518         for (l = devices; l != NULL; l = l->next) {
2519                 bt_ag_info_t *hs = l->data;
2520                 int ret;
2521
2522                 if (cmp && cmp(hs) != 0)
2523                         continue;
2524
2525                 va_start(ap, format);
2526                 ret = __bt_ag_send_at_valist(hs, ap, format);
2527                 if (ret < 0)
2528                         ERR("Failed to send to headset: %s (%d)",
2529                                         strerror(-ret), -ret);
2530                 va_end(ap);
2531         }
2532 }
2533
2534 int _bt_ag_send_response(bt_ag_info_t *hs, hfp_state_manager_err_t err)
2535 {
2536         if ((err != HFP_STATE_MNGR_ERR_NONE) && hs->slc->is_cme_enabled)
2537                 return _bt_ag_send_at(hs, "\r\n+CME ERROR: %d\r\n", err);
2538
2539         switch (err) {
2540         case HFP_STATE_MNGR_ERR_NONE:
2541                 return _bt_ag_send_at(hs, "\r\nOK\r\n");
2542         case HFP_STATE_MNGR_ERR_NO_NETWORK_SERVICE:
2543                 return _bt_ag_send_at(hs, "\r\nNO CARRIER\r\n");
2544         default:
2545                 return _bt_ag_send_at(hs, "\r\nERROR\r\n");
2546         }
2547 }
2548
2549 static gboolean __bt_ag_event_handler(GIOChannel *channel,
2550                                 GIOCondition cond, void *user_data)
2551 {
2552         bt_ag_slconn_t *slconn;
2553         unsigned char event_buf[MAX_BUFFER_SIZE];
2554         ssize_t len;
2555         size_t available_buffer;
2556         int fd;
2557         bt_ag_info_t *bt_ag_info = (bt_ag_info_t *)user_data;
2558         int err_return = 0;
2559
2560
2561         if (cond & G_IO_NVAL)
2562                 return FALSE;
2563
2564         slconn = bt_ag_info->slc;
2565         if (cond & (G_IO_ERR | G_IO_HUP)) {
2566                 if (bt_ag_info->watch_id)
2567                         __bt_ag_agent_remove_watch(&bt_ag_info->watch_id);
2568
2569                 ERR("ERR or HUP on RFCOMM socket");
2570                 INFO_C("Disconnected [AG role] [Terminated by remote dev]");
2571                 goto failed;
2572         }
2573
2574         fd = g_io_channel_unix_get_fd(channel);
2575         len = read(fd, event_buf, sizeof(event_buf) - 1);
2576
2577         if (len < 0)
2578                 return FALSE;
2579         available_buffer = sizeof(slconn->buffer) - (slconn->start) -
2580                                 (slconn->length) - 1;
2581         if (available_buffer < (size_t) len) {
2582                 ERR("Buffer over flow");
2583                 goto failed;
2584         }
2585
2586         memcpy(&slconn->buffer[slconn->start + slconn->length], event_buf, len);
2587         slconn->length += len;
2588
2589         slconn->buffer[slconn->start + slconn->length] = '\0';
2590
2591         while (slconn->length > 0) {
2592                 char *get_cr;
2593                 int err;
2594                 off_t cmd_len;
2595
2596                 get_cr = strchr(&slconn->buffer[slconn->start], '\r');
2597                 if (!get_cr) {
2598                         ERR("Broken AT command received, break");
2599                         break;
2600                 }
2601
2602                 cmd_len = 1 + (off_t) get_cr -
2603                         (off_t) &slconn->buffer[slconn->start];
2604                 *get_cr = '\0';
2605
2606                 if (cmd_len > 1) {
2607                         DBG("Call AT handler");
2608                         err = __bt_ag_at_handler(bt_ag_info,
2609                                         &slconn->buffer[slconn->start]);
2610                 } else {
2611                         ERR("Failed to call AT handler");
2612                         err = 0;
2613                 }
2614
2615                 if (err < 0) {
2616                         switch (err) {
2617                         case -EINVAL:
2618                                 err_return = HFP_STATE_MNGR_ERR_NOT_SUPPORTED;
2619                                 break;
2620                         case -EACCES:
2621                                 err_return = HFP_STATE_MNGR_ERR_NOT_ALLOWED;
2622                                 break;
2623                         default:
2624                                 err_return = HFP_STATE_MNGR_ERR_NOT_SUPPORTED;
2625                                 break;
2626                         }
2627                         ERR("Error handling command %s: %s (%d)",
2628                                                 &slconn->buffer[slconn->start],
2629                                                 strerror(-err), -err);
2630                         err = _bt_ag_send_response(bt_ag_info,
2631                                         err_return);
2632                         if (err < 0)
2633                                 goto failed;
2634                 }
2635
2636                 slconn->start += cmd_len;
2637                 slconn->length -= cmd_len;
2638
2639                 if (slconn->length <= 0)
2640                         slconn->start = 0;
2641         }
2642         return TRUE;
2643 failed:
2644         ERR("Failed in event handler - SLC Disconnect");
2645         _bt_ag_set_headset_state(bt_ag_info,
2646                                         HEADSET_STATE_DISCONNECTED);
2647         return FALSE;
2648 }
2649
2650 static gboolean __bt_ag_agent_connection(gint32 fd, const gchar *device_path,
2651                                                 const gchar *object_path)
2652 {
2653         GIOFlags flags;
2654
2655         bt_ag_info_t *bt_ag_info = g_new0(bt_ag_info_t, 1);
2656         struct sockaddr_remote address;
2657         socklen_t address_len;
2658
2659         INFO_C("Connected [AG role]");
2660         bt_ag_info->rfcomm = NULL;
2661         bt_ag_info->slc = NULL;
2662         bt_ag_info->hfp_active = TRUE;
2663         bt_ag_info->vr_blacklisted = FALSE;
2664         bt_ag_info->state = HEADSET_STATE_DISCONNECTED;
2665         bt_ag_info->sco_server_started = FALSE;
2666         __bt_ag_codec_negotiation_info_reset(bt_ag_info, TRUE);
2667
2668         bt_ag_info->path = device_path;
2669         DBG("device_path = [%s]", device_path);
2670
2671         address_len = sizeof(address);
2672         if (getpeername(fd, (struct sockaddr *) &address, &address_len) != 0)
2673                 ERR("BD_ADDR is NULL");
2674
2675         DBG("RFCOMM connection for HFP/HSP is completed. Fd = [%d]", fd);
2676         bt_ag_info->fd = fd;
2677         bt_ag_info->io_chan = g_io_channel_unix_new(bt_ag_info->fd);
2678         flags = g_io_channel_get_flags(bt_ag_info->io_chan);
2679
2680         flags &= ~G_IO_FLAG_NONBLOCK;
2681         flags &= G_IO_FLAG_MASK;
2682         g_io_channel_set_flags(bt_ag_info->io_chan, flags, NULL);
2683         g_io_channel_set_encoding(bt_ag_info->io_chan, NULL, NULL);
2684         g_io_channel_set_buffered(bt_ag_info->io_chan, FALSE);
2685
2686         bt_ag_info->rfcomm = g_io_channel_ref(bt_ag_info->io_chan);
2687
2688         bt_ag_info->remote_addr = g_malloc0(BT_ADDRESS_STRING_SIZE);
2689         __bt_convert_addr_type_to_rev_string(bt_ag_info->remote_addr,
2690                                                 address.remote_bdaddr.b);
2691
2692 #if defined(TIZEN_SUPPORT_DUAL_HF)
2693         bt_ag_info->is_companion_device =
2694                         __bt_ag_agent_is_companion_device(bt_ag_info->remote_addr);
2695 #endif
2696
2697         DBG("remote Device Address = [%s]", bt_ag_info->remote_addr);
2698
2699         if (g_strcmp0(object_path, BT_HS_AG_AGENT_OBJECT_PATH) == 0) {
2700                 DBG("HSP connection completed");
2701                 _bt_ag_set_headset_state(bt_ag_info,
2702                                                 HEADSET_STATE_CONNECTED);
2703         } else {
2704                 DBG("HFP connection connecting");
2705                 _bt_ag_set_headset_state(bt_ag_info,
2706                                                 HEADSET_STATE_CONNECTING);
2707         }
2708
2709         __bt_ag_agent_start_watch(bt_ag_info);
2710
2711         bt_ag_info->slc = g_new0(bt_ag_slconn_t, 1);
2712         bt_ag_info->slc->speaker_gain = 15;
2713         bt_ag_info->slc->microphone_gain = 15;
2714         bt_ag_info->slc->is_nrec = TRUE;
2715
2716         return TRUE;
2717 }
2718
2719 static gboolean __bt_ag_agent_is_device_vr_blacklisted(const char *lap_addr)
2720 {
2721         char *buffer;
2722         FILE *fp;
2723         long size;
2724         size_t result;
2725         char *token;
2726         char *saveptr;
2727
2728         fp = fopen(AGENT_VR_BLACKLIST_FILE, "r");
2729
2730         if (fp == NULL) {
2731                 ERR("Unable to open VR blacklist file");
2732                 return FALSE;
2733         }
2734
2735         fseek(fp, 0, SEEK_END);
2736         size = ftell(fp);
2737         if (size <= 0) {
2738                 ERR("size is not a positive number");
2739                 fclose(fp);
2740                 return FALSE;
2741         }
2742
2743         rewind(fp);
2744
2745         buffer = g_malloc0(sizeof(char) * size);
2746         if (buffer == NULL) {
2747                 ERR("g_malloc0 is failed");
2748                 fclose(fp);
2749                 return FALSE;
2750         }
2751         result = fread((char *)buffer, 1, size, fp);
2752         fclose(fp);
2753         if (result != size) {
2754                 ERR("Read Error");
2755                 g_free(buffer);
2756                 return FALSE;
2757         }
2758
2759         token = strtok_r(buffer, "=", &saveptr);
2760         if (token == NULL) {
2761                 g_free(buffer);
2762                 return FALSE;
2763         }
2764
2765         while ((token = strtok_r(NULL, ",", &saveptr))) {
2766                 if (strlen(token) > 8)
2767                         token[8] = '\0';
2768                 if (0 == g_strcmp0(token, lap_addr)) {
2769                         INFO("Voice Recognition blacklisted");
2770                         g_free(buffer);
2771                         return TRUE;
2772                 }
2773         }
2774         g_free(buffer);
2775         return FALSE;
2776 }
2777
2778 static gboolean __bt_sco_open_delay_timeout_cb(gpointer user_data)
2779 {
2780         bt_ag_info_t *bt_ag_info = (bt_ag_info_t *)user_data;
2781         sco_open_timer_id = 0;
2782         DBG("sco_open_request (%d)", sco_open_request);
2783
2784         if (sco_open_request && bt_ag_info->state == HEADSET_STATE_CONNECTED) {
2785                 bt_ag_slconn_t *slconn = bt_ag_info->slc;
2786
2787                 INFO("try to open SCO");
2788                 sco_open_request = FALSE;
2789
2790                 if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
2791                                 (slconn && (slconn->hs_features &
2792                                         BT_HF_FEATURE_CODEC_NEGOTIATION))) {
2793                         switch (bt_ag_info->codec_info.final_codec) {
2794                         case BT_CVSD_CODEC_ID:
2795                                 __bt_ag_set_codec(bt_ag_info, "SetNbParameters");
2796                                 __bt_ag_sco_connect(bt_ag_info);
2797                                 break;
2798                         case BT_MSBC_CODEC_ID:
2799                                 __bt_ag_set_codec(bt_ag_info, "SetWbsParameters");
2800                                 __bt_ag_sco_connect(bt_ag_info);
2801                                 break;
2802                         default:
2803                                 __bt_hfp_codec_connection_setup(bt_ag_info, FALSE);
2804                                 break;
2805                         }
2806                 } else
2807                         __bt_ag_sco_connect(bt_ag_info);
2808         }
2809
2810         return FALSE;
2811 }
2812
2813 /*
2814 * Service level connection complete
2815 * indication and state management
2816 */
2817 void _bt_ag_slconn_complete(bt_ag_info_t *hs)
2818 {
2819         char lap_address[BT_LOWER_ADDRESS_LENGTH];
2820
2821         DBG("HFP Service Level Connection established\n");
2822
2823         /* Check device Voice Recognition blacklist status */
2824         g_strlcpy(lap_address, hs->remote_addr, sizeof(lap_address));
2825         hs->vr_blacklisted =
2826                 __bt_ag_agent_is_device_vr_blacklisted(lap_address);
2827
2828         if (sco_open_timer_id > 0) {
2829                 g_source_remove(sco_open_timer_id);
2830                 sco_open_timer_id = 0;
2831         }
2832
2833         sco_open_request = FALSE;
2834         sco_open_timer_id = g_timeout_add(BT_SCO_OPEN_DELAY_TIMER,
2835                                                 __bt_sco_open_delay_timeout_cb, hs);
2836
2837         _bt_ag_set_headset_state(hs, HEADSET_STATE_CONNECTED);
2838 }
2839
2840 static gboolean __bt_ag_agent_connection_release(bt_ag_info_t *hs)
2841 {
2842
2843         g_io_channel_shutdown(hs->io_chan, TRUE, NULL);
2844         g_io_channel_unref(hs->io_chan);
2845         hs->io_chan = NULL;
2846
2847         if (hs->sco) {
2848                 __bt_ag_close_sco(hs);
2849                 _bt_ag_set_headset_state(hs, HEADSET_STATE_CONNECTED);
2850         }
2851         __bt_ag_agent_remove_watch(&hs->watch_id);
2852
2853         _bt_ag_set_headset_state(hs, HEADSET_STATE_DISCONNECTED);
2854         return TRUE;
2855 }
2856
2857 static GQuark __bt_ag_agent_error_quark(void)
2858 {
2859         FN_START;
2860
2861         static GQuark quark = 0;
2862         if (!quark)
2863                 quark = g_quark_from_static_string("ag-agent");
2864
2865         FN_END;
2866         return quark;
2867 }
2868
2869 static GError *__bt_ag_agent_set_error(bt_hfp_agent_error_t error)
2870 {
2871         FN_START;
2872         ERR("error[%d]\n", error);
2873
2874         switch (error) {
2875         case BT_HFP_AGENT_ERROR_NOT_AVAILABLE:
2876                 return g_error_new(BT_AG_AGENT_ERROR, error,
2877                                         BT_ERROR_NOT_AVAILABLE);
2878         case BT_HFP_AGENT_ERROR_NOT_CONNECTED:
2879         return g_error_new(BT_AG_AGENT_ERROR, error,
2880                                         BT_ERROR_NOT_CONNECTED);
2881         case BT_HFP_AGENT_ERROR_BUSY:
2882                 return g_error_new(BT_AG_AGENT_ERROR, error,
2883                                                 BT_ERROR_BUSY);
2884         case BT_HFP_AGENT_ERROR_INVALID_PARAM:
2885                 return g_error_new(BT_AG_AGENT_ERROR, error,
2886                                                 BT_ERROR_INVALID_PARAM);
2887         case BT_HFP_AGENT_ERROR_ALREADY_EXSIST:
2888                 return g_error_new(BT_AG_AGENT_ERROR, error,
2889                                                 BT_ERROR_ALREADY_EXSIST);
2890         case BT_HFP_AGENT_ERROR_ALREADY_CONNECTED:
2891                 return g_error_new(BT_AG_AGENT_ERROR, error,
2892                                                 BT_ERROR_ALREADY_CONNECTED);
2893         case BT_HFP_AGENT_ERROR_NO_MEMORY:
2894                 return g_error_new(BT_AG_AGENT_ERROR, error,
2895                                                 BT_ERROR_NO_MEMORY);
2896         case BT_HFP_AGENT_ERROR_I_O_ERROR:
2897                 return g_error_new(BT_AG_AGENT_ERROR, error,
2898                                                 BT_ERROR_I_O_ERROR);
2899         case BT_HFP_AGENT_ERROR_OPERATION_NOT_AVAILABLE:
2900                 return g_error_new(BT_AG_AGENT_ERROR, error,
2901                                         BT_ERROR_OPERATION_NOT_AVAILABLE);
2902         case BT_HFP_AGENT_ERROR_BATTERY_STATUS:
2903                 return g_error_new(BT_AG_AGENT_ERROR, error,
2904                                         BT_ERROR_BATTERY);
2905         case BT_HFP_AGENT_ERROR_SIGNAL_STATUS:
2906                 return g_error_new(BT_AG_AGENT_ERROR, error,
2907                                         BT_ERROR_SIGNAL);
2908         case BT_HFP_AGENT_ERROR_NO_CALL_LOGS:
2909                 return g_error_new(BT_AG_AGENT_ERROR, error,
2910                                         BT_ERROR_NO_CALL_LOG);
2911         case BT_HFP_AGENT_ERROR_INTERNAL:
2912         default:
2913                 return g_error_new(BT_AG_AGENT_ERROR, error,
2914                                                 BT_ERROR_INTERNAL);
2915         }
2916         FN_END;
2917 }
2918
2919 static bt_ag_info_t *__bt_get_active_headset(const gchar *device_path)
2920 {
2921         GSList *l;
2922
2923         for (l = active_devices ; l; l = l->next) {
2924                 bt_ag_info_t *data = l->data;
2925                 if (device_path == NULL) /*just to avoid crash incase of "play" when dailed from device[NEEDS TO BE CHANGED]*/
2926                         return data;
2927                 if (g_strcmp0(data->path, device_path) == 0) {
2928                         INFO("Active device found");
2929                         return data;
2930                 }
2931         }
2932
2933         INFO("Active device not found");
2934         return NULL;
2935 }
2936
2937 static void __bt_ag_agent_method(GDBusConnection *connection,
2938                         const gchar *sender,
2939                         const gchar *object_path,
2940                         const gchar *interface_name,
2941                         const gchar *method_name,
2942                         GVariant *parameters,
2943                         GDBusMethodInvocation *invocation,
2944                         gpointer user_data)
2945 {
2946         FN_START;
2947
2948         INFO("method %s", method_name);
2949         INFO("object_path %s", object_path);
2950         int ret = BT_HFP_AGENT_ERROR_NONE;
2951         GError *err = NULL;
2952         const gchar *device_path = NULL;
2953
2954         if (g_strcmp0(method_name, "NewConnection") == 0) {
2955                 gint32 fd;
2956                 int index = 0;
2957                 GDBusMessage *msg;
2958                 GUnixFDList *fd_list;
2959                 GVariant *options = NULL;
2960                 int device_count = 0;
2961
2962                 device_count = g_slist_length(active_devices);
2963
2964                 INFO("device_count %d", device_count);
2965
2966                 if (device_count >= MAX_CONNECTED_DEVICES) {
2967                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2968                         goto fail;
2969                 }
2970
2971                 g_variant_get(parameters, "(oha{sv})",
2972                                                 &device_path, &index, &options);
2973
2974 #if defined(TIZEN_SUPPORT_DUAL_HF) && defined(TIZEN_PROFILE_WEARABLE)
2975                 /*
2976                  * Below code is not required for dual HF support for
2977                  * mobile devices
2978                  */
2979                 if (device_count &&
2980                         __bt_ag_agent_check_dual_hf_condition(device_path) == FALSE) {
2981                         INFO("not allow to connect 2nd HF connection");
2982                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2983                         goto fail;
2984                 }
2985 #endif
2986                 msg = g_dbus_method_invocation_get_message(invocation);
2987                 fd_list = g_dbus_message_get_unix_fd_list(msg);
2988                 if (fd_list == NULL) {
2989                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2990                         goto fail;
2991                 }
2992
2993                 fd = g_unix_fd_list_get(fd_list, index, NULL);
2994                 if (fd == -1) {
2995                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
2996                         goto fail;
2997                 }
2998
2999                 DBG("FD is = [%d], device_path = [%s]\n", fd, device_path);
3000
3001                 if (!__bt_ag_agent_connection(fd, device_path, object_path)) {
3002                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3003                         goto fail;
3004                 }
3005
3006                 g_dbus_method_invocation_return_value(invocation, NULL);
3007         } else if (g_strcmp0(method_name, "RequestDisconnection") == 0) {
3008                 GSList *l;
3009
3010                 g_variant_get(parameters, "(o)", &device_path);
3011                 INFO("device_path %s", device_path);
3012
3013                 for (l = active_devices; l; l = l->next) {
3014                         bt_ag_info_t *data = l->data;
3015
3016                         INFO("data->path %s", data->path);
3017                         if (g_strcmp0(data->path, device_path) == 0) {
3018                                 if (!__bt_ag_agent_connection_release(data)) {
3019                                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3020                                         goto fail;
3021                                 }
3022                                 INFO_C("Disconnected [AG role] [Terminated by local host]");
3023                                 g_dbus_method_invocation_return_value(invocation, NULL);
3024                         }
3025                 }
3026         } else if (g_strcmp0(method_name, "RegisterApplication") == 0) {
3027                 gchar *path = NULL;
3028                 gchar *address = NULL;
3029                 g_variant_get(parameters, "(&s&s)", &path, &address);
3030                 /*local_addr = malloc(strlen(address));
3031                 memcpy(local_addr, address, strlen(address));*/
3032
3033                 DBG("Sender = %s, Application path = %s\n", sender, path);
3034                 ret = _bt_hfp_register_telephony_agent(TRUE, path, sender);
3035                 if (ret)
3036                         goto fail;
3037
3038                 g_free(local_addr);
3039                 local_addr = g_strdup(address);
3040                 DBG("Address = %s\n", local_addr);
3041                 g_dbus_method_invocation_return_value(invocation, NULL);
3042         } else if (g_strcmp0(method_name, "UnregisterApplication") == 0) {
3043                 gchar *path = NULL;
3044                 g_variant_get(parameters, "(&s)", &path);
3045
3046                 DBG("Application path = %s\n", path);
3047                 DBG("Sender = %s\n", sender);
3048
3049                 ret = _bt_hfp_register_telephony_agent(FALSE, path, sender);
3050                 if (ret)
3051                         goto fail;
3052
3053                 g_dbus_method_invocation_return_value(invocation, NULL);
3054         } else if (g_strcmp0(method_name, "IncomingCall") == 0) {
3055                 gchar *path = NULL;
3056                 gchar *number = NULL;
3057                 gint call_id = 0;
3058
3059                 g_variant_get(parameters, "(&s&si)", &path, &number, &call_id);
3060
3061                 DBG("Application path = %s", path);
3062                 DBG_SECURE("Phone number = %s", number);
3063                 DBG("Call id = %d", call_id);
3064
3065                 DBG("Sender = %s", sender);
3066
3067                 ret = _bt_hfp_incoming_call(path, number, call_id, sender);
3068                 if (ret)
3069                         goto fail;
3070                 g_dbus_method_invocation_return_value(invocation, NULL);
3071         } else if (g_strcmp0(method_name, "OutgoingCall") == 0) {
3072                 gchar *path = NULL;
3073                 gchar *number = NULL;
3074                 gint call_id = 0;
3075
3076                 g_variant_get(parameters, "(&s&si)", &path, &number, &call_id);
3077
3078                 DBG("Application path = %s", path);
3079                 DBG_SECURE("Phone number = %s", number);
3080                 DBG("Call id = %d", call_id);
3081
3082                 DBG("Sender = %s", sender);
3083
3084                 ret = _bt_hfp_outgoing_call(path, number, call_id, sender);
3085                 if (ret)
3086                         goto fail;
3087                 g_dbus_method_invocation_return_value(invocation, NULL);
3088         } else if (g_strcmp0(method_name, "ChangeCallStatus") == 0) {
3089                 gchar *path = NULL;
3090                 gchar *number = NULL;
3091                 gint status = 0;
3092                 gint call_id = 0;
3093                 GSList *l;
3094
3095                 g_variant_get(parameters, "(&s&sii)",
3096                                         &path, &number, &status, &call_id);
3097                 DBG("Application path = %s\n", path);
3098                 DBG_SECURE("Number = %s\n", number);
3099                 DBG("Status = %d\n", status);
3100                 DBG("Call id = %d\n", call_id);
3101                 DBG("Sender = %s\n", sender);
3102
3103                 ret = _bt_hfp_change_call_status(path,
3104                                         number, status, call_id, sender);
3105
3106                 if (_bt_hfp_is_call_exist() == FALSE) {
3107                         for (l = active_devices; l; l = l->next) {
3108                                 bt_ag_info_t *data = l->data;
3109
3110                                 if (data->state == HEADSET_STATE_ON_CALL) {
3111                                         __bt_ag_close_sco(data);
3112                                         _bt_ag_set_headset_state(data,
3113                                                 HEADSET_STATE_CONNECTED);
3114                                 }
3115                         }
3116                 }
3117
3118                 if (ret)
3119                         goto fail;
3120                 g_dbus_method_invocation_return_value(invocation, NULL);
3121         } else if (g_strcmp0(method_name, "GetProperties") == 0) {
3122                 GVariantBuilder *builder;
3123                 GVariant *var_data;
3124                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3125
3126                 if (bt_ag_info) {
3127                         gchar *codec = g_strdup("codec");
3128                         gchar *nrec = g_strdup("nrec");
3129
3130                         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
3131
3132                         g_variant_builder_add(builder, "{sv}",
3133                                         codec, g_variant_new("u", bt_ag_info->codec_info.final_codec));
3134                         g_variant_builder_add(builder, "{sv}",
3135                                         nrec, g_variant_new("b", bt_ag_info->nrec_status));
3136
3137                         var_data = g_variant_new("(a{sv})", builder);
3138                         g_variant_builder_unref(builder);
3139                         g_dbus_method_invocation_return_value(invocation, var_data);
3140
3141                         g_free(codec);
3142                         g_free(nrec);
3143                 } else {
3144                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3145                         goto fail;
3146                 }
3147         } else if (g_strcmp0(method_name, "Disconnect") == 0) {
3148                 char hdset_address[18] = { 0, };
3149                 GSList *l;
3150
3151                 for (l = active_devices; l; l = l->next) {
3152                         bt_ag_info_t *data = l->data;
3153
3154                         __bt_convert_addr_type_to_rev_string(hdset_address,
3155                                         (unsigned char *)data->remote_addr);
3156
3157                         DBG("Disconnect Headset %s, %s\n",
3158                                                 hdset_address, data->path);
3159                         _bt_ag_set_headset_state(data,
3160                                                 HEADSET_STATE_DISCONNECTED);
3161                 }
3162                 g_dbus_method_invocation_return_value(invocation, NULL);
3163         } else if (g_strcmp0(method_name, "IsConnected") == 0) {
3164                 gboolean is_connected = FALSE;
3165                 GSList *l;
3166
3167                 for (l = active_devices; l; l = l->next) {
3168                         bt_ag_info_t *data = l->data;
3169
3170                         if (data->state == HEADSET_STATE_CONNECTED)
3171                                 is_connected = TRUE;
3172                 }
3173                 DBG("is_connected : %s",
3174                                 is_connected ? "Connected" : "Disconnected");
3175
3176                 g_dbus_method_invocation_return_value(invocation,
3177                                 g_variant_new("(b)", is_connected));
3178         } else if (g_strcmp0(method_name, "IndicateCall") == 0) {
3179                 GSList *l;
3180
3181                 if (0 == g_slist_length(active_devices)) {
3182                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3183                         goto fail;
3184                 }
3185
3186                 if (ag.ring_timer) {
3187                         DBG("IndicateCall received when already indicating");
3188                         g_dbus_method_invocation_return_value(invocation, NULL);
3189                 }
3190
3191                 for (l = active_devices; l; l = l->next) {
3192                         bt_ag_info_t *data = l->data;
3193
3194                         if (data->state >= HEADSET_STATE_CONNECTED)
3195                                 _bt_ag_send_at(data, "\r\nRING\r\n");
3196                 }
3197
3198                 __bt_ring_timer_cb(NULL);
3199                 ag.ring_timer = g_timeout_add(AG_RING_INTERVAL,
3200                                 __bt_ring_timer_cb, NULL);
3201                 g_dbus_method_invocation_return_value(invocation, NULL);
3202         } else if (g_strcmp0(method_name, "CancelCall") == 0) {
3203                 if (0 == g_slist_length(active_devices)) {
3204                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3205                         goto fail;
3206                 }
3207
3208                 if (ag.ring_timer) {
3209                         g_source_remove(ag.ring_timer);
3210                         ag.ring_timer = 0;
3211                 } else
3212                         DBG("Got CancelCall method call but no call is active");
3213
3214                 g_dbus_method_invocation_return_value(invocation, NULL);
3215         } else if (g_strcmp0(method_name, "Play") == 0) {
3216                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3217                 bt_ag_slconn_t *slconn = NULL;
3218
3219                 if (bt_ag_info) {
3220                         slconn = bt_ag_info->slc;
3221                 } else {
3222                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3223                         goto fail;
3224                 }
3225
3226 #ifndef __TIZEN_OPEN__
3227 #ifdef MDM_PHASE_2
3228                 int mode;
3229                 if (slconn && FALSE == slconn->is_voice_recognition_running &&
3230                                 mdm_get_service() == MDM_RESULT_SUCCESS) {
3231                         mode = mdm_get_allow_bluetooth_outgoing_call();
3232                         mdm_release_service();
3233
3234                         if (mode == MDM_RESTRICTED) {
3235                                 ERR("[MDM] Not allow the outgoing call");
3236                                 ret = BT_HFP_AGENT_ERROR_OPERATION_NOT_AVAILABLE;
3237                                 goto fail;
3238                         }
3239                 }
3240 #endif
3241 #endif
3242
3243                 switch (bt_ag_info->state) {
3244                 case HEADSET_STATE_CONNECTING:
3245                 case HEADSET_STATE_DISCONNECTED:
3246                         ERR("HEADSET_STATE  ERROR");
3247                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3248                         break;
3249                 case HEADSET_STATE_CONNECTED:
3250                         break;
3251                 case HEADSET_STATE_PLAY_IN_PROGRESS:
3252                         ERR("Play In Progress");
3253                         ret = BT_HFP_AGENT_ERROR_BUSY;
3254                         break;
3255                 default:
3256                         break;
3257                 }
3258                 if (ret)
3259                         goto fail;
3260
3261                 if (sco_open_timer_id > 0) {
3262                         INFO("SCO open delay");
3263                         sco_open_request = TRUE;
3264                         g_dbus_method_invocation_return_value(invocation, NULL);
3265                         return;
3266                 }
3267
3268                 if ((ag.features & BT_AG_FEATURE_CODEC_NEGOTIATION) &&
3269                                 (slconn && (slconn->hs_features &
3270                                         BT_HF_FEATURE_CODEC_NEGOTIATION))) {
3271                         switch (bt_ag_info->codec_info.final_codec) {
3272                         case BT_CVSD_CODEC_ID:
3273                                 __bt_ag_set_codec(bt_ag_info, "SetNbParameters");
3274                                 ret = __bt_ag_sco_connect(bt_ag_info);
3275                                 break;
3276                         case BT_MSBC_CODEC_ID:
3277                                 __bt_ag_set_codec(bt_ag_info, "SetWbsParameters");
3278                                 ret = __bt_ag_sco_connect(bt_ag_info);
3279                                 break;
3280                         default:
3281                                 ret = __bt_hfp_codec_connection_setup(bt_ag_info, FALSE);
3282                                 break;
3283                         }
3284                 } else
3285                         ret = __bt_ag_sco_connect(bt_ag_info);
3286
3287                 if (ret)
3288                         goto fail;
3289
3290                 g_free(sco_owner);
3291                 sco_owner = g_strdup(sender);
3292
3293                 g_dbus_method_invocation_return_value(invocation, NULL);
3294
3295                 name_owner_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
3296                                         NULL, NULL, "NameOwnerChanged", NULL, NULL, 0,
3297                                         __bt_ag_name_owner_changed_cb, NULL, NULL);
3298         } else if (g_strcmp0(method_name, "Stop") == 0) {
3299                 GSList *l;
3300
3301                 for (l = active_devices; l; l = l->next) {
3302                         bt_ag_info_t *data = l->data;
3303
3304                         if (data->state > HEADSET_STATE_CONNECTED) {
3305                                 __bt_ag_close_sco(data);
3306                                 _bt_ag_set_headset_state(data,
3307                                         HEADSET_STATE_CONNECTED);
3308                         }
3309                 }
3310
3311                 g_dbus_method_invocation_return_value(invocation, NULL);
3312         } else if (g_strcmp0(method_name, "IsPlaying") == 0) {
3313                 gboolean is_playing = FALSE;
3314                 GSList *l;
3315
3316                 for (l = active_devices; l; l = l->next) {
3317                         bt_ag_info_t *data = l->data;
3318
3319                         if (data->state == HEADSET_STATE_ON_CALL)
3320                                 is_playing = TRUE;
3321                 }
3322                 DBG("is_playing : %s", is_playing ? "Playing" : "Not Playing");
3323
3324                 g_dbus_method_invocation_return_value(invocation,
3325                                 g_variant_new("(b)", is_playing));
3326         } else if (g_strcmp0(method_name, "GetSpeakerGain") == 0) {
3327                 bt_ag_slconn_t *slconn = NULL;
3328                 guint16 gain_value = 0;
3329                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3330
3331                 if (bt_ag_info == NULL) {
3332                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3333                         goto fail;
3334                 }
3335
3336                 if (bt_ag_info->state < HEADSET_STATE_CONNECTED) {
3337                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3338                         goto fail;
3339                 }
3340
3341                 slconn = bt_ag_info->slc;
3342                 if (slconn)
3343                         gain_value = (guint16) slconn->speaker_gain;
3344
3345                 g_dbus_method_invocation_return_value(invocation,
3346                                 g_variant_new("(q)", gain_value));
3347         } else if (g_strcmp0(method_name, "SetSpeakerGain") == 0) {
3348                 guint16 gain = 0;
3349                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3350
3351                 g_variant_get(parameters, "(q)", &gain);
3352                 DBG("Speaker gain = %d\n", gain);
3353
3354                 if (bt_ag_info == NULL) {
3355                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3356                         goto fail;
3357                 }
3358
3359                 ret = _bt_hfp_set_speaker_gain(bt_ag_info, gain);
3360                 if (ret)
3361                         goto fail;
3362                 g_dbus_method_invocation_return_value(invocation, NULL);
3363         } else if (g_strcmp0(method_name, "GetMicrophoneGain") == 0) {
3364                 bt_ag_slconn_t *slconn = NULL;
3365                 guint16 gain_value = 0;
3366                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3367
3368                 if (bt_ag_info == NULL) {
3369                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3370                         goto fail;
3371                 }
3372
3373                 if (bt_ag_info->state < HEADSET_STATE_CONNECTED) {
3374                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3375                         goto fail;
3376                 }
3377
3378                 slconn = bt_ag_info->slc;
3379                 if (slconn)
3380                         gain_value = (guint16) slconn->microphone_gain;
3381
3382                 g_dbus_method_invocation_return_value(invocation,
3383                                 g_variant_new("(q)", gain_value));
3384         } else if (g_strcmp0(method_name, "SetMicrophoneGain") == 0) {
3385                 guint16 gain = 0;
3386                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3387
3388                 g_variant_get(parameters, "(q)", &gain);
3389                 DBG("Microphone gain = %d\n", gain);
3390
3391                 if (bt_ag_info == NULL) {
3392                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3393                         goto fail;
3394                 }
3395
3396                 ret = _bt_hfp_set_microphone_gain(bt_ag_info, gain);
3397                 if (ret)
3398                         goto fail;
3399                 g_dbus_method_invocation_return_value(invocation, NULL);
3400         } else if (g_strcmp0(method_name, "SetVoiceDial") == 0) {
3401                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3402                 if (bt_ag_info == NULL) {
3403                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3404                         goto fail;
3405                 }
3406
3407                 bt_ag_slconn_t *slconn = bt_ag_info->slc;
3408                 gboolean enable;
3409
3410                 g_variant_get(parameters, "(b)", &enable);
3411                 DBG("VoiceDail enable = %d\n", enable);
3412
3413                 if ((slconn && !(slconn->hs_features &
3414                                         BT_HF_FEATURE_VOICE_RECOGNITION)))
3415                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3416                 else if (bt_ag_info->vr_blacklisted)
3417                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3418                 else
3419                         ret = _bt_hfp_set_voice_dial(bt_ag_info, enable);
3420
3421                 if (slconn)
3422                         slconn->is_voice_recognition_running = enable;
3423
3424                 if (ret)
3425                         goto fail;
3426                 g_dbus_method_invocation_return_value(invocation, NULL);
3427         } else if (g_strcmp0(method_name, "SendVendorAtCmd") == 0) {
3428                 gchar *cmd;
3429                 bt_ag_info_t *bt_ag_info = __bt_get_active_headset(remote_dev_path);
3430                 if (bt_ag_info == NULL) {
3431                         ret = BT_HFP_AGENT_ERROR_NOT_AVAILABLE;
3432                         goto fail;
3433                 }
3434
3435                 g_variant_get(parameters, "(&s)", &cmd);
3436                 if (cmd == NULL) {
3437                         ret = BT_HFP_AGENT_ERROR_INVALID_PARAM;
3438                         goto fail;
3439                 }
3440
3441                 DBG("vendor cmd = %s", cmd);
3442
3443                 ret = _bt_hfp_send_vendor_cmd(bt_ag_info, cmd);
3444                 if (ret)
3445                         goto fail;
3446                 g_dbus_method_invocation_return_value(invocation, NULL);
3447         } else if (g_strcmp0(method_name, "CheckPrivilege") == 0) {
3448                 DBG("Already pass dbus SMACK for bt-service::platform");
3449                 /* Return success */
3450                 g_dbus_method_invocation_return_value(invocation, NULL);
3451         }  else if (g_strcmp0(method_name, "SwapHeadset") == 0) {
3452                 GSList *l;
3453                 gchar *addr = NULL;
3454                 char address[BT_ADDRESS_STRING_SIZE];
3455                 char remote_addr[BT_ADDRESS_STRING_SIZE];
3456                 gboolean device_found = FALSE;
3457
3458                 g_variant_get(parameters, "(s)", &addr);
3459                 g_strlcpy(address, addr, sizeof(address));
3460                 DBG("Sender = %s", sender);
3461
3462                 /* Loop through connected headset list
3463                  * If found, update the remote_dev_path.
3464                  */
3465                 for (l = active_devices ; l; l = l->next) {
3466                         bt_ag_info_t *data = l->data;
3467                         g_strlcpy(remote_addr, data->remote_addr, sizeof(remote_addr));
3468                         if (g_strcmp0(remote_addr, address) == 0) {
3469                                 DBG("Active device found");
3470                                 if (data->path == NULL) {
3471                                         DBG("device path is null");
3472                                         ret = BT_HFP_AGENT_ERROR_INTERNAL;
3473                                         goto fail;
3474                                 }
3475                                 remote_dev_path = g_strdup(data->path);
3476                                 DBG("Setting device path %s as active device path", remote_dev_path);
3477                                 device_found = TRUE;
3478                                 break;
3479                         }
3480                 }
3481
3482                 if (!device_found) {
3483                         ret = BT_HFP_AGENT_ERROR_NOT_CONNECTED;
3484                         goto fail;
3485                 }
3486
3487                 g_dbus_method_invocation_return_value(invocation, NULL);
3488         }
3489
3490         INFO("-");
3491         return;
3492
3493 fail:
3494         err = __bt_ag_agent_set_error(ret);
3495         g_dbus_method_invocation_return_gerror(invocation, err);
3496         g_error_free(err);
3497         INFO("-");
3498 }
3499
3500 static const GDBusInterfaceVTable method_table = {
3501         __bt_ag_agent_method,
3502         NULL,
3503         NULL,
3504 };
3505
3506 static GDBusNodeInfo *__bt_ag_create_method_node_info
3507                                         (const gchar *introspection_data)
3508 {
3509         GError *err = NULL;
3510         GDBusNodeInfo *node_info = NULL;
3511
3512         if (introspection_data == NULL)
3513                 return NULL;
3514
3515         node_info = g_dbus_node_info_new_for_xml(introspection_data, &err);
3516
3517         if (err) {
3518                 ERR("Unable to create node: %s", err->message);
3519                 g_clear_error(&err);
3520         }
3521         return node_info;
3522 }
3523
3524 static GDBusConnection *__bt_ag_get_gdbus_connection(void)
3525 {
3526         FN_START;
3527
3528         GError *err = NULL;
3529
3530         if (ag_dbus_conn == NULL)
3531                 ag_dbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
3532
3533         if (!ag_dbus_conn) {
3534                 if (err) {
3535                         ERR("Unable to connect to dbus: %s", err->message);
3536                         g_clear_error(&err);
3537                 }
3538                 return NULL;
3539         }
3540         FN_END;
3541
3542         return ag_dbus_conn;
3543 }
3544
3545 static gboolean __bt_ag_register_profile_methods(void)
3546 {
3547         FN_START;
3548         GError *error = NULL;
3549         guint owner_id;
3550         GDBusNodeInfo *node_info = NULL;
3551         gchar *path;
3552
3553         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
3554                                 BT_AG_SERVICE_NAME,
3555                                 G_BUS_NAME_OWNER_FLAGS_NONE,
3556                                 NULL, NULL, NULL,
3557                                 NULL, NULL);
3558
3559         DBG("owner_id is [%d]", owner_id);
3560
3561         node_info = __bt_ag_create_method_node_info(
3562                                 ag_agent_bluez_introspection_xml);
3563         if (node_info == NULL)
3564                 return FALSE;
3565
3566         path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
3567         DBG("path is [%s]", path);
3568
3569         hf_bluez_id = g_dbus_connection_register_object(ag_dbus_conn, path,
3570                                         node_info->interfaces[0],
3571                                         &method_table,
3572                                         NULL, NULL, &error);
3573         if (hf_bluez_id == 0) {
3574                 ERR("Failed to register: %s", error->message);
3575                 g_error_free(error);
3576                 g_free(path);
3577                 g_dbus_node_info_unref(node_info);
3578                 return FALSE;
3579         }
3580         g_free(path);
3581
3582         /* Ag register profile methods for HSP*/
3583
3584         path = g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
3585         DBG("path is [%s]", path);
3586
3587         hs_bluez_id = g_dbus_connection_register_object(ag_dbus_conn, path,
3588                                         node_info->interfaces[0],
3589                                         &method_table,
3590                                         NULL, NULL, &error);
3591         if (hs_bluez_id == 0) {
3592                 ERR("Failed to register: %s", error->message);
3593                 g_error_free(error);
3594                 g_free(path);
3595                 g_dbus_node_info_unref(node_info);
3596                 return FALSE;
3597         }
3598         g_free(path);
3599         g_dbus_node_info_unref(node_info);
3600
3601         node_info = __bt_ag_create_method_node_info
3602                                 (ag_agent_app_introspection_xml);
3603         if (node_info == NULL)
3604                 return FALSE;
3605
3606         path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
3607         DBG("path is [%s]", path);
3608
3609         app_id = g_dbus_connection_register_object(ag_dbus_conn, path,
3610                                                 node_info->interfaces[0],
3611                                                 &method_table,
3612                                                 NULL, NULL, &error);
3613         if (app_id == 0) {
3614                 ERR("Failed to register: %s", error->message);
3615                 g_error_free(error);
3616                 g_free(path);
3617                 g_dbus_node_info_unref(node_info);
3618                 return FALSE;
3619         }
3620         g_free(path);
3621         g_dbus_node_info_unref(node_info);
3622
3623         FN_END;
3624         return TRUE;
3625 }
3626
3627 static void __bt_ag_unregister_profile_methods(void)
3628 {
3629         DBG("");
3630
3631         if (hf_bluez_id > 0) {
3632                 g_dbus_connection_unregister_object(ag_dbus_conn,
3633                                                         hf_bluez_id);
3634                 hf_bluez_id = 0;
3635         }
3636
3637         if (hs_bluez_id > 0) {
3638                 g_dbus_connection_unregister_object(ag_dbus_conn,
3639                                                         hs_bluez_id);
3640                 hs_bluez_id = 0;
3641         }
3642
3643         if (app_id > 0) {
3644                 g_dbus_connection_unregister_object(ag_dbus_conn,
3645                                                         app_id);
3646                 app_id = 0;
3647         }
3648 }
3649
3650 static GDBusProxy *__bt_ag_gdbus_get_service_proxy(const gchar *service,
3651                                 const gchar *path, const gchar *interface)
3652 {
3653         return (service_gproxy) ? service_gproxy :
3654                         __bt_ag_gdbus_init_service_proxy(service,
3655                                         path, interface);
3656 }
3657
3658 static void __bt_ag_agent_register(gchar *path, uint16_t profile_version,
3659                                 char *profile_uuid, const char* profile_name)
3660 {
3661         FN_START;
3662         GDBusProxy *proxy;
3663         GVariant *ret;
3664         GError *error = NULL;
3665         GVariantBuilder *builder;
3666
3667         proxy = __bt_ag_gdbus_get_service_proxy(BLUEZ_SERVICE_NAME,
3668                 "/org/bluez", BLUEZ_PROFILE_MGMT_INTERFACE);
3669         if (proxy == NULL)
3670                 return;
3671
3672
3673         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
3674
3675         g_variant_builder_add(builder, "{sv}",
3676                         "Name", g_variant_new("s",
3677                         profile_name));
3678         g_variant_builder_add(builder, "{sv}",
3679                         "Version", g_variant_new("q", profile_version));
3680         /*g_variant_builder_add(builder, "{sv}",
3681                         "Role", g_variant_new("s","client"));*/
3682         if (g_strcmp0(path, BT_AG_AGENT_OBJECT_PATH) == 0) {
3683                 g_variant_builder_add(builder, "{sv}",
3684                                 "features", g_variant_new("q", ag.sdp_features));
3685         }
3686
3687         ret = g_dbus_proxy_call_sync(proxy, "RegisterProfile",
3688                                         g_variant_new("(osa{sv})", path,
3689                                                         profile_uuid, builder),
3690                                         G_DBUS_CALL_FLAGS_NONE, -1,
3691                                         NULL, &error);
3692         g_variant_builder_unref(builder);
3693         /* set the name and role for the profile*/
3694         if (ret == NULL) {
3695                 /* dBUS-RPC is failed */
3696                 ERR("dBUS-RPC is failed");
3697
3698                 if (error != NULL) {
3699                         /* dBUS gives error cause */
3700                         ERR("D-Bus API failure: errCode[%x], message[%s]",
3701                                         error->code, error->message);
3702
3703                         g_clear_error(&error);
3704                 }
3705                 g_free(path);
3706                 return;
3707         }
3708         g_variant_unref(ret);
3709         g_free(path);
3710
3711         FN_END;
3712         return;
3713 }
3714
3715 static void __bt_ag_agent_unregister(gchar *path)
3716 {
3717         FN_START;
3718         GDBusProxy *proxy;
3719         GVariant *ret;
3720         GError *error = NULL;
3721
3722         proxy = __bt_ag_gdbus_get_service_proxy(BLUEZ_SERVICE_NAME,
3723                 "/org/bluez", BLUEZ_PROFILE_MGMT_INTERFACE);
3724         if (proxy == NULL)
3725                 return;
3726
3727
3728         ret = g_dbus_proxy_call_sync(proxy, "UnregisterProfile",
3729                                         g_variant_new("(o)", path),
3730                                         G_DBUS_CALL_FLAGS_NONE, -1,
3731                                         NULL, &error);
3732         g_free(path);
3733         /* set the name and role for the profile*/
3734         if (ret == NULL) {
3735                 /* dBUS-RPC is failed */
3736                 ERR("dBUS-RPC is failed");
3737
3738                 if (error != NULL) {
3739                         /* dBUS gives error cause */
3740                         ERR("D-Bus API failure: errCode[%x], message[%s]",
3741                                         error->code, error->message);
3742
3743                         g_clear_error(&error);
3744                 }
3745                 return;
3746         }
3747         g_variant_unref(ret);
3748
3749         if (local_addr) {
3750                 g_free(local_addr);
3751                 local_addr = NULL;
3752         }
3753         FN_END;
3754         return;
3755 }
3756
3757 static void __bt_ag_agent_battery_status_cb(keynode_t *node)
3758 {
3759         int batt = vconf_keynode_get_int(node);
3760
3761         _bt_hfp_set_property_value("BatteryBarsChanged", batt);
3762 }
3763
3764 static void __bt_ag_agent_network_signal_status_cb(keynode_t *node)
3765 {
3766         int signal_bar = vconf_keynode_get_int(node);
3767
3768         BT_CHECK_SIGNAL_STRENGTH(signal_bar);
3769         _bt_hfp_set_property_value("SignalBarsChanged", signal_bar);
3770 }
3771
3772 static void __bt_ag_agent_lunar_connection_status_cb(keynode_t *node)
3773 {
3774         gboolean status = vconf_keynode_get_bool(node);
3775         GSList *l;
3776         DBG("status = %d", status);
3777
3778         if (status == TRUE) {
3779                 for (l = active_devices; l; l = l->next) {
3780                         bt_ag_info_t *data = l->data;
3781                         _bt_ag_send_at(data, "\r\n+BSIR:1\r\n");
3782                 }
3783         }
3784 }
3785
3786 static void __bt_ag_agent_network_register_status_cb(keynode_t *node)
3787 {
3788         int service = vconf_keynode_get_int(node);
3789         bt_hfp_agent_network_registration_status_t network_service;
3790         int roam_status;
3791         int ret;
3792
3793         DBG("Current Signal Level = [%d] \n", service);
3794
3795         switch (service) {
3796         case VCONFKEY_TELEPHONY_SVCTYPE_NONE:
3797         case VCONFKEY_TELEPHONY_SVCTYPE_NOSVC:
3798         case VCONFKEY_TELEPHONY_SVCTYPE_SEARCH:
3799                 service = 0;
3800                 break;
3801         default:
3802                 service = 1;
3803                 break;
3804         }
3805
3806         ret = vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &roam_status);
3807         if (ret != 0) {
3808                 ERR("Get roaming status failed err = %d\n", ret);
3809                 return;
3810         }
3811
3812         if (roam_status == 0 && service == 1)
3813                 network_service = BT_AGENT_NETWORK_REG_STATUS_HOME;
3814         else if (roam_status == 1 && service == 1)
3815                 network_service = BT_AGENT_NETWORK_REG_STATUS_ROAMING;
3816         else
3817                 network_service = BT_AGENT_NETWORK_REG_STATUS_UNKOWN;
3818
3819         _bt_hfp_set_property_value("RegistrationChanged", network_service);
3820 }
3821
3822 static void __bt_ag_agent_subscribe_vconf_updates(void)
3823 {
3824         int ret;
3825
3826         DBG("\n");
3827
3828         ret = vconf_notify_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY,
3829                                 (void *)__bt_ag_agent_battery_status_cb, NULL);
3830         if (0 != ret)
3831                 ERR("Subsrciption to battery status failed err =  [%d]\n", ret);
3832
3833         ret = vconf_notify_key_changed(VCONFKEY_TELEPHONY_RSSI,
3834                         (void *)__bt_ag_agent_network_signal_status_cb, NULL);
3835         if (0 != ret)
3836                 ERR("Subsrciption to netowrk signal failed err =  [%d]\n", ret);
3837
3838         ret = vconf_notify_key_changed(VCONFKEY_TELEPHONY_SVCTYPE,
3839                         (void *)__bt_ag_agent_network_register_status_cb, NULL);
3840         if (0 != ret)
3841                 ERR("Subsrciption to network failed err =  [%d]\n", ret);
3842
3843         if (TIZEN_PROFILE_WEARABLE) {
3844                 ret = vconf_notify_key_changed(VCONF_KEY_BT_LUNAR_ENABLED,
3845                                 (void *)__bt_ag_agent_lunar_connection_status_cb, NULL);
3846                 if (0 != ret)
3847                         ERR("Subsrciption to lunar connection failed err =  [%d]\n", ret);
3848         }
3849 }
3850
3851 static void __bt_ag_agent_release_vconf_updates(void)
3852 {
3853         int ret;
3854
3855         DBG("\n");
3856
3857         ret = vconf_ignore_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY,
3858                         (vconf_callback_fn)__bt_ag_agent_battery_status_cb);
3859         if (0 != ret)
3860                 ERR("vconf_ignore_key_changed failed\n");
3861
3862         ret = vconf_ignore_key_changed(VCONFKEY_TELEPHONY_RSSI,
3863                 (vconf_callback_fn)__bt_ag_agent_network_signal_status_cb);
3864         if (0 != ret)
3865                 ERR("vconf_ignore_key_changed failed\n");
3866
3867         ret = vconf_ignore_key_changed(VCONFKEY_TELEPHONY_SVCTYPE,
3868                 (vconf_callback_fn)__bt_ag_agent_network_register_status_cb);
3869         if (0 != ret)
3870                 ERR("vconf_ignore_key_changed failed\n");
3871 }
3872
3873 static gboolean __bt_ag_agent_send_subscriber_number_changed(
3874                                                         const char *number)
3875 {
3876         const char *property = g_strdup("SubscriberNumberChanged");
3877
3878         FN_START;
3879
3880         DBG("Number is %s", number);
3881
3882         if (!_bt_hfp_set_property_name(property, number)) {
3883                 DBG("Error- set property for subscriber no change  - ERROR\n");
3884                 g_free((void *)property);
3885                 return FALSE;
3886         }
3887         g_free((void *)property);
3888         FN_END;
3889         return TRUE;
3890 }
3891 static void __bt_ag_agent_sigterm_handler(int signo)
3892 {
3893         int i;
3894         GSList *l;
3895
3896         ERR_C("***** Signal handler came with signal %d *****", signo);
3897
3898         for (l = active_devices ; l; l = l->next) {
3899                 bt_ag_info_t *data = l->data;
3900                 if (!__bt_ag_agent_connection_release(data))
3901                         ERR("__bt_ag_agent_connection_release failed");
3902         }
3903         if (ag_dbus_conn)
3904                 g_dbus_connection_flush(ag_dbus_conn, NULL, NULL, NULL);
3905
3906         if (gmain_loop) {
3907                 g_main_loop_quit(gmain_loop);
3908                 DBG("Exiting");
3909                 gmain_loop = NULL;
3910         } else {
3911                 INFO("Terminating AG agent");
3912                 exit(0);
3913         }
3914
3915         if (signo == SIGTERM)
3916                 return;
3917
3918         for (i = 0; i < BT_AG_SIG_NUM; i++)
3919                 sigaction(bt_ag_sig_to_handle[i], &(bt_ag_sigoldact[i]), NULL);
3920
3921         raise(signo);
3922 }
3923
3924 static void  __bt_ag_agent_tel_cb(TapiHandle *handle,
3925                                 int result,
3926                                 void *data,
3927                                 void *user_data)
3928 {
3929         TelSimMsisdnList_t *number;
3930         gchar *subscriber_number;
3931
3932         ERR("*********** result = %d", result);
3933
3934         if (result == TAPI_API_SIM_LOCKED ||
3935                 result == TAPI_API_SIM_NOT_INITIALIZED ||
3936                 result == TAPI_API_SERVICE_NOT_READY) {
3937                 DBG("initializing the tapi event for SIM status");
3938                 __bt_ag_agent_reg_sim_event(handle, user_data);
3939                 return;
3940         }
3941
3942         if (data == NULL)
3943                 return;
3944
3945         number = (TelSimMsisdnList_t *)data;
3946         subscriber_number = g_strdup(number->list[0].num);
3947         __bt_ag_agent_send_subscriber_number_changed(subscriber_number);
3948         g_free(subscriber_number);
3949 }
3950
3951 static void __bt_ag_agent_on_noti_sim_status(TapiHandle *handle,
3952                 const char *noti_id, void *data, void *user_data)
3953 {
3954         TelSimCardStatus_t *status = data;
3955         int tapi_result;
3956
3957         DBG("event TAPI_NOTI_SIM_STATUS received!! status[%d]", *status);
3958
3959         if (*status == TAPI_SIM_STATUS_SIM_INIT_COMPLETED) {
3960                 __bt_ag_agent_dereg_sim_event(handle);
3961                 tapi_result = tel_get_sim_msisdn(handle, __bt_ag_agent_tel_cb,
3962                                         user_data);
3963                 if (tapi_result != TAPI_API_SUCCESS)
3964                         ERR("Fail to get sim info: %d", tapi_result);
3965         }
3966 }
3967
3968 static void __bt_ag_agent_reg_sim_event(TapiHandle *handle, void *user_data)
3969 {
3970         int ret;
3971         ret = tel_register_noti_event(handle, TAPI_NOTI_SIM_STATUS,
3972                 __bt_ag_agent_on_noti_sim_status, user_data);
3973
3974         if (ret != TAPI_API_SUCCESS)
3975                 ERR("event register failed(%d)", ret);
3976 }
3977
3978 static void __bt_ag_agent_dereg_sim_event(TapiHandle *handle)
3979 {
3980         int ret;
3981         ret = tel_deregister_noti_event(handle, TAPI_NOTI_SIM_STATUS);
3982
3983         if (ret != TAPI_API_SUCCESS)
3984                 ERR("event deregister failed(%d)", ret);
3985 }
3986
3987 static void __bt_ag_name_owner_changed_cb(GDBusConnection *connection,
3988                                         const gchar *sender_name,
3989                                         const gchar *object_path,
3990                                         const gchar *interface_name,
3991                                         const gchar *signal_name,
3992                                         GVariant *parameters,
3993                                         gpointer user_data)
3994 {
3995         FN_START;
3996         char *name_owner = NULL;
3997         char *old_owner = NULL;
3998         char *new_owner = NULL;
3999
4000         if (strcasecmp(signal_name, "NameOwnerChanged") == 0) {
4001                 GSList *l;
4002
4003                 g_variant_get(parameters, "(sss)", &name_owner, &old_owner, &new_owner);
4004
4005                 _bt_hfp_release_all_calls_by_sender(name_owner);
4006
4007                 if (sco_owner == NULL)
4008                         return;
4009
4010                 if (strcasecmp(name_owner, sco_owner) == 0) {
4011                         if (name_owner_sig_id != -1)
4012                                 g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4013                                                         name_owner_sig_id);
4014                         name_owner_sig_id = -1;
4015                         g_free(sco_owner);
4016                         sco_owner = NULL;
4017
4018                         for (l = active_devices ; l; l = l->next) {
4019                                 bt_ag_info_t *data = l->data;
4020
4021                                 if (data->sco) {
4022                                         __bt_ag_close_sco(data);
4023                                         _bt_ag_set_headset_state(data,
4024                                                 HEADSET_STATE_CONNECTED);
4025                                 }
4026                         }
4027                 }
4028         }
4029 }
4030
4031 static void __bt_ag_agent_filter_cb(GDBusConnection *connection,
4032                                         const gchar *sender_name,
4033                                         const gchar *object_path,
4034                                         const gchar *interface_name,
4035                                         const gchar *signal_name,
4036                                         GVariant *parameters,
4037                                         gpointer user_data)
4038 {
4039         FN_START;
4040         char *path = NULL;
4041         GVariant *optional_param = NULL;
4042
4043         if (strcasecmp(signal_name, "InterfacesAdded") == 0) {
4044                 g_variant_get(parameters, "(&o@a{sa{sv}})", &path, &optional_param);
4045                 if (!path) {
4046                         if (optional_param)
4047                                 g_variant_unref(optional_param);
4048                         ERR("Invalid adapter path");
4049                         return;
4050                 }
4051
4052                 INFO("Adapter Path = [%s]", path);
4053                 if (strcasecmp(path, DEFAULT_ADAPTER_OBJECT_PATH) == 0) {
4054                         gchar *obj_path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
4055                         __bt_ag_agent_register(obj_path, hfp_ver,
4056                                  HFP_AG_UUID, "Hands-Free Audio Gateway");
4057
4058                         obj_path =  g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
4059                         __bt_ag_agent_register(obj_path, hsp_ver,
4060                                 HSP_AG_UUID, "Headset Audio Gateway");
4061                 }
4062         } else if (strcasecmp(signal_name, "InterfacesRemoved") == 0) {
4063                 g_variant_get(parameters, "(&o@as)", &path, &optional_param);
4064                 if (!path) {
4065                         if (optional_param)
4066                                 g_variant_unref(optional_param);
4067                         ERR("Invalid adapter path");
4068                         return;
4069                 }
4070
4071                 INFO("Adapter Path = [%s]", path);
4072                 if (strcasecmp(path, DEFAULT_ADAPTER_OBJECT_PATH) == 0) {
4073                         gchar *obj_path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
4074                         __bt_ag_agent_unregister(obj_path);
4075
4076                         obj_path =  g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
4077                         __bt_ag_agent_unregister(obj_path);
4078                 }
4079         }
4080
4081         if (optional_param)
4082                 g_variant_unref(optional_param);
4083
4084         FN_END;
4085 }
4086
4087 static void __bt_ag_agent_dbus_deinit(void)
4088 {
4089
4090         if (service_gproxy) {
4091                 g_object_unref(service_gproxy);
4092                 service_gproxy = NULL;
4093         }
4094
4095         if (app_gproxy) {
4096                 g_object_unref(app_gproxy);
4097                 app_gproxy = NULL;
4098         }
4099
4100         if (ag_dbus_conn) {
4101                 __bt_ag_unregister_profile_methods();
4102
4103                 if (interface_added_sig_id)
4104                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4105                                                 interface_added_sig_id);
4106
4107                 if (interface_removed_sig_id)
4108                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4109                                                 interface_removed_sig_id);
4110
4111                 if (name_owner_sig_id)
4112                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4113                                                 name_owner_sig_id);
4114 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
4115                 if (media_sig_id)
4116                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4117                                                 media_sig_id);
4118                 media_sig_id = 0;
4119
4120                 if (media_state_sig_id)
4121                         g_dbus_connection_signal_unsubscribe(ag_dbus_conn,
4122                                                 media_state_sig_id);
4123                 media_state_sig_id = 0;
4124 #endif
4125
4126                 interface_added_sig_id = 0;
4127                 interface_removed_sig_id = 0;
4128                 name_owner_sig_id = 0;
4129                 g_free(sco_owner);
4130                 sco_owner = NULL;
4131
4132                 g_object_unref(ag_dbus_conn);
4133                 ag_dbus_conn = NULL;
4134         }
4135         return;
4136 }
4137
4138 static int __bt_ag_agent_get_adapter_path(GDBusConnection *conn, char *path)
4139 {
4140         GError *err = NULL;
4141         GDBusProxy *manager_proxy = NULL;
4142         GVariant *result = NULL;
4143         char *adapter_path = NULL;
4144
4145         if (conn == NULL)
4146                 return BT_HFP_AGENT_ERROR_INTERNAL;
4147
4148         manager_proxy =  g_dbus_proxy_new_sync(conn,
4149                         G_DBUS_PROXY_FLAGS_NONE, NULL,
4150                         BLUEZ_SERVICE_NAME,
4151                         "/",
4152                         BT_MANAGER_INTERFACE,
4153                         NULL, &err);
4154
4155         if (!manager_proxy) {
4156                 ERR("Unable to create proxy: %s", err->message);
4157                 goto fail;
4158         }
4159
4160         result = g_dbus_proxy_call_sync(manager_proxy, "DefaultAdapter", NULL,
4161                         G_DBUS_CALL_FLAGS_NONE, -1, NULL, &err);
4162         if (!result) {
4163                 if (err != NULL)
4164                         ERR("Fail to get DefaultAdapter (Error: %s)", err->message);
4165                 else
4166                         ERR("Fail to get DefaultAdapter");
4167
4168                 goto fail;
4169         }
4170
4171         if (g_strcmp0(g_variant_get_type_string(result), "(o)")) {
4172                 ERR("Incorrect result\n");
4173                 goto fail;
4174         }
4175
4176         g_variant_get(result, "(&o)", &adapter_path);
4177
4178         if (adapter_path == NULL ||
4179                 strlen(adapter_path) >= BT_ADAPTER_OBJECT_PATH_MAX) {
4180                 ERR("Adapter path is inproper\n");
4181                 goto fail;
4182         }
4183
4184         if (path)
4185                 g_strlcpy(path, adapter_path, BT_ADAPTER_OBJECT_PATH_MAX);
4186
4187         g_variant_unref(result);
4188         g_object_unref(manager_proxy);
4189
4190         return 0;
4191
4192 fail:
4193         g_clear_error(&err);
4194
4195         if (result)
4196                 g_variant_unref(result);
4197
4198         if (manager_proxy)
4199                 g_object_unref(manager_proxy);
4200
4201         return BT_HFP_AGENT_ERROR_INTERNAL;
4202
4203 }
4204
4205 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
4206 void _bt_ag_agent_check_transport_state(void)
4207 {
4208         FN_START;
4209
4210         if (transport_state == MEDIA_TRANSPORT_STATE_PLAYING) {
4211                 GDBusProxy *proxy;
4212                 GError *err = NULL;
4213
4214                 proxy =  g_dbus_proxy_new_sync(ag_dbus_conn,
4215                                 G_DBUS_PROXY_FLAGS_NONE, NULL,
4216                                 "org.PulseAudio2", A2DP_SOURCE_ENDPOINT,
4217                                 BLUEZ_MEDIA_ENDPOINT_INTERFACE, NULL, &err);
4218
4219                 if (!proxy) {
4220                         if (err) {
4221                                 ERR("Unable to create proxy: %s", err->message);
4222                                 g_clear_error(&err);
4223                         }
4224                         return;
4225                 }
4226                 INFO_C("SuspendMedia initiated");
4227
4228                 g_dbus_proxy_call(proxy,
4229                                         "SuspendMedia", NULL,
4230                                         G_DBUS_CALL_FLAGS_NONE, 2000,
4231                                         NULL, NULL, NULL);
4232                 transport_state = MEDIA_TRANSPORT_STATE_IDLE;
4233         }
4234
4235         FN_END;
4236 }
4237
4238 static void __bt_ag_agent_transport_state_update(const char *value)
4239 {
4240
4241         if (!g_strcmp0(value, "idle"))
4242                 transport_state = MEDIA_TRANSPORT_STATE_IDLE;
4243         else if (!g_strcmp0(value, "pending") || !g_strcmp0(value, "active"))
4244                 transport_state = MEDIA_TRANSPORT_STATE_PLAYING;
4245         else
4246                 transport_state =  MEDIA_TRANSPORT_STATE_DISCONNECTED;
4247
4248         INFO_C("transport_state %d", transport_state);
4249 }
4250
4251 static void __bt_ag_agent_media_filter_cb(GDBusConnection *connection,
4252                                         const gchar *sender_name,
4253                                         const gchar *object_path,
4254                                         const gchar *interface_name,
4255                                         const gchar *signal_name,
4256                                         GVariant *parameters,
4257                                         gpointer user_data)
4258 {
4259         FN_START;
4260         char *inter = NULL;
4261         GVariant *dict_param = NULL;
4262         GVariant *optional_param = NULL;
4263
4264         if (strcasecmp(signal_name, "PropertiesChanged") == 0) {
4265                 if (g_strcmp0(g_variant_get_type_string(parameters),
4266                                                         "(sa{sv}as)")) {
4267                         ERR("Incorrect parameters\n");
4268                         return;
4269                 }
4270
4271                 g_variant_get(parameters, "(&s@a{sv}@as)",
4272                                         &inter, &dict_param, &optional_param);
4273                 if (dict_param && (!g_strcmp0(inter,
4274                                 BLUEZ_MEDIA_TRANSPORT_INTERFACE))){
4275                         GVariantIter *iter = NULL;
4276                         const gchar *key = NULL;
4277                         GVariant *value_var = NULL;
4278                         gchar *value = NULL;
4279                         g_variant_get(dict_param, "a{sv}", &iter);
4280                         while (g_variant_iter_loop(
4281                                         iter, "{sv}", &key, &value_var)) {
4282                                 DBG("key %s", key);
4283                                 if (g_strcmp0(key, "State") == 0) {
4284                                         value = (gchar *)g_variant_get_string(
4285                                                                 value_var,
4286                                                                 NULL);
4287                                         DBG("value %s", value);
4288                                         __bt_ag_agent_transport_state_update(value);
4289                                         break;
4290                                 }
4291                         }
4292                         g_variant_iter_free(iter);
4293                 }
4294         } else if (strcasecmp(signal_name, "ProfileStateChanged") == 0) {
4295                 char *profile_uuid = NULL;
4296                 int state = 0;
4297
4298                 g_variant_get(parameters, "(&si)", &profile_uuid, &state);
4299                 if ((g_strcmp0(profile_uuid, A2DP_SINK_UUID) == 0)  &&
4300                         (state == BT_PROFILE_STATE_DISCONNECTED)) {
4301                         DBG("Updating the transport state");
4302                         __bt_ag_agent_transport_state_update("Disconnect");
4303                 }
4304         }
4305
4306         if (dict_param)
4307                 g_variant_unref(dict_param);
4308
4309         if (optional_param)
4310                 g_variant_unref(optional_param);
4311
4312         FN_END;
4313 }
4314 #endif
4315 static void __bt_ag_agent_dbus_init(void)
4316 {
4317         FN_START;
4318
4319         if (__bt_ag_get_gdbus_connection() == NULL) {
4320                 ERR("Error in creating the gdbus connection\n");
4321                 return;
4322         }
4323         if (!__bt_ag_register_profile_methods()) {
4324                 ERR("Error in HFP / HSP register_profile_methods\n");
4325                 return;
4326         }
4327
4328         if (!__bt_ag_agent_get_adapter_path(ag_dbus_conn , NULL)) {
4329
4330                 gchar *path = g_strdup(BT_AG_AGENT_OBJECT_PATH);
4331                 __bt_ag_agent_register(path, hfp_ver,
4332                          HFP_AG_UUID, "Hands-Free Audio Gateway");
4333
4334                 path = g_strdup(BT_HS_AG_AGENT_OBJECT_PATH);
4335                 __bt_ag_agent_register(path, hsp_ver,
4336                         HSP_AG_UUID, "Headset Audio Gateway");
4337         }
4338
4339         interface_added_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4340                                 NULL, BT_MANAGER_INTERFACE,
4341                                 BT_INTERFACES_ADDED, NULL, NULL, 0,
4342                                 __bt_ag_agent_filter_cb, NULL, NULL);
4343
4344         interface_removed_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4345                                 NULL, BT_MANAGER_INTERFACE,
4346                                 BT_INTERFACES_REMOVED, NULL, NULL, 0,
4347                                 __bt_ag_agent_filter_cb, NULL, NULL);
4348
4349 #ifdef TIZEN_FEATURE_BT_MEDIA_ENHANCE
4350         media_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4351                                 NULL, BT_PROPERTIES_INTERFACE, NULL, NULL,
4352                                 NULL, 0, __bt_ag_agent_media_filter_cb,
4353                                 NULL, NULL);
4354
4355         media_state_sig_id = g_dbus_connection_signal_subscribe(ag_dbus_conn,
4356                                 NULL, BLUEZ_DEVICE_INTERFACE, NULL, NULL,
4357                                 NULL, 0, __bt_ag_agent_media_filter_cb,
4358                                 NULL, NULL);
4359
4360         transport_state = MEDIA_TRANSPORT_STATE_DISCONNECTED;
4361 #endif
4362         FN_END;
4363         return;
4364 }
4365
4366 static uint32_t __bt_ag_agent_get_ag_features(void)
4367 {
4368
4369         uint32_t ag_features;
4370
4371         if (TIZEN_MODEL_NAME_TM1) {
4372                 ag_features = BT_AG_FEATURE_EC_AND_NR |
4373                                 BT_AG_FEATURE_REJECT_CALL |
4374                                 BT_AG_FEATURE_ENHANCED_CALL_STATUS |
4375                                 BT_AG_FEATURE_THREE_WAY_CALL |
4376                                 BT_AG_FEATURE_EXTENDED_ERROR_RESULT_CODES;
4377         } else {
4378                 ag_features = BT_AG_FEATURE_EC_AND_NR |
4379                                 BT_AG_FEATURE_REJECT_CALL |
4380                                 BT_AG_FEATURE_ENHANCED_CALL_STATUS |
4381                                 BT_AG_FEATURE_THREE_WAY_CALL |
4382                                 BT_AG_FEATURE_VOICE_RECOGNITION |
4383                                 BT_AG_FEATURE_EXTENDED_ERROR_RESULT_CODES;
4384         }
4385
4386         wbs_en = TRUE;
4387 #if defined(TIZEN_FEATURE_BT_HFP_AG)
4388         hfp_ver = HFP_VERSION_1_7;
4389 #else
4390         hfp_ver = HFP_VERSION_1_5;
4391 #endif
4392         hsp_ver = HSP_VERSION_1_2;
4393
4394         if (hfp_ver > HFP_VERSION_1_5)
4395                 ag_features |= BT_AG_FEATURE_CODEC_NEGOTIATION;
4396         if (hfp_ver == HFP_VERSION_1_7)
4397                 ag_features |= BT_AG_FEATURE_ESCO_S4_T2_SUPPORT;
4398
4399         return ag_features;
4400 }
4401
4402 void *__bt_ag_agent_telephony_init(void *arg)
4403 {
4404
4405         int tapi_result;
4406         uint32_t ag_features = *((uint32_t *)arg);
4407
4408         INFO_C("Initializing the telephony info");
4409
4410         _bt_hfp_initialize_telephony_manager(ag_features);
4411         __bt_ag_agent_subscribe_vconf_updates();
4412
4413         tapi_handle = tel_init(NULL);
4414         tapi_result = tel_get_sim_msisdn(tapi_handle, __bt_ag_agent_tel_cb,
4415                                         NULL);
4416         if (tapi_result != TAPI_API_SUCCESS)
4417                 ERR("Fail to get sim info: %d", tapi_result);
4418         return NULL;
4419 }
4420
4421 int main(void)
4422 {
4423         int i;
4424         uint32_t ag_features;
4425         struct sigaction sa;
4426         pthread_t thread_id = 0;
4427
4428         INFO_C("### Starting Bluetooth AG agent");
4429
4430         ag_features = __bt_ag_agent_get_ag_features();
4431
4432         ag.sdp_features = (uint16_t) ag_features & 0x1F;
4433
4434         if (hfp_ver >= HFP_VERSION_1_6 && wbs_en == TRUE)
4435                 ag.sdp_features |= BT_AG_FEATURE_SDP_WIDEBAND_SPEECH;
4436
4437         memset(&sa, 0, sizeof(sa));
4438         sa.sa_flags = SA_NOCLDSTOP;
4439         sa.sa_handler = __bt_ag_agent_sigterm_handler;
4440
4441         for (i = 0; i < BT_AG_SIG_NUM; i++)
4442                 sigaction(bt_ag_sig_to_handle[i], &sa, &(bt_ag_sigoldact[i]));
4443
4444         gmain_loop = g_main_loop_new(NULL, FALSE);
4445
4446         if (gmain_loop == NULL) {
4447                 ERR("GMainLoop create failed");
4448                 return EXIT_FAILURE;
4449         }
4450
4451         __bt_ag_agent_dbus_init();
4452         if (pthread_create(&thread_id, NULL,
4453                         (void *)&__bt_ag_agent_telephony_init,
4454                                         &ag_features) < 0) {
4455                 ERR("pthread_create() is failed");
4456                 return EXIT_FAILURE;
4457         }
4458
4459         if (pthread_detach(thread_id) < 0)
4460                 ERR("pthread_detach() is failed");
4461
4462         g_main_loop_run(gmain_loop);
4463
4464         DBG("Cleaning up");
4465
4466         tel_deinit(tapi_handle);
4467
4468         __bt_ag_agent_dbus_deinit();
4469         _bt_hfp_deinitialize_telephony_manager();
4470         __bt_ag_agent_release_vconf_updates();
4471
4472         if (remote_dev_path)
4473                 g_free(remote_dev_path);
4474
4475         if (gmain_loop)
4476                 g_main_loop_unref(gmain_loop);
4477
4478         INFO_C("### Terminating Bluetooth AG agent");
4479         return 0;
4480 }