sim: Reset additional state info
[platform/upstream/ofono.git] / src / stk.c
1 /*
2  *
3  *  oFono - Open Source Telephony
4  *
5  *  Copyright (C) 2008-2011  Intel Corporation. All rights reserved.
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License version 2 as
9  *  published by the Free Software Foundation.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #define _GNU_SOURCE
27 #include <string.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31
32 #include <glib.h>
33 #include <gdbus.h>
34 #include <errno.h>
35 #include <time.h>
36 #include <sys/time.h>
37
38 #include "ofono.h"
39
40 #include "common.h"
41 #include "smsutil.h"
42 #include "stkutil.h"
43 #include "stkagent.h"
44 #include "util.h"
45
46 static GSList *g_drivers = NULL;
47
48 struct stk_timer {
49         time_t expiry;
50         time_t start;
51 };
52
53 struct ofono_stk {
54         const struct ofono_stk_driver *driver;
55         void *driver_data;
56         struct ofono_atom *atom;
57         struct stk_command *pending_cmd;
58         void (*cancel_cmd)(struct ofono_stk *stk);
59         GQueue *envelope_q;
60         DBusMessage *pending;
61
62         struct stk_timer timers[8];
63         guint timers_source;
64
65         int timeout;
66         int short_timeout;
67         struct stk_agent *session_agent;
68         struct stk_agent *default_agent;
69         struct stk_agent *current_agent; /* Always equals one of the above */
70         struct stk_menu *main_menu, *select_item_menu;
71         gboolean respond_on_exit;
72         ofono_bool_t immediate_response;
73         guint remove_agent_source;
74         struct extern_req *extern_req;
75         char *idle_mode_text;
76         struct stk_icon_id idle_mode_icon;
77         struct timeval get_inkey_start_ts;
78         int dtmf_id;
79
80         __ofono_sms_sim_download_cb_t sms_pp_cb;
81         void *sms_pp_userdata;
82 };
83
84 struct envelope_op {
85         uint8_t tlv[256];
86         unsigned int tlv_len;
87         int retries;
88         void (*cb)(struct ofono_stk *stk, gboolean ok,
89                         const unsigned char *data, int length);
90 };
91
92 struct extern_req {
93         struct ofono_stk *stk;
94         gboolean cancelled;
95 };
96
97 #define ENVELOPE_RETRIES_DEFAULT 5
98
99 static void envelope_queue_run(struct ofono_stk *stk);
100 static void timers_update(struct ofono_stk *stk);
101
102 #define ADD_ERROR_RESULT(result, error, addn_info)              \
103                 result.type = error;                            \
104                 result.additional_len = sizeof(addn_info);      \
105                 result.additional = addn_info;                  \
106
107 static int stk_respond(struct ofono_stk *stk, struct stk_response *rsp,
108                         ofono_stk_generic_cb_t cb)
109 {
110         const guint8 *tlv;
111         unsigned int tlv_len;
112
113         DBG("");
114
115         if (stk->driver->terminal_response == NULL)
116                 return -ENOSYS;
117
118         rsp->src = STK_DEVICE_IDENTITY_TYPE_TERMINAL;
119         rsp->dst = STK_DEVICE_IDENTITY_TYPE_UICC;
120         rsp->number = stk->pending_cmd->number;
121         rsp->type = stk->pending_cmd->type;
122         rsp->qualifier = stk->pending_cmd->qualifier;
123
124         tlv = stk_pdu_from_response(rsp, &tlv_len);
125         if (tlv == NULL)
126                 return -EINVAL;
127
128         stk_command_free(stk->pending_cmd);
129         stk->pending_cmd = NULL;
130         stk->cancel_cmd = NULL;
131         stk->respond_on_exit = FALSE;
132
133         stk->driver->terminal_response(stk, tlv_len, tlv, cb, stk);
134
135         return 0;
136 }
137
138 static void stk_command_cb(const struct ofono_error *error, void *data)
139 {
140         if (error->type != OFONO_ERROR_TYPE_NO_ERROR) {
141                 ofono_error("TERMINAL RESPONSE to a UICC command failed");
142                 return;
143         }
144
145         DBG("TERMINAL RESPONSE to a command reported no errors");
146 }
147
148 static void send_simple_response(struct ofono_stk *stk,
149                                         enum stk_result_type result)
150 {
151         struct stk_response rsp;
152         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
153
154         DBG("result %d", result);
155
156         memset(&rsp, 0, sizeof(rsp));
157         rsp.result.type = result;
158
159         if (stk_respond(stk, &rsp, stk_command_cb))
160                 stk_command_cb(&error, stk);
161 }
162
163 static void envelope_cb(const struct ofono_error *error, const uint8_t *data,
164                         int length, void *user_data)
165 {
166         struct ofono_stk *stk = user_data;
167         struct envelope_op *op = g_queue_peek_head(stk->envelope_q);
168         gboolean result = TRUE;
169
170         DBG("length %d", length);
171
172         if (op->retries > 0 && error->type == OFONO_ERROR_TYPE_SIM &&
173                         error->error == 0x9300) {
174                 op->retries--;
175                 goto out;
176         }
177
178         if (error->type != OFONO_ERROR_TYPE_NO_ERROR)
179                 result = FALSE;
180
181         g_queue_pop_head(stk->envelope_q);
182
183         if (op->cb)
184                 op->cb(stk, result, data, length);
185
186         g_free(op);
187
188 out:
189         envelope_queue_run(stk);
190 }
191
192 static void envelope_queue_run(struct ofono_stk *stk)
193 {
194         if (g_queue_get_length(stk->envelope_q) > 0) {
195                 struct envelope_op *op = g_queue_peek_head(stk->envelope_q);
196
197                 stk->driver->envelope(stk, op->tlv_len, op->tlv,
198                                         envelope_cb, stk);
199         }
200 }
201
202 static int stk_send_envelope(struct ofono_stk *stk, struct stk_envelope *e,
203                                 void (*cb)(struct ofono_stk *stk, gboolean ok,
204                                                 const uint8_t *data,
205                                                 int length), int retries)
206 {
207         const uint8_t *tlv;
208         unsigned int tlv_len;
209         struct envelope_op *op;
210
211         DBG("");
212
213         if (stk->driver->envelope == NULL)
214                 return -ENOSYS;
215
216         e->dst = STK_DEVICE_IDENTITY_TYPE_UICC;
217         tlv = stk_pdu_from_envelope(e, &tlv_len);
218         if (tlv == NULL)
219                 return -EINVAL;
220
221         op = g_new0(struct envelope_op, 1);
222
223         op->cb = cb;
224         op->retries = retries;
225         memcpy(op->tlv, tlv, tlv_len);
226         op->tlv_len = tlv_len;
227
228         g_queue_push_tail(stk->envelope_q, op);
229
230         if (g_queue_get_length(stk->envelope_q) == 1)
231                 envelope_queue_run(stk);
232
233         return 0;
234 }
235
236 static void stk_cbs_download_cb(struct ofono_stk *stk, gboolean ok,
237                                 const unsigned char *data, int len)
238 {
239         if (!ok) {
240                 ofono_error("CellBroadcast download to UICC failed");
241                 return;
242         }
243
244         if (len)
245                 ofono_error("CellBroadcast download returned %i bytes of data",
246                                 len);
247
248         DBG("CellBroadcast download to UICC reported no error");
249 }
250
251 void __ofono_cbs_sim_download(struct ofono_stk *stk, const struct cbs *msg)
252 {
253         struct stk_envelope e;
254         int err;
255
256         DBG("");
257
258         memset(&e, 0, sizeof(e));
259
260         e.type = STK_ENVELOPE_TYPE_CBS_PP_DOWNLOAD;
261         e.src = STK_DEVICE_IDENTITY_TYPE_NETWORK;
262         memcpy(&e.cbs_pp_download.page, msg, sizeof(msg));
263
264         err = stk_send_envelope(stk, &e, stk_cbs_download_cb,
265                                 ENVELOPE_RETRIES_DEFAULT);
266         if (err)
267                 stk_cbs_download_cb(stk, FALSE, NULL, -1);
268 }
269
270 static void stk_sms_download_cb(struct ofono_stk *stk, gboolean ok,
271                                 const unsigned char *data, int len)
272 {
273         DBG("SMS-PP download to UICC reported %s", ok ? "success" : "error");
274
275         if (stk->sms_pp_cb)
276                 stk->sms_pp_cb(ok, data, len, stk->sms_pp_userdata);
277 }
278
279 int __ofono_sms_sim_download(struct ofono_stk *stk, const struct sms *msg,
280                                 __ofono_sms_sim_download_cb_t cb, void *data)
281 {
282         struct stk_envelope e;
283
284         if (msg->type != SMS_TYPE_DELIVER)
285                 return -EINVAL;
286
287         DBG("");
288
289         memset(&e, 0, sizeof(e));
290
291         e.type = STK_ENVELOPE_TYPE_SMS_PP_DOWNLOAD;
292         e.src = STK_DEVICE_IDENTITY_TYPE_NETWORK;
293
294         e.sms_pp_download.address.number = (char *) msg->sc_addr.address;
295         e.sms_pp_download.address.ton_npi = msg->sc_addr.numbering_plan |
296                 (msg->sc_addr.number_type << 4);
297         memcpy(&e.sms_pp_download.message, &msg->deliver, sizeof(msg->deliver));
298
299         stk->sms_pp_cb = cb;
300         stk->sms_pp_userdata = data;
301
302         return stk_send_envelope(stk, &e, stk_sms_download_cb,
303                                         ENVELOPE_RETRIES_DEFAULT);
304 }
305
306 static char *dbus_apply_text_attributes(const char *text,
307                                         const struct stk_text_attribute *attr)
308 {
309         uint16_t buf[256], *i = buf;
310         const uint8_t *j = attr->attributes;
311         const uint8_t *end = j + attr->len;
312
313         if (text == NULL)
314                 return NULL;
315
316         if (attr->len & 3)
317                 return NULL;
318
319         while (j < end)
320                 *i++ = *j++;
321
322         return stk_text_to_html(text, buf, attr->len / 4);
323 }
324
325 static struct stk_menu *stk_menu_create(const char *title,
326                 const struct stk_text_attribute *title_attr,
327                 const struct stk_icon_id *icon, GSList *items,
328                 const struct stk_item_text_attribute_list *item_attrs,
329                 const struct stk_item_icon_id_list *item_icon_ids,
330                 int default_id, gboolean soft_key, gboolean has_help)
331 {
332         unsigned int len = g_slist_length(items);
333         struct stk_menu *ret;
334         GSList *l;
335         int i;
336         struct stk_text_attribute attr;
337
338         DBG("");
339
340         if (item_attrs && item_attrs->len && item_attrs->len != len * 4)
341                 return NULL;
342
343         if (item_icon_ids && item_icon_ids->len && item_icon_ids->len != len)
344                 return NULL;
345
346         ret = g_try_new(struct stk_menu, 1);
347         if (ret == NULL)
348                 return NULL;
349
350         ret->title = dbus_apply_text_attributes(title ? title : "",
351                                                 title_attr);
352         if (ret->title == NULL)
353                 ret->title = g_strdup(title ? title : "");
354
355         memcpy(&ret->icon, icon, sizeof(ret->icon));
356         ret->items = g_new0(struct stk_menu_item, len + 1);
357         ret->default_item = -1;
358         ret->soft_key = soft_key;
359         ret->has_help = has_help;
360
361         for (l = items, i = 0; l; l = l->next, i++) {
362                 struct stk_item *item = l->data;
363                 char *text;
364
365                 ret->items[i].item_id = item->id;
366
367                 text = NULL;
368
369                 if (item_attrs && item_attrs->len) {
370                         memcpy(attr.attributes, &item_attrs->list[i * 4], 4);
371                         attr.len = 4;
372
373                         text = dbus_apply_text_attributes(item->text, &attr);
374                 }
375
376                 if (text == NULL)
377                         text = strdup(item->text);
378
379                 ret->items[i].text = text;
380
381                 if (item_icon_ids && item_icon_ids->len)
382                         ret->items[i].icon_id = item_icon_ids->list[i];
383
384                 if (item->id == default_id)
385                         ret->default_item = i;
386         }
387
388         return ret;
389 }
390
391 static struct stk_menu *stk_menu_create_from_set_up_menu(
392                                                 const struct stk_command *cmd)
393 {
394         gboolean soft_key = (cmd->qualifier & (1 << 0)) != 0;
395         gboolean has_help = (cmd->qualifier & (1 << 7)) != 0;
396
397         return stk_menu_create(cmd->setup_menu.alpha_id,
398                                 &cmd->setup_menu.text_attr,
399                                 &cmd->setup_menu.icon_id,
400                                 cmd->setup_menu.items,
401                                 &cmd->setup_menu.item_text_attr_list,
402                                 &cmd->setup_menu.item_icon_id_list,
403                                 0, soft_key, has_help);
404 }
405
406 static struct stk_menu *stk_menu_create_from_select_item(
407                                                 const struct stk_command *cmd)
408 {
409         gboolean soft_key = (cmd->qualifier & (1 << 2)) != 0;
410         gboolean has_help = (cmd->qualifier & (1 << 7)) != 0;
411
412         return stk_menu_create(cmd->select_item.alpha_id,
413                                 &cmd->select_item.text_attr,
414                                 &cmd->select_item.icon_id,
415                                 cmd->select_item.items,
416                                 &cmd->select_item.item_text_attr_list,
417                                 &cmd->select_item.item_icon_id_list,
418                                 cmd->select_item.item_id, soft_key, has_help);
419 }
420
421 static void stk_menu_free(struct stk_menu *menu)
422 {
423         struct stk_menu_item *i;
424
425         for (i = menu->items; i->text; i++)
426                 g_free(i->text);
427
428         g_free(menu->items);
429         g_free(menu->title);
430         g_free(menu);
431 }
432
433 static void emit_menu_changed(struct ofono_stk *stk)
434 {
435         static struct stk_menu_item end_item = {};
436         static struct stk_menu no_menu = {
437                 .title = "",
438                 .items = &end_item,
439                 .has_help = FALSE,
440                 .default_item = -1,
441         };
442         static char *name = "MainMenu";
443         DBusConnection *conn = ofono_dbus_get_connection();
444         const char *path = __ofono_atom_get_path(stk->atom);
445         struct stk_menu *menu = stk->main_menu ? stk->main_menu : &no_menu;
446         DBusMessage *signal;
447         DBusMessageIter iter;
448
449         ofono_dbus_signal_property_changed(conn, path,
450                                                 OFONO_STK_INTERFACE,
451                                                 "MainMenuTitle",
452                                                 DBUS_TYPE_STRING, &menu->title);
453
454         ofono_dbus_signal_property_changed(conn, path,
455                                                 OFONO_STK_INTERFACE,
456                                                 "MainMenuIcon",
457                                                 DBUS_TYPE_BYTE, &menu->icon.id);
458
459         signal = dbus_message_new_signal(path, OFONO_STK_INTERFACE,
460                                                 "PropertyChanged");
461         if (signal == NULL) {
462                 ofono_error("Unable to allocate new %s.PropertyChanged signal",
463                                 OFONO_SIM_APP_INTERFACE);
464
465                 return;
466         }
467
468         dbus_message_iter_init_append(signal, &iter);
469
470         dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &name);
471
472         append_menu_items_variant(&iter, menu->items);
473
474         g_dbus_send_message(conn, signal);
475 }
476
477 static void cancel_pending_dtmf(struct ofono_stk *stk)
478 {
479         struct ofono_voicecall *vc = NULL;
480         struct ofono_atom *vc_atom;
481
482         vc_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
483                                                 OFONO_ATOM_TYPE_VOICECALL);
484         if (vc_atom)
485                 vc = __ofono_atom_get_data(vc_atom);
486
487         if (vc) /* Should be always true here */
488                 __ofono_voicecall_tone_cancel(vc, stk->dtmf_id);
489 }
490
491 static void user_termination_cb(enum stk_agent_result result, void *user_data)
492 {
493         struct ofono_stk *stk = user_data;
494
495         if (result != STK_AGENT_RESULT_TERMINATE)
496                 return;
497
498         switch (stk->pending_cmd->type) {
499         case STK_COMMAND_TYPE_SEND_DTMF:
500                 cancel_pending_dtmf(stk);
501                 break;
502         }
503
504         send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
505 }
506
507 static gboolean stk_alpha_id_set(struct ofono_stk *stk,
508                         const char *text, const struct stk_text_attribute *attr,
509                         const struct stk_icon_id *icon)
510 {
511         char *alpha = dbus_apply_text_attributes(text, attr);
512
513         /*
514          * Currently, we are treating null data object(len = 0, no value part)
515          * and no alpha identifier cases equally. This may be changed once
516          * better idea is found out.
517          */
518         if (alpha == NULL)
519                 return FALSE;
520
521         if (stk->respond_on_exit)
522                 stk_agent_display_action(stk->current_agent, alpha, icon,
523                                                 user_termination_cb, stk, NULL);
524         else
525                 stk_agent_display_action_info(stk->current_agent, alpha, icon);
526
527         g_free(alpha);
528
529         return TRUE;
530 }
531
532 static void stk_alpha_id_unset(struct ofono_stk *stk)
533 {
534         /*
535          * If there is no default agent, then current agent also will be NULL.
536          * So, call request cancel only when there is a valid current agent.
537          */
538         if (stk->current_agent)
539                 stk_agent_request_cancel(stk->current_agent);
540 }
541
542 static int duration_to_msecs(const struct stk_duration *duration)
543 {
544         int msecs = duration->interval;
545
546         switch (duration->unit) {
547         case STK_DURATION_TYPE_MINUTES:
548                 msecs *= 60;
549                 /* Fall through.  */
550         case STK_DURATION_TYPE_SECONDS:
551                 msecs *= 10;
552                 /* Fall through.  */
553         case STK_DURATION_TYPE_SECOND_TENTHS:
554                 msecs *= 100;
555         }
556
557         return msecs;
558 }
559
560 static DBusMessage *stk_get_properties(DBusConnection *conn,
561                                         DBusMessage *msg, void *data)
562 {
563         struct ofono_stk *stk = data;
564         DBusMessage *reply;
565         DBusMessageIter iter;
566         DBusMessageIter dict;
567         DBusMessageIter entry;
568         const char *key = "MainMenu";
569         const char *str;
570         unsigned char icon;
571
572         reply = dbus_message_new_method_return(msg);
573         if (reply == NULL)
574                 return NULL;
575
576         dbus_message_iter_init_append(reply, &iter);
577
578         dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
579                                         OFONO_PROPERTIES_ARRAY_SIGNATURE,
580                                         &dict);
581
582         str = stk->idle_mode_text;
583         ofono_dbus_dict_append(&dict, "IdleModeText", DBUS_TYPE_STRING, &str);
584
585         icon = stk->idle_mode_icon.id;
586         ofono_dbus_dict_append(&dict, "IdleModeIcon", DBUS_TYPE_BYTE, &icon);
587
588         str = stk->main_menu ? stk->main_menu->title : "";
589         ofono_dbus_dict_append(&dict, "MainMenuTitle", DBUS_TYPE_STRING, &str);
590
591         icon = stk->main_menu ? stk->main_menu->icon.id : 0;
592         ofono_dbus_dict_append(&dict, "MainMenuIcon", DBUS_TYPE_BYTE, &icon);
593
594         dbus_message_iter_open_container(&dict, DBUS_TYPE_DICT_ENTRY,
595                                                 NULL, &entry);
596         dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &key);
597
598         append_menu_items_variant(&entry,
599                                 stk->main_menu ? stk->main_menu->items : NULL);
600
601         dbus_message_iter_close_container(&dict, &entry);
602         dbus_message_iter_close_container(&iter, &dict);
603
604         return reply;
605 }
606
607 static void stk_request_cancel(struct ofono_stk *stk)
608 {
609         if (stk->session_agent)
610                 stk_agent_request_cancel(stk->session_agent);
611
612         if (stk->default_agent)
613                 stk_agent_request_cancel(stk->default_agent);
614 }
615
616 static void default_agent_notify(gpointer user_data)
617 {
618         struct ofono_stk *stk = user_data;
619
620         if (stk->current_agent == stk->default_agent && stk->respond_on_exit) {
621                 if (stk->pending_cmd)
622                         stk->cancel_cmd(stk);
623
624                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
625         }
626
627         stk->default_agent = NULL;
628         stk->current_agent = stk->session_agent;
629 }
630
631 static void session_agent_notify(gpointer user_data)
632 {
633         struct ofono_stk *stk = user_data;
634
635         DBG("Session Agent removed");
636
637         if (stk->current_agent == stk->session_agent && stk->respond_on_exit) {
638                 if (stk->pending_cmd)
639                         stk->cancel_cmd(stk);
640
641                 DBG("Sending Terminate response for session agent");
642                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
643         }
644
645         stk->session_agent = NULL;
646         stk->current_agent = stk->default_agent;
647
648         if (stk->remove_agent_source) {
649                 g_source_remove(stk->remove_agent_source);
650                 stk->remove_agent_source = 0;
651         }
652 }
653
654 static gboolean session_agent_remove_cb(gpointer user_data)
655 {
656         struct ofono_stk *stk = user_data;
657
658         stk->remove_agent_source = 0;
659
660         stk_agent_free(stk->session_agent);
661
662         return FALSE;
663 }
664
665 /* Safely remove the agent even inside a callback */
666 static void session_agent_remove(struct ofono_stk *stk)
667 {
668         if (!stk->remove_agent_source)
669                 stk->remove_agent_source =
670                         g_timeout_add(0, session_agent_remove_cb, stk);
671 }
672
673 static DBusMessage *stk_register_agent(DBusConnection *conn,
674                                         DBusMessage *msg, void *data)
675 {
676         struct ofono_stk *stk = data;
677         const char *agent_path;
678
679         if (stk->default_agent)
680                 return __ofono_error_busy(msg);
681
682         if (dbus_message_get_args(msg, NULL,
683                                         DBUS_TYPE_OBJECT_PATH, &agent_path,
684                                         DBUS_TYPE_INVALID) == FALSE)
685                 return __ofono_error_invalid_args(msg);
686
687         if (!__ofono_dbus_valid_object_path(agent_path))
688                 return __ofono_error_invalid_format(msg);
689
690         stk->default_agent = stk_agent_new(agent_path,
691                                                 dbus_message_get_sender(msg),
692                                                 FALSE);
693         if (stk->default_agent == NULL)
694                 return __ofono_error_failed(msg);
695
696         stk_agent_set_removed_notify(stk->default_agent,
697                                         default_agent_notify, stk);
698
699         if (stk->session_agent == NULL)
700                 stk->current_agent = stk->default_agent;
701
702         return dbus_message_new_method_return(msg);
703 }
704
705 static DBusMessage *stk_unregister_agent(DBusConnection *conn,
706                                                 DBusMessage *msg, void *data)
707 {
708         struct ofono_stk *stk = data;
709         const char *agent_path;
710         const char *agent_bus = dbus_message_get_sender(msg);
711
712         if (dbus_message_get_args(msg, NULL,
713                                         DBUS_TYPE_OBJECT_PATH, &agent_path,
714                                         DBUS_TYPE_INVALID) == FALSE)
715                 return __ofono_error_invalid_args(msg);
716
717         if (stk->default_agent == NULL)
718                 return __ofono_error_failed(msg);
719
720         if (!stk_agent_matches(stk->default_agent, agent_path, agent_bus))
721                 return __ofono_error_failed(msg);
722
723         stk_agent_free(stk->default_agent);
724
725         return dbus_message_new_method_return(msg);
726 }
727
728 static void menu_selection_envelope_cb(struct ofono_stk *stk, gboolean ok,
729                                         const unsigned char *data, int len)
730 {
731         unsigned char selection;
732         const char *agent_path;
733         DBusMessage *reply;
734
735         DBG("");
736
737         if (!ok) {
738                 ofono_error("Sending Menu Selection to UICC failed");
739
740                 reply = __ofono_error_failed(stk->pending);
741
742                 goto out;
743         }
744
745         if (len)
746                 ofono_error("Menu Selection returned %i bytes of unwanted data",
747                                 len);
748
749         DBG("Menu Selection envelope submission gave no error");
750
751         dbus_message_get_args(stk->pending, NULL,
752                                 DBUS_TYPE_BYTE, &selection,
753                                 DBUS_TYPE_OBJECT_PATH, &agent_path,
754                                 DBUS_TYPE_INVALID);
755
756         stk->session_agent = stk_agent_new(agent_path,
757                                         dbus_message_get_sender(stk->pending),
758                                         TRUE);
759         if (stk->session_agent == NULL) {
760                 reply = __ofono_error_failed(stk->pending);
761
762                 goto out;
763         }
764
765         stk_agent_set_removed_notify(stk->session_agent,
766                                         session_agent_notify, stk);
767
768         stk->current_agent = stk->session_agent;
769
770         reply = dbus_message_new_method_return(stk->pending);
771
772 out:
773         __ofono_dbus_pending_reply(&stk->pending, reply);
774 }
775
776 static DBusMessage *stk_select_item(DBusConnection *conn,
777                                         DBusMessage *msg, void *data)
778 {
779         struct ofono_stk *stk = data;
780         const char *agent_path;
781         unsigned char selection, i;
782         struct stk_envelope e;
783         struct stk_menu *menu = stk->main_menu;
784
785         DBG("");
786
787         if (stk->pending || stk->session_agent)
788                 return __ofono_error_busy(msg);
789
790         if (menu == NULL)
791                 return __ofono_error_not_supported(msg);
792
793         if (dbus_message_get_args(msg, NULL,
794                                         DBUS_TYPE_BYTE, &selection,
795                                         DBUS_TYPE_OBJECT_PATH, &agent_path,
796                                         DBUS_TYPE_INVALID) == FALSE)
797                 return __ofono_error_invalid_args(msg);
798
799         if (!__ofono_dbus_valid_object_path(agent_path))
800                 return __ofono_error_invalid_format(msg);
801
802         for (i = 0; i < selection && menu->items[i].text; i++);
803
804         if (i != selection)
805                 return __ofono_error_invalid_format(msg);
806
807         memset(&e, 0, sizeof(e));
808         e.type = STK_ENVELOPE_TYPE_MENU_SELECTION;
809         e.src = STK_DEVICE_IDENTITY_TYPE_KEYPAD,
810         e.menu_selection.item_id = menu->items[selection].item_id;
811         e.menu_selection.help_request = FALSE;
812
813         DBG("");
814
815         if (stk_send_envelope(stk, &e, menu_selection_envelope_cb, 0))
816                 return __ofono_error_failed(msg);
817
818         stk->pending = dbus_message_ref(msg);
819
820         return NULL;
821 }
822
823 static GDBusMethodTable stk_methods[] = {
824         { "GetProperties",              "",     "a{sv}",stk_get_properties },
825         { "SelectItem",                 "yo",   "",     stk_select_item,
826                                         G_DBUS_METHOD_FLAG_ASYNC },
827         { "RegisterAgent",              "o",    "",     stk_register_agent },
828         { "UnregisterAgent",            "o",    "",     stk_unregister_agent },
829
830         { }
831 };
832
833 static GDBusSignalTable stk_signals[] = {
834         { "PropertyChanged",    "sv" },
835
836         { }
837 };
838
839 static gboolean handle_command_more_time(const struct stk_command *cmd,
840                                                 struct stk_response *rsp,
841                                                 struct ofono_stk *stk)
842 {
843         /* Do nothing */
844
845         return TRUE;
846 }
847
848 static void send_sms_cancel(struct ofono_stk *stk)
849 {
850         stk->extern_req->cancelled = TRUE;
851
852         stk_alpha_id_unset(stk);
853 }
854
855 static void send_sms_submit_cb(gboolean ok, void *data)
856 {
857         struct extern_req *req = data;
858         struct ofono_stk *stk = req->stk;
859         struct ofono_error failure = { .type = OFONO_ERROR_TYPE_FAILURE };
860         struct stk_response rsp;
861
862         DBG("SMS submission %s", ok ? "successful" : "failed");
863
864         if (req->cancelled) {
865                 DBG("Received an SMS submitted callback after the "
866                                 "proactive command was cancelled");
867                 return;
868         }
869
870         stk_alpha_id_unset(stk);
871
872         memset(&rsp, 0, sizeof(rsp));
873
874         if (ok == FALSE)
875                 rsp.result.type = STK_RESULT_TYPE_NETWORK_UNAVAILABLE;
876
877         if (stk_respond(stk, &rsp, stk_command_cb))
878                 stk_command_cb(&failure, stk);
879 }
880
881 static void extern_req_start(struct ofono_stk *stk)
882 {
883         stk->extern_req = g_new0(struct extern_req, 1);
884         stk->extern_req->stk = stk;
885 }
886
887 static gboolean handle_command_send_sms(const struct stk_command *cmd,
888                                         struct stk_response *rsp,
889                                         struct ofono_stk *stk)
890 {
891         struct ofono_modem *modem = __ofono_atom_get_modem(stk->atom);
892         struct ofono_atom *sms_atom;
893         struct ofono_sms *sms;
894         GSList msg_list;
895         struct ofono_uuid uuid;
896
897         sms_atom = __ofono_modem_find_atom(modem, OFONO_ATOM_TYPE_SMS);
898
899         if (sms_atom == NULL || !__ofono_atom_get_registered(sms_atom)) {
900                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
901                 return TRUE;
902         }
903
904         sms = __ofono_atom_get_data(sms_atom);
905
906         extern_req_start(stk);
907
908         msg_list.data = (void *) &cmd->send_sms.gsm_sms;
909         msg_list.next = NULL;
910
911         if (__ofono_sms_txq_submit(sms, &msg_list, 0, &uuid, NULL, NULL) < 0) {
912                 unsigned char no_cause_result[] = { 0x00 };
913
914                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
915                                         no_cause_result);
916                 return TRUE;
917         }
918
919         __ofono_sms_txq_set_submit_notify(sms, &uuid, send_sms_submit_cb,
920                                                 stk->extern_req, g_free);
921         stk->cancel_cmd = send_sms_cancel;
922
923         stk_alpha_id_set(stk, cmd->send_sms.alpha_id, &cmd->send_sms.text_attr,
924                                 &cmd->send_sms.icon_id);
925
926         return FALSE;
927 }
928
929 /* Note: may be called from ofono_stk_proactive_command_handled_notify */
930 static gboolean handle_command_set_idle_text(const struct stk_command *cmd,
931                                                 struct stk_response *rsp,
932                                                 struct ofono_stk *stk)
933 {
934         DBusConnection *conn = ofono_dbus_get_connection();
935         const char *path = __ofono_atom_get_path(stk->atom);
936         char *idle_mode_text;
937
938         idle_mode_text = dbus_apply_text_attributes(
939                                         cmd->setup_idle_mode_text.text,
940                                         &cmd->setup_idle_mode_text.text_attr);
941
942         if (idle_mode_text == NULL) {
943                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
944                 return TRUE;
945         }
946
947         if (stk->idle_mode_text)
948                 g_free(stk->idle_mode_text);
949
950         stk->idle_mode_text = idle_mode_text;
951
952         ofono_dbus_signal_property_changed(conn, path, OFONO_STK_INTERFACE,
953                                                 "IdleModeText",
954                                                 DBUS_TYPE_STRING,
955                                                 &idle_mode_text);
956
957         if (stk->idle_mode_icon.id != cmd->setup_idle_mode_text.icon_id.id) {
958                 memcpy(&stk->idle_mode_icon, &cmd->setup_idle_mode_text.icon_id,
959                                 sizeof(stk->idle_mode_icon));
960
961                 ofono_dbus_signal_property_changed(conn, path,
962                                                 OFONO_STK_INTERFACE,
963                                                 "IdleModeIcon", DBUS_TYPE_BYTE,
964                                                 &stk->idle_mode_icon.id);
965         }
966
967         return TRUE;
968 }
969
970 static void timer_expiration_cb(struct ofono_stk *stk, gboolean ok,
971                                 const unsigned char *data, int len)
972 {
973         if (!ok) {
974                 ofono_error("Timer Expiration reporting failed");
975                 return;
976         }
977
978         if (len)
979                 ofono_error("Timer Expiration returned %i bytes of data",
980                                 len);
981
982         DBG("Timer Expiration reporting to UICC reported no error");
983 }
984
985 static gboolean timers_cb(gpointer user_data)
986 {
987         struct ofono_stk *stk = user_data;
988
989         stk->timers_source = 0;
990
991         timers_update(stk);
992
993         return FALSE;
994 }
995
996 static void timer_value_from_seconds(struct stk_timer_value *val, int seconds)
997 {
998         val->has_value = TRUE;
999         val->hour = seconds / 3600;
1000         seconds -= val->hour * 3600;
1001         val->minute = seconds / 60;
1002         seconds -= val->minute * 60;
1003         val->second = seconds;
1004 }
1005
1006 static void timers_update(struct ofono_stk *stk)
1007 {
1008         time_t min = 0, now = time(NULL);
1009         int i;
1010
1011         if (stk->timers_source) {
1012                 g_source_remove(stk->timers_source);
1013                 stk->timers_source = 0;
1014         }
1015
1016         for (i = 0; i < 8; i++) {
1017                 if (!stk->timers[i].expiry)
1018                         continue;
1019
1020                 if (stk->timers[i].expiry <= now) {
1021                         struct stk_envelope e;
1022                         int seconds = now - stk->timers[i].start;
1023
1024                         stk->timers[i].expiry = 0;
1025
1026                         memset(&e, 0, sizeof(e));
1027
1028                         e.type = STK_ENVELOPE_TYPE_TIMER_EXPIRATION;
1029                         e.src = STK_DEVICE_IDENTITY_TYPE_TERMINAL,
1030                         e.timer_expiration.id = i + 1;
1031                         timer_value_from_seconds(&e.timer_expiration.value,
1032                                                         seconds);
1033
1034                         /*
1035                          * TODO: resubmit until success, providing current
1036                          * time difference every time we re-send.
1037                          */
1038                         if (stk_send_envelope(stk, &e, timer_expiration_cb, 0))
1039                                 timer_expiration_cb(stk, FALSE, NULL, -1);
1040
1041                         continue;
1042                 }
1043
1044                 if (stk->timers[i].expiry < now + min || min == 0)
1045                         min = stk->timers[i].expiry - now;
1046         }
1047
1048         if (min)
1049                 stk->timers_source = g_timeout_add_seconds(min, timers_cb, stk);
1050 }
1051
1052 static gboolean handle_command_timer_mgmt(const struct stk_command *cmd,
1053                                                 struct stk_response *rsp,
1054                                                 struct ofono_stk *stk)
1055 {
1056         int op = cmd->qualifier & 3;
1057         time_t seconds, now = time(NULL);
1058         struct stk_timer *tmr;
1059
1060         if (cmd->timer_mgmt.timer_id < 1 || cmd->timer_mgmt.timer_id > 8) {
1061                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1062                 return TRUE;
1063         }
1064
1065         tmr = &stk->timers[cmd->timer_mgmt.timer_id - 1];
1066
1067         switch (op) {
1068         case 0: /* Start */
1069                 seconds = cmd->timer_mgmt.timer_value.second +
1070                         cmd->timer_mgmt.timer_value.minute * 60 +
1071                         cmd->timer_mgmt.timer_value.hour * 3600;
1072
1073                 tmr->expiry = now + seconds;
1074                 tmr->start = now;
1075
1076                 timers_update(stk);
1077                 break;
1078
1079         case 1: /* Deactivate */
1080                 if (!tmr->expiry) {
1081                         rsp->result.type = STK_RESULT_TYPE_TIMER_CONFLICT;
1082
1083                         return TRUE;
1084                 }
1085
1086                 seconds = MAX(0, tmr->expiry - now);
1087                 tmr->expiry = 0;
1088
1089                 timers_update(stk);
1090
1091                 timer_value_from_seconds(&rsp->timer_mgmt.value, seconds);
1092                 break;
1093
1094         case 2: /* Get current value */
1095                 if (!tmr->expiry) {
1096                         rsp->result.type = STK_RESULT_TYPE_TIMER_CONFLICT;
1097
1098                         return TRUE;
1099                 }
1100
1101                 seconds = MAX(0, tmr->expiry - now);
1102                 timer_value_from_seconds(&rsp->timer_mgmt.value, seconds);
1103                 break;
1104
1105         default:
1106                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1107
1108                 return TRUE;
1109         }
1110
1111         rsp->timer_mgmt.id = cmd->timer_mgmt.timer_id;
1112
1113         return TRUE;
1114 }
1115
1116 static gboolean handle_command_poll_interval(const struct stk_command *cmd,
1117                                                 struct stk_response *rsp,
1118                                                 struct ofono_stk *stk)
1119 {
1120         struct ofono_modem *modem = __ofono_atom_get_modem(stk->atom);
1121         int seconds;
1122
1123         if (!cmd->poll_interval.duration.interval) {
1124                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1125                 return TRUE;
1126         }
1127
1128         seconds = MAX(duration_to_msecs(&cmd->poll_interval.duration) / 1000,
1129                         1);
1130
1131         ofono_modem_set_integer(modem, "status-poll-interval", seconds);
1132
1133         if (seconds > 255) {
1134                 rsp->poll_interval.max_interval.unit =
1135                         STK_DURATION_TYPE_MINUTES;
1136                 rsp->poll_interval.max_interval.interval = seconds / 60;
1137         } else {
1138                 rsp->poll_interval.max_interval.unit =
1139                         STK_DURATION_TYPE_SECONDS;
1140                 rsp->poll_interval.max_interval.interval = seconds;
1141         }
1142
1143         return TRUE;
1144 }
1145
1146 /* Note: may be called from ofono_stk_proactive_command_handled_notify */
1147 static gboolean handle_command_set_up_menu(const struct stk_command *cmd,
1148                                                 struct stk_response *rsp,
1149                                                 struct ofono_stk *stk)
1150 {
1151         struct stk_menu *menu = NULL;
1152
1153         if (cmd->setup_menu.items) {
1154                 menu = stk_menu_create_from_set_up_menu(cmd);
1155
1156                 if (menu == NULL) {
1157                         rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1158                         return TRUE;
1159                 }
1160         }
1161
1162         if (menu == NULL && stk->main_menu == NULL)
1163                 return TRUE;
1164
1165         if (stk->main_menu)
1166                 stk_menu_free(stk->main_menu);
1167
1168         stk->main_menu = menu;
1169
1170         emit_menu_changed(stk);
1171
1172         return TRUE;
1173 }
1174
1175 static void request_selection_destroy(void *user_data)
1176 {
1177         struct ofono_stk *stk = user_data;
1178
1179         stk_menu_free(stk->select_item_menu);
1180         stk->select_item_menu = NULL;
1181 }
1182
1183 static void request_selection_cb(enum stk_agent_result result, uint8_t id,
1184                                         void *user_data)
1185 {
1186         struct ofono_stk *stk = user_data;
1187
1188         switch (result) {
1189         case STK_AGENT_RESULT_OK:
1190         {
1191                 static struct ofono_error error = {
1192                         .type = OFONO_ERROR_TYPE_FAILURE
1193                 };
1194                 struct stk_response rsp;
1195
1196                 memset(&rsp, 0, sizeof(rsp));
1197
1198                 rsp.result.type = STK_RESULT_TYPE_SUCCESS;
1199                 rsp.select_item.item_id = id;
1200
1201                 if (stk_respond(stk, &rsp, stk_command_cb))
1202                         stk_command_cb(&error, stk);
1203
1204                 break;
1205         }
1206
1207         case STK_AGENT_RESULT_BACK:
1208                 send_simple_response(stk, STK_RESULT_TYPE_GO_BACK);
1209                 break;
1210
1211         case STK_AGENT_RESULT_TIMEOUT:
1212                 send_simple_response(stk, STK_RESULT_TYPE_NO_RESPONSE);
1213                 break;
1214
1215         case STK_AGENT_RESULT_TERMINATE:
1216         default:
1217                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
1218                 break;
1219         }
1220 }
1221
1222 static gboolean handle_command_select_item(const struct stk_command *cmd,
1223                                                 struct stk_response *rsp,
1224                                                 struct ofono_stk *stk)
1225 {
1226         stk->select_item_menu = stk_menu_create_from_select_item(cmd);
1227
1228         if (stk->select_item_menu == NULL) {
1229                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1230
1231                 return TRUE;
1232         }
1233
1234         /* We most likely got an out of memory error, tell SIM to retry */
1235         if (stk_agent_request_selection(stk->current_agent,
1236                                         stk->select_item_menu,
1237                                         request_selection_cb, stk,
1238                                         request_selection_destroy,
1239                                         stk->timeout * 1000) < 0) {
1240                 unsigned char no_cause_result[] = { 0x00 };
1241
1242                 request_selection_destroy(stk);
1243
1244                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
1245                                         no_cause_result);
1246                 return TRUE;
1247         }
1248
1249         stk->cancel_cmd = stk_request_cancel;
1250         stk->respond_on_exit = TRUE;
1251
1252         return FALSE;
1253 }
1254
1255 static void display_text_destroy(void *user_data)
1256 {
1257         struct ofono_stk *stk = user_data;
1258
1259         stk->immediate_response = FALSE;
1260 }
1261
1262 static void display_text_cb(enum stk_agent_result result, void *user_data)
1263 {
1264         struct ofono_stk *stk = user_data;
1265         gboolean confirm;
1266         struct stk_response rsp;
1267         static unsigned char screen_busy_result[] = { 0x01 };
1268         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
1269
1270         /*
1271          * There are four possible paths for DisplayText with immediate
1272          * response flag set:
1273          *      1. Agent drops off the bus.  In that case regular removal
1274          *      semantics apply and the agent is removed.
1275          *
1276          *      2. A new SIM command arrives.  In this case the agent is
1277          *      canceled and a new command is processed.  This function is
1278          *      not called in this case.
1279          *
1280          *      3. The session is ended by the SIM.  This case is ignored,
1281          *      and will result in either case 1, 2 or 4 occurring.
1282          *
1283          *      4. Agent reports an error or success.  This function is called
1284          *      with the result.
1285          *
1286          *      NOTE: If the agent reports a TERMINATE result, the agent will
1287          *      be removed.  Since the response has been already sent, there
1288          *      is no way to signal the end of session to the SIM.  Hence
1289          *      it is assumed that immediate response flagged commands will
1290          *      only occur at the end of session.
1291          */
1292         if (stk->immediate_response) {
1293                 if (stk->session_agent)
1294                         session_agent_remove(stk);
1295
1296                 return;
1297         }
1298
1299         switch (result) {
1300         case STK_AGENT_RESULT_OK:
1301                 send_simple_response(stk, STK_RESULT_TYPE_SUCCESS);
1302                 break;
1303
1304         case STK_AGENT_RESULT_BACK:
1305                 send_simple_response(stk, STK_RESULT_TYPE_GO_BACK);
1306                 break;
1307
1308         case STK_AGENT_RESULT_TIMEOUT:
1309                 confirm = (stk->pending_cmd->qualifier & (1 << 7)) != 0;
1310                 send_simple_response(stk, confirm ?
1311                         STK_RESULT_TYPE_NO_RESPONSE : STK_RESULT_TYPE_SUCCESS);
1312                 break;
1313
1314         case STK_AGENT_RESULT_BUSY:
1315                 memset(&rsp, 0, sizeof(rsp));
1316                 ADD_ERROR_RESULT(rsp.result, STK_RESULT_TYPE_TERMINAL_BUSY,
1317                                         screen_busy_result);
1318                 if (stk_respond(stk, &rsp, stk_command_cb))
1319                         stk_command_cb(&error, stk);
1320                 break;
1321
1322         case STK_AGENT_RESULT_TERMINATE:
1323         default:
1324                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
1325                 break;
1326         }
1327 }
1328
1329 static gboolean handle_command_display_text(const struct stk_command *cmd,
1330                                                 struct stk_response *rsp,
1331                                                 struct ofono_stk *stk)
1332 {
1333         int timeout = stk->short_timeout * 1000;
1334         struct stk_command_display_text *dt = &stk->pending_cmd->display_text;
1335         uint8_t qualifier = stk->pending_cmd->qualifier;
1336         ofono_bool_t priority = (qualifier & (1 << 0)) != 0;
1337         char *text = dbus_apply_text_attributes(dt->text, &dt->text_attr);
1338         int err;
1339
1340         if (text == NULL) {
1341                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1342                 return TRUE;
1343         }
1344
1345         if (qualifier & (1 << 7))
1346                 timeout = stk->timeout * 1000;
1347
1348         if (dt->duration.interval)
1349                 timeout = duration_to_msecs(&dt->duration);
1350
1351         err = stk_agent_display_text(stk->current_agent, text, &dt->icon_id,
1352                                         priority, display_text_cb, stk,
1353                                         display_text_destroy, timeout);
1354         g_free(text);
1355
1356         /* We most likely got an out of memory error, tell SIM to retry */
1357         if (err < 0) {
1358                 unsigned char no_cause_result[] = { 0x00 };
1359
1360                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
1361                                         no_cause_result);
1362                 return TRUE;
1363         }
1364
1365         if (cmd->display_text.immediate_response)
1366                 stk->immediate_response = TRUE;
1367
1368         DBG("Immediate Response: %d", stk->immediate_response);
1369
1370         if (stk->immediate_response == FALSE) {
1371                 stk->respond_on_exit = TRUE;
1372                 stk->cancel_cmd = stk_request_cancel;
1373         }
1374
1375         return stk->immediate_response;
1376 }
1377
1378 static void set_get_inkey_duration(struct stk_duration *duration,
1379                                         struct timeval *start_ts)
1380 {
1381         struct timeval end_ts;
1382         int interval;
1383
1384         gettimeofday(&end_ts, NULL);
1385
1386         interval = (end_ts.tv_usec + 1099999 - start_ts->tv_usec) / 100000;
1387         interval += (end_ts.tv_sec - start_ts->tv_sec) * 10;
1388         interval -= 10;
1389
1390         switch (duration->unit) {
1391         case STK_DURATION_TYPE_MINUTES:
1392                 interval = (interval + 59) / 60;
1393         case STK_DURATION_TYPE_SECONDS:
1394                 interval = (interval + 9) / 10;
1395         case STK_DURATION_TYPE_SECOND_TENTHS:
1396                 break;
1397         }
1398
1399         duration->interval = interval;
1400 }
1401
1402 static void request_confirmation_cb(enum stk_agent_result result,
1403                                         gboolean confirm,
1404                                         void *user_data)
1405 {
1406         struct ofono_stk *stk = user_data;
1407         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
1408         struct stk_command_get_inkey *cmd = &stk->pending_cmd->get_inkey;
1409         struct stk_response rsp;
1410
1411         switch (result) {
1412         case STK_AGENT_RESULT_OK:
1413                 memset(&rsp, 0, sizeof(rsp));
1414
1415                 rsp.result.type = STK_RESULT_TYPE_SUCCESS;
1416                 rsp.get_inkey.text.text = confirm ? "" : NULL;
1417                 rsp.get_inkey.text.yesno = TRUE;
1418
1419                 if (cmd->duration.interval) {
1420                         rsp.get_inkey.duration.unit = cmd->duration.unit;
1421                         set_get_inkey_duration(&rsp.get_inkey.duration,
1422                                                 &stk->get_inkey_start_ts);
1423                 }
1424
1425                 if (stk_respond(stk, &rsp, stk_command_cb))
1426                         stk_command_cb(&error, stk);
1427
1428                 break;
1429
1430         case STK_AGENT_RESULT_BACK:
1431                 send_simple_response(stk, STK_RESULT_TYPE_GO_BACK);
1432                 break;
1433
1434         case STK_AGENT_RESULT_TIMEOUT:
1435                 memset(&rsp, 0, sizeof(rsp));
1436
1437                 rsp.result.type = STK_RESULT_TYPE_NO_RESPONSE;
1438
1439                 if (cmd->duration.interval) {
1440                         rsp.get_inkey.duration.unit = cmd->duration.unit;
1441                         set_get_inkey_duration(&rsp.get_inkey.duration,
1442                                                 &stk->get_inkey_start_ts);
1443                 }
1444
1445                 if (stk_respond(stk, &rsp, stk_command_cb))
1446                         stk_command_cb(&error, stk);
1447
1448                 break;
1449
1450         case STK_AGENT_RESULT_TERMINATE:
1451         default:
1452                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
1453                 break;
1454         }
1455 }
1456
1457 static void request_key_cb(enum stk_agent_result result, char *string,
1458                                 void *user_data)
1459 {
1460         struct ofono_stk *stk = user_data;
1461         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
1462         struct stk_command_get_inkey *cmd = &stk->pending_cmd->get_inkey;
1463         struct stk_response rsp;
1464
1465         switch (result) {
1466         case STK_AGENT_RESULT_OK:
1467                 memset(&rsp, 0, sizeof(rsp));
1468
1469                 rsp.result.type = STK_RESULT_TYPE_SUCCESS;
1470                 rsp.get_inkey.text.text = string;
1471
1472                 if (cmd->duration.interval) {
1473                         rsp.get_inkey.duration.unit = cmd->duration.unit;
1474                         set_get_inkey_duration(&rsp.get_inkey.duration,
1475                                                 &stk->get_inkey_start_ts);
1476                 }
1477
1478                 if (stk_respond(stk, &rsp, stk_command_cb))
1479                         stk_command_cb(&error, stk);
1480
1481                 break;
1482
1483         case STK_AGENT_RESULT_BACK:
1484                 send_simple_response(stk, STK_RESULT_TYPE_GO_BACK);
1485                 break;
1486
1487         case STK_AGENT_RESULT_TIMEOUT:
1488                 memset(&rsp, 0, sizeof(rsp));
1489
1490                 rsp.result.type = STK_RESULT_TYPE_NO_RESPONSE;
1491
1492                 if (cmd->duration.interval) {
1493                         rsp.get_inkey.duration.unit = cmd->duration.unit;
1494                         set_get_inkey_duration(&rsp.get_inkey.duration,
1495                                                 &stk->get_inkey_start_ts);
1496                 }
1497
1498                 if (stk_respond(stk, &rsp, stk_command_cb))
1499                         stk_command_cb(&error, stk);
1500
1501                 break;
1502
1503         case STK_AGENT_RESULT_TERMINATE:
1504         default:
1505                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
1506                 break;
1507         }
1508 }
1509
1510 static gboolean handle_command_get_inkey(const struct stk_command *cmd,
1511                                                 struct stk_response *rsp,
1512                                                 struct ofono_stk *stk)
1513 {
1514         int timeout = stk->timeout * 1000;
1515         const struct stk_command_get_inkey *gi = &cmd->get_inkey;
1516         char *text = dbus_apply_text_attributes(gi->text, &gi->text_attr);
1517         uint8_t qualifier = stk->pending_cmd->qualifier;
1518         gboolean alphabet = (qualifier & (1 << 0)) != 0;
1519         gboolean ucs2 = (qualifier & (1 << 1)) != 0;
1520         gboolean yesno = (qualifier & (1 << 2)) != 0;
1521         /*
1522          * Note: immediate response and help parameter values are not
1523          * provided by current api.
1524          */
1525         int err;
1526
1527         if (text == NULL) {
1528                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1529                 return TRUE;
1530         }
1531
1532         if (gi->duration.interval)
1533                 timeout = duration_to_msecs(&gi->duration);
1534
1535         gettimeofday(&stk->get_inkey_start_ts, NULL);
1536
1537         if (yesno)
1538                 err = stk_agent_request_confirmation(stk->current_agent,
1539                                                         text, &gi->icon_id,
1540                                                         request_confirmation_cb,
1541                                                         stk, NULL, timeout);
1542         else if (alphabet)
1543                 err = stk_agent_request_key(stk->current_agent, text,
1544                                                 &gi->icon_id, ucs2,
1545                                                 request_key_cb, stk, NULL,
1546                                                 timeout);
1547         else
1548                 err = stk_agent_request_digit(stk->current_agent, text,
1549                                                 &gi->icon_id, request_key_cb,
1550                                                 stk, NULL, timeout);
1551
1552         g_free(text);
1553
1554         if (err < 0) {
1555                 unsigned char no_cause_result[] = { 0x00 };
1556
1557                 /*
1558                  * We most likely got an out of memory error, tell SIM
1559                  * to retry
1560                  */
1561                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
1562                                         no_cause_result);
1563                 return TRUE;
1564         }
1565
1566         stk->respond_on_exit = TRUE;
1567         stk->cancel_cmd = stk_request_cancel;
1568
1569         return FALSE;
1570 }
1571
1572 static void request_string_cb(enum stk_agent_result result, char *string,
1573                                 void *user_data)
1574 {
1575         struct ofono_stk *stk = user_data;
1576         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
1577         uint8_t qualifier = stk->pending_cmd->qualifier;
1578         gboolean packed = (qualifier & (1 << 3)) != 0;
1579         struct stk_response rsp;
1580
1581         switch (result) {
1582         case STK_AGENT_RESULT_OK:
1583                 memset(&rsp, 0, sizeof(rsp));
1584
1585                 rsp.result.type = STK_RESULT_TYPE_SUCCESS;
1586                 rsp.get_input.text.text = string;
1587                 rsp.get_input.text.packed = packed;
1588
1589                 if (stk_respond(stk, &rsp, stk_command_cb))
1590                         stk_command_cb(&error, stk);
1591
1592                 break;
1593
1594         case STK_AGENT_RESULT_BACK:
1595                 send_simple_response(stk, STK_RESULT_TYPE_GO_BACK);
1596                 break;
1597
1598         case STK_AGENT_RESULT_TIMEOUT:
1599                 send_simple_response(stk, STK_RESULT_TYPE_NO_RESPONSE);
1600                 break;
1601
1602         case STK_AGENT_RESULT_TERMINATE:
1603         default:
1604                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
1605                 break;
1606         }
1607 }
1608
1609 static gboolean handle_command_get_input(const struct stk_command *cmd,
1610                                                 struct stk_response *rsp,
1611                                                 struct ofono_stk *stk)
1612 {
1613         int timeout = stk->timeout * 1000;
1614         const struct stk_command_get_input *gi = &cmd->get_input;
1615         char *text = dbus_apply_text_attributes(gi->text, &gi->text_attr);
1616         uint8_t qualifier = stk->pending_cmd->qualifier;
1617         gboolean alphabet = (qualifier & (1 << 0)) != 0;
1618         gboolean ucs2 = (qualifier & (1 << 1)) != 0;
1619         gboolean hidden = (qualifier & (1 << 2)) != 0;
1620         int err;
1621
1622         if (text == NULL) {
1623                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1624                 return TRUE;
1625         }
1626
1627         if (alphabet)
1628                 err = stk_agent_request_input(stk->current_agent, text,
1629                                                 &gi->icon_id, gi->default_text,
1630                                                 ucs2, gi->resp_len.min,
1631                                                 gi->resp_len.max, hidden,
1632                                                 request_string_cb,
1633                                                 stk, NULL, timeout);
1634         else
1635                 err = stk_agent_request_digits(stk->current_agent, text,
1636                                                 &gi->icon_id, gi->default_text,
1637                                                 gi->resp_len.min,
1638                                                 gi->resp_len.max, hidden,
1639                                                 request_string_cb,
1640                                                 stk, NULL, timeout);
1641
1642         g_free(text);
1643
1644         if (err < 0) {
1645                 unsigned char no_cause_result[] = { 0x00 };
1646
1647                 /*
1648                  * We most likely got an out of memory error, tell SIM
1649                  * to retry
1650                  */
1651                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
1652                                         no_cause_result);
1653                 return TRUE;
1654         }
1655
1656         stk->respond_on_exit = TRUE;
1657         stk->cancel_cmd = stk_request_cancel;
1658
1659         return FALSE;
1660 }
1661
1662 static void call_setup_connected(struct ofono_call *call, void *data)
1663 {
1664         struct ofono_stk *stk = data;
1665         struct stk_response rsp;
1666         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
1667         static unsigned char facility_rejected_result[] = { 0x9d };
1668
1669         if (call == NULL || call->status == CALL_STATUS_DISCONNECTED) {
1670                 memset(&rsp, 0, sizeof(rsp));
1671
1672                 ADD_ERROR_RESULT(rsp.result,
1673                                         STK_RESULT_TYPE_NETWORK_UNAVAILABLE,
1674                                         facility_rejected_result);
1675
1676                 if (stk_respond(stk, &rsp, stk_command_cb))
1677                         stk_command_cb(&error, stk);
1678
1679                 return;
1680         }
1681
1682         if (call->status == CALL_STATUS_ACTIVE)
1683                 send_simple_response(stk, STK_RESULT_TYPE_SUCCESS);
1684         else
1685                 send_simple_response(stk, STK_RESULT_TYPE_USER_CANCEL);
1686 }
1687
1688 static void call_setup_cancel(struct ofono_stk *stk)
1689 {
1690         struct ofono_voicecall *vc;
1691         struct ofono_atom *vc_atom;
1692
1693         vc_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
1694                                                 OFONO_ATOM_TYPE_VOICECALL);
1695         if (vc_atom == NULL)
1696                 return;
1697
1698         vc = __ofono_atom_get_data(vc_atom);
1699         if (vc)
1700                 __ofono_voicecall_dial_cancel(vc);
1701 }
1702
1703 static void confirm_call_cb(enum stk_agent_result result, gboolean confirm,
1704                                 void *user_data)
1705 {
1706         struct ofono_stk *stk = user_data;
1707         static struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
1708         const struct stk_command_setup_call *sc = &stk->pending_cmd->setup_call;
1709         uint8_t qualifier = stk->pending_cmd->qualifier;
1710         static unsigned char busy_on_call_result[] = { 0x02 };
1711         static unsigned char no_cause_result[] = { 0x00 };
1712         char *alpha_id = NULL;
1713         struct ofono_voicecall *vc = NULL;
1714         struct ofono_atom *vc_atom;
1715         struct stk_response rsp;
1716         int err;
1717
1718         switch (result) {
1719         case STK_AGENT_RESULT_TIMEOUT:
1720                 confirm = FALSE;
1721                 /* Fall through */
1722
1723         case STK_AGENT_RESULT_OK:
1724                 if (confirm)
1725                         break;
1726
1727                 send_simple_response(stk, STK_RESULT_TYPE_USER_REJECT);
1728                 return;
1729
1730         case STK_AGENT_RESULT_TERMINATE:
1731         default:
1732                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
1733                 return;
1734         }
1735
1736         vc_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
1737                                                 OFONO_ATOM_TYPE_VOICECALL);
1738         if (vc_atom)
1739                 vc = __ofono_atom_get_data(vc_atom);
1740
1741         if (vc == NULL) {
1742                 send_simple_response(stk, STK_RESULT_TYPE_NOT_CAPABLE);
1743                 return;
1744         }
1745
1746         if (sc->alpha_id_call_setup) {
1747                 alpha_id = dbus_apply_text_attributes(sc->alpha_id_call_setup,
1748                                                 &sc->text_attr_call_setup);
1749                 if (alpha_id == NULL) {
1750                         send_simple_response(stk,
1751                                         STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD);
1752                         return;
1753                 }
1754         }
1755
1756         err = __ofono_voicecall_dial(vc, sc->addr.number, sc->addr.ton_npi,
1757                                         alpha_id, sc->icon_id_call_setup.id,
1758                                         qualifier >> 1, call_setup_connected,
1759                                         stk);
1760         g_free(alpha_id);
1761
1762         if (err >= 0) {
1763                 stk->cancel_cmd = call_setup_cancel;
1764
1765                 return;
1766         }
1767
1768         if (err == -EBUSY) {
1769                 memset(&rsp, 0, sizeof(rsp));
1770
1771                 ADD_ERROR_RESULT(rsp.result, STK_RESULT_TYPE_TERMINAL_BUSY,
1772                                         busy_on_call_result);
1773
1774                 if (stk_respond(stk, &rsp, stk_command_cb))
1775                         stk_command_cb(&error, stk);
1776
1777                 return;
1778         }
1779
1780         if (err == -ENOSYS) {
1781                 send_simple_response(stk, STK_RESULT_TYPE_NOT_CAPABLE);
1782
1783                 return;
1784         }
1785
1786         memset(&rsp, 0, sizeof(rsp));
1787
1788         ADD_ERROR_RESULT(rsp.result, STK_RESULT_TYPE_NETWORK_UNAVAILABLE,
1789                                 no_cause_result);
1790
1791         if (stk_respond(stk, &rsp, stk_command_cb))
1792                 stk_command_cb(&error, stk);
1793 }
1794
1795 static void confirm_handled_call_cb(enum stk_agent_result result,
1796                                         gboolean confirm, void *user_data)
1797 {
1798         struct ofono_stk *stk = user_data;
1799         const struct stk_command_setup_call *sc =
1800                                         &stk->pending_cmd->setup_call;
1801         struct ofono_voicecall *vc = NULL;
1802         struct ofono_atom *vc_atom;
1803
1804         if (stk->driver->user_confirmation == NULL)
1805                 goto out;
1806
1807         if (result != STK_AGENT_RESULT_OK) {
1808                 stk->driver->user_confirmation(stk, FALSE);
1809                 goto out;
1810         }
1811
1812         stk->driver->user_confirmation(stk, confirm);
1813
1814         vc_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
1815                                                 OFONO_ATOM_TYPE_VOICECALL);
1816         if (vc_atom)
1817                 vc = __ofono_atom_get_data(vc_atom);
1818
1819         if (vc == NULL)
1820                 goto out;
1821
1822         __ofono_voicecall_set_alpha_and_icon_id(vc, sc->addr.number,
1823                                                 sc->addr.ton_npi,
1824                                                 sc->alpha_id_call_setup,
1825                                                 sc->icon_id_call_setup.id);
1826
1827         return;
1828
1829 out:
1830         stk_command_free(stk->pending_cmd);
1831         stk->pending_cmd = NULL;
1832 }
1833
1834 static gboolean handle_command_set_up_call(const struct stk_command *cmd,
1835                                                 struct stk_response *rsp,
1836                                                 struct ofono_stk *stk)
1837 {
1838         const struct stk_command_setup_call *sc = &cmd->setup_call;
1839         uint8_t qualifier = cmd->qualifier;
1840         static unsigned char busy_on_call_result[] = { 0x02 };
1841         char *alpha_id = NULL;
1842         struct ofono_voicecall *vc = NULL;
1843         struct ofono_atom *vc_atom;
1844         int err;
1845
1846         if (qualifier > 5) {
1847                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1848                 return TRUE;
1849         }
1850
1851         /*
1852          * Passing called party subaddress and establishing non-speech
1853          * calls are not supported.
1854          */
1855         if (sc->ccp.len || sc->subaddr.len) {
1856                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
1857                 return TRUE;
1858         }
1859
1860         vc_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
1861                                                 OFONO_ATOM_TYPE_VOICECALL);
1862         if (vc_atom)
1863                 vc = __ofono_atom_get_data(vc_atom);
1864
1865         if (vc == NULL) {
1866                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
1867                 return TRUE;
1868         }
1869
1870         if (__ofono_voicecall_is_busy(vc, qualifier >> 1)) {
1871                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
1872                                         busy_on_call_result);
1873                 return TRUE;
1874         }
1875
1876         alpha_id = dbus_apply_text_attributes(sc->alpha_id_usr_cfm ?
1877                                                 sc->alpha_id_usr_cfm : "",
1878                                                 &sc->text_attr_usr_cfm);
1879         if (alpha_id == NULL) {
1880                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
1881                 return TRUE;
1882         }
1883
1884         err = stk_agent_confirm_call(stk->current_agent, alpha_id,
1885                                         &sc->icon_id_usr_cfm, confirm_call_cb,
1886                                         stk, NULL, stk->timeout * 1000);
1887         g_free(alpha_id);
1888
1889         if (err < 0) {
1890                 unsigned char no_cause_result[] = { 0x00 };
1891
1892                 /*
1893                  * We most likely got an out of memory error, tell SIM
1894                  * to retry
1895                  */
1896                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
1897                                         no_cause_result);
1898                 return TRUE;
1899         }
1900
1901         stk->respond_on_exit = TRUE;
1902         stk->cancel_cmd = stk_request_cancel;
1903
1904         return FALSE;
1905 }
1906
1907 static void send_ussd_cancel(struct ofono_stk *stk)
1908 {
1909         struct ofono_ussd *ussd;
1910         struct ofono_atom *atom;
1911
1912         atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
1913                                                 OFONO_ATOM_TYPE_USSD);
1914         if (atom == NULL)
1915                 return;
1916
1917         ussd = __ofono_atom_get_data(atom);
1918         if (ussd)
1919                 __ofono_ussd_initiate_cancel(ussd);
1920
1921         stk_alpha_id_unset(stk);
1922 }
1923
1924 static void send_ussd_callback(int error, int dcs, const unsigned char *msg,
1925                                 int msg_len, void *userdata)
1926 {
1927         struct ofono_stk *stk = userdata;
1928         struct ofono_error failure = { .type = OFONO_ERROR_TYPE_FAILURE };
1929         struct stk_response rsp;
1930         enum sms_charset charset;
1931         unsigned char no_cause[] = { 0x00 };
1932
1933         stk_alpha_id_unset(stk);
1934
1935         memset(&rsp, 0, sizeof(rsp));
1936
1937         switch (error) {
1938         case 0:
1939                 if (cbs_dcs_decode(dcs, NULL, NULL, &charset,
1940                                         NULL, NULL, NULL)) {
1941                         if (charset == SMS_CHARSET_7BIT)
1942                                 rsp.send_ussd.text.dcs = 0x00;
1943                         else if (charset == SMS_CHARSET_8BIT)
1944                                 rsp.send_ussd.text.dcs = 0x04;
1945                         else if (charset == SMS_CHARSET_UCS2)
1946                                 rsp.send_ussd.text.dcs = 0x08;
1947
1948                         rsp.result.type = STK_RESULT_TYPE_SUCCESS;
1949                         rsp.send_ussd.text.text = msg;
1950                         rsp.send_ussd.text.len = msg_len;
1951                         rsp.send_ussd.text.has_text = TRUE;
1952                 } else
1953                         rsp.result.type = STK_RESULT_TYPE_USSD_RETURN_ERROR;
1954
1955                 if (stk_respond(stk, &rsp, stk_command_cb))
1956                         stk_command_cb(&failure, stk);
1957
1958                 break;
1959
1960         case -ECANCELED:
1961                 send_simple_response(stk,
1962                                 STK_RESULT_TYPE_USSD_OR_SS_USER_TERMINATION);
1963                 break;
1964
1965         case -ETIMEDOUT:
1966                 send_simple_response(stk, STK_RESULT_TYPE_NETWORK_UNAVAILABLE);
1967                 break;
1968
1969         default:
1970                 ADD_ERROR_RESULT(rsp.result, STK_RESULT_TYPE_USSD_RETURN_ERROR,
1971                                         no_cause);
1972
1973                 if (stk_respond(stk, &rsp, stk_command_cb))
1974                         stk_command_cb(&failure, stk);
1975
1976                 break;
1977         }
1978 }
1979
1980 static gboolean ss_is_busy(struct ofono_modem *modem)
1981 {
1982         struct ofono_atom *atom;
1983
1984         atom = __ofono_modem_find_atom(modem, OFONO_ATOM_TYPE_CALL_FORWARDING);
1985         if (atom != NULL) {
1986                 struct ofono_call_forwarding *cf = __ofono_atom_get_data(atom);
1987
1988                 if (__ofono_call_forwarding_is_busy(cf))
1989                         return TRUE;
1990         }
1991
1992         atom = __ofono_modem_find_atom(modem, OFONO_ATOM_TYPE_CALL_BARRING);
1993         if (atom != NULL) {
1994                 struct ofono_call_barring *cb = __ofono_atom_get_data(atom);
1995
1996                 if (__ofono_call_barring_is_busy(cb))
1997                         return TRUE;
1998         }
1999
2000         atom = __ofono_modem_find_atom(modem, OFONO_ATOM_TYPE_CALL_SETTINGS);
2001         if (atom != NULL) {
2002                 struct ofono_call_settings *cs = __ofono_atom_get_data(atom);
2003
2004                 if (__ofono_call_settings_is_busy(cs))
2005                         return TRUE;
2006         }
2007
2008         return FALSE;
2009 }
2010
2011 static gboolean handle_command_send_ussd(const struct stk_command *cmd,
2012                                         struct stk_response *rsp,
2013                                         struct ofono_stk *stk)
2014 {
2015         struct ofono_modem *modem = __ofono_atom_get_modem(stk->atom);
2016         static unsigned char busy_on_ss_result[] = { 0x03 };
2017         static unsigned char busy_on_ussd_result[] = { 0x08 };
2018         struct ofono_atom *atom;
2019         struct ofono_ussd *ussd;
2020         int err;
2021
2022         atom = __ofono_modem_find_atom(modem, OFONO_ATOM_TYPE_USSD);
2023         if (atom == NULL || !__ofono_atom_get_registered(atom)) {
2024                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2025                 return TRUE;
2026         }
2027
2028         ussd = __ofono_atom_get_data(atom);
2029         if (__ofono_ussd_is_busy(ussd)) {
2030                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2031                                         busy_on_ussd_result);
2032                 return TRUE;
2033         }
2034
2035         if (ss_is_busy(modem)) {
2036                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2037                                         busy_on_ss_result);
2038                 return TRUE;
2039         }
2040
2041         err = __ofono_ussd_initiate(ussd, cmd->send_ussd.ussd_string.dcs,
2042                                         cmd->send_ussd.ussd_string.string,
2043                                         cmd->send_ussd.ussd_string.len,
2044                                         send_ussd_callback, stk);
2045
2046         if (err >= 0) {
2047                 stk->cancel_cmd = send_ussd_cancel;
2048
2049                 return FALSE;
2050         }
2051
2052         if (err == -ENOSYS) {
2053                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2054                 return TRUE;
2055         }
2056
2057         if (err == -EBUSY) {
2058                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2059                                         busy_on_ussd_result);
2060                 return TRUE;
2061         }
2062
2063         stk_alpha_id_set(stk, cmd->send_ussd.alpha_id,
2064                                 &cmd->send_ussd.text_attr,
2065                                 &cmd->send_ussd.icon_id);
2066
2067         return FALSE;
2068 }
2069
2070 static void free_idle_mode_text(struct ofono_stk *stk)
2071 {
2072         g_free(stk->idle_mode_text);
2073         stk->idle_mode_text = NULL;
2074
2075         memset(&stk->idle_mode_icon, 0, sizeof(stk->idle_mode_icon));
2076 }
2077
2078 /* Note: may be called from ofono_stk_proactive_command_handled_notify */
2079 static gboolean handle_command_refresh(const struct stk_command *cmd,
2080                                         struct stk_response *rsp,
2081                                         struct ofono_stk *stk)
2082 {
2083         struct ofono_error failure = { .type = OFONO_ERROR_TYPE_FAILURE };
2084         struct ofono_sim *sim = NULL;
2085         struct ofono_atom *sim_atom;
2086         struct ofono_ussd *ussd = NULL;
2087         struct ofono_atom *ussd_atom;
2088         struct ofono_voicecall *vc = NULL;
2089         struct ofono_atom *vc_atom;
2090         uint8_t addnl_info[1];
2091         int err;
2092         GSList *l;
2093
2094         DBG("");
2095
2096         switch (cmd->qualifier) {
2097         case 0:
2098                 DBG("NAA Initialization and "
2099                                 "Full File Change Notification");
2100                 break;
2101
2102         case 1:
2103                 DBG("File Change Notification");
2104                 break;
2105
2106         case 2:
2107                 DBG("NAA Initialization and File Change Notification");
2108                 break;
2109
2110         case 3:
2111                 DBG("NAA Initialization");
2112                 break;
2113
2114         case 4:
2115                 DBG("UICC Reset");
2116                 break;
2117
2118         case 5:
2119                 DBG("NAA Application Reset");
2120                 break;
2121
2122         case 6:
2123                 DBG("NAA Session Reset");
2124                 break;
2125
2126         default:
2127                 ofono_info("Undefined Refresh qualifier: %d", cmd->qualifier);
2128
2129                 if (rsp != NULL)
2130                         rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2131
2132                 return TRUE;
2133         }
2134
2135         DBG("Files:");
2136         for (l = cmd->refresh.file_list; l; l = l->next) {
2137                 struct stk_file *file = l->data;
2138                 char buf[17];
2139
2140                 encode_hex_own_buf(file->file, file->len, 0, buf);
2141                 DBG("%s", buf);
2142         }
2143
2144         DBG("Icon: %d, qualifier: %d", cmd->refresh.icon_id.id,
2145                                         cmd->refresh.icon_id.qualifier);
2146         DBG("Alpha ID: %s", cmd->refresh.alpha_id);
2147
2148         sim_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
2149                                                 OFONO_ATOM_TYPE_SIM);
2150         if (sim_atom)
2151                 sim = __ofono_atom_get_data(sim_atom);
2152
2153         if (sim == NULL) {
2154                 if (rsp != NULL)
2155                         rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2156
2157                 return TRUE;
2158         }
2159
2160         if (rsp != NULL) {
2161                 ussd_atom = __ofono_modem_find_atom(
2162                                         __ofono_atom_get_modem(stk->atom),
2163                                         OFONO_ATOM_TYPE_USSD);
2164                 if (ussd_atom)
2165                         ussd = __ofono_atom_get_data(ussd_atom);
2166
2167                 if (ussd && __ofono_ussd_is_busy(ussd)) {
2168                         addnl_info[0] = STK_RESULT_ADDNL_ME_PB_USSD_BUSY;
2169
2170                         ADD_ERROR_RESULT(rsp->result,
2171                                         STK_RESULT_TYPE_TERMINAL_BUSY,
2172                                         addnl_info);
2173                         return TRUE;
2174                 }
2175
2176                 vc_atom = __ofono_modem_find_atom(
2177                                         __ofono_atom_get_modem(stk->atom),
2178                                         OFONO_ATOM_TYPE_VOICECALL);
2179                 if (vc_atom)
2180                         vc = __ofono_atom_get_data(vc_atom);
2181
2182                 if (vc && __ofono_voicecall_is_busy(vc,
2183                                         OFONO_VOICECALL_INTERACTION_NONE)) {
2184                         addnl_info[0] = STK_RESULT_ADDNL_ME_PB_BUSY_ON_CALL;
2185
2186                         ADD_ERROR_RESULT(rsp->result,
2187                                         STK_RESULT_TYPE_TERMINAL_BUSY,
2188                                         addnl_info);
2189                         return TRUE;
2190                 }
2191
2192                 if (ss_is_busy(__ofono_atom_get_modem(stk->atom))) {
2193                         addnl_info[0] = STK_RESULT_ADDNL_ME_PB_SS_BUSY;
2194
2195                         ADD_ERROR_RESULT(rsp->result,
2196                                         STK_RESULT_TYPE_TERMINAL_BUSY,
2197                                         addnl_info);
2198                         return TRUE;
2199                 }
2200         }
2201
2202         /*
2203          * For now we can handle the Refresh types that don't require
2204          * a SIM reset except if that part of the task has been already
2205          * handled by modem firmware (indicated by rsp == NULL) in which
2206          * case we just restart our SIM initialisation.
2207          */
2208         if (cmd->qualifier < 4 || rsp == NULL) {
2209                 int qualifier = stk->pending_cmd->qualifier;
2210                 GSList *file_list = stk->pending_cmd->refresh.file_list;
2211
2212                 /* Don't free the list yet */
2213                 stk->pending_cmd->refresh.file_list = NULL;
2214
2215                 /*
2216                  * Queue the TERMINAL RESPONSE before triggering potential
2217                  * file accesses.
2218                  *
2219                  * TODO: Find out if we need to send the "Refresh performed
2220                  * with additional EFs read" response.
2221                  */
2222                 if (rsp != NULL) {
2223                         err = stk_respond(stk, rsp, stk_command_cb);
2224                         if (err)
2225                                 stk_command_cb(&failure, stk);
2226                 }
2227
2228                 /* TODO: use the alphaId / icon */
2229                 /* TODO: if AID is supplied, check its value */
2230                 /* TODO: possibly check if a D-bus call is pending or
2231                  * an STK session ongoing. */
2232
2233                 /* TODO: free some elements of the atom state */
2234
2235                 switch (qualifier) {
2236                 case 0:
2237                         free_idle_mode_text(stk);
2238                         __ofono_sim_refresh(sim, file_list, TRUE, TRUE);
2239                         break;
2240                 case 1:
2241                         __ofono_sim_refresh(sim, file_list, FALSE, FALSE);
2242                         break;
2243                 case 2:
2244                 case 3:
2245                 case 4:
2246                 case 5:
2247                 case 6:
2248                         free_idle_mode_text(stk);
2249                         __ofono_sim_refresh(sim, file_list, FALSE, TRUE);
2250                         break;
2251                 }
2252
2253                 g_slist_foreach(file_list, (GFunc) g_free, NULL);
2254                 g_slist_free(file_list);
2255
2256                 return FALSE;
2257         }
2258
2259         rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2260         return TRUE;
2261 }
2262
2263 static void get_time(struct stk_response *rsp)
2264 {
2265         time_t now;
2266         struct tm *t;
2267
2268         time(&now);
2269         t = localtime(&now);
2270
2271         rsp->result.type = STK_RESULT_TYPE_SUCCESS;
2272
2273         if (t->tm_year > 100)
2274                 rsp->provide_local_info.datetime.year = t->tm_year - 100;
2275         else
2276                 rsp->provide_local_info.datetime.year = t->tm_year;
2277
2278         rsp->provide_local_info.datetime.month = t->tm_mon + 1;
2279         rsp->provide_local_info.datetime.day = t->tm_mday;
2280         rsp->provide_local_info.datetime.hour = t->tm_hour;
2281         rsp->provide_local_info.datetime.minute = t->tm_min;
2282         rsp->provide_local_info.datetime.second = t->tm_sec;
2283         rsp->provide_local_info.datetime.timezone = t->tm_gmtoff / 900;
2284         rsp->provide_local_info.datetime.has_timezone = TRUE;
2285
2286         return;
2287 }
2288
2289 static void get_lang(struct stk_response *rsp, struct ofono_stk *stk)
2290 {
2291         char *l;
2292         char lang[3];
2293         struct ofono_error failure = { .type = OFONO_ERROR_TYPE_FAILURE };
2294
2295         l = getenv("LANG");
2296         if (l == NULL) {
2297                 l = "en";
2298                 ofono_warn("LANG environment variable not set"
2299                                 " - defaulting to en");
2300         }
2301
2302         memcpy(lang, l, 2);
2303         lang[2] = '\0';
2304
2305         rsp->result.type = STK_RESULT_TYPE_SUCCESS;
2306         rsp->provide_local_info.language = lang;
2307
2308         if (stk_respond(stk, rsp, stk_command_cb))
2309                 stk_command_cb(&failure, stk);
2310 }
2311
2312 static gboolean handle_command_provide_local_info(const struct stk_command *cmd,
2313                                 struct stk_response *rsp, struct ofono_stk *stk)
2314 {
2315         switch (cmd->qualifier) {
2316         case 3:
2317                 DBG("Date, time and time zone");
2318                 get_time(rsp);
2319                 return TRUE;
2320
2321         case 4:
2322                 DBG("Language setting");
2323                 get_lang(rsp, stk);
2324                 return FALSE;
2325
2326         default:
2327                 ofono_info("Unsupported Provide Local Info qualifier: %d",
2328                                 cmd->qualifier);
2329                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2330                 return TRUE;
2331         }
2332 }
2333
2334 static void send_dtmf_cancel(struct ofono_stk *stk)
2335 {
2336         cancel_pending_dtmf(stk);
2337         stk_alpha_id_unset(stk);
2338 }
2339
2340 static void dtmf_sent_cb(int error, void *user_data)
2341 {
2342         struct ofono_stk *stk = user_data;
2343
2344         stk_alpha_id_unset(stk);
2345
2346         if (error == ENOENT) {
2347                 struct stk_response rsp;
2348                 static unsigned char not_in_speech_call_result[] = { 0x07 };
2349                 static struct ofono_error failure = {
2350                         .type = OFONO_ERROR_TYPE_FAILURE
2351                 };
2352
2353                 memset(&rsp, 0, sizeof(rsp));
2354
2355                 ADD_ERROR_RESULT(rsp.result, STK_RESULT_TYPE_TERMINAL_BUSY,
2356                                         not_in_speech_call_result);
2357
2358                 if (stk_respond(stk, &rsp, stk_command_cb))
2359                         stk_command_cb(&failure, stk);
2360
2361                 return;
2362         }
2363
2364         if (error != 0)
2365                 send_simple_response(stk, STK_RESULT_TYPE_NOT_CAPABLE);
2366         else
2367                 send_simple_response(stk, STK_RESULT_TYPE_SUCCESS);
2368 }
2369
2370 static gboolean handle_command_send_dtmf(const struct stk_command *cmd,
2371                                                 struct stk_response *rsp,
2372                                                 struct ofono_stk *stk)
2373 {
2374         static unsigned char not_in_speech_call_result[] = { 0x07 };
2375         struct ofono_voicecall *vc = NULL;
2376         struct ofono_atom *vc_atom;
2377         char dtmf[256], *digit;
2378         char *dtmf_from = "01234567890abcABC";
2379         char *dtmf_to = "01234567890*#p*#p";
2380         int err, pos;
2381
2382         vc_atom = __ofono_modem_find_atom(__ofono_atom_get_modem(stk->atom),
2383                                                 OFONO_ATOM_TYPE_VOICECALL);
2384         if (vc_atom)
2385                 vc = __ofono_atom_get_data(vc_atom);
2386
2387         if (vc == NULL) {
2388                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2389                 return TRUE;
2390         }
2391
2392         /* Convert the DTMF string to phone number format */
2393         for (pos = 0; cmd->send_dtmf.dtmf[pos] != '\0'; pos++) {
2394                 digit = strchr(dtmf_from, cmd->send_dtmf.dtmf[pos]);
2395                 if (digit == NULL) {
2396                         rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
2397                         return TRUE;
2398                 }
2399
2400                 dtmf[pos] = dtmf_to[digit - dtmf_from];
2401         }
2402
2403         dtmf[pos] = '\0';
2404
2405         err = __ofono_voicecall_tone_send(vc, dtmf, dtmf_sent_cb, stk);
2406
2407         if (err == -ENOSYS) {
2408                 rsp->result.type = STK_RESULT_TYPE_NOT_CAPABLE;
2409                 return TRUE;
2410         }
2411
2412         if (err == -ENOENT) {
2413                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2414                                         not_in_speech_call_result);
2415                 return TRUE;
2416         }
2417
2418         if (err == -EINVAL) {
2419                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
2420                 return TRUE;
2421         }
2422
2423         if (err < 0) {
2424                 unsigned char no_cause_result[] = { 0x00 };
2425
2426                 /*
2427                  * We most likely got an out of memory error, tell SIM
2428                  * to retry
2429                  */
2430                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2431                                         no_cause_result);
2432                 return TRUE;
2433         }
2434
2435         /*
2436          * Note that we don't strictly require an agent to be connected,
2437          * but to comply with 6.4.24 we need to send a End Session when
2438          * the user decides so.
2439          */
2440         stk->respond_on_exit = TRUE;
2441         stk->cancel_cmd = send_dtmf_cancel;
2442         stk->dtmf_id = err;
2443
2444         stk_alpha_id_set(stk, cmd->send_dtmf.alpha_id,
2445                                 &cmd->send_dtmf.text_attr,
2446                                 &cmd->send_dtmf.icon_id);
2447
2448         return FALSE;
2449 }
2450
2451 static void play_tone_cb(enum stk_agent_result result, void *user_data)
2452 {
2453         struct ofono_stk *stk = user_data;
2454
2455         switch (result) {
2456         case STK_AGENT_RESULT_OK:
2457         case STK_AGENT_RESULT_TIMEOUT:
2458                 send_simple_response(stk, STK_RESULT_TYPE_SUCCESS);
2459                 break;
2460
2461         default:
2462                 send_simple_response(stk, STK_RESULT_TYPE_USER_TERMINATED);
2463                 break;
2464         }
2465 }
2466
2467 static gboolean handle_command_play_tone(const struct stk_command *cmd,
2468                                                 struct stk_response *rsp,
2469                                                 struct ofono_stk *stk)
2470 {
2471         static int manufacturer_timeout = 10000; /* 10 seconds */
2472         static const struct {
2473                 const char *name;
2474                 /* Continuous true/false according to 02.40 */
2475                 gboolean continuous;
2476         } tone_infos[] = {
2477                 /* Default */
2478                 [0x00] = { "general-beep", FALSE },
2479
2480                 /* Standard */
2481                 [0x01] = { "dial-tone", TRUE },
2482                 [0x02] = { "busy", TRUE },
2483                 [0x03] = { "congestion", TRUE },
2484                 [0x04] = { "radio-path-acknowledge", FALSE },
2485                 [0x05] = { "radio-path-not-available", FALSE },
2486                 [0x06] = { "error", TRUE },
2487                 [0x07] = { "call-waiting", FALSE },
2488                 [0x08] = { "ringing-tone", TRUE },
2489
2490                 /* Proprietary */
2491                 [0x10] = { "general-beep", FALSE },
2492                 [0x11] = { "positive-acknowledgement", FALSE },
2493                 [0x12] = { "negative-acknowledgement", FALSE },
2494                 [0x13] = { "user-ringing-tone", TRUE },
2495                 [0x14] = { "user-sms-alert", FALSE },
2496                 [0x15] = { "critical", FALSE },
2497                 [0x20] = { "vibrate", TRUE },
2498
2499                 /* Themed */
2500                 [0x30] = { "happy", FALSE },
2501                 [0x31] = { "sad", FALSE },
2502                 [0x32] = { "urgent-action", FALSE },
2503                 [0x33] = { "question", FALSE },
2504                 [0x34] = { "message-received", FALSE },
2505
2506                 /* Melody */
2507                 [0x40] = { "melody-1", FALSE },
2508                 [0x41] = { "melody-2", FALSE },
2509                 [0x42] = { "melody-3", FALSE },
2510                 [0x43] = { "melody-4", FALSE },
2511                 [0x44] = { "melody-5", FALSE },
2512                 [0x45] = { "melody-6", FALSE },
2513                 [0x46] = { "melody-7", FALSE },
2514                 [0x47] = { "melody-8", FALSE },
2515         };
2516
2517         const struct stk_command_play_tone *pt = &cmd->play_tone;
2518         uint8_t qualifier = stk->pending_cmd->qualifier;
2519         gboolean vibrate = (qualifier & (1 << 0)) != 0;
2520         char *text;
2521         int timeout;
2522         int err;
2523
2524         if (pt->tone > sizeof(tone_infos) / sizeof(*tone_infos) ||
2525                         tone_infos[pt->tone].name == NULL) {
2526                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
2527
2528                 return TRUE;
2529         }
2530
2531         text = dbus_apply_text_attributes(pt->alpha_id ? pt->alpha_id : "",
2532                                                 &pt->text_attr);
2533         if (text == NULL) {
2534                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
2535
2536                 return TRUE;
2537         }
2538
2539         if (pt->duration.interval)
2540                 timeout = duration_to_msecs(&pt->duration);
2541         else
2542                 timeout = manufacturer_timeout;
2543
2544         if (!tone_infos[pt->tone].continuous)
2545                 /* Duration ignored */
2546                 err = stk_agent_play_tone(stk->current_agent, text,
2547                                                 &pt->icon_id, vibrate,
2548                                                 tone_infos[pt->tone].name,
2549                                                 play_tone_cb, stk, NULL,
2550                                                 stk->timeout * 1000);
2551         else
2552                 err = stk_agent_loop_tone(stk->current_agent, text,
2553                                                 &pt->icon_id, vibrate,
2554                                                 tone_infos[pt->tone].name,
2555                                                 play_tone_cb, stk, NULL,
2556                                                 timeout);
2557
2558         g_free(text);
2559
2560         if (err < 0) {
2561                 unsigned char no_cause_result[] = { 0x00 };
2562
2563                 /*
2564                  * We most likely got an out of memory error, tell SIM
2565                  * to retry
2566                  */
2567                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2568                                         no_cause_result);
2569                 return TRUE;
2570         }
2571
2572         stk->respond_on_exit = TRUE;
2573         stk->cancel_cmd = stk_request_cancel;
2574
2575         return FALSE;
2576 }
2577
2578 static void confirm_launch_browser_cb(enum stk_agent_result result,
2579                                         gboolean confirm,
2580                                         void *user_data)
2581 {
2582         struct ofono_stk *stk = user_data;
2583         unsigned char no_cause[] = { 0x00 };
2584         struct ofono_error failure = { .type = OFONO_ERROR_TYPE_FAILURE };
2585         struct stk_response rsp;
2586
2587         switch (result) {
2588         case STK_AGENT_RESULT_TIMEOUT:
2589                 confirm = FALSE;
2590                 /* Fall through */
2591
2592         case STK_AGENT_RESULT_OK:
2593                 if (confirm)
2594                         break;
2595                 /* Fall through */
2596
2597         default:
2598                 memset(&rsp, 0, sizeof(rsp));
2599                 ADD_ERROR_RESULT(rsp.result, STK_RESULT_TYPE_TERMINAL_BUSY,
2600                                         no_cause);
2601
2602                 if (stk_respond(stk, &rsp, stk_command_cb))
2603                         stk_command_cb(&failure, stk);
2604
2605                 return;
2606         }
2607
2608         send_simple_response(stk, STK_RESULT_TYPE_SUCCESS);
2609 }
2610
2611 static gboolean handle_command_launch_browser(const struct stk_command *cmd,
2612                                                 struct stk_response *rsp,
2613                                                 struct ofono_stk *stk)
2614 {
2615         const struct stk_command_launch_browser *lb = &cmd->launch_browser;
2616         char *alpha_id;
2617         int err;
2618
2619         alpha_id = dbus_apply_text_attributes(lb->alpha_id ? lb->alpha_id : "",
2620                                                         &lb->text_attr);
2621         if (alpha_id == NULL) {
2622                 rsp->result.type = STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD;
2623                 return TRUE;
2624         }
2625
2626         err = stk_agent_confirm_launch_browser(stk->current_agent, alpha_id,
2627                                                 lb->icon_id.id, lb->url,
2628                                                 confirm_launch_browser_cb,
2629                                                 stk, NULL, stk->timeout * 1000);
2630         g_free(alpha_id);
2631
2632         if (err < 0) {
2633                 unsigned char no_cause_result[] = { 0x00 };
2634
2635                 /*
2636                  * We most likely got an out of memory error, tell SIM
2637                  * to retry
2638                  */
2639                 ADD_ERROR_RESULT(rsp->result, STK_RESULT_TYPE_TERMINAL_BUSY,
2640                                         no_cause_result);
2641                 return TRUE;
2642         }
2643
2644         stk->respond_on_exit = TRUE;
2645         stk->cancel_cmd = stk_request_cancel;
2646
2647         return FALSE;
2648 }
2649
2650 static void setup_call_handled_cancel(struct ofono_stk *stk)
2651 {
2652         struct ofono_voicecall *vc = NULL;
2653         struct ofono_atom *vc_atom;
2654
2655         vc_atom = __ofono_modem_find_atom(
2656                                 __ofono_atom_get_modem(stk->atom),
2657                                 OFONO_ATOM_TYPE_VOICECALL);
2658         if (vc_atom)
2659                 vc = __ofono_atom_get_data(vc_atom);
2660
2661         if (vc != NULL)
2662                 __ofono_voicecall_clear_alpha_and_icon_id(vc);
2663 }
2664
2665 static gboolean handle_setup_call_confirmation_req(struct stk_command *cmd,
2666                                                 struct ofono_stk *stk)
2667 {
2668         const struct stk_command_setup_call *sc = &cmd->setup_call;
2669         int err;
2670         char *alpha_id = dbus_apply_text_attributes(
2671                                         sc->alpha_id_usr_cfm ?
2672                                         sc->alpha_id_usr_cfm : "",
2673                                         &sc->text_attr_usr_cfm);
2674         if (alpha_id == NULL)
2675                 goto out;
2676
2677         err = stk_agent_confirm_call(stk->current_agent, alpha_id,
2678                                         &sc->icon_id_usr_cfm,
2679                                         confirm_handled_call_cb,
2680                                         stk, NULL,
2681                                         stk->timeout * 1000);
2682         g_free(alpha_id);
2683
2684         if (err < 0)
2685                 goto out;
2686
2687         stk->cancel_cmd = setup_call_handled_cancel;
2688
2689         return TRUE;
2690
2691 out:
2692         if (stk->driver->user_confirmation)
2693                 stk->driver->user_confirmation(stk, FALSE);
2694
2695         return FALSE;
2696 }
2697
2698 static void stk_proactive_command_cancel(struct ofono_stk *stk)
2699 {
2700         if (stk->immediate_response)
2701                 stk_request_cancel(stk);
2702
2703         if (stk->pending_cmd) {
2704                 stk->cancel_cmd(stk);
2705                 stk_command_free(stk->pending_cmd);
2706                 stk->pending_cmd = NULL;
2707                 stk->cancel_cmd = NULL;
2708                 stk->respond_on_exit = FALSE;
2709         }
2710 }
2711
2712 void ofono_stk_proactive_session_end_notify(struct ofono_stk *stk)
2713 {
2714         /* Wait until we receive the next command */
2715         if (stk->immediate_response)
2716                 return;
2717
2718         stk_proactive_command_cancel(stk);
2719
2720         if (stk->session_agent)
2721                 stk_agent_free(stk->session_agent);
2722 }
2723
2724 void ofono_stk_proactive_command_notify(struct ofono_stk *stk,
2725                                         int length, const unsigned char *pdu)
2726 {
2727         struct ofono_error error = { .type = OFONO_ERROR_TYPE_FAILURE };
2728         struct stk_response rsp;
2729         int err;
2730         gboolean respond = TRUE;
2731
2732         /*
2733          * Depending on the hardware we may have received a new
2734          * command before we managed to send a TERMINAL RESPONSE to
2735          * the previous one.  3GPP says in the current revision only
2736          * one command can be executing at any time, so assume that
2737          * the previous one is being cancelled and the card just
2738          * expects a response to the new one.
2739          */
2740         stk_proactive_command_cancel(stk);
2741
2742         stk->pending_cmd = stk_command_new_from_pdu(pdu, length);
2743         if (stk->pending_cmd == NULL) {
2744                 ofono_error("Can't parse proactive command");
2745
2746                 /*
2747                  * Nothing we can do, we'd need at least Command Details
2748                  * to be able to respond with an error.
2749                  */
2750                 return;
2751         }
2752
2753         switch (stk->pending_cmd->status) {
2754         case STK_PARSE_RESULT_OK:
2755                 break;
2756
2757         case STK_PARSE_RESULT_MISSING_VALUE:
2758                 send_simple_response(stk, STK_RESULT_TYPE_MINIMUM_NOT_MET);
2759                 return;
2760
2761         case STK_PARSE_RESULT_DATA_NOT_UNDERSTOOD:
2762                 send_simple_response(stk, STK_RESULT_TYPE_DATA_NOT_UNDERSTOOD);
2763                 return;
2764
2765         case STK_PARSE_RESULT_TYPE_NOT_UNDERSTOOD:
2766         default:
2767                 send_simple_response(stk,
2768                                         STK_RESULT_TYPE_COMMAND_NOT_UNDERSTOOD);
2769                 return;
2770         }
2771
2772         /*
2773          * In case no agent is registered, we should reject commands destined
2774          * to the Agent with a NOT_CAPABLE error.
2775          */
2776         if (stk->current_agent == NULL) {
2777                 switch (stk->pending_cmd->type) {
2778                 case STK_COMMAND_TYPE_SELECT_ITEM:
2779                 case STK_COMMAND_TYPE_DISPLAY_TEXT:
2780                 case STK_COMMAND_TYPE_GET_INKEY:
2781                 case STK_COMMAND_TYPE_GET_INPUT:
2782                 case STK_COMMAND_TYPE_PLAY_TONE:
2783                 case STK_COMMAND_TYPE_SETUP_CALL:
2784                         send_simple_response(stk, STK_RESULT_TYPE_NOT_CAPABLE);
2785                         return;
2786
2787                 default:
2788                         break;
2789                 }
2790         }
2791
2792         memset(&rsp, 0, sizeof(rsp));
2793
2794         switch (stk->pending_cmd->type) {
2795         case STK_COMMAND_TYPE_MORE_TIME:
2796                 respond = handle_command_more_time(stk->pending_cmd,
2797                                                         &rsp, stk);
2798                 break;
2799
2800         case STK_COMMAND_TYPE_SEND_SMS:
2801                 respond = handle_command_send_sms(stk->pending_cmd,
2802                                                         &rsp, stk);
2803                 break;
2804
2805         case STK_COMMAND_TYPE_SETUP_IDLE_MODE_TEXT:
2806                 respond = handle_command_set_idle_text(stk->pending_cmd,
2807                                                         &rsp, stk);
2808                 break;
2809
2810         case STK_COMMAND_TYPE_TIMER_MANAGEMENT:
2811                 respond = handle_command_timer_mgmt(stk->pending_cmd,
2812                                                         &rsp, stk);
2813                 break;
2814
2815         case STK_COMMAND_TYPE_POLL_INTERVAL:
2816                 respond = handle_command_poll_interval(stk->pending_cmd,
2817                                                         &rsp, stk);
2818                 break;
2819
2820         case STK_COMMAND_TYPE_SETUP_MENU:
2821                 respond = handle_command_set_up_menu(stk->pending_cmd,
2822                                                         &rsp, stk);
2823                 break;
2824
2825         case STK_COMMAND_TYPE_SELECT_ITEM:
2826                 respond = handle_command_select_item(stk->pending_cmd,
2827                                                         &rsp, stk);
2828                 break;
2829
2830         case STK_COMMAND_TYPE_DISPLAY_TEXT:
2831                 respond = handle_command_display_text(stk->pending_cmd,
2832                                                         &rsp, stk);
2833                 break;
2834
2835         case STK_COMMAND_TYPE_GET_INKEY:
2836                 respond = handle_command_get_inkey(stk->pending_cmd,
2837                                                         &rsp, stk);
2838                 break;
2839
2840         case STK_COMMAND_TYPE_GET_INPUT:
2841                 respond = handle_command_get_input(stk->pending_cmd,
2842                                                         &rsp, stk);
2843                 break;
2844
2845         case STK_COMMAND_TYPE_SETUP_CALL:
2846                 respond = handle_command_set_up_call(stk->pending_cmd,
2847                                                         &rsp, stk);
2848                 break;
2849
2850         case STK_COMMAND_TYPE_SEND_USSD:
2851                 respond = handle_command_send_ussd(stk->pending_cmd,
2852                                                         &rsp, stk);
2853                 break;
2854
2855         case STK_COMMAND_TYPE_LANGUAGE_NOTIFICATION:
2856                 /*
2857                  * If any clients are interested, then the ISO639
2858                  * 2-letter codes has to be convered to language strings.
2859                  * Converted language strings has to be added to the
2860                  * property list.
2861                  */
2862                 ofono_info("Language Code: %s",
2863                         stk->pending_cmd->language_notification.language);
2864                 break;
2865
2866         case STK_COMMAND_TYPE_REFRESH:
2867                 respond = handle_command_refresh(stk->pending_cmd,
2868                                                         &rsp, stk);
2869                 break;
2870
2871         case STK_COMMAND_TYPE_PROVIDE_LOCAL_INFO:
2872                 respond = handle_command_provide_local_info(stk->pending_cmd,
2873                                                                 &rsp, stk);
2874                 break;
2875
2876         case STK_COMMAND_TYPE_SEND_DTMF:
2877                 respond = handle_command_send_dtmf(stk->pending_cmd,
2878                                                         &rsp, stk);
2879                 break;
2880
2881         case STK_COMMAND_TYPE_PLAY_TONE:
2882                 respond = handle_command_play_tone(stk->pending_cmd,
2883                                                         &rsp, stk);
2884                 break;
2885
2886         case STK_COMMAND_TYPE_LAUNCH_BROWSER:
2887                 respond = handle_command_launch_browser(stk->pending_cmd,
2888                                                         &rsp, stk);
2889                 break;
2890
2891         default:
2892                 rsp.result.type = STK_RESULT_TYPE_COMMAND_NOT_UNDERSTOOD;
2893                 break;
2894         }
2895
2896         if (respond == FALSE)
2897                 return;
2898
2899         err = stk_respond(stk, &rsp, stk_command_cb);
2900         if (err)
2901                 stk_command_cb(&error, stk);
2902 }
2903
2904 static gboolean handled_alpha_id_set(struct ofono_stk *stk,
2905                         const char *text, const struct stk_text_attribute *attr,
2906                         const struct stk_icon_id *icon)
2907 {
2908         if (stk_alpha_id_set(stk, text, attr, icon) == FALSE)
2909                 return FALSE;
2910
2911         stk->cancel_cmd = stk_alpha_id_unset;
2912         return TRUE;
2913 }
2914
2915 void ofono_stk_proactive_command_handled_notify(struct ofono_stk *stk,
2916                                                 int length,
2917                                                 const unsigned char *pdu)
2918 {
2919         struct stk_response dummyrsp;
2920         gboolean ok = FALSE;
2921
2922         /*
2923          * Modems send us the proactive command details and terminal responses
2924          * sent by the modem as a response to the command.  Terminal responses
2925          * start with the Command Details CTLV tag (0x81).  We filter terminal
2926          * responses here
2927          */
2928         if (length > 0 && pdu[0] == 0x81) {
2929                 stk_proactive_command_cancel(stk);
2930                 return;
2931         }
2932
2933         stk_proactive_command_cancel(stk);
2934
2935         stk->pending_cmd = stk_command_new_from_pdu(pdu, length);
2936         if (stk->pending_cmd == NULL)
2937                 return;
2938
2939         if (stk->pending_cmd->status != STK_PARSE_RESULT_OK) {
2940                 ofono_error("Can't parse modem-handled proactive command");
2941                 ok = FALSE;
2942                 goto out;
2943         }
2944
2945         DBG("type: %d", stk->pending_cmd->type);
2946
2947         switch (stk->pending_cmd->type) {
2948         case STK_COMMAND_TYPE_SEND_SMS:
2949                 ok = handled_alpha_id_set(stk,
2950                                         stk->pending_cmd->send_sms.alpha_id,
2951                                         &stk->pending_cmd->send_sms.text_attr,
2952                                         &stk->pending_cmd->send_sms.icon_id);
2953                 break;
2954
2955         case STK_COMMAND_TYPE_SETUP_IDLE_MODE_TEXT:
2956                 handle_command_set_idle_text(stk->pending_cmd, &dummyrsp, stk);
2957                 break;
2958
2959         case STK_COMMAND_TYPE_SETUP_MENU:
2960                 handle_command_set_up_menu(stk->pending_cmd, &dummyrsp, stk);
2961                 break;
2962
2963         case STK_COMMAND_TYPE_SETUP_CALL:
2964                 ok = handle_setup_call_confirmation_req(stk->pending_cmd, stk);
2965                 break;
2966
2967         case STK_COMMAND_TYPE_SEND_USSD:
2968                 ok = handled_alpha_id_set(stk,
2969                                         stk->pending_cmd->send_ussd.alpha_id,
2970                                         &stk->pending_cmd->send_ussd.text_attr,
2971                                         &stk->pending_cmd->send_ussd.icon_id);
2972                 break;
2973
2974         case STK_COMMAND_TYPE_SEND_SS:
2975                 ok = handled_alpha_id_set(stk,
2976                                         stk->pending_cmd->send_ss.alpha_id,
2977                                         &stk->pending_cmd->send_ss.text_attr,
2978                                         &stk->pending_cmd->send_ss.icon_id);
2979                 break;
2980
2981         case STK_COMMAND_TYPE_SEND_DTMF:
2982                 ok = handled_alpha_id_set(stk,
2983                                         stk->pending_cmd->send_dtmf.alpha_id,
2984                                         &stk->pending_cmd->send_dtmf.text_attr,
2985                                         &stk->pending_cmd->send_dtmf.icon_id);
2986                 break;
2987
2988         case STK_COMMAND_TYPE_REFRESH:
2989                 handle_command_refresh(stk->pending_cmd, NULL, stk);
2990                 break;
2991         }
2992
2993 out:
2994         if (ok == FALSE) {
2995                 stk_command_free(stk->pending_cmd);
2996                 stk->pending_cmd = NULL;
2997         }
2998 }
2999
3000 int ofono_stk_driver_register(const struct ofono_stk_driver *d)
3001 {
3002         DBG("driver: %p, name: %s", d, d->name);
3003
3004         if (d->probe == NULL)
3005                 return -EINVAL;
3006
3007         g_drivers = g_slist_prepend(g_drivers, (void *) d);
3008
3009         return 0;
3010 }
3011
3012 void ofono_stk_driver_unregister(const struct ofono_stk_driver *d)
3013 {
3014         DBG("driver: %p, name: %s", d, d->name);
3015
3016         g_drivers = g_slist_remove(g_drivers, (void *) d);
3017 }
3018
3019 static void stk_unregister(struct ofono_atom *atom)
3020 {
3021         struct ofono_stk *stk = __ofono_atom_get_data(atom);
3022         DBusConnection *conn = ofono_dbus_get_connection();
3023         struct ofono_modem *modem = __ofono_atom_get_modem(atom);
3024         const char *path = __ofono_atom_get_path(atom);
3025
3026         if (stk->session_agent)
3027                 stk_agent_free(stk->session_agent);
3028
3029         if (stk->default_agent)
3030                 stk_agent_free(stk->default_agent);
3031
3032         if (stk->pending_cmd) {
3033                 stk_command_free(stk->pending_cmd);
3034                 stk->pending_cmd = NULL;
3035                 stk->cancel_cmd = NULL;
3036         }
3037
3038         g_free(stk->idle_mode_text);
3039         stk->idle_mode_text = NULL;
3040
3041         if (stk->timers_source) {
3042                 g_source_remove(stk->timers_source);
3043                 stk->timers_source = 0;
3044         }
3045
3046         if (stk->main_menu) {
3047                 stk_menu_free(stk->main_menu);
3048                 stk->main_menu = NULL;
3049         }
3050
3051         g_queue_foreach(stk->envelope_q, (GFunc) g_free, NULL);
3052         g_queue_free(stk->envelope_q);
3053
3054         ofono_modem_remove_interface(modem, OFONO_STK_INTERFACE);
3055         g_dbus_unregister_interface(conn, path, OFONO_STK_INTERFACE);
3056 }
3057
3058 static void stk_remove(struct ofono_atom *atom)
3059 {
3060         struct ofono_stk *stk = __ofono_atom_get_data(atom);
3061
3062         DBG("atom: %p", atom);
3063
3064         if (stk == NULL)
3065                 return;
3066
3067         if (stk->driver && stk->driver->remove)
3068                 stk->driver->remove(stk);
3069
3070         g_free(stk);
3071 }
3072
3073 struct ofono_stk *ofono_stk_create(struct ofono_modem *modem,
3074                                         unsigned int vendor,
3075                                         const char *driver,
3076                                         void *data)
3077 {
3078         struct ofono_stk *stk;
3079         GSList *l;
3080
3081         if (driver == NULL)
3082                 return NULL;
3083
3084         stk = g_try_new0(struct ofono_stk, 1);
3085
3086         if (stk == NULL)
3087                 return NULL;
3088
3089         stk->atom = __ofono_modem_add_atom(modem, OFONO_ATOM_TYPE_STK,
3090                                                 stk_remove, stk);
3091
3092         for (l = g_drivers; l; l = l->next) {
3093                 const struct ofono_stk_driver *drv = l->data;
3094
3095                 if (g_strcmp0(drv->name, driver))
3096                         continue;
3097
3098                 if (drv->probe(stk, vendor, data) < 0)
3099                         continue;
3100
3101                 stk->driver = drv;
3102                 break;
3103         }
3104
3105         return stk;
3106 }
3107
3108 void ofono_stk_register(struct ofono_stk *stk)
3109 {
3110         DBusConnection *conn = ofono_dbus_get_connection();
3111         struct ofono_modem *modem = __ofono_atom_get_modem(stk->atom);
3112         const char *path = __ofono_atom_get_path(stk->atom);
3113
3114         if (!g_dbus_register_interface(conn, path, OFONO_STK_INTERFACE,
3115                                         stk_methods, stk_signals, NULL,
3116                                         stk, NULL)) {
3117                 ofono_error("Could not create %s interface",
3118                                 OFONO_STK_INTERFACE);
3119
3120                 return;
3121         }
3122
3123         ofono_modem_add_interface(modem, OFONO_STK_INTERFACE);
3124
3125         __ofono_atom_register(stk->atom, stk_unregister);
3126
3127         stk->timeout = 180; /* 3 minutes */
3128         stk->short_timeout = 20; /* 20 seconds */
3129         stk->envelope_q = g_queue_new();
3130 }
3131
3132 void ofono_stk_remove(struct ofono_stk *stk)
3133 {
3134         __ofono_atom_free(stk->atom);
3135 }
3136
3137 void ofono_stk_set_data(struct ofono_stk *stk, void *data)
3138 {
3139         stk->driver_data = data;
3140 }
3141
3142 void *ofono_stk_get_data(struct ofono_stk *stk)
3143 {
3144         return stk->driver_data;
3145 }