stktest: Fail test if DisplayText is not expected
[platform/upstream/ofono.git] / tools / stktest.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 #include <stdio.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35
36 #include <gdbus.h>
37 #include <gatchat/gatserver.h>
38
39 #include "unit/stk-test-data.h"
40
41 #define OFONO_SERVICE   "org.ofono"
42 #define STKTEST_PATH    "/stktest"
43 #define STKTEST_ERROR   "org.ofono.stktest.Error"
44 #define OFONO_ERROR     "org.ofono.Error"
45 #define OFONO_MANAGER_INTERFACE         OFONO_SERVICE ".Manager"
46 #define OFONO_MODEM_INTERFACE           OFONO_SERVICE ".Modem"
47 #define OFONO_STK_INTERFACE             OFONO_SERVICE ".SimToolkit"
48 #define OFONO_STKAGENT_INTERFACE        OFONO_SERVICE ".SimToolkitAgent"
49
50 #define LISTEN_PORT     12765
51
52 enum test_state {
53         TEST_STATE_POWERING_UP = 1,
54         TEST_STATE_REGISTERING_AGENT,
55         TEST_STATE_RUNNING,
56         TEST_STATE_POWERING_DOWN,
57 };
58
59 enum test_result {
60         TEST_RESULT_NOT_RUN = 0,
61         TEST_RESULT_PASSED,
62         TEST_RESULT_FAILED
63 };
64
65 typedef DBusMessage *(*display_text_cb_t)(DBusMessage *msg, const char *text,
66                                                 unsigned char icon_id,
67                                                 gboolean urgent);
68 typedef void (*terminal_response_func)(const unsigned char *pdu,
69                                         unsigned int len);
70
71 struct test {
72         char *name;
73         char *method;
74         unsigned char *req_pdu;
75         unsigned int req_len;
76         unsigned char *rsp_pdu;
77         unsigned int rsp_len;
78         void *agent_func;
79         terminal_response_func tr_func;
80         enum test_result result;
81 };
82
83 static GMainLoop *main_loop = NULL;
84 static volatile sig_atomic_t __terminated = 0;
85 GList *tests = NULL;
86 GList *cur_test = NULL;
87
88 /* DBus related */
89 static DBusConnection *conn;
90 static gboolean ofono_running = FALSE;
91 static guint modem_changed_watch;
92 enum test_state state;
93 DBusMessage *pending = NULL;
94
95 /* Emulator setup */
96 static guint server_watch;
97 static GAtServer *emulator;
98
99 /* Emulated modem state variables */
100 static int modem_mode = 0;
101
102 void __stktest_test_next();
103 void __stktest_test_finish(gboolean successful);
104 static gboolean create_tcp(void);
105
106 #define STKTEST_AGENT_ASSERT(expr)                                      \
107         do {                                                            \
108                 if (!(expr)) {                                          \
109                         g_printerr("Assertion Failed %s:%d %s\n",       \
110                                         __FILE__, __LINE__, #expr);     \
111                         __stktest_test_finish(FALSE);                   \
112                         return stktest_error_failed(msg);               \
113                 }                                                       \
114         } while (0)
115
116 #define STKTEST_RESPONSE_ASSERT(expect_pdu, expect_pdu_len,             \
117                                 got_pdu, got_pdu_len)                   \
118         do {                                                            \
119                 if ((expect_pdu_len) != (got_pdu_len)) {                \
120                         g_printerr("Assertion Failed %s:%d"             \
121                                         " Wrong response len"           \
122                                         " want: %d, got: %d\n",         \
123                                         __FILE__, __LINE__,             \
124                                         expect_pdu_len, got_pdu_len);   \
125                         __stktest_test_finish(FALSE);                   \
126                         return;                                         \
127                 }                                                       \
128                                                                         \
129                 if (memcmp(expect_pdu, got_pdu, expect_pdu_len) != 0) { \
130                         g_printerr("Assertion Failed %s:%d"             \
131                                         "Wrong response\n",             \
132                                         __FILE__, __LINE__);            \
133                         __stktest_test_finish(FALSE);                   \
134                         return;                                         \
135                 }                                                       \
136         } while (0)
137
138 static const char *to_hex(const unsigned char *data, unsigned int len)
139 {
140         static char buf[512+1];
141         unsigned int i;
142
143         for (i = 0; i < len; i++)
144                 sprintf(buf + i * 2, "%02hhX", data[i]);
145
146         buf[i*2] = '\0';
147
148         return buf;
149 }
150
151 static void send_proactive_command(const unsigned char *pdu, unsigned int len)
152 {
153         char buf[1024];
154
155         sprintf(buf, "+CUSATP: %s", to_hex(pdu, len));
156         g_at_server_send_unsolicited(emulator, buf);
157 }
158
159 static DBusMessage *stktest_error_invalid_args(DBusMessage *msg)
160 {
161         return g_dbus_create_error(msg, STKTEST_ERROR ".InvalidArguments",
162                                         "Invalid arguments provided");
163 }
164
165 static DBusMessage *stktest_error_failed(DBusMessage *msg)
166 {
167         return g_dbus_create_error(msg, STKTEST_ERROR ".Failed",
168                                         "Operation failed");
169 }
170
171 static DBusMessage *stktest_error_end_session(DBusMessage *msg)
172 {
173         return g_dbus_create_error(msg, OFONO_ERROR ".EndSession",
174                                         "End Session Request");
175 }
176
177 static DBusMessage *stktest_error_go_back(DBusMessage *msg)
178 {
179         return g_dbus_create_error(msg, OFONO_ERROR ".GoBack",
180                                         "Go Back Request");
181 }
182
183 static DBusMessage *stktest_error_busy(DBusMessage *msg)
184 {
185         return g_dbus_create_error(msg, OFONO_ERROR ".Busy",
186                                         "UI Busy");
187 }
188
189 static DBusMessage *agent_release(DBusConnection *conn, DBusMessage *msg,
190                                         void *data)
191 {
192         g_print("Got Release\n");
193
194         if (pending) {
195                 dbus_message_unref(pending);
196                 pending = NULL;
197         }
198
199         return dbus_message_new_method_return(msg);
200 }
201
202 static DBusMessage *agent_cancel(DBusConnection *conn, DBusMessage *msg,
203                                         void *data)
204 {
205         if (pending) {
206                 dbus_message_unref(pending);
207                 pending = NULL;
208         }
209
210         return NULL;
211 }
212
213 static DBusMessage *agent_display_text(DBusConnection *conn, DBusMessage *msg,
214                                         void *data)
215 {
216         const char *text;
217         unsigned char icon_id;
218         dbus_bool_t urgent;
219         struct test *test;
220         display_text_cb_t func;
221
222         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &text,
223                                                 DBUS_TYPE_BYTE, &icon_id,
224                                                 DBUS_TYPE_BOOLEAN, &urgent,
225                                                 DBUS_TYPE_INVALID) == FALSE)
226                 return stktest_error_invalid_args(msg);
227
228         if (cur_test == NULL)
229                 return stktest_error_failed(msg);
230
231         test = cur_test->data;
232         func = test->agent_func;
233
234         if (strcmp(test->method, "DisplayText")) {
235                 g_printerr("Wrong method called!\n");
236                 __stktest_test_finish(FALSE);
237                 return stktest_error_failed(msg);
238         }
239
240         if (func == NULL) {
241                 g_printerr("DisplayText not expected to be called");
242                 __stktest_test_finish(FALSE);
243                 return stktest_error_failed(msg);
244         }
245
246         return func(msg, text, icon_id, urgent);
247 }
248
249 static void server_debug(const char *str, void *data)
250 {
251         g_print("%s: %s\n", (char *) data, str);
252 }
253
254 static void cgmi_cb(GAtServer *server, GAtServerRequestType type,
255                         GAtResult *cmd, gpointer user)
256 {
257         switch (type) {
258         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
259                 g_at_server_send_info(server, "oFono", TRUE);
260                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
261                 break;
262         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
263                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
264                 break;
265         default:
266                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
267         };
268 }
269
270 static void cgmm_cb(GAtServer *server, GAtServerRequestType type,
271                         GAtResult *cmd, gpointer user)
272 {
273         switch (type) {
274         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
275                 g_at_server_send_info(server, "oFono pre-1.0", TRUE);
276                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
277                 break;
278         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
279                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
280                 break;
281         default:
282                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
283         };
284 }
285
286 static void cgmr_cb(GAtServer *server, GAtServerRequestType type,
287                         GAtResult *cmd, gpointer user)
288 {
289         char buf[256];
290
291         switch (type) {
292         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
293                 sprintf(buf, "oFono pre-1.0 version: %s", VERSION);
294                 g_at_server_send_info(server, buf, TRUE);
295                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
296                 break;
297         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
298                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
299                 break;
300         default:
301                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
302         };
303 }
304
305 static void cgsn_cb(GAtServer *server, GAtServerRequestType type,
306                         GAtResult *cmd, gpointer user)
307 {
308         switch (type) {
309         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
310                 g_at_server_send_info(server, "123456789", TRUE);
311                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
312                 break;
313         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
314                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
315                 break;
316         default:
317                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
318         };
319 }
320
321 static gboolean send_ok(gpointer user)
322 {
323         GAtServer *server = user;
324
325         g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
326
327         return FALSE;
328 }
329
330 static void cfun_cb(GAtServer *server, GAtServerRequestType type,
331                         GAtResult *cmd, gpointer user)
332 {
333         char buf[12];
334
335         switch (type) {
336         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
337                 g_at_server_send_info(server, "+CFUN: (0-1,4)", TRUE);
338                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
339                 break;
340         case G_AT_SERVER_REQUEST_TYPE_QUERY:
341                 snprintf(buf, sizeof(buf), "+CFUN: %d", modem_mode);
342                 g_at_server_send_info(server, buf, TRUE);
343                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
344                 break;
345         case G_AT_SERVER_REQUEST_TYPE_SET:
346         {
347                 GAtResultIter iter;
348                 int mode;
349
350                 g_at_result_iter_init(&iter, cmd);
351                 g_at_result_iter_next(&iter, "");
352
353                 if (g_at_result_iter_next_number(&iter, &mode) == FALSE)
354                         goto error;
355
356                 if (mode != 0 && mode != 1)
357                         goto error;
358
359                 if (modem_mode == mode) {
360                         g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
361                         break;
362                 }
363
364                 modem_mode = mode;
365                 g_timeout_add_seconds(1, send_ok, server);
366                 break;
367         }
368         default:
369                 goto error;
370         };
371
372         return;
373
374 error:
375         g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
376 }
377
378 static void cusatt_cb(GAtServer *server, GAtServerRequestType type,
379                         GAtResult *cmd, gpointer user)
380 {
381         switch (type) {
382         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
383                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
384                 break;
385         case G_AT_SERVER_REQUEST_TYPE_QUERY:
386                 g_at_server_send_ext_final(server, "+CME ERROR: 4");
387                 break;
388         case G_AT_SERVER_REQUEST_TYPE_SET:
389         {
390                 GAtResultIter iter;
391                 const unsigned char *pdu;
392                 int len;
393                 struct test *test;
394                 terminal_response_func func;
395
396                 g_at_result_iter_init(&iter, cmd);
397                 g_at_result_iter_next(&iter, "");
398
399                 if (g_at_result_iter_next_hexstring(&iter, &pdu, &len) == FALSE)
400                         goto error;
401
402                 if (cur_test == NULL)
403                         goto error;
404
405                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
406
407                 test = cur_test->data;
408                 func = test->tr_func;
409                 func(pdu, len);
410                 break;
411         }
412         default:
413                 goto error;
414         };
415
416         return;
417
418 error:
419         g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
420 }
421
422 static void listen_again(gpointer user_data)
423 {
424         g_at_server_unref(emulator);
425         emulator = NULL;
426
427         if (create_tcp() == TRUE)
428                 return;
429
430         g_print("Error listening to socket\n");
431         g_main_loop_quit(main_loop);
432 }
433
434 static void setup_emulator(GAtServer *server)
435 {
436         g_at_server_set_debug(server, server_debug, "Server");
437
438         g_at_server_register(server, "+CGMI", cgmi_cb, NULL, NULL);
439         g_at_server_register(server, "+CGMM", cgmm_cb, NULL, NULL);
440         g_at_server_register(server, "+CGMR", cgmr_cb, NULL, NULL);
441         g_at_server_register(server, "+CGSN", cgsn_cb, NULL, NULL);
442         g_at_server_register(server, "+CFUN", cfun_cb, NULL, NULL);
443         g_at_server_register(server, "+CUSATT", cusatt_cb, NULL, NULL);
444
445         g_at_server_set_disconnect_function(server, listen_again, NULL);
446 }
447
448 static gboolean on_socket_connected(GIOChannel *chan, GIOCondition cond,
449                                                         gpointer user)
450 {
451         struct sockaddr saddr;
452         unsigned int len = sizeof(saddr);
453         int fd;
454         GIOChannel *client_io = NULL;
455
456         if (cond != G_IO_IN)
457                 goto error;
458
459         fd = accept(g_io_channel_unix_get_fd(chan), &saddr, &len);
460         if (fd == -1)
461                 goto error;
462
463         client_io = g_io_channel_unix_new(fd);
464
465         emulator = g_at_server_new(client_io);
466         g_at_server_set_echo(emulator, FALSE);
467         g_io_channel_unref(client_io);
468
469         if (emulator == NULL)
470                 goto error;
471
472         setup_emulator(emulator);
473
474 error:
475         server_watch = 0;
476         return FALSE;
477 }
478
479 static gboolean create_tcp(void)
480 {
481         struct sockaddr_in addr;
482         int sk;
483         int reuseaddr = 1;
484         GIOChannel *server_io;
485
486         sk = socket(PF_INET, SOCK_STREAM, 0);
487         if (sk < 0) {
488                 g_print("Can't create tcp/ip socket: %s (%d)\n",
489                                                 strerror(errno), errno);
490                 return FALSE;
491         }
492
493         memset(&addr, 0, sizeof(addr));
494
495         addr.sin_family = AF_INET;
496         addr.sin_addr.s_addr = INADDR_ANY;
497         addr.sin_port = htons(LISTEN_PORT);
498
499         setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
500         if (bind(sk, (struct sockaddr *) &addr, sizeof(struct sockaddr)) < 0) {
501                 g_print("Can't bind socket: %s (%d)", strerror(errno), errno);
502                 close(sk);
503                 return FALSE;
504         }
505
506         if (listen(sk, 1) < 0) {
507                 g_print("Can't listen on socket: %s (%d)",
508                                                 strerror(errno), errno);
509                 close(sk);
510                 return FALSE;
511         }
512
513         g_print("new tcp is created at tcp port %d\n", LISTEN_PORT);
514
515         server_io = g_io_channel_unix_new(sk);
516         g_io_channel_set_close_on_unref(server_io, TRUE);
517
518         server_watch = g_io_add_watch_full(server_io,
519                                 G_PRIORITY_DEFAULT,
520                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
521                                 on_socket_connected, NULL, NULL);
522
523         g_io_channel_unref(server_io);
524
525         return TRUE;
526 }
527
528 static gboolean has_stk_interface(DBusMessageIter *iter)
529 {
530         DBusMessageIter entry;
531
532         dbus_message_iter_recurse(iter, &entry);
533
534         while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
535                 const char *interface;
536
537                 dbus_message_iter_get_basic(&entry, &interface);
538
539                 if (g_str_equal(interface, OFONO_STK_INTERFACE) == TRUE)
540                         return TRUE;
541
542                 dbus_message_iter_next(&entry);
543         }
544
545         return FALSE;
546 }
547
548 static int send_with_reply(const char *path, const char *interface,
549                                 const char *method, DBusPendingCall **call,
550                                 DBusPendingCallNotifyFunction cb,
551                                 void *user_data, DBusFreeFunction free_func,
552                                 int timeout, int type, ...)
553 {
554         DBusMessage *msg;
555         DBusPendingCall *c;
556         va_list args;
557         int err;
558
559         msg = dbus_message_new_method_call(OFONO_SERVICE, path,
560                                                 interface, method);
561         if (msg == NULL) {
562                 g_printerr("Unable to allocate new D-Bus %s message\n", method);
563                 err = -ENOMEM;
564                 goto fail;
565         }
566
567         va_start(args, type);
568
569         if (!dbus_message_append_args_valist(msg, type, args)) {
570                 va_end(args);
571                 err = -EIO;
572                 goto fail;
573         }
574
575         va_end(args);
576
577         if (timeout > 0)
578                 timeout *= 1000;
579
580         if (!dbus_connection_send_with_reply(conn, msg, &c, timeout)) {
581                 g_printerr("Sending %s failed\n", method);
582                 err = -EIO;
583                 goto fail;
584         }
585
586         if (call != NULL)
587                 *call = c;
588
589         dbus_pending_call_set_notify(c, cb, user_data, free_func);
590         dbus_pending_call_unref(c);
591
592         dbus_message_unref(msg);
593
594         return 0;
595
596 fail:
597         if (free_func && user_data)
598                 free_func(user_data);
599
600         if (msg)
601                 dbus_message_unref(msg);
602
603         return err;
604 }
605
606 static void set_property_reply(DBusPendingCall *call, void *user_data)
607 {
608         DBusMessage *reply = dbus_pending_call_steal_reply(call);
609         DBusError err;
610
611         dbus_error_init(&err);
612
613         if (dbus_set_error_from_message(&err, reply) == TRUE) {
614                 g_printerr("%s: %s\n", err.name, err.message);
615                 dbus_error_free(&err);
616         }
617
618         dbus_message_unref(reply);
619 }
620
621 static int set_property(const char *path, const char *interface,
622                         const char *key, int type, const void *val,
623                         DBusPendingCallNotifyFunction notify,
624                         gpointer user_data,
625                         DBusFreeFunction destroy)
626 {
627         DBusMessage *msg;
628         DBusMessageIter iter, value;
629         DBusPendingCall *call;
630         const char *signature;
631
632         msg = dbus_message_new_method_call(OFONO_SERVICE, path, interface,
633                                                 "SetProperty");
634         if (msg == NULL)
635                 return -ENOMEM;
636
637         dbus_message_set_auto_start(msg, FALSE);
638
639         dbus_message_iter_init_append(msg, &iter);
640
641         dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key);
642
643         switch (type) {
644         case DBUS_TYPE_BOOLEAN:
645                 signature = DBUS_TYPE_BOOLEAN_AS_STRING;
646                 break;
647         default:
648                 dbus_message_unref(msg);
649                 return -EINVAL;
650         }
651
652         dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT,
653                                                         signature, &value);
654         dbus_message_iter_append_basic(&value, type, val);
655         dbus_message_iter_close_container(&iter, &value);
656
657         if (dbus_connection_send_with_reply(conn, msg, &call, -1) == FALSE) {
658                 dbus_message_unref(msg);
659                 return -EIO;
660         }
661
662         dbus_message_unref(msg);
663
664         if (call == NULL)
665                 return -EINVAL;
666
667         dbus_pending_call_set_notify(call, notify, user_data, destroy);
668
669         dbus_pending_call_unref(call);
670
671         return 0;
672 }
673
674 static void register_agent_reply(DBusPendingCall *call, void *user_data)
675 {
676         DBusMessage *reply = dbus_pending_call_steal_reply(call);
677         DBusError err;
678         struct test *test;
679
680         dbus_error_init(&err);
681
682         if (dbus_set_error_from_message(&err, reply) == TRUE) {
683                 g_printerr("%s: %s\n", err.name, err.message);
684                 dbus_error_free(&err);
685         }
686
687         dbus_message_unref(reply);
688
689         state = TEST_STATE_RUNNING;
690         test = cur_test->data;
691         send_proactive_command(test->req_pdu, test->req_len);
692 }
693
694 static void register_agent()
695 {
696         const char *path = "/default";
697         int status;
698
699         g_print("Gained STK interface, registering agent...\n");
700
701         status = send_with_reply(STKTEST_PATH, OFONO_STK_INTERFACE,
702                                         "RegisterAgent", NULL,
703                                         register_agent_reply, NULL, NULL, 1,
704                                         DBUS_TYPE_OBJECT_PATH, &path,
705                                         DBUS_TYPE_INVALID);
706
707         if (status < 0) {
708                 g_printerr("Unable to register agent with oFono\n");
709                 g_main_loop_quit(main_loop);
710                 return;
711         }
712
713         state = TEST_STATE_REGISTERING_AGENT;
714 }
715
716 static gboolean modem_changed(DBusConnection *conn,
717                                 DBusMessage *msg, void *user_data)
718 {
719         DBusMessageIter iter, value;
720         const char *path, *key;
721         gboolean has_stk;
722
723         if (dbus_message_iter_init(msg, &iter) == FALSE)
724                 return TRUE;
725
726         path = dbus_message_get_path(msg);
727
728         if (g_str_equal(STKTEST_PATH, path) == FALSE)
729                 return TRUE;
730
731         dbus_message_iter_get_basic(&iter, &key);
732
733         dbus_message_iter_next(&iter);
734         dbus_message_iter_recurse(&iter, &value);
735
736         if (g_str_equal(key, "Interfaces") == FALSE)
737                 return TRUE;
738
739         has_stk = has_stk_interface(&value);
740
741         switch (state) {
742         case TEST_STATE_POWERING_UP:
743                 if (has_stk)
744                         register_agent();
745                 break;
746         case TEST_STATE_REGISTERING_AGENT:
747         case TEST_STATE_RUNNING:
748                 if (has_stk == FALSE)
749                         g_printerr("Unexpectedly lost STK interface\n");
750                 /* Fall through */
751         case TEST_STATE_POWERING_DOWN:
752                 break;
753         };
754
755         return TRUE;
756 }
757
758 static void powerup(void)
759 {
760         dbus_bool_t powered = TRUE;
761
762         state = TEST_STATE_POWERING_UP;
763         set_property(STKTEST_PATH, OFONO_MODEM_INTERFACE, "Powered",
764                         DBUS_TYPE_BOOLEAN, &powered,
765                         set_property_reply, NULL, NULL);
766 }
767
768 static void get_modems_reply(DBusPendingCall *call, void *user_data)
769 {
770         DBusMessage *reply = dbus_pending_call_steal_reply(call);
771         DBusMessageIter iter, list;
772         DBusError err;
773         gboolean found = FALSE;
774
775         dbus_error_init(&err);
776
777         if (dbus_set_error_from_message(&err, reply) == TRUE) {
778                 g_printerr("%s: %s\n", err.name, err.message);
779                 dbus_error_free(&err);
780                 goto done;
781         }
782
783         if (dbus_message_has_signature(reply, "a(oa{sv})") == FALSE)
784                 goto done;
785
786         if (dbus_message_iter_init(reply, &iter) == FALSE)
787                 goto done;
788
789         dbus_message_iter_recurse(&iter, &list);
790
791         while (dbus_message_iter_get_arg_type(&list) == DBUS_TYPE_STRUCT) {
792                 DBusMessageIter entry;
793                 const char *path;
794
795                 dbus_message_iter_recurse(&list, &entry);
796                 dbus_message_iter_get_basic(&entry, &path);
797
798                 if (g_str_equal(path, STKTEST_PATH))
799                         found = TRUE;
800
801                 dbus_message_iter_next(&list);
802         }
803
804 done:
805         dbus_message_unref(reply);
806
807         if (found == FALSE) {
808                 g_printerr("STK Test modem not found\n");
809                 g_main_loop_quit(main_loop);
810                 return;
811         }
812
813         g_print("Test modem found\n");
814
815         modem_changed_watch = g_dbus_add_signal_watch(conn, OFONO_SERVICE,
816                                                         STKTEST_PATH,
817                                                         OFONO_MODEM_INTERFACE,
818                                                         "PropertyChanged",
819                                                         modem_changed,
820                                                         NULL, NULL);
821
822         if (create_tcp() == FALSE) {
823                 g_printerr("Unable to listen on modem emulator socket\n");
824                 g_main_loop_quit(main_loop);
825         }
826
827         __stktest_test_next();
828 }
829
830 static int get_modems(DBusConnection *conn)
831 {
832         DBusMessage *msg;
833         DBusPendingCall *call;
834
835         msg = dbus_message_new_method_call(OFONO_SERVICE, "/",
836                                         OFONO_MANAGER_INTERFACE, "GetModems");
837         if (msg == NULL)
838                 return -ENOMEM;
839
840         dbus_message_set_auto_start(msg, FALSE);
841
842         g_print("getting modems\n");
843
844         if (dbus_connection_send_with_reply(conn, msg, &call, -1) == FALSE) {
845                 dbus_message_unref(msg);
846                 return -EIO;
847         }
848
849         dbus_message_unref(msg);
850
851         if (call == NULL)
852                 return -EINVAL;
853
854         dbus_pending_call_set_notify(call, get_modems_reply, conn, NULL);
855
856         dbus_pending_call_unref(call);
857
858         return 0;
859 }
860
861 static const GDBusMethodTable agent_methods[] = {
862         { GDBUS_METHOD("Release", NULL, NULL, agent_release) },
863         { GDBUS_ASYNC_METHOD("DisplayText",
864                 GDBUS_ARGS({ "text", "s" }, { "icon_id", "y" },
865                                 { "urgent", "b" }), NULL,
866                                 agent_display_text) },
867         { GDBUS_NOREPLY_METHOD("Cancel", NULL, NULL, agent_cancel) },
868         { },
869 };
870
871 static void ofono_connect(DBusConnection *conn, void *user_data)
872 {
873         g_print("starting telephony interface\n");
874
875         if (!g_dbus_register_interface(conn, "/default",
876                                         OFONO_STKAGENT_INTERFACE,
877                                         agent_methods, NULL, NULL,
878                                         NULL, NULL)) {
879                 g_printerr("Unable to register local agent");
880                 g_main_loop_quit(main_loop);
881         }
882
883         ofono_running = TRUE;
884         get_modems(conn);
885 }
886
887 static void ofono_disconnect(DBusConnection *conn, void *user_data)
888 {
889         g_print("stopping telephony interface\n");
890
891         g_dbus_unregister_interface(conn, "/default", OFONO_STKAGENT_INTERFACE);
892
893         ofono_running = FALSE;
894
895         g_dbus_remove_watch(conn, modem_changed_watch);
896         modem_changed_watch = 0;
897
898         if (server_watch) {
899                 g_source_remove(server_watch);
900                 server_watch = 0;
901         }
902
903         g_at_server_unref(emulator);
904         emulator = NULL;
905 }
906
907 static void sig_term(int sig)
908 {
909         if (__terminated > 0)
910                 return;
911
912         __terminated = 1;
913
914         g_print("Terminating\n");
915
916         g_main_loop_quit(main_loop);
917 }
918
919 static void disconnect_callback(DBusConnection *conn, void *user_data)
920 {
921         g_printerr("D-Bus disconnect\n");
922
923         g_main_loop_quit(main_loop);
924 }
925
926 static gboolean end_session_and_finish(gpointer user_data)
927 {
928         g_at_server_send_unsolicited(emulator, "+CUSATEND");
929         __stktest_test_finish(TRUE);
930
931         return FALSE;
932 }
933
934 static void expect_response(const unsigned char *pdu, unsigned int len)
935 {
936         struct test *test = cur_test->data;
937
938         STKTEST_RESPONSE_ASSERT(test->rsp_pdu, test->rsp_len, pdu, len);
939
940         g_idle_add(end_session_and_finish, NULL);
941 }
942
943 static DBusMessage *test_display_text_11(DBusMessage *msg,
944                                                 const char *text,
945                                                 unsigned char icon_id,
946                                                 gboolean urgent)
947 {
948         STKTEST_AGENT_ASSERT(g_str_equal(text, "Toolkit Test 1"));
949         STKTEST_AGENT_ASSERT(icon_id == 0);
950         STKTEST_AGENT_ASSERT(urgent == FALSE);
951
952         return dbus_message_new_method_return(msg);
953 }
954
955 static DBusMessage *test_display_text_12(DBusMessage *msg,
956                                                 const char *text,
957                                                 unsigned char icon_id,
958                                                 gboolean urgent)
959 {
960         STKTEST_AGENT_ASSERT(g_str_equal(text, "Toolkit Test 1"));
961         STKTEST_AGENT_ASSERT(icon_id == 0);
962         STKTEST_AGENT_ASSERT(urgent == FALSE);
963
964         return stktest_error_busy(msg);
965 }
966
967 static DBusMessage *test_display_text_13(DBusMessage *msg,
968                                                 const char *text,
969                                                 unsigned char icon_id,
970                                                 gboolean urgent)
971 {
972         STKTEST_AGENT_ASSERT(g_str_equal(text, "Toolkit Test 2"));
973         STKTEST_AGENT_ASSERT(icon_id == 0);
974         STKTEST_AGENT_ASSERT(urgent == TRUE);
975
976         return dbus_message_new_method_return(msg);
977 }
978
979 static DBusMessage *test_display_text_14(DBusMessage *msg,
980                                                 const char *text,
981                                                 unsigned char icon_id,
982                                                 gboolean urgent)
983 {
984         STKTEST_AGENT_ASSERT(g_str_equal(text, "Toolkit Test 3"));
985         STKTEST_AGENT_ASSERT(icon_id == 0);
986         STKTEST_AGENT_ASSERT(urgent == FALSE);
987
988         return dbus_message_new_method_return(msg);
989 }
990
991 static DBusMessage *test_display_text_15(DBusMessage *msg,
992                                                 const char *text,
993                                                 unsigned char icon_id,
994                                                 gboolean urgent)
995 {
996         STKTEST_AGENT_ASSERT(g_str_equal(text, "Toolkit Test 4"));
997         STKTEST_AGENT_ASSERT(icon_id == 0);
998         STKTEST_AGENT_ASSERT(urgent == FALSE);
999
1000         pending = dbus_message_ref(msg);
1001
1002         return NULL;
1003 }
1004
1005 static DBusMessage *test_display_text_16(DBusMessage *msg,
1006                                                 const char *text,
1007                                                 unsigned char icon_id,
1008                                                 gboolean urgent)
1009 {
1010         STKTEST_AGENT_ASSERT(g_str_equal(text, "This command instructs the ME"
1011                                                 " to display a text message. "
1012                                                 "It allows the SIM to define "
1013                                                 "the priority of that message, "
1014                                                 "and the text string format. "
1015                                                 "Two types of prio"));
1016         STKTEST_AGENT_ASSERT(icon_id == 0);
1017         STKTEST_AGENT_ASSERT(urgent == FALSE);
1018
1019         return dbus_message_new_method_return(msg);
1020 }
1021
1022 static DBusMessage *test_display_text_17(DBusMessage *msg,
1023                                                 const char *text,
1024                                                 unsigned char icon_id,
1025                                                 gboolean urgent)
1026 {
1027         /* oFono gives rich text formatting in HTML */
1028         STKTEST_AGENT_ASSERT(g_str_equal(text, "&lt;GO-BACKWARDS&gt;"));
1029         STKTEST_AGENT_ASSERT(icon_id == 0);
1030         STKTEST_AGENT_ASSERT(urgent == FALSE);
1031
1032         return stktest_error_go_back(msg);
1033 }
1034
1035 static DBusMessage *test_display_text_18(DBusMessage *msg,
1036                                                 const char *text,
1037                                                 unsigned char icon_id,
1038                                                 gboolean urgent)
1039 {
1040         /* oFono gives rich text formatting in HTML */
1041         STKTEST_AGENT_ASSERT(g_str_equal(text, "&lt;ABORT&gt;"));
1042         STKTEST_AGENT_ASSERT(icon_id == 0);
1043         STKTEST_AGENT_ASSERT(urgent == FALSE);
1044
1045         return stktest_error_end_session(msg);
1046 }
1047
1048 static void power_down_reply(DBusPendingCall *call, void *user_data)
1049 {
1050         __stktest_test_next();
1051 }
1052
1053 void __stktest_test_finish(gboolean successful)
1054 {
1055         struct test *test = cur_test->data;
1056         dbus_bool_t powered = FALSE;
1057
1058         test->result = successful ? TEST_RESULT_PASSED : TEST_RESULT_FAILED;
1059
1060         state = TEST_STATE_POWERING_DOWN;
1061         set_property(STKTEST_PATH, OFONO_MODEM_INTERFACE, "Powered",
1062                         DBUS_TYPE_BOOLEAN, &powered,
1063                         power_down_reply, NULL, NULL);
1064 }
1065
1066 void __stktest_test_next()
1067 {
1068         if (cur_test == NULL)
1069                 cur_test = tests;
1070         else
1071                 cur_test = cur_test->next;
1072
1073         if (cur_test == NULL)
1074                 g_main_loop_quit(main_loop);
1075
1076         powerup();
1077 }
1078
1079 static void stktest_add_test(const char *name, const char *method,
1080                                 const unsigned char *req, unsigned int req_len,
1081                                 const unsigned char *rsp, unsigned int rsp_len,
1082                                 void *agent_func,
1083                                 terminal_response_func tr_func)
1084 {
1085         struct test *test = g_new0(struct test, 1);
1086
1087         test->name = g_strdup(name);
1088         test->method = g_strdup(method);
1089         test->req_pdu = g_memdup(req, req_len);
1090         test->req_len = req_len;
1091         test->rsp_pdu = g_memdup(rsp, rsp_len);
1092         test->rsp_len = rsp_len;
1093         test->agent_func = agent_func;
1094         test->tr_func = tr_func;
1095
1096         tests = g_list_append(tests, test);
1097 }
1098
1099 static void __stktest_test_init(void)
1100 {
1101         stktest_add_test("Display Text 1.1", "DisplayText",
1102                                 display_text_111, sizeof(display_text_111),
1103                                 display_text_response_111,
1104                                 sizeof(display_text_response_111),
1105                                 test_display_text_11, expect_response);
1106         stktest_add_test("Display Text 1.2", "DisplayText",
1107                                 display_text_111, sizeof(display_text_111),
1108                                 display_text_response_121,
1109                                 sizeof(display_text_response_121),
1110                                 test_display_text_12, expect_response);
1111         stktest_add_test("Display Text 1.3", "DisplayText",
1112                                 display_text_131, sizeof(display_text_131),
1113                                 display_text_response_131,
1114                                 sizeof(display_text_response_131),
1115                                 test_display_text_13, expect_response);
1116         stktest_add_test("Display Text 1.4", "DisplayText",
1117                                 display_text_141, sizeof(display_text_141),
1118                                 display_text_response_141,
1119                                 sizeof(display_text_response_141),
1120                                 test_display_text_14, expect_response);
1121         stktest_add_test("Display Text 1.5", "DisplayText",
1122                                 display_text_151, sizeof(display_text_151),
1123                                 display_text_response_151,
1124                                 sizeof(display_text_response_151),
1125                                 test_display_text_15, expect_response);
1126         stktest_add_test("Display Text 1.6", "DisplayText",
1127                                 display_text_161, sizeof(display_text_161),
1128                                 display_text_response_161,
1129                                 sizeof(display_text_response_161),
1130                                 test_display_text_16, expect_response);
1131         stktest_add_test("Display Text 1.7", "DisplayText",
1132                                 display_text_171, sizeof(display_text_171),
1133                                 display_text_response_171,
1134                                 sizeof(display_text_response_171),
1135                                 test_display_text_17, expect_response);
1136         stktest_add_test("Display Text 1.8", "DisplayText",
1137                                 display_text_181, sizeof(display_text_181),
1138                                 display_text_response_181,
1139                                 sizeof(display_text_response_181),
1140                                 test_display_text_18, expect_response);
1141 }
1142
1143 static void test_destroy(gpointer user_data)
1144 {
1145         struct test *test = user_data;
1146
1147         g_free(test->name);
1148         g_free(test->method);
1149         g_free(test->req_pdu);
1150         g_free(test->rsp_pdu);
1151
1152         g_free(test);
1153 }
1154
1155 static void __stktest_test_summarize(void)
1156 {
1157         GList *l;
1158
1159         g_print("\n\nTest Summary\n");
1160         g_print("============\n");
1161
1162         for (l = tests; l; l = l->next) {
1163                 struct test *test = l->data;
1164
1165                 g_print("%-60s", test->name);
1166
1167                 switch (test->result) {
1168                 case TEST_RESULT_NOT_RUN:
1169                         g_print("Not Run\n");
1170                         break;
1171                 case TEST_RESULT_PASSED:
1172                         g_print("Passed\n");
1173                         break;
1174                 case TEST_RESULT_FAILED:
1175                         g_print("Failed\n");
1176                 break;
1177                 }
1178         }
1179 }
1180
1181 static void __stktest_test_cleanup(void)
1182 {
1183         g_list_free_full(tests, test_destroy);
1184         tests = NULL;
1185         cur_test = NULL;
1186 }
1187
1188 static gboolean option_version = FALSE;
1189
1190 static GOptionEntry options[] = {
1191         { "version", 'v', 0, G_OPTION_ARG_NONE, &option_version,
1192                                 "Show version information and exit" },
1193         { NULL },
1194 };
1195
1196 int main(int argc, char **argv)
1197 {
1198         GOptionContext *context;
1199         GError *error = NULL;
1200         DBusError err;
1201         guint watch;
1202         struct sigaction sa;
1203
1204         context = g_option_context_new(NULL);
1205         g_option_context_add_main_entries(context, options, NULL);
1206
1207         if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
1208                 if (error != NULL) {
1209                         g_printerr("%s\n", error->message);
1210                         g_error_free(error);
1211                 } else
1212                         g_printerr("An unknown error occurred\n");
1213                 exit(1);
1214         }
1215
1216         g_option_context_free(context);
1217
1218         if (option_version == TRUE) {
1219                 printf("%s\n", VERSION);
1220                 exit(0);
1221         }
1222
1223         __stktest_test_init();
1224
1225         main_loop = g_main_loop_new(NULL, FALSE);
1226
1227         dbus_error_init(&err);
1228
1229         conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, &err);
1230         if (conn == NULL) {
1231                 if (dbus_error_is_set(&err) == TRUE) {
1232                         fprintf(stderr, "%s\n", err.message);
1233                         dbus_error_free(&err);
1234                 } else
1235                         fprintf(stderr, "Can't register with system bus\n");
1236                 exit(1);
1237         }
1238
1239         g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);
1240
1241         memset(&sa, 0, sizeof(sa));
1242         sa.sa_handler = sig_term;
1243         sigaction(SIGINT, &sa, NULL);
1244         sigaction(SIGTERM, &sa, NULL);
1245
1246         watch = g_dbus_add_service_watch(conn, OFONO_SERVICE,
1247                                 ofono_connect, ofono_disconnect, NULL, NULL);
1248
1249         g_main_loop_run(main_loop);
1250
1251         g_dbus_remove_watch(conn, watch);
1252
1253         if (ofono_running == TRUE)
1254                 ofono_disconnect(conn, NULL);
1255
1256         dbus_connection_unref(conn);
1257
1258         g_main_loop_unref(main_loop);
1259
1260         __stktest_test_summarize();
1261         __stktest_test_cleanup();
1262
1263         return 0;
1264 }