stktest: Fix error interface
[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 #define OFONO_SERVICE   "org.ofono"
40 #define STKTEST_PATH    "/stktest"
41 #define STKTEST_ERROR   "org.ofono.stktest.Error"
42 #define OFONO_MANAGER_INTERFACE         OFONO_SERVICE ".Manager"
43 #define OFONO_MODEM_INTERFACE           OFONO_SERVICE ".Modem"
44 #define OFONO_STK_INTERFACE             OFONO_SERVICE ".SimToolkit"
45 #define OFONO_STKAGENT_INTERFACE        OFONO_SERVICE ".SimToolkitAgent"
46
47 #define LISTEN_PORT     12765
48
49 enum test_state {
50         TEST_STATE_POWERING_UP = 1,
51         TEST_STATE_REGISTERING_AGENT,
52         TEST_STATE_RUNNING,
53         TEST_STATE_POWERING_DOWN,
54 };
55
56 static GMainLoop *main_loop = NULL;
57 static volatile sig_atomic_t __terminated = 0;
58
59 /* DBus related */
60 static DBusConnection *conn;
61 static gboolean ofono_running = FALSE;
62 static guint modem_changed_watch;
63 enum test_state state;
64
65 /* Emulator setup */
66 static guint server_watch;
67 static GAtServer *emulator;
68
69 /* Emulated modem state variables */
70 static int modem_mode = 0;
71
72 static gboolean create_tcp(void);
73
74 static const char *to_hex(const unsigned char *data, unsigned int len)
75 {
76         static char buf[512+1];
77         unsigned int i;
78
79         for (i = 0; i < len; i++)
80                 sprintf(buf + i * 2, "%02hhX", data[i]);
81
82         buf[i*2] = '\0';
83
84         return buf;
85 }
86
87 static void send_proactive_command(const unsigned char *pdu, unsigned int len)
88 {
89         char buf[1024];
90
91         sprintf(buf, "+CUSATP: %s", to_hex(pdu, len));
92         g_at_server_send_unsolicited(emulator, buf);
93 }
94
95 static DBusMessage *stktest_error_invalid_args(DBusMessage *msg)
96 {
97         return g_dbus_create_error(msg, STKTEST_ERROR ".InvalidArguments",
98                                         "Invalid arguments provided");
99 }
100
101 static DBusMessage *agent_release(DBusConnection *conn, DBusMessage *msg,
102                                         void *data)
103 {
104         g_print("Got Release");
105
106         return dbus_message_new_method_return(msg);
107 }
108
109 static DBusMessage *agent_display_text(DBusConnection *conn, DBusMessage *msg,
110                                         void *data)
111 {
112         const char *text;
113         unsigned char icon_id;
114         dbus_bool_t urgent;
115
116         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &text,
117                                                 DBUS_TYPE_BYTE, &icon_id,
118                                                 DBUS_TYPE_BOOLEAN, &urgent,
119                                                 DBUS_TYPE_INVALID) == FALSE)
120                 return stktest_error_invalid_args(msg);
121
122         g_print("Got DisplayText with: %s, %u, %d\n", text, icon_id, urgent);
123
124         return dbus_message_new_method_return(msg);
125 }
126
127 static void server_debug(const char *str, void *data)
128 {
129         g_print("%s: %s\n", (char *) data, str);
130 }
131
132 static void cgmi_cb(GAtServer *server, GAtServerRequestType type,
133                         GAtResult *cmd, gpointer user)
134 {
135         switch (type) {
136         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
137                 g_at_server_send_info(server, "oFono", TRUE);
138                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
139                 break;
140         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
141                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
142                 break;
143         default:
144                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
145         };
146 }
147
148 static void cgmm_cb(GAtServer *server, GAtServerRequestType type,
149                         GAtResult *cmd, gpointer user)
150 {
151         switch (type) {
152         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
153                 g_at_server_send_info(server, "oFono pre-1.0", TRUE);
154                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
155                 break;
156         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
157                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
158                 break;
159         default:
160                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
161         };
162 }
163
164 static void cgmr_cb(GAtServer *server, GAtServerRequestType type,
165                         GAtResult *cmd, gpointer user)
166 {
167         char buf[256];
168
169         switch (type) {
170         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
171                 sprintf(buf, "oFono pre-1.0 version: %s", VERSION);
172                 g_at_server_send_info(server, buf, TRUE);
173                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
174                 break;
175         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
176                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
177                 break;
178         default:
179                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
180         };
181 }
182
183 static void cgsn_cb(GAtServer *server, GAtServerRequestType type,
184                         GAtResult *cmd, gpointer user)
185 {
186         switch (type) {
187         case G_AT_SERVER_REQUEST_TYPE_COMMAND_ONLY:
188                 g_at_server_send_info(server, "123456789", TRUE);
189                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
190                 break;
191         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
192                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
193                 break;
194         default:
195                 g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
196         };
197 }
198
199 static gboolean send_ok(gpointer user)
200 {
201         GAtServer *server = user;
202
203         g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
204
205         return FALSE;
206 }
207
208 static void cfun_cb(GAtServer *server, GAtServerRequestType type,
209                         GAtResult *cmd, gpointer user)
210 {
211         char buf[12];
212
213         switch (type) {
214         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
215                 g_at_server_send_info(server, "+CFUN: (0-1,4)", TRUE);
216                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
217                 break;
218         case G_AT_SERVER_REQUEST_TYPE_QUERY:
219                 snprintf(buf, sizeof(buf), "+CFUN: %d", modem_mode);
220                 g_at_server_send_info(server, buf, TRUE);
221                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
222                 break;
223         case G_AT_SERVER_REQUEST_TYPE_SET:
224         {
225                 GAtResultIter iter;
226                 int mode;
227
228                 g_at_result_iter_init(&iter, cmd);
229                 g_at_result_iter_next(&iter, "");
230
231                 if (g_at_result_iter_next_number(&iter, &mode) == FALSE)
232                         goto error;
233
234                 if (mode != 0 && mode != 1)
235                         goto error;
236
237                 if (modem_mode == mode) {
238                         g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
239                         break;
240                 }
241
242                 modem_mode = mode;
243                 g_timeout_add_seconds(1, send_ok, server);
244                 break;
245         }
246         default:
247                 goto error;
248         };
249
250         return;
251
252 error:
253         g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
254 }
255
256 static void cusatt_cb(GAtServer *server, GAtServerRequestType type,
257                         GAtResult *cmd, gpointer user)
258 {
259         char buf[12];
260
261         switch (type) {
262         case G_AT_SERVER_REQUEST_TYPE_SUPPORT:
263                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
264                 break;
265         case G_AT_SERVER_REQUEST_TYPE_QUERY:
266                 g_at_server_send_ext_final(server, "+CME ERROR: 4");
267                 break;
268         case G_AT_SERVER_REQUEST_TYPE_SET:
269         {
270                 GAtResultIter iter;
271                 const unsigned char *pdu;
272                 int len;
273
274                 g_at_result_iter_init(&iter, cmd);
275                 g_at_result_iter_next(&iter, "");
276
277                 if (g_at_result_iter_next_hexstring(&iter, &pdu, &len) == FALSE)
278                         goto error;
279
280                 g_at_server_send_final(server, G_AT_SERVER_RESULT_OK);
281                 break;
282         }
283         default:
284                 goto error;
285         };
286
287         return;
288
289 error:
290         g_at_server_send_final(server, G_AT_SERVER_RESULT_ERROR);
291 }
292
293 static void listen_again(gpointer user_data)
294 {
295         if (create_tcp() == TRUE)
296                 return;
297
298         g_print("Error listening to socket\n");
299         g_main_loop_quit(main_loop);
300 }
301
302 static void setup_emulator(GAtServer *server)
303 {
304         g_at_server_set_debug(server, server_debug, "Server");
305
306         g_at_server_register(server, "+CGMI", cgmi_cb, NULL, NULL);
307         g_at_server_register(server, "+CGMM", cgmm_cb, NULL, NULL);
308         g_at_server_register(server, "+CGMR", cgmr_cb, NULL, NULL);
309         g_at_server_register(server, "+CGSN", cgsn_cb, NULL, NULL);
310         g_at_server_register(server, "+CFUN", cfun_cb, NULL, NULL);
311         g_at_server_register(server, "+CUSATT", cusatt_cb, NULL, NULL);
312
313         g_at_server_set_disconnect_function(server, listen_again, NULL);
314 }
315
316 static gboolean on_socket_connected(GIOChannel *chan, GIOCondition cond,
317                                                         gpointer user)
318 {
319         struct sockaddr saddr;
320         unsigned int len = sizeof(saddr);
321         int fd;
322         GIOChannel *client_io = NULL;
323
324         if (cond != G_IO_IN)
325                 goto error;
326
327         fd = accept(g_io_channel_unix_get_fd(chan), &saddr, &len);
328         if (fd == -1)
329                 goto error;
330
331         client_io = g_io_channel_unix_new(fd);
332
333         emulator = g_at_server_new(client_io);
334         g_at_server_set_echo(emulator, FALSE);
335         g_io_channel_unref(client_io);
336
337         if (emulator == NULL)
338                 goto error;
339
340         setup_emulator(emulator);
341
342 error:
343         server_watch = 0;
344         return FALSE;
345 }
346
347 static gboolean create_tcp(void)
348 {
349         struct sockaddr_in addr;
350         int sk;
351         int reuseaddr = 1;
352         GIOChannel *server_io;
353
354         sk = socket(PF_INET, SOCK_STREAM, 0);
355         if (sk < 0) {
356                 g_print("Can't create tcp/ip socket: %s (%d)\n",
357                                                 strerror(errno), errno);
358                 return FALSE;
359         }
360
361         memset(&addr, 0, sizeof(addr));
362
363         addr.sin_family = AF_INET;
364         addr.sin_addr.s_addr = INADDR_ANY;
365         addr.sin_port = htons(LISTEN_PORT);
366
367         setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
368         if (bind(sk, (struct sockaddr *) &addr, sizeof(struct sockaddr)) < 0) {
369                 g_print("Can't bind socket: %s (%d)", strerror(errno), errno);
370                 close(sk);
371                 return FALSE;
372         }
373
374         if (listen(sk, 1) < 0) {
375                 g_print("Can't listen on socket: %s (%d)",
376                                                 strerror(errno), errno);
377                 close(sk);
378                 return FALSE;
379         }
380
381         g_print("new tcp is created at tcp port %d\n", LISTEN_PORT);
382
383         server_io = g_io_channel_unix_new(sk);
384         g_io_channel_set_close_on_unref(server_io, TRUE);
385
386         server_watch = g_io_add_watch_full(server_io,
387                                 G_PRIORITY_DEFAULT,
388                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
389                                 on_socket_connected, NULL, NULL);
390
391         g_io_channel_unref(server_io);
392
393         return TRUE;
394 }
395
396 static gboolean has_stk_interface(DBusMessageIter *iter)
397 {
398         DBusMessageIter entry;
399
400         dbus_message_iter_recurse(iter, &entry);
401
402         while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
403                 const char *interface;
404
405                 dbus_message_iter_get_basic(&entry, &interface);
406
407                 if (g_str_equal(interface, OFONO_STK_INTERFACE) == TRUE)
408                         return TRUE;
409
410                 dbus_message_iter_next(&entry);
411         }
412
413         return FALSE;
414 }
415
416 static int send_with_reply(const char *path, const char *interface,
417                                 const char *method, DBusPendingCall **call,
418                                 DBusPendingCallNotifyFunction cb,
419                                 void *user_data, DBusFreeFunction free_func,
420                                 int timeout, int type, ...)
421 {
422         DBusMessage *msg;
423         DBusPendingCall *c;
424         va_list args;
425         int err;
426
427         msg = dbus_message_new_method_call(OFONO_SERVICE, path,
428                                                 interface, method);
429         if (msg == NULL) {
430                 g_printerr("Unable to allocate new D-Bus %s message\n", method);
431                 err = -ENOMEM;
432                 goto fail;
433         }
434
435         va_start(args, type);
436
437         if (!dbus_message_append_args_valist(msg, type, args)) {
438                 va_end(args);
439                 err = -EIO;
440                 goto fail;
441         }
442
443         va_end(args);
444
445         if (timeout > 0)
446                 timeout *= 1000;
447
448         if (!dbus_connection_send_with_reply(conn, msg, &c, timeout)) {
449                 g_printerr("Sending %s failed\n", method);
450                 err = -EIO;
451                 goto fail;
452         }
453
454         if (call != NULL)
455                 *call = c;
456
457         dbus_pending_call_set_notify(c, cb, user_data, free_func);
458         dbus_pending_call_unref(c);
459
460         dbus_message_unref(msg);
461
462         return 0;
463
464 fail:
465         if (free_func && user_data)
466                 free_func(user_data);
467
468         if (msg)
469                 dbus_message_unref(msg);
470
471         return err;
472 }
473
474 static void set_property_reply(DBusPendingCall *call, void *user_data)
475 {
476         DBusMessage *reply = dbus_pending_call_steal_reply(call);
477         DBusError err;
478
479         dbus_error_init(&err);
480
481         if (dbus_set_error_from_message(&err, reply) == TRUE) {
482                 g_printerr("%s: %s\n", err.name, err.message);
483                 dbus_error_free(&err);
484         }
485
486         dbus_message_unref(reply);
487 }
488
489 static int set_property(const char *path, const char *interface,
490                         const char *key, int type, const void *val,
491                         DBusPendingCallNotifyFunction notify,
492                         gpointer user_data,
493                         DBusFreeFunction destroy)
494 {
495         DBusMessage *msg;
496         DBusMessageIter iter, value;
497         DBusPendingCall *call;
498         const char *signature;
499
500         msg = dbus_message_new_method_call(OFONO_SERVICE, path, interface,
501                                                 "SetProperty");
502         if (msg == NULL)
503                 return -ENOMEM;
504
505         dbus_message_set_auto_start(msg, FALSE);
506
507         dbus_message_iter_init_append(msg, &iter);
508
509         dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key);
510
511         switch (type) {
512         case DBUS_TYPE_BOOLEAN:
513                 signature = DBUS_TYPE_BOOLEAN_AS_STRING;
514                 break;
515         default:
516                 dbus_message_unref(msg);
517                 return -EINVAL;
518         }
519
520         dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT,
521                                                         signature, &value);
522         dbus_message_iter_append_basic(&value, type, val);
523         dbus_message_iter_close_container(&iter, &value);
524
525         if (dbus_connection_send_with_reply(conn, msg, &call, -1) == FALSE) {
526                 dbus_message_unref(msg);
527                 return -EIO;
528         }
529
530         dbus_message_unref(msg);
531
532         if (call == NULL)
533                 return -EINVAL;
534
535         dbus_pending_call_set_notify(call, notify, user_data, destroy);
536
537         dbus_pending_call_unref(call);
538
539         return 0;
540 }
541
542 static void register_agent_reply(DBusPendingCall *call, void *user_data)
543 {
544         DBusMessage *reply = dbus_pending_call_steal_reply(call);
545         DBusError err;
546
547         dbus_error_init(&err);
548
549         if (dbus_set_error_from_message(&err, reply) == TRUE) {
550                 g_printerr("%s: %s\n", err.name, err.message);
551                 dbus_error_free(&err);
552         }
553
554         dbus_message_unref(reply);
555
556         state = TEST_STATE_RUNNING;
557 }
558
559 static void register_agent()
560 {
561         const char *path = "/default";
562         int status;
563
564         g_print("Gained STK interface, registering agent...\n");
565
566         status = send_with_reply(STKTEST_PATH, OFONO_STK_INTERFACE,
567                                         "RegisterAgent", NULL,
568                                         register_agent_reply, NULL, NULL, 1,
569                                         DBUS_TYPE_OBJECT_PATH, &path,
570                                         DBUS_TYPE_INVALID);
571
572         if (status < 0) {
573                 g_printerr("Unable to register agent with oFono\n");
574                 g_main_loop_quit(main_loop);
575                 return;
576         }
577
578         state = TEST_STATE_REGISTERING_AGENT;
579 }
580
581 static gboolean modem_changed(DBusConnection *conn,
582                                 DBusMessage *msg, void *user_data)
583 {
584         DBusMessageIter iter, value;
585         const char *path, *key;
586         gboolean has_stk;
587
588         if (dbus_message_iter_init(msg, &iter) == FALSE)
589                 return TRUE;
590
591         path = dbus_message_get_path(msg);
592
593         if (g_str_equal(STKTEST_PATH, path) == FALSE)
594                 return TRUE;
595
596         dbus_message_iter_get_basic(&iter, &key);
597
598         dbus_message_iter_next(&iter);
599         dbus_message_iter_recurse(&iter, &value);
600
601         if (g_str_equal(key, "Interfaces") == FALSE)
602                 return TRUE;
603
604         has_stk = has_stk_interface(&value);
605
606         switch (state) {
607         case TEST_STATE_POWERING_UP:
608                 if (has_stk)
609                         register_agent();
610                 break;
611         case TEST_STATE_REGISTERING_AGENT:
612         case TEST_STATE_RUNNING:
613                 if (has_stk == FALSE)
614                         g_printerr("Unexpectedly lost STK interface\n");
615                 /* Fall through */
616         case TEST_STATE_POWERING_DOWN:
617                 break;
618         };
619
620         return TRUE;
621 }
622
623 static void powerup(void)
624 {
625         dbus_bool_t powered = TRUE;
626
627         state = TEST_STATE_POWERING_UP;
628         set_property(STKTEST_PATH, OFONO_MODEM_INTERFACE, "Powered",
629                         DBUS_TYPE_BOOLEAN, &powered,
630                         set_property_reply, NULL, NULL);
631 }
632
633 static void get_modems_reply(DBusPendingCall *call, void *user_data)
634 {
635         DBusMessage *reply = dbus_pending_call_steal_reply(call);
636         DBusMessageIter iter, list;
637         DBusError err;
638         gboolean found = FALSE;
639
640         dbus_error_init(&err);
641
642         if (dbus_set_error_from_message(&err, reply) == TRUE) {
643                 g_printerr("%s: %s\n", err.name, err.message);
644                 dbus_error_free(&err);
645                 goto done;
646         }
647
648         if (dbus_message_has_signature(reply, "a(oa{sv})") == FALSE)
649                 goto done;
650
651         if (dbus_message_iter_init(reply, &iter) == FALSE)
652                 goto done;
653
654         dbus_message_iter_recurse(&iter, &list);
655
656         while (dbus_message_iter_get_arg_type(&list) == DBUS_TYPE_STRUCT) {
657                 DBusMessageIter entry;
658                 const char *path;
659
660                 dbus_message_iter_recurse(&list, &entry);
661                 dbus_message_iter_get_basic(&entry, &path);
662
663                 if (g_str_equal(path, STKTEST_PATH))
664                         found = TRUE;
665
666                 dbus_message_iter_next(&list);
667         }
668
669 done:
670         dbus_message_unref(reply);
671
672         if (found == FALSE) {
673                 g_printerr("STK Test modem not found\n");
674                 g_main_loop_quit(main_loop);
675                 return;
676         }
677
678         g_print("Test modem found\n");
679
680         modem_changed_watch = g_dbus_add_signal_watch(conn, OFONO_SERVICE,
681                                                         STKTEST_PATH,
682                                                         OFONO_MODEM_INTERFACE,
683                                                         "PropertyChanged",
684                                                         modem_changed,
685                                                         NULL, NULL);
686
687         if (create_tcp() == FALSE) {
688                 g_printerr("Unable to listen on modem emulator socket\n");
689                 g_main_loop_quit(main_loop);
690         }
691
692         powerup();
693 }
694
695 static int get_modems(DBusConnection *conn)
696 {
697         DBusMessage *msg;
698         DBusPendingCall *call;
699
700         msg = dbus_message_new_method_call(OFONO_SERVICE, "/",
701                                         OFONO_MANAGER_INTERFACE, "GetModems");
702         if (msg == NULL)
703                 return -ENOMEM;
704
705         dbus_message_set_auto_start(msg, FALSE);
706
707         g_print("getting modems\n");
708
709         if (dbus_connection_send_with_reply(conn, msg, &call, -1) == FALSE) {
710                 dbus_message_unref(msg);
711                 return -EIO;
712         }
713
714         dbus_message_unref(msg);
715
716         if (call == NULL)
717                 return -EINVAL;
718
719         dbus_pending_call_set_notify(call, get_modems_reply, conn, NULL);
720
721         dbus_pending_call_unref(call);
722
723         return 0;
724 }
725
726 static const GDBusMethodTable agent_methods[] = {
727         { GDBUS_METHOD("Release", NULL, NULL, agent_release) },
728         { GDBUS_METHOD("DisplayText",
729                 GDBUS_ARGS({ "text", "s" }, { "icon_id", "y" },
730                                 { "urgent", "b" }), NULL,
731                                 agent_display_text) },
732         { },
733 };
734
735 static void ofono_connect(DBusConnection *conn, void *user_data)
736 {
737         g_print("starting telephony interface\n");
738
739         if (!g_dbus_register_interface(conn, "/default",
740                                         OFONO_STKAGENT_INTERFACE,
741                                         agent_methods, NULL, NULL,
742                                         NULL, NULL)) {
743                 g_printerr("Unable to register local agent");
744                 g_main_loop_quit(main_loop);
745         }
746
747         ofono_running = TRUE;
748         get_modems(conn);
749 }
750
751 static void ofono_disconnect(DBusConnection *conn, void *user_data)
752 {
753         g_print("stopping telephony interface\n");
754
755         g_dbus_unregister_interface(conn, "/default", OFONO_STKAGENT_INTERFACE);
756
757         ofono_running = FALSE;
758
759         g_dbus_remove_watch(conn, modem_changed_watch);
760         modem_changed_watch = 0;
761
762         if (server_watch) {
763                 g_source_remove(server_watch);
764                 server_watch = 0;
765         }
766
767         g_at_server_unref(emulator);
768         emulator = NULL;
769 }
770
771 static void sig_term(int sig)
772 {
773         if (__terminated > 0)
774                 return;
775
776         __terminated = 1;
777
778         g_print("Terminating\n");
779
780         g_main_loop_quit(main_loop);
781 }
782
783 static void disconnect_callback(DBusConnection *conn, void *user_data)
784 {
785         g_printerr("D-Bus disconnect\n");
786
787         g_main_loop_quit(main_loop);
788 }
789
790 static gboolean option_version = FALSE;
791
792 static GOptionEntry options[] = {
793         { "version", 'v', 0, G_OPTION_ARG_NONE, &option_version,
794                                 "Show version information and exit" },
795         { NULL },
796 };
797
798 int main(int argc, char **argv)
799 {
800         GOptionContext *context;
801         GError *error = NULL;
802         DBusError err;
803         guint watch;
804         struct sigaction sa;
805
806         context = g_option_context_new(NULL);
807         g_option_context_add_main_entries(context, options, NULL);
808
809         if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
810                 if (error != NULL) {
811                         g_printerr("%s\n", error->message);
812                         g_error_free(error);
813                 } else
814                         g_printerr("An unknown error occurred\n");
815                 exit(1);
816         }
817
818         g_option_context_free(context);
819
820         if (option_version == TRUE) {
821                 printf("%s\n", VERSION);
822                 exit(0);
823         }
824
825         main_loop = g_main_loop_new(NULL, FALSE);
826
827         dbus_error_init(&err);
828
829         conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, &err);
830         if (conn == NULL) {
831                 if (dbus_error_is_set(&err) == TRUE) {
832                         fprintf(stderr, "%s\n", err.message);
833                         dbus_error_free(&err);
834                 } else
835                         fprintf(stderr, "Can't register with system bus\n");
836                 exit(1);
837         }
838
839         g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);
840
841         memset(&sa, 0, sizeof(sa));
842         sa.sa_handler = sig_term;
843         sigaction(SIGINT, &sa, NULL);
844         sigaction(SIGTERM, &sa, NULL);
845
846         watch = g_dbus_add_service_watch(conn, OFONO_SERVICE,
847                                 ofono_connect, ofono_disconnect, NULL, NULL);
848
849         g_main_loop_run(main_loop);
850
851         g_dbus_remove_watch(conn, watch);
852
853         if (ofono_running == TRUE)
854                 ofono_disconnect(conn, NULL);
855
856         dbus_connection_unref(conn);
857
858         g_main_loop_unref(main_loop);
859
860         return 0;
861 }