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