Fix Svave issue - MEMORY_LEAK.STRDUP
[platform/core/connectivity/bluetooth-agent.git] / hf-agent / bluetooth-hf-agent.c
1 /*
2  * Bluetooth-hf-agent
3  *
4  * Copyright (c) 2000 - 2011 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  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  *              http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <glib.h>
28 #include <signal.h>
29 #include <fcntl.h>
30 #include <inttypes.h>
31 #include <sys/socket.h>
32 #include <sys/poll.h>
33 #include <aul.h>
34 #include <gio/gio.h>
35 #include <gio/gunixfdlist.h>
36 #include <device/power.h>
37 #include <app_manager.h>
38 #include <vconf.h>
39 #include <vconf-keys.h>
40 #include <bundle_internal.h>
41
42 #include "bluetooth-hf-agent.h"
43
44 #define BT_AGENT_SYSPOPUP_MAX_ATTEMPT 3
45 #define CALL_APP_ID "org.tizen.call-ui"
46
47 #define MAX_WAITING_DELAY 8
48 #define READ_TX_POWER_MIN -30
49
50 #define BT_ADDRESS_STRING_SIZE 18
51 #define BT_AT_COMMAND_BUFFER_MAX 4000
52 #define BT_HF_ERROR_RESP "\r\nERROR\r\n"
53 #define BT_HF_COMMAND_TIMEOUT 3
54
55 #define ret_if(expr) \
56         do { \
57                 if (expr) { \
58                         ERR("(%s) return", #expr); \
59                         return; \
60                 } \
61         } while (0)
62
63 static GMainLoop *gmain_loop = NULL;
64 static char *g_obj_path;
65
66 static GDBusConnection *gdbus_conn;
67 static GDBusProxy *service_gproxy;
68 static int owner_sig_id = -1;
69 int g_id = 0;
70 uint16_t hf_ver;
71
72 #define HFP_HF_UUID "0000111e-0000-1000-8000-00805f9b34fb"
73 #define DEFAULT_ADAPTER_OBJECT_PATH "/org/bluez/hci0"
74
75 /*Below Inrospection data is exposed to bluez from agent*/
76 static const gchar hf_agent_bluez_introspection_xml[] =
77 "<node name='/'>"
78 "       <interface name='org.bluez.Profile1'>"
79 "               <method name='NewConnection'>"
80 "                       <arg type='o' name='device' direction='in'/>"
81 "                       <arg type='h' name='fd' direction='in'/>"
82 "                       <arg type='a{sv}' name='options' direction='in'/>"
83 "               </method>"
84 "               <method name='RequestDisconnection'>"
85 "                       <arg type='o' name='device' direction='in'/>"
86 "               </method>"
87 "       </interface>"
88 "</node>";
89
90 /*Below Inrospection data is exposed to application from agent*/
91 static const gchar hf_agent_introspection_xml[] =
92 "<node name='/'>"
93 " <interface name='org.tizen.HfApp'>"
94 "               <method name='AnswerCall'>"
95 "                </method>"
96 "                <method name='TerminateCall'>"
97 "                </method>"
98 "                <method name='InitiateCall'>"
99 "                        <arg type='s' name='phoneno' direction='in'/>"
100 "                </method>"
101 "                <method name='VoiceRecognition'>"
102 "                        <arg type='i' name='status' direction='in'/>"
103 "                </method>"
104 "                <method name='ScoDisconnect'>"
105 "                </method>"
106 "                <method name='SpeakerGain'>"
107 "                        <arg type='u' name='gain' direction='in'/>"
108 "                </method>"
109 "                <method name='SendDtmf'>"
110 "                        <arg type='s' name='dtmf' direction='in'/>"
111 "                </method>"
112 "                <method name='SendAtCmd'>"
113 "                        <arg type='s' name='atcmd' direction='in'/>"
114 "                </method>"
115 "                <method name='ReleaseAndAccept'>"
116 "                </method>"
117 "                <method name='CallSwap'>"
118 "                </method>"
119 "                <method name='ReleaseAllCall'>"
120 "                </method>"
121 "                <method name='JoinCall'>"
122 "                </method>"
123 "                <method name='GetCurrentCodec'>"
124 "                       <arg type='i' name='codec' direction='out'/>"
125 "                </method>"
126 "                <method name='RequestCallList'>"
127 "                       <arg type='i' name='count' direction='out'/>"
128 "                       <arg type='a(siiii)' name='callList' direction='out'/>"
129 "                </method>"
130 "                <method name='GetAudioConnected'>"
131 "                       <arg type='i' name='status' direction='out'/>"
132 "                </method>"
133 "                <method name='IsHfConnected'>"
134 "                       <arg type='b' name='status' direction='out'/>"
135 "                </method>"
136 " </interface>"
137 "</node>";
138
139 static bt_hf_agent_info_t bt_hf_info;
140 static gboolean is_hf_connected = FALSE;
141 static int32_t current_codec_id = BT_HF_CODEC_ID_CVSD;
142 static int32_t sco_audio_connected = BT_HF_AUDIO_DISCONNECTED;
143
144 static char global_buff[BT_AT_COMMAND_BUFFER_MAX] = {0,};
145 int send_flag;
146
147 static char prev_cmd[BT_HF_CMD_BUF_SIZE];
148
149 typedef struct {
150         int idx;
151         int dir;
152         int status;
153         int mode;
154         int multi_party;
155         int type;
156         char *number;
157 } hf_call_list_info_t;
158
159 static GError *__bt_hf_agent_set_error(bt_hf_agent_error_t error);
160
161 static gboolean __bt_hf_agent_emit_property_changed(
162                                 GDBusConnection *connection,
163                                 const char *path,
164                                 const char *interface,
165                                 const char *name,
166                                 GVariant *property);
167
168 static gboolean __bt_hf_agent_data_cb(GIOChannel *chan, GIOCondition cond,
169                                         bt_hf_agent_info_t *bt_hf_info);
170 static void __bt_hf_agent_stop_watch(bt_hf_agent_info_t *bt_hf_info);
171 static void __bt_hf_agent_start_watch(bt_hf_agent_info_t *bt_hf_info);
172 static gboolean __bt_hf_channel_write(GIOChannel *io, gchar *data,
173                                         gsize count);
174 static gboolean __bt_hf_send_only_without_queue(bt_hf_agent_info_t *bt_hf_info,
175                                                 gchar *data, gsize count);
176
177 static gboolean __bt_hf_send_only(bt_hf_agent_info_t *bt_hf_info, gchar *data,
178                                         gsize count);
179 static gboolean __bt_hf_send_and_read(bt_hf_agent_info_t *bt_hf_info,
180                                 gchar *data, gchar *response, gsize count);
181 static GSList *__bt_hf_parse_indicator_names(gchar *names, GSList *indies);
182 static GSList *__bt_hf_parse_indicator_values(gchar *values, GSList *indies);
183 static guint __bt_hf_get_hold_mpty_features(gchar *features);
184 static gboolean __bt_establish_service_level_conn(bt_hf_agent_info_t *bt_hf_info);
185 static void __bt_hf_agent_sigterm_handler(int signo);
186 static gboolean __bt_hf_agent_release(void);
187
188 static gboolean __bt_get_current_indicators(bt_hf_agent_info_t *bt_hf_info);
189 static gboolean __bt_get_supported_indicators(bt_hf_agent_info_t *bt_hf_info);
190 static gboolean __bt_hf_agent_connection(gint32 fd, const gchar * object_path);
191 static gboolean __bt_hf_agent_connection_release(void);
192
193 struct indicator {
194         gchar descr[BT_HF_INDICATOR_DESCR_SIZE];
195         gint value;
196 };
197
198 static int _hf_agent_answer_call(GDBusMethodInvocation *context);
199
200 static int _hf_agent_terminate_call(GDBusMethodInvocation *context);
201
202 static int _hf_agent_dial_no(GDBusMethodInvocation *context, char *no);
203
204 static int _hf_agent_set_speaker_gain(GDBusMethodInvocation *context,
205                                                         unsigned int gain);
206
207 static int _hf_agent_send_3way_cmd(GDBusMethodInvocation *context, char *cmd);
208
209 static int _hf_agent_voice_recognition(GDBusMethodInvocation *context,
210                                                         unsigned int status);
211
212 static gboolean bt_hf_agent_sco_disconnect(void);
213
214 static int _hf_agent_send_dtmf(GDBusMethodInvocation *context, char *dtmf);
215
216 static GVariant *bt_hf_agent_request_call_list(void);
217
218 static int bt_hf_agent_send_at_cmd(GDBusMethodInvocation *context, char *atcmd);
219
220 static int hf_handle_rx_at_cmd(bt_hf_agent_info_t *bt_hf_info, const char *buf);
221 static GQuark __bt_hf_agent_error_quark(void)
222 {
223         DBG("");
224
225         static GQuark quark = 0;
226         if (!quark)
227                 quark = g_quark_from_static_string("hf-agent");
228
229         return quark;
230 }
231
232 static GError *__bt_hf_agent_set_error(bt_hf_agent_error_t error)
233 {
234         ERR("error[%d]", error);
235
236         switch (error) {
237         case BT_HF_AGENT_ERROR_NOT_AVAILABLE:
238                 return g_error_new(BT_HF_AGENT_ERROR, error,
239                                         BT_ERROR_NOT_AVAILABLE);
240         case BT_HF_AGENT_ERROR_NOT_CONNECTED:
241                 return g_error_new(BT_HF_AGENT_ERROR, error,
242                                         BT_ERROR_NOT_CONNECTED);
243         case BT_HF_AGENT_ERROR_CONNECTION_FAILED:
244                 return g_error_new(BT_HF_AGENT_ERROR, error,
245                                         BT_ERROR_NOT_CONNECTION_FAILED);
246         case BT_HF_AGENT_ERROR_BUSY:
247                 return g_error_new(BT_HF_AGENT_ERROR, error,
248                                         BT_ERROR_BUSY);
249         case BT_HF_AGENT_ERROR_INVALID_PARAM:
250                 return g_error_new(BT_HF_AGENT_ERROR, error,
251                                         BT_ERROR_INVALID_PARAM);
252         case BT_HF_AGENT_ERROR_ALREADY_EXIST:
253                 return g_error_new(BT_HF_AGENT_ERROR, error,
254                                         BT_ERROR_ALREADY_EXIST);
255         case BT_HF_AGENT_ERROR_ALREADY_CONNECTED:
256                 return g_error_new(BT_HF_AGENT_ERROR, error,
257                                         BT_ERROR_ALREADY_CONNECTED);
258         case BT_HF_AGENT_ERROR_NO_MEMORY:
259                 return g_error_new(BT_HF_AGENT_ERROR, error,
260                                         BT_ERROR_NO_MEMORY);
261         case BT_HF_AGENT_ERROR_I_O_ERROR:
262                 return g_error_new(BT_HF_AGENT_ERROR, error,
263                                         BT_ERROR_I_O_ERROR);
264         case BT_HF_AGENT_ERROR_APPLICATION:
265                 return g_error_new(BT_HF_AGENT_ERROR, error,
266                                         BT_ERROR_OPERATION_NOT_AVAILABLE);
267         case BT_HF_AGENT_ERROR_NOT_ALLOWED:
268                 return g_error_new(BT_HF_AGENT_ERROR, error,
269                                         BT_ERROR_OPERATION_NOT_ALLOWED);
270         case BT_HF_AGENT_ERROR_NOT_SUPPORTED:
271                 return g_error_new(BT_HF_AGENT_ERROR, error,
272                                         BT_ERROR_OPERATION_NOT_SUPPORTED);
273         case BT_HF_AGENT_ERROR_INVALID_FILE_DESCRIPTOR:
274                 return g_error_new(BT_HF_AGENT_ERROR, error,
275                                         BT_ERROR_INVALID_FILE_DESCRIPTOR);
276         case BT_HF_AGENT_ERROR_INTERNAL:
277         default:
278                 return g_error_new(BT_HF_AGENT_ERROR, error,
279                                                 BT_ERROR_INTERNAL);
280         }
281 }
282
283 static void __bt_hf_lock_display(int timeout)
284 {
285         int ret;
286
287         ret = device_power_request_lock(POWER_LOCK_DISPLAY, timeout);
288         if (ret >= 0)
289                 DBG("Lock PM state as current state!");
290         else
291                 ERR("deviced error!");
292 }
293
294 static void __bt_hf_unlock_display()
295 {
296         int ret;
297
298         ret = device_power_release_lock(POWER_LOCK_DISPLAY);
299         if (ret >= 0)
300                 DBG("UnLock PM state");
301         else
302                 ERR("deviced error!");
303 }
304
305 static void __hf_agent_method(GDBusConnection *connection,
306                             const gchar *sender,
307                             const gchar *object_path,
308                             const gchar *interface_name,
309                             const gchar *method_name,
310                             GVariant *parameters,
311                             GDBusMethodInvocation *context,
312                             gpointer user_data)
313 {
314         DBG("+");
315
316         INFO("method %s", method_name);
317         int ret = 0;
318         GError *err;
319
320         if (g_strcmp0(method_name, "NewConnection") == 0) {
321                 gint32 fd;
322                 int index;
323                 GDBusMessage *msg;
324                 GUnixFDList *fd_list;
325                 const gchar *object_path;
326                 GVariant *options;
327
328                 g_variant_get(parameters, "(oha{sv})",
329                         &object_path, &index, &options);
330
331                 msg = g_dbus_method_invocation_get_message(context);
332                 fd_list = g_dbus_message_get_unix_fd_list(msg);
333                 if (fd_list == NULL) {
334                         ret = BT_HF_AGENT_ERROR_INVALID_FILE_DESCRIPTOR;
335                         goto fail;
336                 }
337
338                 fd = g_unix_fd_list_get(fd_list, index, NULL);
339                 if (fd == -1) {
340                         ret = BT_HF_AGENT_ERROR_INVALID_FILE_DESCRIPTOR;
341                         goto fail;
342                 }
343
344                 DBG("FD is = [%d], Object path = [%s]", fd, object_path);
345
346                 if (!__bt_hf_agent_connection(fd, object_path)) {
347                         ret = BT_HF_AGENT_ERROR_INTERNAL;
348                         goto fail;
349                 }
350
351                 g_dbus_method_invocation_return_value(context, NULL);
352         } else if (g_strcmp0(method_name, "RequestDisconnection") == 0) {
353                 if (!__bt_hf_agent_connection_release()) {
354                         ret = BT_HF_AGENT_ERROR_INTERNAL;
355                         goto fail;
356                 }
357                 INFO_C("Disconnected [HF role] [Terminated by local host]");
358                 g_dbus_method_invocation_return_value(context, NULL);
359         } else if (g_strcmp0(method_name, "Release") == 0) {
360                 if (!__bt_hf_agent_connection_release()) {
361                         ret = BT_HF_AGENT_ERROR_INTERNAL;
362                         goto fail;
363                 }
364
365                 g_dbus_method_invocation_return_value(context, NULL);
366         } else if (g_strcmp0(method_name, "AnswerCall") == 0) {
367                 DBG("Going to call AnswerCall");
368                 ret = _hf_agent_answer_call(context);
369                 if (ret)
370                         goto fail;
371
372         } else if (g_strcmp0(method_name, "TerminateCall") == 0) {
373                 DBG("Going to call TerminateCall");
374                 ret = _hf_agent_terminate_call(context);
375                 if (ret)
376                         goto fail;
377
378         } else if (g_strcmp0(method_name, "InitiateCall") == 0) {
379                 char *phoneno = NULL;
380
381                 g_variant_get(parameters, "(&s)", &phoneno);
382
383                 DBG_SECURE("Going to call InitiateCall, Number is = [%s]\n", phoneno);
384                 ret = _hf_agent_dial_no(NULL, phoneno);
385                 if (ret)
386                         goto fail;
387
388                 g_dbus_method_invocation_return_value(context, NULL);
389
390         } else if (g_strcmp0(method_name, "VoiceRecognition") == 0) {
391                 int status = 0;
392
393                 g_variant_get(parameters, "(i)", &status);
394
395                 DBG("Going to call VoiceRecognition, Status [%d]", status);
396                 ret = _hf_agent_voice_recognition(context, status);
397                 if (ret)
398                         goto fail;
399
400         } else if (g_strcmp0(method_name, "ScoDisconnect") == 0) {
401                 DBG("Going to call ScoDisconnect");
402                 if (!bt_hf_agent_sco_disconnect()) {
403                         ret = BT_HF_AGENT_ERROR_INTERNAL;
404                         goto fail;
405                 }
406
407                 g_dbus_method_invocation_return_value(context, NULL);
408         } else if (g_strcmp0(method_name, "SpeakerGain") == 0) {
409                 unsigned int gain = 0;
410
411                 g_variant_get(parameters, "(u)", &gain);
412
413                 DBG("Going to call SpeakerGain, gain is = [%d]\n", gain);
414                 ret = _hf_agent_set_speaker_gain(context, gain);
415                 if (ret)
416                         goto fail;
417
418         } else if (g_strcmp0(method_name, "SendDtmf") == 0) {
419                 char *dtmf = NULL;
420
421                 g_variant_get(parameters, "(&s)", &dtmf);
422
423                 DBG("Going to call SendDtmf, dtmf is = [%s]\n", dtmf);
424                 ret = _hf_agent_send_dtmf(NULL, dtmf);
425                 if (ret)
426                         goto fail;
427                 g_dbus_method_invocation_return_value(context, NULL);
428
429         } else if (g_strcmp0(method_name, "SendAtCmd") == 0) {
430                 char *cmd = NULL;
431
432                 g_variant_get(parameters, "(&s)", &cmd);
433
434                 DBG("Going to call SendAtCmd, cmd is = [%s]\n", cmd);
435                 ret = bt_hf_agent_send_at_cmd(context, cmd);
436                 if (ret)
437                         goto fail;
438
439         } else if (g_strcmp0(method_name, "ReleaseAndAccept") == 0) {
440                 DBG("Going to call ReleaseAndAccept");
441                 ret = _hf_agent_send_3way_cmd(context,
442                                                 BT_HF_RELEASE_AND_ACCEPT);
443                 if (ret)
444                         goto fail;
445
446         } else if (g_strcmp0(method_name, "CallSwap") == 0) {
447                 DBG("Going to call CallSwap");
448                 ret = _hf_agent_send_3way_cmd(context,
449                                                         BT_HF_ACCEPT_AND_HOLD);
450                 if (ret)
451                         goto fail;
452
453         } else if (g_strcmp0(method_name, "ReleaseAllCall") == 0) {
454                 DBG("Going to call ReleaseAllCall");
455                 ret = _hf_agent_send_3way_cmd(context, BT_HF_RELEASE_ALL);
456                 if (ret)
457                         goto fail;
458
459         } else if (g_strcmp0(method_name, "JoinCall") == 0) {
460                 DBG("Going to call JoinCall");
461                 ret = _hf_agent_send_3way_cmd(context, BT_HF_JOIN_CALL);
462                 if (ret)
463                         goto fail;
464
465         } else if (g_strcmp0(method_name, "GetCurrentCodec") == 0) {
466                 DBG("Going to call GetCurrentCodec");
467                 INFO("Current codec : %d", current_codec_id);
468                 g_dbus_method_invocation_return_value(context,
469                                 g_variant_new("(i)", current_codec_id));
470         } else if (g_strcmp0(method_name, "RequestCallList") == 0) {
471                 GVariant *call_var;
472
473                 DBG("Going to call RequestCallList");
474                 call_var = bt_hf_agent_request_call_list();
475                 if (!call_var) {
476                         ret = BT_HF_AGENT_ERROR_NOT_AVAILABLE;
477                         goto fail;
478                 }
479                 g_dbus_method_invocation_return_value(context, call_var);
480         } else if (g_strcmp0(method_name, "GetAudioConnected") == 0) {
481                 DBG("Going to call GetAudioConnected");
482                 g_dbus_method_invocation_return_value(context,
483                                 g_variant_new("(i)", sco_audio_connected));
484         } else if (g_strcmp0(method_name, "IsHfConnected") == 0) {
485                 DBG("Going to call IsHfConnected");
486                 INFO("is_hf_connected : %s", is_hf_connected ? "Connected":"Disconnected");
487
488                 g_dbus_method_invocation_return_value(context,
489                                 g_variant_new("(b)", is_hf_connected));
490         }
491         INFO("-");
492         return;
493
494 fail:
495         err = __bt_hf_agent_set_error(ret);
496         g_dbus_method_invocation_return_gerror(context, err);
497         g_error_free(err);
498         INFO("-");
499 }
500
501 static const GDBusInterfaceVTable method_table = {
502         __hf_agent_method,
503         NULL,
504         NULL,
505 };
506
507 static GDBusNodeInfo *__bt_hf_create_method_node_info
508                                         (const gchar *introspection_data)
509 {
510         if (introspection_data == NULL)
511                 return NULL;
512
513         return g_dbus_node_info_new_for_xml(introspection_data, NULL);
514 }
515
516 static GDBusConnection *__bt_hf_get_gdbus_connection(void)
517 {
518         GDBusConnection *local_system_gconn = NULL;
519         GError *err = NULL;
520
521         if (gdbus_conn == NULL) {
522                 gdbus_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
523                 if (!gdbus_conn) {
524                         if (err) {
525                                 ERR("Unable to connect to dbus: %s", err->message);
526                                 g_clear_error(&err);
527                         }
528                         gdbus_conn = NULL;
529                 }
530         } else if (g_dbus_connection_is_closed(gdbus_conn)) {
531                 local_system_gconn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
532
533                 if (!local_system_gconn) {
534                         ERR("Unable to connect to dbus: %s", err->message);
535                         g_clear_error(&err);
536                 }
537
538                 gdbus_conn = local_system_gconn;
539         }
540
541         return gdbus_conn;
542 }
543
544 static gboolean __bt_hf_register_profile_methods(void)
545 {
546         DBG("+");
547         GError *error = NULL;
548         guint object_id;
549         guint owner_id;
550         GDBusNodeInfo *node_info;
551         gchar *path;
552         GDBusConnection *conn;
553
554         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
555                                 BT_HF_SERVICE_NAME,
556                                 G_BUS_NAME_OWNER_FLAGS_NONE,
557                                 NULL, NULL, NULL,
558                                 NULL, NULL);
559
560         DBG("owner_id is [%d]", owner_id);
561
562         node_info = __bt_hf_create_method_node_info(
563                                 hf_agent_bluez_introspection_xml);
564         if (node_info == NULL)
565                 return FALSE;
566
567         path = g_strdup(BT_HF_BLUEZ_OBJECT_PATH);
568         DBG("path is [%s]", path);
569
570         conn = __bt_hf_get_gdbus_connection();
571         if (!conn) {
572                 ERR("Unable to get connection");
573                 g_free(path);
574                 return FALSE;
575         }
576
577         object_id = g_dbus_connection_register_object(conn, path,
578                                         node_info->interfaces[0],
579                                         &method_table,
580                                         NULL, NULL, &error);
581         if (object_id == 0) {
582                 ERR("Failed to register: %s", error->message);
583                 g_error_free(error);
584                 g_dbus_node_info_unref(node_info);
585                 g_free(path);
586                 return FALSE;
587         }
588         g_free(path);
589         g_dbus_node_info_unref(node_info);
590
591         node_info = __bt_hf_create_method_node_info(hf_agent_introspection_xml);
592         if (node_info == NULL)
593                 return FALSE;
594
595         path = g_strdup(BT_HF_AGENT_OBJECT_PATH);
596         DBG("path is [%s]", path);
597
598         object_id = g_dbus_connection_register_object(conn, path,
599                                                 node_info->interfaces[0],
600                                                 &method_table,
601                                                 NULL, NULL, &error);
602         if (object_id == 0) {
603                 if (error != NULL) {
604                         ERR("Failed to register: %s", error->message);
605                         g_error_free(error);
606                 }
607                 g_dbus_node_info_unref(node_info);
608                 g_free(path);
609                 return FALSE;
610         }
611         g_free(path);
612         g_dbus_node_info_unref(node_info);
613
614         DBG("-");
615         return TRUE;
616 }
617
618 static GDBusProxy *__bt_hf_gdbus_init_service_proxy(const gchar *service,
619                                 const gchar *path, const gchar *interface)
620 {
621         DBG("+");
622
623         GDBusProxy *proxy;
624         GError *err = NULL;
625         GDBusConnection *conn;
626
627         conn = __bt_hf_get_gdbus_connection();
628         if (!conn) {
629                 ERR("Unable to get connection");
630                 return NULL;
631         }
632
633         proxy =  g_dbus_proxy_new_sync(conn,
634                         G_DBUS_PROXY_FLAGS_NONE, NULL,
635                         service, path,
636                         interface, NULL, &err);
637
638         if (!proxy) {
639                 if (err) {
640                         ERR("Unable to create proxy: %s", err->message);
641                          g_clear_error(&err);
642                 }
643                 return NULL;
644         }
645
646         DBG("-");
647         return proxy;
648 }
649
650 static GDBusProxy *__bt_hf_gdbus_get_service_proxy(const gchar *service,
651                                 const gchar *path, const gchar *interface)
652 {
653         return (service_gproxy) ? service_gproxy :
654                         __bt_hf_gdbus_init_service_proxy(service,
655                                         path, interface);
656 }
657
658 static char __bt_hf_agent_get_tx_power(char *address)
659 {
660         GVariant *ret;
661         GDBusProxy *proxy;
662         GError *error = NULL;
663         char result = READ_TX_POWER_MIN; /* default minimum */
664
665         proxy = __bt_hf_gdbus_get_service_proxy(BLUEZ_SERVICE_NAME, g_obj_path,
666                                                 BLUEZ_HF_INTERFACE_NAME);
667         if (!proxy) {
668                 ERR("Proxy is NULL");
669                 return result;
670         }
671
672         ret = g_dbus_proxy_call_sync(proxy,
673                                 "GetTxPowerLevel", g_variant_new("(s)", address),
674                                 G_DBUS_CALL_FLAGS_NONE, -1,
675                                 NULL, &error);
676         if (ret == NULL) {
677                 ERR("DBus is failed");
678                 if (error != NULL) {
679                         /* Dbus gives error cause */
680                         ERR("D-Bus API failure: errCode[%x], message[%s]",
681                                                 error->code, error->message);
682                         g_clear_error(&error);
683                 }
684                 return result;
685         }
686         g_variant_get(ret, "(y)", &result);
687         DBG("TX power level = %d", result);
688         g_variant_unref(ret);
689         return result;
690 }
691
692 static int __bt_hf_agent_gdbus_method_send(const char *service,
693                                 GVariant *path, const char *interface,
694                                 const char *method)
695 {
696         DBG("+");
697
698         GVariant *ret;
699         GDBusProxy *proxy;
700         GError *error = NULL;
701
702         proxy = __bt_hf_gdbus_get_service_proxy(service, g_obj_path, interface);
703         if (!proxy)
704                 return BT_HF_AGENT_ERROR_INTERNAL;
705
706         ret = g_dbus_proxy_call_sync(proxy,
707                                 method, path,
708                                 G_DBUS_CALL_FLAGS_NONE, -1,
709                                 NULL, &error);
710         if (ret == NULL) {
711                 /* dBUS-RPC is failed */
712                 ERR("dBUS-RPC is failed");
713                 if (error != NULL) {
714                         /* dBUS gives error cause */
715                         ERR("D-Bus API failure: errCode[%x], message[%s]",
716                                error->code, error->message);
717
718                         g_clear_error(&error);
719                 }
720                 return BT_HF_AGENT_ERROR_INTERNAL;
721         }
722
723         g_variant_unref(ret);
724
725         return BT_HF_AGENT_ERROR_NONE;
726 }
727
728 static void  __bt_hf_agent_release_queue(void)
729 {
730         int i, len;
731         bt_hf_agent_send_at_info *cmd;
732         GError *err;
733
734         len = g_slist_length(bt_hf_info.cmd_send_queue);
735         for (i = 0; i < len; ++i) {
736                 cmd = g_slist_nth_data(bt_hf_info.cmd_send_queue, i);
737                 if (cmd && cmd->context) {
738                         DBG("Pending context found for %.6s[%d]",
739                                                         cmd->at_cmd, cmd->id);
740                         err = __bt_hf_agent_set_error(BT_HF_AGENT_ERROR_INTERNAL);
741                         g_dbus_method_invocation_return_gerror(cmd->context, err);
742                         g_error_free(err);
743                 }
744                 if (cmd && cmd->timer_id)
745                         g_source_remove(cmd->timer_id);
746         }
747         g_slist_free(bt_hf_info.cmd_send_queue);
748         bt_hf_info.cmd_send_queue = NULL;
749         send_flag = 0;
750 }
751
752 static gboolean __bt_hf_monitor_timer_cb(gpointer data)
753 {
754         DBG("+");
755         bt_hf_agent_send_at_info *cmd = data;
756         ERR_C("Monitor timer came becuase of timeout for sendflag %d, %s",
757                                                 send_flag, cmd->at_cmd);
758         /* In the case of ATD, we have to inform the remote to end the call */
759         if (strstr(cmd->at_cmd, "ATD") || strstr(cmd->at_cmd, "BLDN")) {
760                 INFO_C("Sending CHUP for remote call termination");
761                 __bt_hf_send_only_without_queue(&bt_hf_info, BT_HF_END_CALL,
762                                                          strlen(BT_HF_END_CALL));
763                 /* Here there is a high posisbility that we do not get response
764                  * for CHUP. Hence we need to decrement send_flag to process further
765                  * incomming packets because we already incremented it in the CHUP case. */
766                  if (send_flag)
767                         send_flag--;
768
769                 /* In the case of ATD, prev_cmd will be always ATD, because we will not
770                  * allow further commands. For safer side again set prev_cmd as ATD */
771                 strncpy(prev_cmd, "ATD\0", BT_HF_CMD_BUF_SIZE - 1);
772         }
773         hf_handle_rx_at_cmd(&bt_hf_info, BT_HF_ERROR_RESP);
774
775         DBG("-");
776
777         return FALSE;
778 }
779
780
781 gboolean __bt_hf_agent_add_queue(GDBusMethodInvocation *context, char *at,
782                                         int count, gboolean pending_flag)
783 {
784         int i, len;
785         if (bt_hf_info.slc == FALSE)
786                 return FALSE;
787
788         if (pending_flag)
789                 DBG("*** Add Pending queue request for = %s **** ", at);
790         else
791                  DBG("Add Pending queue respnse for = %s ", at);
792
793         bt_hf_agent_send_at_info *cmd = g_new0(bt_hf_agent_send_at_info, 1);
794         cmd->id = ++g_id;
795         memcpy(cmd->at_cmd, at, count);
796         cmd->count = count;
797         cmd->context =  context;
798         cmd->pending = pending_flag;
799         bt_hf_info.cmd_send_queue = g_slist_append(bt_hf_info.cmd_send_queue,
800                                                                         cmd);
801         len = g_slist_length(bt_hf_info.cmd_send_queue);
802         for (i = 0; i < len; ++i) {
803                 cmd = g_slist_nth_data(bt_hf_info.cmd_send_queue, i);
804                 DBG("Q> %.6s[%d]", cmd->at_cmd, cmd->id);
805         }
806
807         /* We need to have base timeout + tolerance value to process other request */
808         if (strstr(at, "ATD") || strstr(at, "BLDN")) {
809                 /* Android 15 seconds timeout in case of ATD timeout in flight mode */
810                 cmd->timer_id = g_timeout_add_seconds(BT_HF_COMMAND_TIMEOUT * 5 + len,
811                                          __bt_hf_monitor_timer_cb, cmd);
812         } else {
813                 cmd->timer_id = g_timeout_add_seconds(BT_HF_COMMAND_TIMEOUT + len,
814                                          __bt_hf_monitor_timer_cb, cmd);
815         }
816         return TRUE;
817 }
818
819 /*
820 Below methods exposed to Applicatoins
821 */
822 static gboolean __bt_hf_agent_emit_signal(GDBusConnection *connection,
823                                 const char *path, const char *interface,
824                                 const char *signal_name, GVariant *param)
825 {
826         GError *error = NULL;
827         gboolean ret;
828         ret =  g_dbus_connection_emit_signal(connection,
829                                  NULL, path,
830                                  interface, signal_name,
831                                  param, &error);
832         if (!ret) {
833                 if (error != NULL) {
834                         /* dBUS gives error cause */
835                         ERR("D-Bus API failure: errCode[%x], message[%s]",
836                                error->code, error->message);
837                         g_clear_error(&error);
838                 }
839         }
840         INFO_C("Emit Signal [%s]", signal_name);
841
842         return ret;
843 }
844
845 static gboolean __bt_hf_agent_emit_property_changed(
846                                 GDBusConnection *connection,
847                                 const char *path,
848                                 const char *interface,
849                                 const char *name,
850                                 GVariant *property)
851 {
852         DBG("+");
853
854         GError *error = NULL;
855         gboolean ret;
856         ret =  g_dbus_connection_emit_signal(connection,
857                                 NULL, path, interface,
858                                 "PropertyChanged",
859                                 g_variant_new("s(v)", name, property),
860                                 &error);
861         if (!ret) {
862                 if (error != NULL) {
863                         /* dBUS gives error cause */
864                         ERR("D-Bus API failure: errCode[%x], message[%s]",
865                                error->code, error->message);
866                         g_clear_error(&error);
867                 }
868         }
869         DBG("-");
870         return ret;
871 }
872
873 /*
874 Below methods exposed to Bluez
875 */
876
877 static void __bt_hf_agent_handle_ind_change(bt_hf_agent_info_t *bt_hf_info,
878                                                         guint index, gint value)
879 {
880         GDBusConnection *conn;
881         gchar *name;
882         struct indicator *ind = g_slist_nth_data(bt_hf_info->indies, index - 1);
883         if (ind == NULL) {
884                 ERR("Indicator is NULL");
885                 return;
886         }
887
888         name = ind->descr;
889         ind->value = value;
890
891         conn = __bt_hf_get_gdbus_connection();
892         if (!conn) {
893                 ERR("Unable to get connection");
894                 return;
895         }
896
897         INFO("Indicator name is %s, value = [%d]", name, value);
898         if (!strcmp(name, "\"call\"")) {
899                 bt_hf_info->ciev_call_status = value;
900                 if (value > 0) {
901                         __bt_hf_agent_emit_signal(conn,
902                                         BT_HF_AGENT_OBJECT_PATH,
903                                         BT_HF_SERVICE_INTERFACE,
904                                         "CallStarted", NULL);
905                         bt_hf_info->is_dialing = FALSE;
906                         bt_hf_info->call_active = TRUE;
907                 } else if (bt_hf_info->call_active) {
908                         __bt_hf_agent_emit_signal(conn,
909                                         BT_HF_AGENT_OBJECT_PATH,
910                                         BT_HF_SERVICE_INTERFACE,
911                                         "CallEnded", NULL);
912                         bt_hf_info->call_active = FALSE;
913                 }
914
915         } else if (!strcmp(name, "\"callsetup\"")) {
916                 bt_hf_info->ciev_call_setup_status = value;
917                 if (value == 0 && bt_hf_info->is_dialing) {
918                         __bt_hf_agent_emit_signal(conn,
919                                         BT_HF_AGENT_OBJECT_PATH,
920                                         BT_HF_SERVICE_INTERFACE,
921                                         "CallTerminated",
922                                         NULL);
923                         bt_hf_info->is_dialing = FALSE;
924                 } else if (!bt_hf_info->is_dialing && value > 0)
925                         bt_hf_info->is_dialing = TRUE;
926
927                 if (bt_hf_info->ciev_call_status == 0 &&
928                                                 bt_hf_info->ciev_call_setup_status == 0)
929                         __bt_hf_agent_emit_signal(gdbus_conn,
930                                         BT_HF_AGENT_OBJECT_PATH,
931                                         BT_HF_SERVICE_INTERFACE,
932                                         "CallEnded", NULL);
933
934         } else if (!strcmp(name, "\"callheld\"")) {
935                 if (value == 0) { /* No calls held*/
936                         __bt_hf_agent_emit_signal(conn,
937                                         BT_HF_AGENT_OBJECT_PATH,
938                                         BT_HF_SERVICE_INTERFACE,
939                                         "NoCallsHeld",
940                                         NULL);
941                 } else if (value == 1) {
942                         /*Call is placed on hold or active/held calls swapped */
943                         __bt_hf_agent_emit_signal(conn,
944                                         BT_HF_AGENT_OBJECT_PATH,
945                                         BT_HF_SERVICE_INTERFACE,
946                                         "CallsSwapped", NULL);
947                         bt_hf_info->is_dialing = FALSE;
948                 } else {
949                         /*Call on hold, no active call*/
950                         __bt_hf_agent_emit_signal(conn,
951                                         BT_HF_AGENT_OBJECT_PATH,
952                                         BT_HF_SERVICE_INTERFACE,
953                                         "CallOnHold", NULL);
954                         bt_hf_info->is_dialing = FALSE;
955                 }
956         } else if (!strcmp(name, "\"service\""))
957                 __bt_hf_agent_emit_property_changed(conn,
958                                 BT_HF_AGENT_OBJECT_PATH,
959                                 BT_HF_SERVICE_INTERFACE,
960                                 "RegistrationStatus",
961                                 g_variant_new("(q)", value));
962         else if (!strcmp(name, "\"signal\""))
963                 __bt_hf_agent_emit_property_changed(conn,
964                                 BT_HF_AGENT_OBJECT_PATH,
965                                 BT_HF_SERVICE_INTERFACE, "SignalStrength",
966                                 g_variant_new("(q)", value));
967         else if (!strcmp(name, "\"roam\""))
968                 __bt_hf_agent_emit_property_changed(conn,
969                                 BT_HF_AGENT_OBJECT_PATH,
970                                 BT_HF_SERVICE_INTERFACE, "RoamingStatus",
971                                 g_variant_new("(q)", value));
972         else if (!strcmp(name, "\"battchg\""))
973                 __bt_hf_agent_emit_property_changed(conn,
974                                 BT_HF_AGENT_OBJECT_PATH,
975                                 BT_HF_SERVICE_INTERFACE, "BatteryCharge",
976                                 g_variant_new("(q)", value));
977 }
978
979
980 static gboolean  __bt_hf_agent_launch_call_app(const char *launch_type,
981                                                         const char *number)
982 {
983         bundle *b;
984         bool is_running;
985
986         DBG("+");
987         app_manager_is_running(CALL_APP_ID, &is_running);
988         if (is_running)
989                 return FALSE;
990
991         DBG_SECURE("Launch type = %s, number(%s)", launch_type, number);
992
993         b = bundle_create();
994         if (NULL == b) {
995                 ERR("bundle_create() Failed");
996                 return FALSE;
997         }
998
999         bundle_add(b, "launch-type", launch_type);
1000
1001         if (strlen(number) != 0)
1002                 bundle_add(b, "number", number);
1003
1004         bundle_add(b, "carrier-type", "BT");
1005         DBG("For 3G, carrier-type: BT has been added");
1006
1007         aul_launch_app(CALL_APP_ID, b);
1008         bundle_free(b);
1009
1010         DBG("-");
1011
1012         return TRUE;
1013 }
1014
1015 static void __bt_hf_agent_handle_voice_activation(gint value)
1016 {
1017         GDBusConnection *conn;
1018
1019         conn = __bt_hf_get_gdbus_connection();
1020                 if (!conn) {
1021                 ERR("Unable to get connection");
1022                 return;
1023         }
1024
1025         __bt_hf_agent_emit_signal(conn, BT_HF_AGENT_OBJECT_PATH,
1026                 BT_HF_SERVICE_INTERFACE,
1027                 "VoiceRecognition",
1028                 g_variant_new("(i)", value));
1029
1030         return;
1031 }
1032
1033 static void __bt_hf_agent_handle_speaker_gain(gint value)
1034 {
1035         GDBusConnection *conn;
1036
1037         conn = __bt_hf_get_gdbus_connection();
1038         if (!conn) {
1039                 ERR("Unable to get connection");
1040                 return;
1041         }
1042
1043         __bt_hf_agent_emit_signal(conn, BT_HF_AGENT_OBJECT_PATH,
1044                                 BT_HF_SERVICE_INTERFACE, "VolumeSpeaker",
1045                                 g_variant_new("(i)", value));
1046
1047         return;
1048 }
1049
1050 static int __bt_hf_agent_handle_ccwa(bt_hf_agent_info_t *bt_hf_info,
1051                                                         const gchar *buf)
1052 {
1053         GDBusConnection *conn;
1054         gchar *ccwa;
1055         gchar number[BT_HF_CALLER_NUM_SIZE];
1056         gchar *sep;
1057         char fmt_str[BT_HF_FMT_STR_SIZE];
1058         int len = strlen(buf);
1059
1060         DBG("__bt_hf_agent_handle_ccwa +");
1061         if (len > BT_HF_CALLER_NUM_SIZE + 10) {
1062                 ERR("buf len %d is too long", len);
1063                 return 1;
1064         }
1065
1066         if ((ccwa = strstr(buf, "\r\n+CCWA"))) {
1067                 snprintf(fmt_str, sizeof(fmt_str), "\r\n+CCWA: \"%%%ds", sizeof(number) - 1);
1068                 if (sscanf(ccwa, fmt_str, number) == 1) {
1069                         sep = strchr(number, '"');
1070                         sep[0] = '\0';
1071
1072                         ccwa = number;
1073
1074                         conn = __bt_hf_get_gdbus_connection();
1075                         if (!conn) {
1076                                 ERR("Unable to get connection");
1077                                 return 1;
1078                         }
1079
1080                         __bt_hf_agent_emit_signal(conn,
1081                                         BT_HF_AGENT_OBJECT_PATH,
1082                                         BT_HF_SERVICE_INTERFACE, "CallWaiting",
1083                                         g_variant_new("(s)", ccwa));
1084                 } else {
1085                         ERR_SECURE("CCWA '%s' is Call Wating", buf);
1086                         return 1;
1087                 }
1088         }
1089         DBG("__bt_hf_agent_handle_ccwa -");
1090         return 0;
1091 }
1092
1093 static GSList *__bt_hf_prepare_call_list(const char *buf) {
1094         GSList *call_list = NULL;
1095         char *str = NULL;
1096         char *ptr = NULL;
1097         char *temp = NULL;
1098         char *sp;
1099         char delim_sep[] = "\r\n";
1100         char temp_buf[BT_HF_DATA_BUF_SIZE] = {0,};
1101
1102         hf_call_list_info_t *call_info;
1103
1104         DBG("+");
1105         strncpy(temp_buf, buf, BT_HF_DATA_BUF_SIZE - 1);
1106
1107         str = strtok_r(temp_buf, delim_sep, &sp);
1108         while (str != NULL) {
1109                 if (!(strstr(str, "+CLCC:"))) {
1110                         str = strtok_r(NULL, delim_sep, &sp);
1111                         continue;
1112                 }
1113
1114                 call_info = g_new0(hf_call_list_info_t, 1);
1115
1116                 sscanf(str, "+CLCC: %1d,%1d, %1d, %1d, %1d",
1117                                 &call_info->idx, &call_info->dir,
1118                                 &call_info->status, &call_info->mode,
1119                                 &call_info->multi_party);
1120                 DBG("Index = [%d], Direction = [%d], Status = [%d], Mode = [%d], Multi_party = [%d]\n",
1121                                 call_info->idx, call_info->dir, call_info->status,
1122                                 call_info->mode, call_info->multi_party);
1123
1124                 ptr = strstr(str, "\"");
1125                 if (ptr) {
1126                         temp = strstr(ptr + 1, "\"");
1127                         if (temp) {
1128                                 *temp = '\0';
1129                                 DBG_SECURE("\tPhone Number = [%s]\n", ptr + 1);
1130                                 call_info->number = g_strdup(ptr + 1);
1131
1132                                 if (strstr(temp + 1, ",")) {
1133                                         temp += 2;
1134                                         DBG("\tType = [%s]\n", temp);
1135                                         call_info->type = atoi(temp);
1136                                 }
1137                         }
1138                 } else {
1139                         /*In case of no phone no. in CLCC respnse, we should launch call application
1140                          * with NULL string. By doing so "unknown" shall be displayed*/
1141                         DBG("Phone number does not exist\n");
1142                         call_info->number = g_strdup("");
1143                 }
1144
1145                 call_list = g_slist_append(call_list, call_info);
1146                 str = strtok_r(NULL, delim_sep, &sp);
1147         }
1148         DBG("-");
1149         return call_list;
1150 }
1151
1152 static GSList *__bt_hf_get_call_list(bt_hf_agent_info_t *bt_hf_info)
1153 {
1154         char buf[BT_HF_DATA_BUF_SIZE] = {0,};
1155         GSList *call_list = NULL;
1156
1157         DBG("+");
1158
1159         /* Send CLCC when the callsetup */
1160         __bt_hf_send_and_read(bt_hf_info, BT_HF_CALLLIST, buf,
1161                         sizeof(BT_HF_CALLLIST) - 1);
1162         DBG_SECURE("Receive CLCC response buffer = '%s'", buf);
1163
1164         call_list =  __bt_hf_prepare_call_list(buf);
1165         DBG("-");
1166         return call_list;
1167 }
1168
1169 static void __bt_hf_call_info_free(void *data)
1170 {
1171         DBG("+");
1172
1173         hf_call_list_info_t *call_info = data;
1174         g_free(call_info->number);
1175         g_free(call_info);
1176
1177         DBG("-");
1178 }
1179
1180 static void __bt_hf_free_call_list(GSList *call_list)
1181 {
1182         DBG("+");
1183
1184         g_slist_free_full(call_list, __bt_hf_call_info_free);
1185
1186         DBG("-");
1187 }
1188
1189 static void __bt_hf_launch_call_using_call_list(GSList *call_list,
1190                                         bt_hf_agent_info_t *bt_hf_info)
1191 {
1192         guint len;
1193         const char *launch_type_str;
1194         hf_call_list_info_t *call_info;
1195
1196         DBG("+");
1197         if (call_list == NULL)
1198                 return;
1199
1200         len = g_slist_length(call_list);
1201
1202         while (len--) {
1203                 call_info = g_slist_nth_data(call_list, len);
1204
1205                 /* Launch based on below conditions
1206                   * DC - Active call which is initiated from H
1207                   * MR - Alerting call which is initiated from H
1208                   * MT - Incoming call */
1209                 if (call_info->status == BT_HF_CALL_STAT_ACTIVE) {
1210                         launch_type_str =  "DC";
1211                 } else {
1212                         if (call_info->dir == BT_HF_CALL_DIR_INCOMING)
1213                                 launch_type_str =  "MT";
1214                         else
1215                                 launch_type_str =  "MR";
1216                 }
1217
1218                 if (__bt_hf_agent_launch_call_app(launch_type_str,
1219                                         call_info->number)  == FALSE)
1220                         DBG("call app launching failed");
1221         }
1222         DBG("-");
1223 }
1224
1225 static GVariant *__bt_hf_agent_get_call_status_info(GSList *call_list)
1226 {
1227         DBG("+");
1228
1229         int32_t call_count;
1230         gchar *caller;
1231         hf_call_list_info_t *call_info;
1232
1233         GVariantBuilder *builder;
1234         GVariant *var_data;
1235
1236         builder = g_variant_builder_new(G_VARIANT_TYPE("a(siiii)"));
1237
1238         call_count = g_slist_length(call_list);
1239         DBG("Total call count = '%d'", call_count);
1240
1241         while (call_count--) {
1242                 call_info = g_slist_nth_data(call_list, call_count);
1243                 INFO("Idx=%d, Dir=%d, status=%d, mode=%d, mparty=%d",
1244                 call_info->idx, call_info->dir, call_info->status,
1245                 call_info->mode, call_info->multi_party);
1246                 caller = call_info->number;
1247
1248                 g_variant_builder_add(builder, "(siiii)",
1249                                 caller, call_info->dir, call_info->status,
1250                                 call_info->multi_party, call_info->idx);
1251         }
1252         var_data = g_variant_new("(ia(siiii))",
1253                                 g_slist_length(call_list), builder);
1254
1255         g_variant_builder_unref(builder);
1256         DBG("-");
1257         return  var_data;
1258 }
1259
1260 static void __bt_hf_clear_prev_sent_cmd(void)
1261 {
1262         if (prev_cmd[0] != 0)
1263                 ERR("No sent command");
1264
1265         memset(prev_cmd, 0, BT_HF_CMD_BUF_SIZE);
1266
1267         return;
1268 }
1269
1270 static void __bt_hf_agent_send_call_status_info(GSList *call_list)
1271 {
1272         GDBusConnection *conn;
1273         GVariant *var_data;
1274
1275         var_data = __bt_hf_agent_get_call_status_info(call_list);
1276         conn = __bt_hf_get_gdbus_connection();
1277         if (!conn) {
1278                 ERR("Unable to get connection");
1279                 return;
1280         }
1281
1282         if (conn)
1283                 __bt_hf_agent_emit_signal(conn,
1284                                 BT_HF_AGENT_OBJECT_PATH,
1285                                 BT_HF_SERVICE_INTERFACE,
1286                                 "CallStatusUpdate",
1287                                 var_data);
1288 }
1289
1290 static void __bt_hf_agent_handle_call_list(bt_hf_agent_info_t *bt_hf_info)
1291 {
1292         int ret;
1293
1294         __bt_hf_lock_display(0);
1295
1296         bt_hf_info->context = NULL;
1297
1298         /* Send CLCC. The response will be handled in the handler */
1299         ret = __bt_hf_send_only(bt_hf_info, BT_HF_CALLLIST,
1300                                                 sizeof(BT_HF_CALLLIST) - 1);
1301         if (!ret)
1302                 ERR("Failed to send CLCC");
1303
1304         __bt_hf_unlock_display();
1305 }
1306
1307 static void __bt_hf_agent_request_call_list_info(bt_hf_agent_info_t *bt_hf_info,
1308                                                                 guint index)
1309 {
1310         char *name;
1311         struct indicator *ind = g_slist_nth_data(bt_hf_info->indies, index - 1);
1312         if (ind == NULL) {
1313                 ERR("Indicator is NULL");
1314                 return;
1315         }
1316         name = ind->descr;
1317         DBG("name : %s", name);
1318
1319         if ((strcmp(name, "\"callsetup\"") != 0) &&
1320                         (strcmp(name, "\"call\"") != 0) &&
1321                                 (strcmp(name, "\"callheld\"") != 0))
1322                 return;
1323
1324         __bt_hf_lock_display(0);
1325
1326         __bt_hf_agent_handle_call_list(bt_hf_info);
1327
1328         __bt_hf_unlock_display();
1329
1330 }
1331
1332 static gboolean __bt_hf_send_available_codec(bt_hf_agent_info_t *bt_hf_info, int send_only)
1333 {
1334         gchar buf[BT_HF_DATA_BUF_SIZE];
1335         gchar cmd_buf[BT_HF_CMD_BUF_SIZE] = {0};
1336         gboolean ret;
1337
1338         snprintf(cmd_buf, sizeof(cmd_buf), BT_HF_AVAILABLE_CODEC,
1339                         BT_HF_CODEC_ID_CVSD, BT_HF_CODEC_ID_MSBC);
1340         if (send_only) {
1341                 bt_hf_info->context = NULL;
1342
1343                 ret = __bt_hf_send_only(bt_hf_info, cmd_buf, strlen(cmd_buf));
1344                 return TRUE;
1345         } else {
1346                 ret = __bt_hf_send_and_read(bt_hf_info, cmd_buf, buf,
1347                                 strlen(cmd_buf));
1348         }
1349         if (!ret || !strstr(buf, "OK"))
1350                 return FALSE;
1351
1352         return TRUE;
1353 }
1354
1355 static  int _hf_agent_codec_setup(const char *addr, guint codec_id)
1356 {
1357         int ret;
1358
1359         if (!g_obj_path) {
1360                 ERR("g_obj_path is NULL\n");
1361                 return BT_HF_AGENT_ERROR_INTERNAL;
1362         }
1363
1364         switch (codec_id) {
1365         case BT_HF_CODEC_ID_CVSD:
1366                 INFO("Set NB parameters");
1367                 ret = __bt_hf_agent_gdbus_method_send(BLUEZ_SERVICE_NAME,
1368                                                 g_variant_new("(ss)", "Handsfree", addr),
1369                                                 BT_ADAPTER_INTERFACE,
1370                                                 "SetNbParameters");
1371                 break;
1372         case BT_HF_CODEC_ID_MSBC:
1373                 INFO("Set WBS parameters");
1374                 ret = __bt_hf_agent_gdbus_method_send(BLUEZ_SERVICE_NAME,
1375                                                 g_variant_new("(ss)", "Handsfree", addr),
1376                                                 BT_ADAPTER_INTERFACE,
1377                                                 "SetWbsParameters");
1378                 break;
1379         default:
1380                 ret = BT_HF_AGENT_ERROR_INTERNAL;
1381                 ERR("Invalid Codec\n");
1382                 break;
1383         }
1384
1385         if (ret)
1386                 ERR("Failed to setup the Codec\n");
1387         else
1388                 current_codec_id = codec_id;
1389
1390         return ret;
1391 }
1392
1393 static void __bt_hf_agent_handle_codec_select(bt_hf_agent_info_t *bt_hf_info,
1394                                                         guint codec_id)
1395 {
1396         gchar cmd_buf[BT_HF_CMD_BUF_SIZE] = {0};
1397         gboolean ret;
1398
1399         if (codec_id != BT_HF_CODEC_ID_CVSD && codec_id != BT_HF_CODEC_ID_MSBC) {
1400                 INFO("Codec id doesn't match, so send available codec again");
1401                 ret = __bt_hf_send_available_codec(bt_hf_info, 1);
1402                 if (!ret)
1403                         ERR("Failed to send avalable codec");
1404                 return;
1405         }
1406
1407         /* HF should be ready accpet SCO connection before sending theresponse for
1408         "\r\n+BCS=>Codec ID\r\n", Keep the BT chip ready to recevie encoded SCO data */
1409         ret = _hf_agent_codec_setup(bt_hf_info->remote_addr, codec_id);
1410
1411         snprintf(cmd_buf, sizeof(cmd_buf), BT_HF_CODEC_SELECT, codec_id);
1412
1413         bt_hf_info->context = NULL;
1414
1415         ret = __bt_hf_send_only(bt_hf_info, cmd_buf, strlen(cmd_buf));
1416         if (!ret)
1417                 ERR("Failed to select the Codec");
1418 }
1419
1420 void __bt_hf_agent_print_at_buffer(char *message, const char *buf)
1421 {
1422
1423         int i = 0;
1424         char s[BT_HF_DATA_BUF_SIZE] = {0, };
1425         gboolean hide = FALSE;
1426
1427         gboolean has_clcc = FALSE;
1428         gboolean has_clip = FALSE;
1429         gboolean has_ccwa = FALSE;
1430         char *xsat_ptr;
1431
1432         strncpy(s, buf, BT_HF_DATA_BUF_SIZE - 1);
1433
1434         has_clcc = strstr(buf, "CLCC:") ? TRUE : FALSE;
1435         if (has_clcc == TRUE)
1436                 goto done;
1437         has_clip = strstr(buf, "+CLIP:") ? TRUE : FALSE;
1438         if (has_clip == TRUE)
1439                 goto done;
1440         has_ccwa = strstr(buf, "+CCWA:") ? TRUE : FALSE;
1441
1442 done:
1443         /* +XSAT: 11,DISC */
1444         xsat_ptr =  strstr(s, "11,DISC,");
1445         if (xsat_ptr) {
1446                 xsat_ptr = xsat_ptr + 8;
1447                 int x = 0;
1448                 while (xsat_ptr[x] != '\0' && xsat_ptr[x] != '\r' && xsat_ptr[x] != '\n') {
1449                         xsat_ptr[x] = 'X';
1450                         x++;
1451                 }
1452         }
1453
1454         /* AT+XSAT=11,Q_CT,X,XXXX */
1455         xsat_ptr =  strstr(s, "11,Q_CT,");
1456         if (xsat_ptr) {
1457                 xsat_ptr = xsat_ptr + 8;
1458                 int x = 0;
1459                 while (xsat_ptr[x] != '\0' && xsat_ptr[x] != '\r' && xsat_ptr[x] != '\n') {
1460                         if (x > 1) /* ignore 0 and 1 position */
1461                                 xsat_ptr[x] = 'X';
1462                         x++;
1463                 }
1464         }
1465
1466         i = 0;
1467         while (s[i] != '\0') {
1468                 if (s[i] == '\r' || s[i] == '\n') {
1469                         s[i] = '.';
1470                 } else {
1471                         if (s[i] == '\"')
1472                                 hide = hide ? FALSE : TRUE;
1473                         else if ((has_clcc || has_clip || has_ccwa) && hide) {
1474                                 if (i % 2)
1475                                         s[i] = 'X';
1476                         }
1477                 }
1478                 i++;
1479         }
1480         if (message)
1481                 INFO("%s Buffer = %s, Length = %d ", message, s, strlen(s));
1482         else
1483                 INFO("%s", s);
1484 }
1485
1486 static int __bt_hf_agent_handler_ciev(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1487 {
1488         gchar indicator[BT_HF_INDICATOR_DESCR_SIZE + 4];
1489         gchar *sep;
1490         gint value;
1491         guint index;
1492         char fmt_str[BT_HF_FMT_STR_SIZE];
1493
1494         DBG("++++++++ __bt_hf_agent_handler_ciev +++++++++");
1495
1496         snprintf(fmt_str, sizeof(fmt_str), "\r\n+CIEV:%%%ds\r\n", sizeof(indicator) - 1);
1497         if (sscanf(buf, fmt_str, indicator) == 1) {
1498                 sep = strchr(indicator, ',');
1499                 sep[0] = '\0';
1500                 sep += 1;
1501                 index = atoi(indicator);
1502                 value = atoi(sep);
1503                 __bt_hf_agent_handle_ind_change(bt_hf_info, index, value);
1504
1505                 if (bt_hf_info->ciev_call_status == 0 &&
1506                                 bt_hf_info->ciev_call_setup_status == 0)
1507                         INFO("No active call");
1508                 else
1509                         /* Request CLCC based on indicator change for call/callsetup/callHeld */
1510                         __bt_hf_agent_request_call_list_info(bt_hf_info, index);
1511         }
1512         DBG("--------- __bt_hf_agent_handler_ciev ------------");
1513         return 0;
1514 }
1515
1516 static void __bt_hf_agent_handle_ven_samsung(bt_hf_agent_info_t *bt_hf_info,
1517                                                 gint app_id, const char *msg)
1518 {
1519         /* Whomesoever wants need to handle it */
1520         char *sig_name = "SamsungXSAT";
1521         GDBusConnection *conn;
1522
1523         conn = __bt_hf_get_gdbus_connection();
1524         if (!conn) {
1525                 ERR("Unable to get connection");
1526                 return;
1527         }
1528
1529         __bt_hf_agent_emit_signal(conn,
1530                                 BT_HF_AGENT_OBJECT_PATH,
1531                                 BT_HF_SERVICE_INTERFACE,
1532                                 sig_name,
1533                                 g_variant_new("(is)", app_id, msg));
1534 }
1535
1536 static int __bt_hf_agent_handler_ring(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1537 {
1538         DBG("++++++++ __bt_hf_agent_handler_ring ++++++++");
1539         DBG("---------__bt_hf_agent_handler_ring --------");
1540
1541         return 0;
1542 }
1543
1544 static int __bt_hf_agent_handler_clip(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1545 {
1546         DBG("+++++++++ __bt_hf_agent_handler_clip ++++++++");
1547         DBG("---------__bt_hf_agent_handler_clip --------");
1548
1549         return 0;
1550 }
1551
1552 static int __bt_hf_agent_handler_bvra(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1553 {
1554         DBG("+++++++++ __bt_hf_agent_handler_bvra +++++++++");
1555         gint value;
1556          if (sscanf(buf, "\r\n+BVRA:%1d\r\n", &value) == 1)
1557                 __bt_hf_agent_handle_voice_activation(value);
1558
1559          DBG("---------__bt_hf_agent_handler_bvra --------");
1560         return 0;
1561 }
1562
1563 static int __bt_hf_agent_handler_bcs(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1564 {
1565         guint codec_id;
1566         DBG("+++++++++ __bt_hf_agent_handler_bcs +++++++++-");
1567         if (sscanf(buf, "\r\n+BCS:%3d\r\n", &codec_id))
1568                 __bt_hf_agent_handle_codec_select(bt_hf_info, codec_id);
1569
1570         DBG("---------__bt_hf_agent_handler_bcs --------");
1571         return 0;
1572 }
1573
1574 static int __bt_hf_agent_handler_vgs(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1575 {
1576         gint value;
1577         DBG("+++++++++ __bt_hf_agent_handler_vgs +++++++++");
1578         if (sscanf(buf, "\r\n+VGS:%2d\r\n", &value))
1579                 __bt_hf_agent_handle_speaker_gain(value);
1580
1581         DBG("---------__bt_hf_agent_handler_vgs --------");
1582
1583         return 0;
1584 }
1585
1586 static int __bt_hf_agent_handler_ccwa(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1587 {
1588         DBG("+++++++++ __bt_hf_agent_handler_ccwa ++++++++");
1589                 __bt_hf_agent_handle_ccwa(bt_hf_info, buf);
1590         DBG("---------__bt_hf_agent_handler_ccwa --------");
1591
1592         return 0;
1593 }
1594
1595
1596 static int __bt_hf_agent_handler_xsat(bt_hf_agent_info_t *bt_hf_info,
1597                                                         const char *buf)
1598 {
1599         gint app_id;
1600         char msg[BT_HF_DATA_BUF_SIZE];
1601         char fmt_str[BT_HF_CMD_BUF_SIZE];
1602
1603         DBG("+++++++++ __bt_hf_agent_handler_xsat +++++++++");
1604         snprintf(fmt_str, sizeof(fmt_str), "\r\n+XSAT:%%d,%%%ds\r\n", sizeof(msg) - 1);
1605         if (sscanf(buf, fmt_str, &app_id, msg)) {
1606                 if (app_id == 2 && strstr(msg, "READTXPOWER")) {
1607                         char cmd_buf[BT_HF_CMD_BUF_SIZE * 2] = {0, };
1608                         char power = __bt_hf_agent_get_tx_power(bt_hf_info->remote_addr);
1609                         snprintf(cmd_buf, sizeof(cmd_buf), "AT+XSAT: 2,%d", power);
1610                         bt_hf_agent_send_at_cmd(NULL, cmd_buf);
1611                 } else {
1612                         __bt_hf_agent_handle_ven_samsung(bt_hf_info, app_id, msg);
1613                 }
1614         }
1615
1616         DBG("---------__bt_hf_agent_handler_xsat --------");
1617
1618         return 0;
1619 }
1620
1621 static int __bt_hf_agent_handler_cme_error(bt_hf_agent_info_t *bt_hf_info,
1622                                                         const char *buf)
1623 {
1624         DBG("+++++++++ __bt_hf_agent_handler_cme_error ++++++++");
1625
1626         GDBusConnection *conn;
1627
1628         if (strstr(prev_cmd, "ATD") || strstr(prev_cmd, BT_HF_REDIAL)) {
1629                 conn = __bt_hf_get_gdbus_connection();
1630                 if (!conn) {
1631                         ERR("Unable to get connection");
1632                         return 0;
1633                 }
1634
1635                 __bt_hf_agent_emit_signal(conn,
1636                                         BT_HF_AGENT_OBJECT_PATH,
1637                                         BT_HF_SERVICE_INTERFACE,
1638                                         "CallTerminated",
1639                                         NULL);
1640         }
1641
1642         __bt_hf_clear_prev_sent_cmd();
1643
1644         return 0;
1645 }
1646
1647 static int __bt_hf_agent_handler_response_ok(bt_hf_agent_info_t *bt_hf_info,
1648                                                         const char *buf)
1649 {
1650         DBG("+++++++++ __bt_hf_agent_handler_response_ok ++++++++");
1651
1652         __bt_hf_clear_prev_sent_cmd();
1653
1654         return 0;
1655 }
1656
1657 static int __bt_hf_agent_handler_response_err(bt_hf_agent_info_t *bt_hf_info,
1658                                                         const char *buf)
1659 {
1660         DBG("+++++++++ __bt_hf_agent_handler_response_err ++++++++");
1661         GDBusConnection *conn;
1662
1663         if (strstr(prev_cmd, "ATD") || strstr(prev_cmd, BT_HF_REDIAL)) {
1664                 conn = __bt_hf_get_gdbus_connection();
1665                 if (!conn) {
1666                         ERR("Unable to get connection");
1667                         return 0;
1668                 }
1669
1670                 __bt_hf_agent_emit_signal(conn, BT_HF_AGENT_OBJECT_PATH,
1671                                         BT_HF_SERVICE_INTERFACE,
1672                                         "CallTerminated",
1673                                         NULL);
1674         }
1675         __bt_hf_clear_prev_sent_cmd();
1676
1677         return 0;
1678 }
1679
1680 static int __bt_hf_agent_handler_response_serr(bt_hf_agent_info_t *bt_hf_info,
1681                                                         const char *buf)
1682 {
1683         DBG("+");
1684         GDBusConnection *conn;
1685
1686         if (strstr(prev_cmd, "ATD") || strstr(prev_cmd, BT_HF_REDIAL)) {
1687                 conn = __bt_hf_get_gdbus_connection();
1688                 if (!conn) {
1689                         ERR("Unable to get connection");
1690                         return 0;
1691                 }
1692
1693                 __bt_hf_agent_emit_signal(conn, BT_HF_AGENT_OBJECT_PATH,
1694                                         BT_HF_SERVICE_INTERFACE,
1695                                         "CallTerminated",
1696                                         NULL);
1697         }
1698
1699         __bt_hf_clear_prev_sent_cmd();
1700
1701         DBG("-");
1702         return 0;
1703 }
1704
1705 static int __bt_hf_agent_handler_clcc(bt_hf_agent_info_t *bt_hf_info, const char *buffer)
1706 {
1707
1708         GSList *call_list = NULL;
1709         DBG("+++++++++ __bt_hf_agent_handler_clcc ++++++++");
1710         DBG_SECURE("Receive CLCC response buffer = '%s'", buffer);
1711
1712         __bt_hf_lock_display(0);
1713
1714         call_list = __bt_hf_prepare_call_list(buffer);
1715
1716         if (call_list == NULL)
1717                 goto done;
1718
1719         __bt_hf_launch_call_using_call_list(call_list, bt_hf_info);
1720
1721         __bt_hf_agent_send_call_status_info(call_list);
1722
1723         __bt_hf_free_call_list(call_list);
1724
1725 done:
1726         __bt_hf_unlock_display();
1727         DBG("---------__bt_hf_agent_handler_clcc --------");
1728         return 0;
1729 }
1730
1731 static struct hf_event hf_event_callbacks[] = {
1732         { "\r\n+CIEV:", __bt_hf_agent_handler_ciev },
1733         { "\r\nRING", __bt_hf_agent_handler_ring },
1734         { "\r\n+CLIP:", __bt_hf_agent_handler_clip },
1735         { "\r\n+BVRA:", __bt_hf_agent_handler_bvra },
1736         { "\r\n+BCS:", __bt_hf_agent_handler_bcs },
1737         { "\r\n+VGS:", __bt_hf_agent_handler_vgs },
1738         { "\r\n+CCWA:", __bt_hf_agent_handler_ccwa },
1739         { "\r\n+XSAT:", __bt_hf_agent_handler_xsat },
1740         {"\r\n+CLCC:", __bt_hf_agent_handler_clcc },
1741         { 0 }
1742 };
1743
1744 static struct hf_event hf_event_resp_callbacks[] = {
1745         { "\r\n+CME ERROR:", __bt_hf_agent_handler_cme_error },
1746         { "\r\nOK\r\n", __bt_hf_agent_handler_response_ok },
1747         { "ERROR", __bt_hf_agent_handler_response_err },
1748         { "SERR", __bt_hf_agent_handler_response_serr },
1749         { 0 }
1750 };
1751
1752 bt_hf_agent_send_at_info *__bt_hf_agent_find_next(bt_hf_agent_info_t *bt_hf_info)
1753 {
1754         int len;
1755         int i;
1756         bt_hf_agent_send_at_info *cmd;
1757         len = g_slist_length(bt_hf_info->cmd_send_queue);
1758         for (i = 0; i < len; ++i) {
1759                 cmd = g_slist_nth_data(bt_hf_info->cmd_send_queue, i);
1760                 DBG("F> %.6s[%d]", cmd->at_cmd, cmd->id);
1761         }
1762         len = g_slist_length(bt_hf_info->cmd_send_queue);
1763         DBG("Context queue length = %d", len);
1764         if (len == 0)
1765                 return NULL;
1766
1767         cmd = g_slist_nth_data(bt_hf_info->cmd_send_queue, 0);
1768         if (cmd) {
1769                 bt_hf_info->cmd_send_queue = g_slist_remove(bt_hf_info->cmd_send_queue, cmd);
1770                 DBG("NEXT[%d] Found %s, context = 0x%x, pending = %d", cmd->id,
1771                                 cmd->at_cmd, cmd->context, cmd->pending);
1772                         return cmd;
1773         }
1774
1775         DBG("**** Not found any pending command on list length %d ****", len);
1776
1777         return NULL;
1778 }
1779
1780 static int hf_handle_rx_at_cmd(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1781 {
1782         struct hf_event *ev;
1783         int ret = -EINVAL;
1784         bt_hf_agent_send_at_info *cmd = NULL;
1785
1786         __bt_hf_agent_print_at_buffer("Processing [Rx cmd]:", buf);
1787
1788         for (ev = hf_event_resp_callbacks; ev->cmd; ev++) {
1789                 if (strstr(buf, ev->cmd)) {
1790                         if (send_flag)
1791                                 send_flag--;
1792                         DBG("Send flag value = %d(after)", send_flag);
1793                         ret = ev->callback(bt_hf_info, buf);
1794                 }
1795         }
1796
1797         if (ret != -EINVAL)
1798                 goto done;
1799
1800         for (ev = hf_event_callbacks; ev->cmd; ev++) {
1801                 if (!strncmp(buf, ev->cmd, strlen(ev->cmd))) {
1802                         ret = ev->callback(bt_hf_info, buf);
1803                         break;
1804                 }
1805         }
1806
1807                 return ret;
1808 done:
1809
1810         cmd = __bt_hf_agent_find_next(bt_hf_info);
1811
1812         if (cmd && cmd->context) {
1813                 DBG("Pending context found for %.6s[%d]", cmd->at_cmd, cmd->id);
1814                 g_dbus_method_invocation_return_value(cmd->context, NULL);
1815                 if (cmd->timer_id)
1816                         g_source_remove(cmd->timer_id);
1817                 g_free(cmd);
1818                 cmd = NULL;
1819         }
1820
1821         if (cmd == NULL)
1822                 cmd = __bt_hf_agent_find_next(bt_hf_info);
1823
1824         if (cmd && cmd->pending && send_flag == 0) {
1825                 DBG("Pending only found of %.6s[%d]", cmd->at_cmd, cmd->id);
1826                 __bt_hf_send_only_without_queue(bt_hf_info,
1827                                         cmd->at_cmd, cmd->count);
1828                  cmd->pending = FALSE;
1829                 bt_hf_info->cmd_send_queue = g_slist_prepend(bt_hf_info->cmd_send_queue,
1830                                                                         cmd);
1831                 DBG("Prepend %.6s[%d]", cmd->at_cmd, cmd->id);
1832         } else {
1833                 if (cmd) {
1834                         DBG("Pending free for %.6s[%d] - send_flag = %d",
1835                                         cmd->at_cmd, cmd->id, send_flag);
1836                         if (cmd->timer_id)
1837                                 g_source_remove(cmd->timer_id);
1838                         g_free(cmd);
1839                 }
1840
1841
1842
1843                 /* Need to process further pending */
1844                 cmd = __bt_hf_agent_find_next(bt_hf_info);
1845                 if (cmd) {
1846                         if (cmd->pending && send_flag == 0) {
1847                                 DBG("2nd Pending only found of %.6s[%d]",
1848                                                         cmd->at_cmd, cmd->id);
1849                                 __bt_hf_send_only_without_queue(bt_hf_info,
1850                                                 cmd->at_cmd, cmd->count);
1851                                  cmd->pending = FALSE;
1852                         }
1853                         bt_hf_info->cmd_send_queue = g_slist_prepend(bt_hf_info->cmd_send_queue,
1854                                                                         cmd);
1855                         DBG("2nd Prepend %.6s[%d]", cmd->at_cmd, cmd->id);
1856                 }
1857         }
1858         return ret;
1859 }
1860
1861 static int hf_handle_append_clcc_buff(char *cmd_buf, const char *buf)
1862 {
1863         int buf_length;
1864         int cmd_length =  0;
1865         int cmd_buf_len = 0;
1866         char *pos_start, *pos_end;
1867         const char *datap = buf;
1868
1869         cmd_buf_len = strlen(cmd_buf);
1870         buf_length = strlen(buf);
1871         DBG("buf_length = %d, cmd_buf_len = %d", buf_length, cmd_buf_len);
1872
1873         if (buf_length > 0 && strstr(datap, "+CLCC")) {
1874                 pos_start = strstr(datap, "\r\n");
1875                 if (pos_start == NULL) {
1876                         ERR("Invalid AT command signature..\n");
1877                         return 0;
1878                 }
1879
1880                 pos_end = g_strrstr(datap, "+CLCC");
1881                 if (pos_end == NULL) {
1882                         ERR("Invalid AT command signature..\n");
1883                         return 0;
1884                 }
1885                 pos_end =  strstr(pos_end, "\r\n");
1886                 cmd_length =   (pos_end - pos_start) + 2;
1887                 INFO("CLCC balance Cmd Length = %d\n", cmd_length);
1888                 memcpy(cmd_buf + cmd_buf_len, pos_start, cmd_length);
1889                 cmd_buf[cmd_buf_len + cmd_length] = '\0';
1890
1891                 if (strstr(cmd_buf, "\r\nOK\r\n")) {
1892                         pos_end = strstr(datap, "\r\nOK\r\n");
1893                         cmd_length =   (pos_end - pos_start);
1894                         memcpy(cmd_buf + cmd_buf_len, pos_start, cmd_length);
1895                         cmd_buf[cmd_buf_len + cmd_length] = '\0';
1896                         INFO("New CLCC balance Cmd Length = %d", cmd_length);
1897                 }
1898         }
1899         return cmd_length;
1900 }
1901
1902
1903 static int hf_handle_rx_at_buff(bt_hf_agent_info_t *bt_hf_info, const char *buf)
1904 {
1905         int buf_length;
1906         int cmd_length;
1907         char *pos_start, *pos_end;
1908         int tmp;
1909         gchar cmd_buf[BT_HF_DATA_BUF_SIZE] = {0,};
1910         const char *datap = buf;
1911
1912         __bt_hf_agent_print_at_buffer("[HF AT CMD] Recv >>>>>:", buf);
1913
1914         buf_length = strlen(buf);
1915
1916         while (buf_length > 0) {
1917                 pos_start = strstr(datap, "\r\n");
1918                 if (pos_start == NULL) {
1919                         ERR("Invalid AT command start signature..\n");
1920                         break;
1921                 }
1922
1923                 datap += 2;
1924                 pos_end = strstr(datap, "\r\n");
1925                 if (pos_end == NULL) {
1926                         ERR("Invalid AT command end signature..\n");
1927                         break;
1928                 }
1929                 cmd_length =   (pos_end - pos_start) + 2;
1930                 DBG("Cmd Length = %d\n", cmd_length);
1931
1932                 memcpy(cmd_buf, pos_start, cmd_length);
1933                 cmd_buf[cmd_length] = '\0';
1934
1935                 buf_length = buf_length - cmd_length;
1936                 datap = datap + cmd_length - 2;
1937
1938                 /* We need to pass all the CLCC's together to its handler */
1939                 if (strstr(cmd_buf, "+CLCC")) {
1940                         tmp = hf_handle_append_clcc_buff(cmd_buf, datap);
1941                         datap += tmp;
1942                         buf_length = buf_length - tmp;
1943                 }
1944                 hf_handle_rx_at_cmd(bt_hf_info, cmd_buf);
1945                 DBG("Pending buf_length = %d\n", buf_length);
1946         }
1947         return TRUE;
1948
1949 }
1950 static gboolean __bt_hf_agent_data_cb(GIOChannel *chan, GIOCondition cond,
1951                                         bt_hf_agent_info_t *bt_hf_info)
1952 {
1953         gchar buf[BT_HF_DATA_BUF_SIZE] = {0,};
1954         gsize read;
1955         GError *gerr = NULL;
1956         gboolean recvd_ok = FALSE;
1957         gboolean recvd_error = FALSE;
1958         gboolean recvd_sec_error = FALSE;
1959
1960         if (cond & (G_IO_ERR | G_IO_HUP)) {
1961                 ERR("ERR or HUP on RFCOMM socket");
1962                 INFO_C("Disconnected [HF role] [Terminated by remote dev]");
1963                 is_hf_connected = FALSE;
1964                 bt_hf_info->slc = FALSE;
1965                 __bt_hf_agent_release();
1966                 return FALSE;
1967         }
1968
1969         if (g_io_channel_read_chars(chan, buf, sizeof(buf) - 1, &read, &gerr)
1970                         != G_IO_STATUS_NORMAL) {
1971                 if (gerr) {
1972                         ERR("Read failed, cond = [%d], Err msg = [%s]",
1973                                                         cond, gerr->message);
1974                         g_error_free(gerr);
1975                 }
1976                 return TRUE;
1977         }
1978         buf[read] = '\0';
1979         recvd_ok = NULL != strstr(buf, BT_HF_OK_RESPONSE);
1980         recvd_error = NULL != strstr(buf, BT_HF_ERROR_RESPONSE);
1981         recvd_sec_error = NULL != strstr(buf, BT_HF_SEC_ERROR_RESPONSE);
1982         DBG("<-------Received data --send flag status = %d ----->", send_flag);
1983
1984         /* Once service level connection is established we need to handle
1985          * all the intermediate AT commands */
1986         if (bt_hf_info->state != BT_HF_STATE_CONNECTED)
1987                 return TRUE;
1988
1989         if (send_flag) {
1990                 strncat(global_buff, buf,
1991                         (BT_AT_COMMAND_BUFFER_MAX - 1) - strlen(global_buff));
1992                 if (!(recvd_ok || recvd_error || recvd_sec_error)) {
1993                         __bt_hf_agent_print_at_buffer("Concat ()", global_buff);
1994                 } else {
1995                         DBG("*** Received terminator.. process Rx buffer ***");
1996                         hf_handle_rx_at_buff(bt_hf_info, global_buff);
1997                         memset(global_buff, 0, sizeof(global_buff));
1998                 }
1999         } else {
2000                 INFO("***  Received Direct AT buffer packet handling ****");
2001                 hf_handle_rx_at_buff(bt_hf_info, buf);
2002         }
2003         return TRUE;
2004 }
2005
2006 static void __bt_hf_agent_start_watch(bt_hf_agent_info_t *bt_hf_info)
2007 {
2008         bt_hf_info->watch_id = g_io_add_watch(bt_hf_info->io_chan,
2009                         G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
2010                         (GIOFunc) __bt_hf_agent_data_cb, bt_hf_info);
2011 }
2012
2013 static void __bt_hf_agent_stop_watch(bt_hf_agent_info_t *bt_hf_info)
2014 {
2015         if (bt_hf_info->watch_id > 0) {
2016                 g_source_remove(bt_hf_info->watch_id);
2017                 bt_hf_info->watch_id = 0;
2018         }
2019 }
2020
2021 static gboolean __bt_hf_channel_write(GIOChannel *io, gchar *data,
2022                                         gsize count)
2023 {
2024         gsize written = 0;
2025         GIOStatus status;
2026
2027         while (count > 0) {
2028                 status = g_io_channel_write_chars(io, data, count, &written,
2029                                                 NULL);
2030                 if (status != G_IO_STATUS_NORMAL)
2031                         return FALSE;
2032
2033                 data += written;
2034                 count -= written;
2035         }
2036         return TRUE;
2037 }
2038
2039 static gboolean __bt_hf_send_only_without_queue(bt_hf_agent_info_t *bt_hf_info,
2040                                                 gchar *data, gsize count)
2041 {
2042         GIOChannel *io_chan = bt_hf_info->io_chan;
2043         if (!__bt_hf_channel_write(io_chan, data, count))
2044                 return FALSE;
2045
2046         g_io_channel_flush(io_chan, NULL);
2047
2048         if (count > 2 && data[2] == 'D') { /* ATDXXXXX */
2049                 INFO("Send only buffer size =[%d] No len = %d - Send <<<<<| %s",
2050                                          count, count - 6, "ATDXXXXXXX");
2051                 snprintf(prev_cmd, BT_HF_CMD_BUF_SIZE, "%s", data);
2052         } else {
2053                 INFO("No queue....Send only buffer size =[%d] - Send <<<<<| %s",
2054                                                                 count, data);
2055         }
2056
2057         send_flag++;
2058         /* DBG("Ref %d(after) on Send only buffer size =[%d] - Send <<<<<| %s",
2059          * send_flag, count, data); */
2060         return TRUE;
2061
2062 }
2063
2064 static gboolean __bt_hf_send_only(bt_hf_agent_info_t *bt_hf_info, gchar *data,
2065                                                                 gsize count)
2066 {
2067         gboolean pending = FALSE;
2068         GIOChannel *io_chan = bt_hf_info->io_chan;
2069
2070         if (send_flag) {
2071                 pending = TRUE;
2072         }
2073         __bt_hf_agent_add_queue(bt_hf_info->context, data, count, pending);
2074
2075         if (pending)
2076                 return TRUE;
2077
2078         if (!__bt_hf_channel_write(io_chan, data, count))
2079                 return FALSE;
2080
2081         g_io_channel_flush(io_chan, NULL);
2082
2083         if (count > 2 && data[2] == 'D') /* ATDXXXXX */
2084                 INFO("Send only buffer size =[%d] No len = %d - Send <<<<<| %s",
2085                                          count, count - 6, "ATDXXXXXXX");
2086         else
2087                 INFO("Send only buffer size =[%d] - Send <<<<<| %s", count, data);
2088
2089         send_flag++;
2090         DBG("Ref %d(after) on Send only buffer size =[%d] - Send <<<<<| %s",
2091                                                 send_flag, count, data);
2092         return TRUE;
2093 }
2094
2095 static gboolean __bt_hf_send_and_read(bt_hf_agent_info_t *bt_hf_info,
2096                 gchar *data, gchar *response, gsize count)
2097 {
2098         GIOChannel *io_chan = bt_hf_info->io_chan;
2099         gsize rd_size = 0;
2100         gboolean recvd_ok = FALSE;
2101         gboolean recvd_error = FALSE;
2102         gboolean recvd_sec_error = FALSE;
2103         gchar *resp_buf = response;
2104         gsize toread = BT_HF_DATA_BUF_SIZE - 1;
2105         int i = 0;
2106         int fd;
2107         int err;
2108         struct pollfd p;
2109         GDBusConnection *conn;
2110
2111         /* Should not send cmds if DUT send a command and wait the response */
2112         if (prev_cmd[0] != 0) {
2113                 INFO("DUT is waiting a respond for previous TX cmd. Skip sending.");
2114                 return FALSE;
2115         }
2116
2117         memset(resp_buf, 0, BT_HF_DATA_BUF_SIZE);
2118
2119         if (!__bt_hf_channel_write(io_chan, data, count))
2120                 return FALSE;
2121
2122         g_io_channel_flush(io_chan, NULL);
2123
2124         __bt_hf_agent_print_at_buffer("[HF AT CMD] Send <<<<<:", data);
2125
2126         fd = g_io_channel_unix_get_fd(io_chan);
2127         p.fd = fd;
2128         p.events = POLLIN | POLLERR | POLLHUP | POLLNVAL;
2129
2130         /* Maximun 8 seconds of poll or 8 minus no of cmd received */
2131         for (i = 1; i <= MAX_WAITING_DELAY; i++) {
2132                 DBG("Loop Counter = %d", i);
2133                 p.revents = 0;
2134                 err = poll(&p, 1, 1000);
2135                 if (err < 0) {
2136                         ERR("Loop Counter = %d, >>>> Poll error happen", i);
2137                         return FALSE;
2138                 } else if (err == 0) {
2139                         INFO("Loop Counter = %d, >>>> Poll Timeout", i);
2140                 }
2141
2142                 if (p.revents & (POLLERR | POLLHUP | POLLNVAL)) {
2143                         ERR("Loop Counter = %d, >> Poll ERR/HUP/INV (%d)",
2144                                                                 i, p.revents);
2145
2146                         conn = __bt_hf_get_gdbus_connection();
2147                         if (!conn) {
2148                                 ERR("Unable to get connection");
2149                                 return FALSE;
2150                         }
2151
2152                         __bt_hf_agent_emit_signal(conn,
2153                                 BT_HF_AGENT_OBJECT_PATH,
2154                                 BT_HF_SERVICE_INTERFACE,
2155                                 "Disconnected",
2156                                 g_variant_new("(s)",
2157                                                 bt_hf_info->remote_addr));
2158
2159                         bt_hf_info->state = BT_HF_STATE_DISCONNECTED;
2160                         return FALSE;
2161                 }
2162
2163                 if (p.revents & POLLIN) {
2164                         rd_size = read(fd, resp_buf, toread);
2165                         resp_buf[rd_size] = '\0';
2166                         DBG_SECURE("size = %d, Buffer=[%s]", rd_size, resp_buf);
2167                         recvd_ok = NULL != strstr(resp_buf, BT_HF_OK_RESPONSE);
2168                         recvd_error = NULL != strstr(resp_buf, BT_HF_ERROR_RESPONSE);
2169                         recvd_sec_error = NULL != strstr(resp_buf, BT_HF_SEC_ERROR_RESPONSE);
2170
2171                         resp_buf += rd_size;
2172                         toread -= rd_size;
2173
2174                         if (recvd_ok || recvd_error || recvd_sec_error) {
2175                                 DBG("Break Loop Counter = %d", i);
2176                                 break;
2177                         }
2178                 }
2179         }
2180
2181         /* Once service level connection is established we need to handle
2182          * all the intermediate AT commands */
2183         if (bt_hf_info->state == BT_HF_STATE_CONNECTED)
2184                 hf_handle_rx_at_buff(bt_hf_info, response);
2185         return TRUE;
2186 }
2187
2188 static GSList *__bt_hf_parse_indicator_names(gchar *names, GSList *indices)
2189 {
2190         struct indicator *ind;
2191         gchar *cur = names - 1;
2192         GSList *list = indices;
2193         gchar *next;
2194
2195         DBG("Indicator buffer = %s", names);
2196         __bt_hf_agent_print_at_buffer("Indicator names :", names);
2197         while (cur != NULL) {
2198                 cur += 2;
2199                 next = strstr(cur, ",(");
2200                 ind = g_new0(struct indicator, 1);
2201                 g_strlcpy(ind->descr, cur, BT_HF_INDICATOR_DESCR_SIZE);
2202                 ind->descr[(intptr_t) next - (intptr_t) cur] = '\0';
2203                 list = g_slist_append(list, (gpointer) ind);
2204                 cur = strstr(next + 1, ",(");
2205         }
2206         return list;
2207 }
2208
2209 static GSList *__bt_hf_parse_indicator_values(gchar *values, GSList *indices)
2210 {
2211         gint val;
2212         struct indicator *ind;
2213         GSList *runner = indices;
2214
2215         gchar *cur = values - 1;
2216         DBG("Indicator string = %s", values);
2217         __bt_hf_agent_print_at_buffer("Indicator values :", values);
2218         while (cur != NULL) {
2219                 cur += 1;
2220                 sscanf(cur, "%1d", &val);
2221                 cur = strchr(cur, ',');
2222                 ind = g_slist_nth_data(runner, 0);
2223                 ind->value = val;
2224                 runner = g_slist_next(runner);
2225         }
2226         return indices;
2227 }
2228
2229 static guint __bt_hf_get_hold_mpty_features(gchar *features)
2230 {
2231         guint result = 0;
2232
2233         if (strstr(features, "0"))
2234                 result |= BT_HF_CHLD_0;
2235
2236         if (strstr(features, "1"))
2237                 result |= BT_HF_CHLD_1;
2238
2239         if (strstr(features, "1x"))
2240                 result |= BT_HF_CHLD_1x;
2241
2242         if (strstr(features, "2"))
2243                 result |= BT_HF_CHLD_2;
2244
2245         if (strstr(features, "2x"))
2246                 result |= BT_HF_CHLD_2x;
2247
2248         if (strstr(features, "3"))
2249                 result |= BT_HF_CHLD_3;
2250
2251         if (strstr(features, "4"))
2252                 result |= BT_HF_CHLD_4;
2253
2254         return result;
2255 }
2256
2257 static gboolean __bt_hf_agent_sco_conn_cb(GIOChannel *chan, GIOCondition cond, gpointer user_data)
2258 {
2259         bt_hf_agent_info_t *bt_hf_info = user_data;
2260         GDBusConnection *conn;
2261
2262         DBG("");
2263         if (cond & G_IO_NVAL)
2264                 return FALSE;
2265
2266         if (cond & (G_IO_HUP | G_IO_ERR)) {
2267                 g_io_channel_shutdown(chan, TRUE, NULL);
2268                 close(bt_hf_info->cli_sco_fd);
2269                 g_io_channel_unref(chan);
2270                 DBG("Emit AudioDisconnected Signal");
2271
2272                 sco_audio_connected = BT_HF_AUDIO_DISCONNECTED;
2273
2274                 conn = __bt_hf_get_gdbus_connection();
2275                 if (!conn) {
2276                         ERR("Unable to get connection");
2277                         return FALSE;
2278                 }
2279                 __bt_hf_agent_emit_signal(conn,
2280                                 BT_HF_AGENT_OBJECT_PATH,
2281                                 BT_HF_SERVICE_INTERFACE,
2282                                 "AudioDisconnected", NULL);
2283
2284                 return FALSE;
2285         }
2286
2287         return TRUE;
2288 }
2289
2290 static gboolean __bt_agent_query_and_update_call_list(gpointer data)
2291 {
2292         DBG("+");
2293         bt_hf_agent_info_t *bt_hf_info = data;
2294
2295         if (bt_hf_info->cli_sco_fd >= 0)
2296                 __bt_hf_agent_handle_call_list(bt_hf_info);
2297         else
2298                 INFO("SCO Audio is already disconnected");
2299
2300         DBG("-");
2301
2302         return FALSE;
2303 }
2304
2305 static gboolean __bt_hf_agent_sco_accept_cb(GIOChannel *chan, GIOCondition cond, gpointer user_data)
2306 {
2307         bt_hf_agent_info_t *bt_hf_info = user_data;
2308         int sco_skt;
2309         int cli_sco_sock;
2310         GIOChannel *sco_io;
2311         GDBusConnection *conn;
2312
2313         INFO("Incoming SCO....");
2314
2315         if (cond & G_IO_NVAL)
2316                 return FALSE;
2317
2318         sco_skt = g_io_channel_unix_get_fd(chan);
2319
2320         if (cond & (G_IO_HUP | G_IO_ERR)) {
2321                 close(sco_skt);
2322                 return FALSE;
2323         }
2324
2325         cli_sco_sock = accept(sco_skt, NULL, NULL);
2326         if (cli_sco_sock < 0)
2327                 return FALSE;
2328
2329         bt_hf_info->cli_sco_fd = cli_sco_sock;
2330
2331         sco_io = g_io_channel_unix_new(cli_sco_sock);
2332         g_io_channel_set_close_on_unref(sco_io, TRUE);
2333         g_io_channel_set_encoding(sco_io, NULL, NULL);
2334         g_io_channel_set_flags(sco_io, G_IO_FLAG_NONBLOCK, NULL);
2335         g_io_channel_set_buffered(sco_io, FALSE);
2336
2337         g_io_add_watch(sco_io, G_IO_HUP | G_IO_ERR | G_IO_NVAL,
2338                                         __bt_hf_agent_sco_conn_cb, bt_hf_info);
2339
2340         /* S-Voice app requires the AudioConnected signal earlier */
2341         DBG("Emit AudioConnected Signal");
2342
2343         sco_audio_connected = BT_HF_AUDIO_CONNECTED;
2344
2345         conn = __bt_hf_get_gdbus_connection();
2346         if (!conn) {
2347                 ERR("Unable to get connection");
2348                 return FALSE;
2349         }
2350
2351         __bt_hf_agent_emit_signal(conn,
2352                         BT_HF_AGENT_OBJECT_PATH,
2353                         BT_HF_SERVICE_INTERFACE,
2354                         "AudioConnected", NULL);
2355
2356         /* In the case of incoming call, the call app is already launched,
2357          * hence AudioConnected signal is enough to update the call status.
2358          * In the case of outgoing call we need to lauch the callapp.
2359          */
2360
2361         g_idle_add(__bt_agent_query_and_update_call_list, bt_hf_info);
2362
2363         return TRUE;
2364 }
2365
2366 void _bt_convert_addr_string_to_type_rev(unsigned char *addr,
2367                                         const char *address)
2368 {
2369         int i;
2370         char *ptr = NULL;
2371
2372         ret_if(address == NULL);
2373         ret_if(addr == NULL);
2374
2375         for (i = 0; i < 6; i++) {
2376                 addr[5 - i] = strtol(address, &ptr, 16);
2377                 if (ptr[0] != '\0') {
2378                         if (ptr[0] != ':')
2379                                 return;
2380
2381                         address = ptr + 1;
2382                 }
2383         }
2384 }
2385
2386 static gboolean __bt_hf_agent_sco_accept(bt_hf_agent_info_t *bt_hf_info)
2387 {
2388         struct sockaddr_sco addr;
2389         GIOChannel *sco_io;
2390         bdaddr_t bd_addr = {{0},};
2391         int sco_skt;
2392
2393         if (bt_hf_info->state != BT_HF_STATE_CONNECTED)
2394                 return FALSE;
2395
2396         /* Create socket */
2397         sco_skt = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO);
2398         if (sco_skt < 0) {
2399                 ERR("Can't create socket:\n");
2400                 return FALSE;
2401         }
2402
2403         /* Bind to local address */
2404         memset(&addr, 0, sizeof(addr));
2405         addr.sco_family = AF_BLUETOOTH;
2406
2407         DBG("Bind to address %s", bt_hf_info->remote_addr);
2408
2409         _bt_convert_addr_string_to_type_rev(bd_addr.b, bt_hf_info->remote_addr);
2410         memcpy(&addr.sco_bdaddr, &bd_addr, sizeof(bdaddr_t));
2411
2412         if (bind(sco_skt, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
2413                 ERR("Can't bind socket:\n");
2414                 goto error;
2415         }
2416
2417         if (listen(sco_skt, 1)) {
2418                 ERR("Can not listen on the socket:\n");
2419                 goto error;
2420         }
2421
2422         sco_io = g_io_channel_unix_new(sco_skt);
2423         g_io_channel_set_close_on_unref(sco_io, TRUE);
2424         g_io_channel_set_encoding(sco_io, NULL, NULL);
2425         g_io_channel_set_flags(sco_io, G_IO_FLAG_NONBLOCK, NULL);
2426         g_io_channel_set_buffered(sco_io, FALSE);
2427
2428         bt_hf_info->sco_fd = sco_skt;
2429         bt_hf_info->sco_io_chan = sco_io;
2430
2431         bt_hf_info->sco_watch_id = g_io_add_watch(sco_io,
2432                         G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, __bt_hf_agent_sco_accept_cb, bt_hf_info);
2433
2434         g_io_channel_unref(sco_io);
2435
2436         return TRUE;
2437
2438 error:
2439         close(sco_skt);
2440         return FALSE;
2441 }
2442
2443 static gboolean __bt_get_supported_indicators(bt_hf_agent_info_t *bt_hf_info)
2444 {
2445         gchar buf[BT_HF_DATA_BUF_SIZE] = {0,};
2446         gboolean ret;
2447
2448         ret = __bt_hf_send_and_read(bt_hf_info, BT_HF_INDICATORS_SUPP, buf,
2449                                 sizeof(BT_HF_INDICATORS_SUPP) - 1);
2450         if (!ret || !strstr(buf, "+CIND:"))
2451                 return FALSE;
2452
2453         bt_hf_info->indies = __bt_hf_parse_indicator_names(strchr(buf, '('), NULL);
2454
2455         return TRUE;
2456 }
2457
2458 static gboolean __bt_get_bia_cmd(bt_hf_agent_info_t *bt_hf_info, gchar *cmd, gsize cmd_size)
2459 {
2460         GSList *l;
2461         gsize ret;
2462
2463         if (bt_hf_info == NULL || cmd == NULL) {
2464                 ERR("Invalid parameter");
2465                 return FALSE;
2466         }
2467
2468         ret = g_strlcpy(cmd, BT_HF_INDICATORS_ACTIVATION, cmd_size);
2469
2470         for (l = bt_hf_info->indies; l != NULL; l = g_slist_next(l)) {
2471                 ret = g_strlcat(cmd, "0,", cmd_size);
2472                 if (ret >= cmd_size) {
2473                         ERR("Too many indices");
2474                         return FALSE;
2475                 }
2476
2477         }
2478
2479         cmd[ret - 1] = '\0';
2480         DBG("BIA Str : %s", cmd);
2481
2482         ret = g_strlcat(cmd, "\r", cmd_size);
2483         if (ret >= cmd_size) {
2484                 ERR("Too many indices");
2485                 return FALSE;
2486         }
2487
2488         return TRUE;
2489 }
2490
2491 static gboolean __bt_get_current_indicators(bt_hf_agent_info_t *bt_hf_info)
2492 {
2493         gchar buf[BT_HF_DATA_BUF_SIZE] = {0,};
2494         gboolean ret;
2495         gchar *str;
2496         GSList *l;
2497         int index =  1;
2498
2499         ret = __bt_hf_send_and_read(bt_hf_info, BT_HF_INDICATORS_VAL, buf,
2500                 sizeof(BT_HF_INDICATORS_VAL) - 1);
2501         if (!ret || !strstr(buf, "+CIND:"))
2502                 return FALSE;
2503
2504         /* if buf has other command prefix, skip it */
2505         str = strstr(buf, "+CIND");
2506         if (str == NULL)
2507                 return FALSE;
2508
2509         bt_hf_info->indies = __bt_hf_parse_indicator_values(str + 6, bt_hf_info->indies);
2510
2511         /* Parse the updated value */
2512         for (l = bt_hf_info->indies; l != NULL; l = g_slist_next(l), ++index) {
2513                 struct indicator *ind = l->data;
2514                 if (!ind) {
2515                         DBG("Index is NULL");
2516                         break;
2517                 }
2518
2519                 if (0 == g_strcmp0(ind->descr, "\"call\"")) {
2520                         DBG("CIND Match found index = %d, %s, value = %d",
2521                                                 index, ind->descr, ind->value);
2522                         bt_hf_info->ciev_call_status = ind->value;
2523                         if (ind->value > 0) {
2524                                 bt_hf_info->is_dialing = FALSE;
2525                                 bt_hf_info->call_active = TRUE;
2526                         }
2527                 } else if (0 == g_strcmp0(ind->descr, "\"callsetup\"")) {
2528                         DBG("CIND Match found index = %d, %s, value = %d",
2529                                                 index, ind->descr, ind->value);
2530                         bt_hf_info->ciev_call_setup_status = ind->value;
2531                         if (!bt_hf_info->is_dialing && ind->value > 0)
2532                                 bt_hf_info->is_dialing = TRUE;
2533                 }
2534         }
2535
2536         return TRUE;
2537 }
2538
2539 static gboolean __bt_establish_service_level_conn(bt_hf_agent_info_t *bt_hf_info)
2540 {
2541         gchar buf[BT_HF_DATA_BUF_SIZE];
2542         gchar cmd_buf[BT_HF_CMD_BUF_SIZE] = {0};
2543         gboolean ret;
2544         char *buf_ptr;
2545         guint feature = BT_HF_FEATURE_EC_ANDOR_NR |
2546                         BT_HF_FEATURE_CALL_WAITING_AND_3WAY |
2547                         BT_HF_FEATURE_CLI_PRESENTATION |
2548                         BT_HF_FEATURE_VOICE_RECOGNITION |
2549                         BT_HF_FEATURE_REMOTE_VOLUME_CONTROL |
2550                         BT_HF_FEATURE_ENHANCED_CALL_STATUS |
2551                         BT_HF_FEATURE_CODEC_NEGOTIATION;
2552
2553         snprintf(cmd_buf, sizeof(cmd_buf), BT_HF_FEATURES, feature);
2554         ret = __bt_hf_send_and_read(bt_hf_info, cmd_buf, buf,
2555                                 strlen(cmd_buf));
2556         if (!ret )
2557                 return FALSE;
2558
2559         buf_ptr = strstr(buf, "\r\n+BRSF:");
2560         if (buf_ptr == NULL)
2561                 return FALSE;
2562
2563         if (!ret || sscanf(buf_ptr, "\r\n+BRSF:%5d", &bt_hf_info->ag_features) != 1)
2564                 return FALSE;
2565         INFO("Gateway supported features are 0x%X", bt_hf_info->ag_features);
2566
2567         if (bt_hf_info->ag_features & BT_AG_FEATURE_CODEC_NEGOTIATION) {
2568                 ret = _hf_agent_codec_setup(bt_hf_info->remote_addr, BT_HF_CODEC_ID_MSBC);
2569                 if (ret != BT_HF_AGENT_ERROR_NONE)
2570                         ERR("Unable to set the default WBC codec");
2571
2572                 ret = __bt_hf_send_available_codec(bt_hf_info, 0);
2573                 if (!ret)
2574                         return FALSE;
2575         } else {
2576                 /* Default codec is NB */
2577                 ret = _hf_agent_codec_setup(bt_hf_info->remote_addr, BT_HF_CODEC_ID_CVSD);
2578                 if (ret != BT_HF_AGENT_ERROR_NONE)
2579                         ERR("Unable to set the default NBC codec");
2580         }
2581
2582         ret = __bt_get_supported_indicators(bt_hf_info);
2583         if (!ret)
2584                 return FALSE;
2585
2586
2587         ret = __bt_get_current_indicators(bt_hf_info);
2588         if (!ret)
2589                 return FALSE;
2590
2591         ret = __bt_hf_send_and_read(bt_hf_info, BT_HF_INDICATORS_ENABLE, buf,
2592                                         sizeof(BT_HF_INDICATORS_ENABLE) - 1);
2593         if (!ret || !strstr(buf, "OK"))
2594                 return FALSE;
2595
2596         if ((bt_hf_info->ag_features & BT_AG_FEATURE_3WAY) != 0) {
2597                 ret = __bt_hf_send_and_read(bt_hf_info, BT_HF_HOLD_MPTY_SUPP,
2598                                         buf, sizeof(BT_HF_HOLD_MPTY_SUPP) - 1);
2599                 if (!ret || !strstr(buf, "+CHLD:")) {
2600                         ERR("Unable to get the CHLD Supported info");
2601                         return FALSE;
2602                 }
2603                 bt_hf_info->hold_multiparty_features = __bt_hf_get_hold_mpty_features(
2604                                                         strchr(buf, '('));
2605         } else
2606                 bt_hf_info->hold_multiparty_features = 0;
2607
2608         INFO("Service layer connection successfully established...!");
2609
2610         __bt_hf_send_and_read(bt_hf_info, BT_HF_CALLER_IDENT_ENABLE, buf,
2611                         sizeof(BT_HF_CALLER_IDENT_ENABLE) - 1);
2612         __bt_hf_send_and_read(bt_hf_info, BT_HF_CARRIER_FORMAT, buf,
2613                         sizeof(BT_HF_CARRIER_FORMAT) - 1);
2614         __bt_hf_send_and_read(bt_hf_info, BT_HF_CALLWAIT_NOTI_ENABLE, buf,
2615                         sizeof(BT_HF_CALLWAIT_NOTI_ENABLE) - 1);
2616
2617         if ((bt_hf_info->ag_features & BT_AG_FEATURE_NREC) != 0)
2618                 __bt_hf_send_and_read(bt_hf_info, BT_HF_NREC, buf,
2619                                                 sizeof(BT_HF_NREC) - 1);
2620
2621         if ((bt_hf_info->ag_features & BT_AG_FEATURE_EXTENDED_RES_CODE) != 0)
2622                 __bt_hf_send_and_read(bt_hf_info, BT_HF_EXTENDED_RESULT_CODE,
2623                         buf, sizeof(BT_HF_EXTENDED_RESULT_CODE) - 1);
2624
2625         if (__bt_get_bia_cmd(bt_hf_info, cmd_buf, sizeof(cmd_buf)) == TRUE)
2626                 __bt_hf_send_and_read(bt_hf_info, cmd_buf, buf, strlen(cmd_buf));
2627         else
2628                 ERR("__bt_get_bia_cmd is failed");
2629
2630         ret = __bt_hf_send_and_read(bt_hf_info, BT_HF_XSAT, buf,
2631                                                 sizeof(BT_HF_XSAT) - 1);
2632         if (ret)
2633                 DBG("sent BT_HF_XSAT");
2634         else
2635                 ERR("BT_HF_XSAT sending failed");
2636
2637         /* send Bluetooth Samsung Support Feature cmd */
2638         ret = __bt_hf_send_and_read(bt_hf_info, BT_HF_BSSF, buf,
2639                                                 sizeof(BT_HF_BSSF) - 1);
2640         if (ret)
2641                 INFO("SLC completed with all commands");
2642         else
2643                 ERR("BT_HF_BSSF sending failed");
2644
2645         bt_hf_info->slc = TRUE;
2646         send_flag = FALSE;
2647         g_id = 0;
2648         memset(global_buff, 0, sizeof(global_buff));
2649         return TRUE;
2650 }
2651
2652 static void __bt_hf_agent_sigterm_handler(int signo)
2653 {
2654         ERR_C("***** Signal handler came with signal %d *****", signo);
2655         GDBusConnection *conn;
2656
2657         conn = __bt_hf_get_gdbus_connection();
2658         if (!conn) {
2659                 ERR("Unable to get connection");
2660                 return;
2661         }
2662
2663         __bt_hf_agent_emit_signal(conn,
2664                         BT_HF_AGENT_OBJECT_PATH,
2665                         BT_HF_SERVICE_INTERFACE,
2666                         "CallEnded", NULL);
2667         DBG("CallEnded Signal done");
2668         if (gmain_loop) {
2669                 g_main_loop_quit(gmain_loop);
2670                 DBG("Exiting");
2671                 gmain_loop = NULL;
2672         } else {
2673                 INFO_C("Terminating HF agent");
2674                 exit(0);
2675         }
2676 }
2677
2678 static void __bt_convert_addr_type_to_rev_string(char *address,
2679                                 unsigned char *addr)
2680 {
2681         ret_if(address == NULL);
2682         ret_if(addr == NULL);
2683
2684         g_snprintf(address, BT_ADDRESS_STRING_SIZE,
2685                         "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X",
2686                         addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]);
2687 }
2688
2689
2690 static gboolean __bt_hf_agent_release_after(gpointer user_data)
2691 {
2692         if (__bt_hf_agent_release() == FALSE)
2693                 ERR("Unable to release hf connection");
2694
2695         return FALSE;
2696 }
2697
2698 static gboolean __bt_agent_request_service_level_conn(gpointer data)
2699 {
2700         char *remote_addr;
2701         int bt_device_state = VCONFKEY_BT_DEVICE_NONE;
2702         GDBusConnection *conn;
2703
2704         DBG("+");
2705         memset(prev_cmd, 0, BT_HF_CMD_BUF_SIZE);
2706
2707         if (!__bt_establish_service_level_conn(&bt_hf_info)) {
2708                 ERR("Service Level Connection is fail");
2709
2710                 conn = __bt_hf_get_gdbus_connection();
2711                 if (conn) {
2712                         remote_addr = bt_hf_info.remote_addr;
2713                         __bt_hf_agent_emit_signal(conn,
2714                                         BT_HF_AGENT_OBJECT_PATH,
2715                                         BT_HF_SERVICE_INTERFACE,
2716                                         "Connected",
2717                                         g_variant_new("(s)", remote_addr));
2718                 }
2719                 bt_hf_info.state = BT_HF_STATE_CONNECTED;
2720
2721                 if (vconf_get_int(VCONFKEY_BT_DEVICE, &bt_device_state) == 0) {
2722                         DBG("BT device state is : 0x%X", bt_device_state);
2723                         bt_device_state |= VCONFKEY_BT_DEVICE_AG_CONNECTED;
2724                         if (vconf_set_int(VCONFKEY_BT_DEVICE, bt_device_state) != 0) {
2725                                 ERR("vconf_set_int failed");
2726                         }
2727                 } else {
2728                         ERR("vconf_get_int failed");
2729                 }
2730
2731                 g_idle_add(__bt_hf_agent_release_after, NULL);
2732
2733                 goto done;
2734         }
2735
2736         bt_hf_info.state = BT_HF_STATE_CONNECTED;
2737
2738         __bt_hf_agent_sco_accept(&bt_hf_info);
2739
2740         __bt_hf_agent_start_watch(&bt_hf_info);
2741
2742         remote_addr = bt_hf_info.remote_addr;
2743
2744         INFO_SECURE("Address is : %s", remote_addr);
2745         INFO_C("Connected [HF role]");
2746
2747         if (vconf_get_int(VCONFKEY_BT_DEVICE, &bt_device_state) == 0) {
2748                 DBG("BT device state is : 0x%X", bt_device_state);
2749                 bt_device_state |= VCONFKEY_BT_DEVICE_AG_CONNECTED;
2750                 if (vconf_set_int(VCONFKEY_BT_DEVICE, bt_device_state) != 0) {
2751                         ERR("vconf_set_int failed");
2752                 }
2753         } else {
2754                 ERR("vconf_get_int failed");
2755         }
2756
2757         conn = __bt_hf_get_gdbus_connection();
2758         if (!conn) {
2759                 ERR("Unable to get connection");
2760                 return FALSE;
2761         }
2762
2763         __bt_hf_agent_emit_signal(conn,
2764                         BT_HF_AGENT_OBJECT_PATH,
2765                         BT_HF_SERVICE_INTERFACE,
2766                         "Connected",
2767                         g_variant_new("(s)", remote_addr));
2768
2769         /* Request the call list and launch call app if required */
2770         __bt_hf_agent_handle_call_list(&bt_hf_info);
2771
2772 done:
2773         DBG("-");
2774         return FALSE;
2775 }
2776
2777 static gboolean __bt_hf_agent_connection(gint32 fd, const gchar *obj_path)
2778 {
2779         GIOFlags flags;
2780
2781         struct sockaddr_remote address;
2782         socklen_t address_len;
2783         bt_hf_info.path = g_strdup(obj_path);
2784
2785         INFO_C("**** New HFP connection ****");
2786
2787         is_hf_connected = TRUE;
2788
2789         address_len = sizeof(address);
2790         if (getpeername(fd, (struct sockaddr *) &address, &address_len) != 0)
2791                 ERR("BD_ADDR is NULL");
2792
2793         DBG("RFCOMM connection for HFP is completed. Fd = [%d]\n", fd);
2794         bt_hf_info.fd = fd;
2795         bt_hf_info.io_chan = g_io_channel_unix_new(bt_hf_info.fd);
2796         flags = g_io_channel_get_flags(bt_hf_info.io_chan);
2797
2798         flags &= ~G_IO_FLAG_NONBLOCK;
2799         flags &= G_IO_FLAG_MASK;
2800         g_io_channel_set_flags(bt_hf_info.io_chan, flags, NULL);
2801         g_io_channel_set_encoding(bt_hf_info.io_chan, NULL, NULL);
2802         g_io_channel_set_buffered(bt_hf_info.io_chan, FALSE);
2803
2804         bt_hf_info.remote_addr = g_malloc0(BT_ADDRESS_STRING_SIZE);
2805         __bt_convert_addr_type_to_rev_string(bt_hf_info.remote_addr,
2806                                                 address.remote_bdaddr.b);
2807
2808         g_idle_add(__bt_agent_request_service_level_conn, NULL);
2809
2810         return TRUE;
2811 }
2812
2813 static void __bt_hf_agent_indicator_free(gpointer mem)
2814 {
2815         g_free(mem);
2816 }
2817
2818 static gboolean __bt_hf_agent_release(void)
2819 {
2820         int bt_device_state = VCONFKEY_BT_DEVICE_NONE;
2821         GDBusConnection *conn;
2822
2823         if (bt_hf_info.state == BT_HF_STATE_DISCONNECTED) {
2824                 ERR("hf is already disconnected");
2825                 return FALSE;
2826         }
2827
2828         if (bt_hf_info.indies) {
2829                 g_slist_free_full(bt_hf_info.indies, __bt_hf_agent_indicator_free);
2830                 bt_hf_info.indies = NULL;
2831         }
2832
2833         if (bt_hf_info.io_chan) {
2834                 g_io_channel_shutdown(bt_hf_info.io_chan, TRUE, NULL);
2835                 g_io_channel_unref(bt_hf_info.io_chan);
2836                 bt_hf_info.io_chan = NULL;
2837         }
2838
2839         if (bt_hf_info.sco_watch_id > 0) {
2840                 g_source_remove(bt_hf_info.sco_watch_id);
2841                 bt_hf_info.sco_watch_id = 0;
2842         }
2843
2844         bt_hf_info.state = BT_HF_STATE_DISCONNECTED;
2845
2846         __bt_hf_agent_release_queue();
2847
2848         if (vconf_get_int(VCONFKEY_BT_DEVICE, &bt_device_state) == 0) {
2849                 DBG("BT device state is : 0x%X", bt_device_state);
2850                 bt_device_state ^= VCONFKEY_BT_DEVICE_AG_CONNECTED;
2851                 if (vconf_set_int(VCONFKEY_BT_DEVICE, bt_device_state) != 0) {
2852                         ERR("vconf_set_int failed");
2853                 }
2854         } else {
2855                 ERR("vconf_get_int failed");
2856         }
2857
2858         __bt_hf_agent_stop_watch(&bt_hf_info);
2859         conn = __bt_hf_get_gdbus_connection();
2860         if (!conn) {
2861                 ERR("Unable to get connection");
2862                 return FALSE;
2863         }
2864
2865         __bt_hf_agent_emit_signal(conn,
2866                         BT_HF_AGENT_OBJECT_PATH,
2867                         BT_HF_SERVICE_INTERFACE,
2868                         "Disconnected",
2869                         g_variant_new("(s)", bt_hf_info.remote_addr));
2870
2871         g_free(bt_hf_info.path);
2872         bt_hf_info.path = NULL;
2873
2874         g_free(bt_hf_info.remote_addr);
2875         bt_hf_info.remote_addr = NULL;
2876
2877         is_hf_connected = FALSE;
2878
2879         return TRUE;
2880 }
2881
2882 static gboolean __bt_hf_agent_connection_release(void)
2883 {
2884         return __bt_hf_agent_release();
2885 }
2886
2887 static int __bt_hf_register_profile(const char *uuid, uint16_t version,
2888                  const char *name, const char *object, uint16_t features)
2889 {
2890         DBG("+");
2891         GDBusProxy *proxy;
2892         GVariant *ret;
2893         GError *error = NULL;
2894         GVariantBuilder *builder;
2895         gchar *path = NULL;
2896
2897         proxy = __bt_hf_gdbus_get_service_proxy(BLUEZ_SERVICE_NAME,
2898                         "/org/bluez", BLUEZ_PROFILE_MGMT_INTERFACE);
2899
2900         if (proxy == NULL)
2901                 return BT_HF_AGENT_ERROR_INTERNAL;
2902
2903         path = g_strdup(BT_HF_BLUEZ_OBJECT_PATH);
2904
2905         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
2906
2907         g_variant_builder_add(builder, "{sv}",
2908                         "Name", g_variant_new("s",
2909                         name));
2910         g_variant_builder_add(builder, "{sv}",
2911                         "Version", g_variant_new("q", version));
2912
2913         g_variant_builder_add(builder, "{sv}",
2914                         "features", g_variant_new("q", features));
2915
2916         ret = g_dbus_proxy_call_sync(proxy, "RegisterProfile",
2917                                 g_variant_new("(osa{sv})", path,
2918                                         HFP_HF_UUID, builder),
2919                                 G_DBUS_CALL_FLAGS_NONE, -1,
2920                                 NULL, &error);
2921
2922         g_variant_builder_unref(builder);
2923
2924         if (ret == NULL) {
2925                 /* dBUS-RPC is failed */
2926                 ERR("dBUS-RPC is failed");
2927                 if (error != NULL) {
2928                         /* dBUS gives error cause */
2929                         ERR("D-Bus API failure: errCode[%x], message[%s]",
2930                                 error->code, error->message);
2931                         g_clear_error(&error);
2932                 }
2933                 g_free(path);
2934                 return BT_HF_AGENT_ERROR_INTERNAL;
2935         }
2936         g_variant_unref(ret);
2937         g_free(path);
2938
2939         DBG("-");
2940         return BT_HF_AGENT_ERROR_NONE;
2941 }
2942
2943 static void __bt_hf_agent_register(void)
2944 {
2945         DBG("+");
2946         int ret;
2947         char *name;
2948         uint16_t version = hf_ver;
2949         uint16_t features = bt_hf_info.feature;
2950
2951         gchar *path = g_strdup(BT_HF_BLUEZ_OBJECT_PATH);
2952         name = g_strdup("Hands-Free");
2953
2954         ret = __bt_hf_register_profile(HFP_HF_UUID, version, name, path,
2955                                                                 features);
2956         if (ret)
2957                 ERR("Error in register");
2958
2959         g_free(path);
2960         g_free(name);
2961
2962         DBG("-");
2963         return;
2964 }
2965
2966 static void __bt_hf_agent_unregister(void)
2967 {
2968         DBG("+");
2969
2970         gchar *path = g_strdup(BT_HF_BLUEZ_OBJECT_PATH);
2971
2972         if (g_obj_path) {
2973                 __bt_hf_agent_gdbus_method_send(BLUEZ_SERVICE_NAME,
2974                                                 g_variant_new("(o)", path),
2975                                                 BLUEZ_HF_INTERFACE_NAME,
2976                                                 "UnregisterAgent");
2977                 g_free(g_obj_path);
2978                 g_obj_path = NULL;
2979         }
2980
2981         g_free(path);
2982
2983         DBG("-");
2984         return;
2985 }
2986
2987 static void __bt_hf_agent_filter_cb(GDBusConnection *connection,
2988                                                  const gchar *sender_name,
2989                                                  const gchar *object_path,
2990                                                  const gchar *interface_name,
2991                                                  const gchar *signal_name,
2992                                                  GVariant *parameters,
2993                                                  gpointer user_data)
2994 {
2995         DBG("+");
2996         char *path = NULL;
2997
2998         GVariant *optional_param;
2999
3000         if (strcasecmp(signal_name, "InterfacesAdded") == 0) {
3001
3002                 g_variant_get(parameters, "(&o@a{sa{sv}})",
3003                                 &path, &optional_param);
3004                 if (!path) {
3005                         ERR("Invalid adapter path");
3006                         return;
3007                 }
3008
3009                 if (strcasecmp(path, DEFAULT_ADAPTER_OBJECT_PATH) == 0) {
3010                         g_obj_path = g_strdup(path);
3011                         INFO("Adapter Path = [%s]", path);
3012                         __bt_hf_agent_register();
3013                 }
3014         } else if (strcasecmp(signal_name, "InterfacesRemoved") == 0) {
3015                 g_variant_get(parameters, "(&o@as)", &path, &optional_param);
3016                 if (!path)
3017                         __bt_hf_agent_unregister();
3018         }
3019         DBG("-");
3020 }
3021
3022 static void __bt_hf_agent_dbus_init(void)
3023 {
3024         GDBusConnection *conn;
3025
3026         DBG("+");
3027
3028         conn = __bt_hf_get_gdbus_connection();
3029         if (conn == NULL) {
3030                 ERR("Error in creating the gdbus connection\n");
3031                 return;
3032         }
3033         if (!__bt_hf_register_profile_methods()) {
3034                 ERR("Error in register_profile_methods\n");
3035                 return;
3036         }
3037
3038         owner_sig_id = g_dbus_connection_signal_subscribe(conn,
3039                                 NULL, BT_MANAGER_INTERFACE, NULL, NULL, NULL, 0,
3040                                 __bt_hf_agent_filter_cb, NULL, NULL);
3041         DBG("-");
3042         return;
3043 }
3044
3045 static void __bt_hf_agent_dbus_deinit(void)
3046 {
3047
3048         if (service_gproxy) {
3049                 g_object_unref(service_gproxy);
3050                 service_gproxy = NULL;
3051         }
3052
3053         if (gdbus_conn) {
3054                 if (owner_sig_id != -1)
3055                         g_dbus_connection_signal_unsubscribe(gdbus_conn,
3056                                                 owner_sig_id);
3057
3058                 g_object_unref(gdbus_conn);
3059                 gdbus_conn = NULL;
3060         }
3061         return;
3062 }
3063
3064 static int _hf_agent_answer_call(GDBusMethodInvocation *context)
3065 {
3066         int ret;
3067
3068         DBG("+\n");
3069         if (bt_hf_info.state != BT_HF_STATE_CONNECTED) {
3070                 ERR("HF not Connected");
3071                 return BT_HF_AGENT_ERROR_NOT_CONNECTED;
3072         }
3073         bt_hf_info.context = context;
3074
3075         ret = __bt_hf_send_only(&bt_hf_info, BT_HF_ANSWER_CALL,
3076                                 sizeof(BT_HF_ANSWER_CALL) - 1);
3077         if (!ret)
3078                 return BT_HF_AGENT_ERROR_INTERNAL;
3079
3080         DBG("-\n");
3081         return BT_HF_AGENT_ERROR_NONE;
3082
3083 }
3084
3085 static int _hf_agent_terminate_call(GDBusMethodInvocation *context)
3086 {
3087         int ret;
3088
3089         DBG("+\n");
3090         if (bt_hf_info.state != BT_HF_STATE_CONNECTED) {
3091                 ERR("HF not Connected");
3092                 return BT_HF_AGENT_ERROR_NOT_CONNECTED;
3093         }
3094
3095         bt_hf_info.context = context;
3096
3097         ret = __bt_hf_send_only(&bt_hf_info, BT_HF_END_CALL,
3098                                 sizeof(BT_HF_END_CALL) - 1);
3099         if (!ret)
3100                 return BT_HF_AGENT_ERROR_INTERNAL;
3101
3102         DBG("-\n");
3103         return BT_HF_AGENT_ERROR_NONE;
3104 }
3105
3106 static int _hf_agent_dial_no(GDBusMethodInvocation *context, char *no)
3107 {
3108         int ret;
3109         char buf[BT_MAX_TEL_NUM_STR + 6] = {0};
3110
3111         if (bt_hf_info.state != BT_HF_STATE_CONNECTED) {
3112                 ERR("HF not Connected");
3113                 return BT_HF_AGENT_ERROR_NOT_CONNECTED;
3114         }
3115
3116         bt_hf_info.context = context;
3117
3118         if (strlen(no) > 0) {
3119                 snprintf(buf, sizeof(buf),  BT_HF_DIAL_NO, no);
3120
3121                 if (strstr(prev_cmd, "ATD") && bt_hf_info.ciev_call_status == 0
3122                                                 && bt_hf_info.ciev_call_setup_status == 0) {
3123                         INFO("RAD POPUP CANCEL CASE. send ATD w/o response - KOR REQUEST");
3124                         ret = __bt_hf_send_only_without_queue(&bt_hf_info, buf, strlen(buf));
3125                         if (send_flag)
3126                                 send_flag--;
3127                 } else {
3128                         ret = __bt_hf_send_only(&bt_hf_info, buf, strlen(buf));
3129                 }
3130
3131                 /* prev_cmd is meant for only meant for ATD & AT+BLDN Error handling */
3132                 snprintf(prev_cmd, BT_HF_CMD_BUF_SIZE, "%s", buf);
3133
3134                 if (!ret)
3135                         return BT_HF_AGENT_ERROR_INTERNAL;
3136
3137                 return BT_HF_AGENT_ERROR_NONE;
3138         }
3139
3140         /* prev_cmd is meant for only meant for ATD & AT+BLDN Error handling */
3141         snprintf(prev_cmd, BT_HF_CMD_BUF_SIZE, "%s", BT_HF_REDIAL);
3142
3143         ret = __bt_hf_send_only(&bt_hf_info, BT_HF_REDIAL,
3144                                                 sizeof(BT_HF_REDIAL) - 1);
3145         if (!ret)
3146                 return BT_HF_AGENT_ERROR_INTERNAL;
3147
3148         return BT_HF_AGENT_ERROR_NONE;
3149 }
3150
3151 static int _hf_agent_voice_recognition(GDBusMethodInvocation *context, unsigned int status)
3152 {
3153         int ret;
3154         char buf[20] = {0};
3155
3156         if (bt_hf_info.state != BT_HF_STATE_CONNECTED) {
3157                 ERR("HF not Connected");
3158                 return BT_HF_AGENT_ERROR_NOT_CONNECTED;
3159         }
3160
3161         snprintf(buf, sizeof(buf),  BT_HF_VOICE_RECOGNITION, status);
3162
3163         bt_hf_info.context = context;
3164
3165         ret = __bt_hf_send_only(&bt_hf_info, buf, strlen(buf));
3166         if (!ret)
3167                 return BT_HF_AGENT_ERROR_INTERNAL;
3168
3169
3170         return BT_HF_AGENT_ERROR_NONE;
3171 }
3172
3173 static int _hf_agent_set_speaker_gain(GDBusMethodInvocation *context, unsigned int gain)
3174 {
3175         int ret;
3176         char buf[20] = {0};
3177
3178         if (bt_hf_info.state != BT_HF_STATE_CONNECTED) {
3179                 ERR("HF not Connected");
3180                 return BT_HF_AGENT_ERROR_NOT_CONNECTED;
3181         }
3182
3183         if (gain > BT_HF_MAX_SPEAKER_GAIN)
3184                 return BT_HF_AGENT_ERROR_INVALID_PARAM;
3185
3186         snprintf(buf, sizeof(buf),  BT_HF_SPEAKER_GAIN, gain);
3187
3188         bt_hf_info.context = context;
3189
3190         ret = __bt_hf_send_only(&bt_hf_info, buf,
3191                                 strlen(buf));
3192         if (!ret)
3193                 return BT_HF_AGENT_ERROR_INTERNAL;
3194
3195         return BT_HF_AGENT_ERROR_NONE;
3196
3197 }
3198
3199 static int _hf_agent_send_dtmf(GDBusMethodInvocation *context, char *dtmf)
3200 {
3201         int ret;
3202         char buf[20] = {0};
3203
3204         if (strlen(dtmf) <= 0)
3205                 return BT_HF_AGENT_ERROR_INVALID_PARAM;
3206
3207         if (bt_hf_info.state != BT_HF_STATE_CONNECTED) {
3208                 ERR("HF not Connected");
3209                 return BT_HF_AGENT_ERROR_NOT_CONNECTED;
3210         }
3211
3212         snprintf(buf, sizeof(buf),  BT_HF_DTMF, dtmf);
3213
3214         bt_hf_info.context = context;
3215
3216         ret = __bt_hf_send_only(&bt_hf_info, buf, strlen(buf));
3217         if (!ret)
3218                 return BT_HF_AGENT_ERROR_INTERNAL;
3219
3220
3221         return BT_HF_AGENT_ERROR_NONE;
3222 }
3223
3224
3225 static int _hf_agent_send_3way_cmd(GDBusMethodInvocation *context, char *cmd)
3226 {
3227         int ret;
3228
3229         if (strlen(cmd) <= 0)
3230                 return BT_HF_AGENT_ERROR_INVALID_PARAM;
3231
3232         bt_hf_info.context = context;
3233
3234         ret = __bt_hf_send_only(&bt_hf_info, cmd,
3235                                 strlen(cmd));
3236         if (!ret)
3237                 return BT_HF_AGENT_ERROR_INTERNAL;
3238
3239         return BT_HF_AGENT_ERROR_NONE;
3240 }
3241
3242 static gboolean bt_hf_agent_sco_disconnect(void)
3243 {
3244         DBG("+");
3245         GDBusConnection *conn;
3246
3247         close(bt_hf_info.cli_sco_fd);
3248         bt_hf_info.cli_sco_fd = -1;
3249
3250         DBG("Emit AudioDisconnected Signal");
3251         conn = __bt_hf_get_gdbus_connection();
3252         if (!conn) {
3253                 ERR("Unable to get connection");
3254                 return FALSE;
3255         }
3256
3257         sco_audio_connected = BT_HF_AUDIO_DISCONNECTED;
3258
3259         __bt_hf_agent_emit_signal(conn,
3260                         BT_HF_AGENT_OBJECT_PATH,
3261                         BT_HF_SERVICE_INTERFACE,
3262                         "AudioDisconnected", NULL);
3263         DBG("-");
3264         return TRUE;
3265 }
3266
3267 static GVariant *bt_hf_agent_request_call_list(void)
3268 {
3269         GSList *call_list = NULL;
3270         GVariant *var_data;
3271         DBG("+");
3272
3273         call_list = __bt_hf_get_call_list(&bt_hf_info);
3274         if (!call_list) {
3275                 INFO("call list is NULL");
3276                 return NULL;
3277         }
3278
3279         var_data = __bt_hf_agent_get_call_status_info(call_list);
3280         __bt_hf_free_call_list(call_list);
3281
3282         DBG("-");
3283         return var_data;
3284 }
3285
3286 static int bt_hf_agent_send_at_cmd(GDBusMethodInvocation *context, char *atcmd)
3287
3288 {
3289         gboolean ret;
3290         char cmd_buf[BT_MAX_TEL_NUM_STR + 20] = {0, };
3291
3292         DBG("+");
3293
3294         if (atcmd == NULL)
3295                 return  BT_HF_AGENT_ERROR_INVALID_PARAM;
3296
3297         if (bt_hf_info.state != BT_HF_STATE_CONNECTED)
3298                 return  BT_HF_AGENT_ERROR_NOT_CONNECTED;
3299
3300         /* Should not send cmds if DUT has sent a command and waiting for response */
3301         if (prev_cmd[0] != 0) {
3302                 INFO("DUT is waiting a respond for previous TX cmd. Skip sending.");
3303                 return BT_HF_AGENT_ERROR_INTERNAL;
3304         }
3305
3306         strncpy(cmd_buf, atcmd, sizeof(cmd_buf) - 2);
3307         strncat(cmd_buf, "\r", (sizeof(cmd_buf) - 1) - strlen(cmd_buf));
3308
3309         bt_hf_info.context = context;
3310
3311         ret = __bt_hf_send_only(&bt_hf_info, cmd_buf, strlen(cmd_buf));
3312         if (ret == FALSE)
3313                 return BT_HF_AGENT_ERROR_INTERNAL;
3314
3315         DBG("-");
3316         return BT_HF_AGENT_ERROR_NONE;
3317 }
3318
3319 static uint32_t __bt_hf_agent_get_hf_features(void)
3320 {
3321
3322         uint32_t hf_features = BT_HF_FEATURE_EC_ANDOR_NR |
3323                         BT_HF_FEATURE_CALL_WAITING_AND_3WAY |
3324                         BT_HF_FEATURE_CLI_PRESENTATION |
3325                         BT_HF_FEATURE_VOICE_RECOGNITION |
3326                         BT_HF_FEATURE_REMOTE_VOLUME_CONTROL |
3327                         BT_HF_FEATURE_ENHANCED_CALL_STATUS |
3328                         BT_HF_FEATURE_CODEC_NEGOTIATION;
3329
3330         hf_ver = HFP_VERSION_1_6;
3331
3332         return hf_features;
3333 }
3334
3335 int main(void)
3336 {
3337         struct sigaction sa;
3338         uint32_t hf_features;
3339
3340         INFO("Starting Bluetooth HF agent");
3341
3342         hf_features = __bt_hf_agent_get_hf_features();
3343         bt_hf_info.feature = (uint16_t) hf_features & 0x3F;
3344
3345         memset(&sa, 0, sizeof(sa));
3346         sa.sa_flags = SA_NOCLDSTOP;
3347         sa.sa_handler = __bt_hf_agent_sigterm_handler;
3348         sigaction(SIGTERM, &sa, NULL);
3349
3350         /* Temporarily, block the below signal for debugging */
3351 //      sigaction(SIGSEGV, &sa, NULL);
3352 //      sigaction(SIGABRT, &sa, NULL);
3353         gmain_loop = g_main_loop_new(NULL, FALSE);
3354
3355         if (gmain_loop == NULL) {
3356                 ERR("GMainLoop create failed\n");
3357                 return EXIT_FAILURE;
3358         }
3359
3360         __bt_hf_agent_dbus_init();
3361         g_main_loop_run(gmain_loop);
3362
3363         __bt_hf_agent_dbus_deinit();
3364
3365         if (gmain_loop)
3366                 g_main_loop_unref(gmain_loop);
3367
3368         INFO("Terminating Bluetooth HF agent");
3369         return 0;
3370 }