sktest: Turn off echo
[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"
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 static void listen_again(gpointer user_data)
293 {
294         if (create_tcp() == TRUE)
295                 return;
296
297         g_print("Error listening to socket\n");
298         g_main_loop_quit(main_loop);
299 }
300
301 static void setup_emulator(GAtServer *server)
302 {
303         g_at_server_set_debug(server, server_debug, "Server");
304
305         g_at_server_register(server, "+CGMI", cgmi_cb, NULL, NULL);
306         g_at_server_register(server, "+CGMM", cgmm_cb, NULL, NULL);
307         g_at_server_register(server, "+CGMR", cgmr_cb, NULL, NULL);
308         g_at_server_register(server, "+CGSN", cgsn_cb, NULL, NULL);
309         g_at_server_register(server, "+CFUN", cfun_cb, NULL, NULL);
310         g_at_server_register(server, "+CUSATT", cusatt_cb, NULL, NULL);
311
312         g_at_server_set_disconnect_function(server, listen_again, NULL);
313 }
314
315 static gboolean on_socket_connected(GIOChannel *chan, GIOCondition cond,
316                                                         gpointer user)
317 {
318         struct sockaddr saddr;
319         unsigned int len = sizeof(saddr);
320         int fd;
321         GIOChannel *client_io = NULL;
322
323         if (cond != G_IO_IN)
324                 goto error;
325
326         fd = accept(g_io_channel_unix_get_fd(chan), &saddr, &len);
327         if (fd == -1)
328                 goto error;
329
330         client_io = g_io_channel_unix_new(fd);
331
332         emulator = g_at_server_new(client_io);
333         g_at_server_set_echo(emulator, FALSE);
334         g_io_channel_unref(client_io);
335
336         if (emulator == NULL)
337                 goto error;
338
339         setup_emulator(emulator);
340
341 error:
342         server_watch = 0;
343         return FALSE;
344 }
345
346 static gboolean create_tcp(void)
347 {
348         struct sockaddr_in addr;
349         int sk;
350         int reuseaddr = 1;
351         GIOChannel *server_io;
352
353         sk = socket(PF_INET, SOCK_STREAM, 0);
354         if (sk < 0) {
355                 g_print("Can't create tcp/ip socket: %s (%d)\n",
356                                                 strerror(errno), errno);
357                 return FALSE;
358         }
359
360         memset(&addr, 0, sizeof(addr));
361
362         addr.sin_family = AF_INET;
363         addr.sin_addr.s_addr = INADDR_ANY;
364         addr.sin_port = htons(LISTEN_PORT);
365
366         setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
367         if (bind(sk, (struct sockaddr *) &addr, sizeof(struct sockaddr)) < 0) {
368                 g_print("Can't bind socket: %s (%d)", strerror(errno), errno);
369                 close(sk);
370                 return FALSE;
371         }
372
373         if (listen(sk, 1) < 0) {
374                 g_print("Can't listen on socket: %s (%d)",
375                                                 strerror(errno), errno);
376                 close(sk);
377                 return FALSE;
378         }
379
380         g_print("new tcp is created at tcp port %d\n", LISTEN_PORT);
381
382         server_io = g_io_channel_unix_new(sk);
383         g_io_channel_set_close_on_unref(server_io, TRUE);
384
385         server_watch = g_io_add_watch_full(server_io,
386                                 G_PRIORITY_DEFAULT,
387                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
388                                 on_socket_connected, NULL, NULL);
389
390         g_io_channel_unref(server_io);
391
392         return TRUE;
393 }
394
395 static gboolean has_stk_interface(DBusMessageIter *iter)
396 {
397         DBusMessageIter entry;
398
399         dbus_message_iter_recurse(iter, &entry);
400
401         while (dbus_message_iter_get_arg_type(&entry) == DBUS_TYPE_STRING) {
402                 const char *interface;
403
404                 dbus_message_iter_get_basic(&entry, &interface);
405
406                 if (g_str_equal(interface, OFONO_STK_INTERFACE) == TRUE)
407                         return TRUE;
408
409                 dbus_message_iter_next(&entry);
410         }
411
412         return FALSE;
413 }
414
415 static int send_with_reply(const char *path, const char *interface,
416                                 const char *method, DBusPendingCall **call,
417                                 DBusPendingCallNotifyFunction cb,
418                                 void *user_data, DBusFreeFunction free_func,
419                                 int timeout, int type, ...)
420 {
421         DBusMessage *msg;
422         DBusPendingCall *c;
423         va_list args;
424         int err;
425
426         msg = dbus_message_new_method_call(OFONO_SERVICE, path,
427                                                 interface, method);
428         if (msg == NULL) {
429                 g_printerr("Unable to allocate new D-Bus %s message\n", method);
430                 err = -ENOMEM;
431                 goto fail;
432         }
433
434         va_start(args, type);
435
436         if (!dbus_message_append_args_valist(msg, type, args)) {
437                 va_end(args);
438                 err = -EIO;
439                 goto fail;
440         }
441
442         va_end(args);
443
444         if (timeout > 0)
445                 timeout *= 1000;
446
447         if (!dbus_connection_send_with_reply(conn, msg, &c, timeout)) {
448                 g_printerr("Sending %s failed\n", method);
449                 err = -EIO;
450                 goto fail;
451         }
452
453         if (call != NULL)
454                 *call = c;
455
456         dbus_pending_call_set_notify(c, cb, user_data, free_func);
457         dbus_pending_call_unref(c);
458
459         dbus_message_unref(msg);
460
461         return 0;
462
463 fail:
464         if (free_func && user_data)
465                 free_func(user_data);
466
467         if (msg)
468                 dbus_message_unref(msg);
469
470         return err;
471 }
472
473 static void set_property_reply(DBusPendingCall *call, void *user_data)
474 {
475         DBusMessage *reply = dbus_pending_call_steal_reply(call);
476         DBusError err;
477
478         dbus_error_init(&err);
479
480         if (dbus_set_error_from_message(&err, reply) == TRUE) {
481                 g_printerr("%s: %s\n", err.name, err.message);
482                 dbus_error_free(&err);
483         }
484
485         dbus_message_unref(reply);
486 }
487
488 static int set_property(const char *path, const char *interface,
489                         const char *key, int type, const void *val,
490                         DBusPendingCallNotifyFunction notify,
491                         gpointer user_data,
492                         DBusFreeFunction destroy)
493 {
494         DBusMessage *msg;
495         DBusMessageIter iter, value;
496         DBusPendingCall *call;
497         const char *signature;
498
499         msg = dbus_message_new_method_call(OFONO_SERVICE, path, interface,
500                                                 "SetProperty");
501         if (msg == NULL)
502                 return -ENOMEM;
503
504         dbus_message_set_auto_start(msg, FALSE);
505
506         dbus_message_iter_init_append(msg, &iter);
507
508         dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key);
509
510         switch (type) {
511         case DBUS_TYPE_BOOLEAN:
512                 signature = DBUS_TYPE_BOOLEAN_AS_STRING;
513                 break;
514         default:
515                 dbus_message_unref(msg);
516                 return -EINVAL;
517         }
518
519         dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT,
520                                                         signature, &value);
521         dbus_message_iter_append_basic(&value, type, val);
522         dbus_message_iter_close_container(&iter, &value);
523
524         if (dbus_connection_send_with_reply(conn, msg, &call, -1) == FALSE) {
525                 dbus_message_unref(msg);
526                 return -EIO;
527         }
528
529         dbus_message_unref(msg);
530
531         if (call == NULL)
532                 return -EINVAL;
533
534         dbus_pending_call_set_notify(call, notify, user_data, destroy);
535
536         dbus_pending_call_unref(call);
537
538         return 0;
539 }
540
541 static void register_agent_reply(DBusPendingCall *call, void *user_data)
542 {
543         DBusMessage *reply = dbus_pending_call_steal_reply(call);
544         DBusError err;
545
546         dbus_error_init(&err);
547
548         if (dbus_set_error_from_message(&err, reply) == TRUE) {
549                 g_printerr("%s: %s\n", err.name, err.message);
550                 dbus_error_free(&err);
551         }
552
553         dbus_message_unref(reply);
554
555         state = TEST_STATE_RUNNING;
556 }
557
558 static void register_agent()
559 {
560         const char *path = "/default";
561         int status;
562
563         g_print("Gained STK interface, registering agent...\n");
564
565         status = send_with_reply(STKTEST_PATH, OFONO_STK_INTERFACE,
566                                         "RegisterAgent", NULL,
567                                         register_agent_reply, NULL, NULL, 1,
568                                         DBUS_TYPE_OBJECT_PATH, &path,
569                                         DBUS_TYPE_INVALID);
570
571         if (status < 0) {
572                 g_printerr("Unable to register agent with oFono\n");
573                 g_main_loop_quit(main_loop);
574                 return;
575         }
576
577         state = TEST_STATE_REGISTERING_AGENT;
578 }
579
580 static gboolean modem_changed(DBusConnection *conn,
581                                 DBusMessage *msg, void *user_data)
582 {
583         DBusMessageIter iter, value;
584         const char *path, *key;
585         gboolean has_stk;
586
587         if (dbus_message_iter_init(msg, &iter) == FALSE)
588                 return TRUE;
589
590         path = dbus_message_get_path(msg);
591
592         if (g_str_equal(STKTEST_PATH, path) == FALSE)
593                 return TRUE;
594
595         dbus_message_iter_get_basic(&iter, &key);
596
597         dbus_message_iter_next(&iter);
598         dbus_message_iter_recurse(&iter, &value);
599
600         if (g_str_equal(key, "Interfaces") == FALSE)
601                 return TRUE;
602
603         has_stk = has_stk_interface(&value);
604
605         switch (state) {
606         case TEST_STATE_POWERING_UP:
607                 if (has_stk)
608                         register_agent();
609                 break;
610         case TEST_STATE_REGISTERING_AGENT:
611         case TEST_STATE_RUNNING:
612                 if (has_stk == FALSE)
613                         g_printerr("Unexpectedly lost STK interface\n");
614                 /* Fall through */
615         case TEST_STATE_POWERING_DOWN:
616                 break;
617         };
618
619         return TRUE;
620 }
621
622 static void powerup(void)
623 {
624         dbus_bool_t powered = TRUE;
625
626         state = TEST_STATE_POWERING_UP;
627         set_property(STKTEST_PATH, OFONO_MODEM_INTERFACE, "Powered",
628                         DBUS_TYPE_BOOLEAN, &powered,
629                         set_property_reply, NULL, NULL);
630 }
631
632 static void get_modems_reply(DBusPendingCall *call, void *user_data)
633 {
634         DBusMessage *reply = dbus_pending_call_steal_reply(call);
635         DBusMessageIter iter, list;
636         DBusError err;
637         gboolean found = FALSE;
638
639         dbus_error_init(&err);
640
641         if (dbus_set_error_from_message(&err, reply) == TRUE) {
642                 g_printerr("%s: %s\n", err.name, err.message);
643                 dbus_error_free(&err);
644                 goto done;
645         }
646
647         if (dbus_message_has_signature(reply, "a(oa{sv})") == FALSE)
648                 goto done;
649
650         if (dbus_message_iter_init(reply, &iter) == FALSE)
651                 goto done;
652
653         dbus_message_iter_recurse(&iter, &list);
654
655         while (dbus_message_iter_get_arg_type(&list) == DBUS_TYPE_STRUCT) {
656                 DBusMessageIter entry;
657                 const char *path;
658
659                 dbus_message_iter_recurse(&list, &entry);
660                 dbus_message_iter_get_basic(&entry, &path);
661
662                 if (g_str_equal(path, STKTEST_PATH))
663                         found = TRUE;
664
665                 dbus_message_iter_next(&list);
666         }
667
668 done:
669         dbus_message_unref(reply);
670
671         if (found == FALSE) {
672                 g_printerr("STK Test modem not found\n");
673                 g_main_loop_quit(main_loop);
674                 return;
675         }
676
677         g_print("Test modem found\n");
678
679         modem_changed_watch = g_dbus_add_signal_watch(conn, OFONO_SERVICE,
680                                                         STKTEST_PATH,
681                                                         OFONO_MODEM_INTERFACE,
682                                                         "PropertyChanged",
683                                                         modem_changed,
684                                                         NULL, NULL);
685
686         if (create_tcp() == FALSE) {
687                 g_printerr("Unable to listen on modem emulator socket\n");
688                 g_main_loop_quit(main_loop);
689         }
690
691         powerup();
692 }
693
694 static int get_modems(DBusConnection *conn)
695 {
696         DBusMessage *msg;
697         DBusPendingCall *call;
698
699         msg = dbus_message_new_method_call(OFONO_SERVICE, "/",
700                                         OFONO_MANAGER_INTERFACE, "GetModems");
701         if (msg == NULL)
702                 return -ENOMEM;
703
704         dbus_message_set_auto_start(msg, FALSE);
705
706         g_print("getting modems\n");
707
708         if (dbus_connection_send_with_reply(conn, msg, &call, -1) == FALSE) {
709                 dbus_message_unref(msg);
710                 return -EIO;
711         }
712
713         dbus_message_unref(msg);
714
715         if (call == NULL)
716                 return -EINVAL;
717
718         dbus_pending_call_set_notify(call, get_modems_reply, conn, NULL);
719
720         dbus_pending_call_unref(call);
721
722         return 0;
723 }
724
725 static const GDBusMethodTable agent_methods[] = {
726         { GDBUS_METHOD("Release", NULL, NULL, agent_release) },
727         { GDBUS_METHOD("DisplayText",
728                 GDBUS_ARGS({ "text", "s" }, { "icon_id", "y" },
729                                 { "urgent", "b" }), NULL,
730                                 agent_display_text) },
731         { },
732 };
733
734 static void ofono_connect(DBusConnection *conn, void *user_data)
735 {
736         g_print("starting telephony interface\n");
737
738         if (!g_dbus_register_interface(conn, "/default",
739                                         OFONO_STKAGENT_INTERFACE,
740                                         agent_methods, NULL, NULL,
741                                         NULL, NULL)) {
742                 g_printerr("Unable to register local agent");
743                 g_main_loop_quit(main_loop);
744         }
745
746         ofono_running = TRUE;
747         get_modems(conn);
748 }
749
750 static void ofono_disconnect(DBusConnection *conn, void *user_data)
751 {
752         g_print("stopping telephony interface\n");
753
754         g_dbus_unregister_interface(conn, "/default", OFONO_STKAGENT_INTERFACE);
755
756         ofono_running = FALSE;
757
758         g_dbus_remove_watch(conn, modem_changed_watch);
759         modem_changed_watch = 0;
760
761         if (server_watch) {
762                 g_source_remove(server_watch);
763                 server_watch = 0;
764         }
765
766         g_at_server_unref(emulator);
767         emulator = NULL;
768 }
769
770 static void sig_term(int sig)
771 {
772         if (__terminated > 0)
773                 return;
774
775         __terminated = 1;
776
777         g_print("Terminating\n");
778
779         g_main_loop_quit(main_loop);
780 }
781
782 static void disconnect_callback(DBusConnection *conn, void *user_data)
783 {
784         g_printerr("D-Bus disconnect\n");
785
786         g_main_loop_quit(main_loop);
787 }
788
789 static gboolean option_version = FALSE;
790
791 static GOptionEntry options[] = {
792         { "version", 'v', 0, G_OPTION_ARG_NONE, &option_version,
793                                 "Show version information and exit" },
794         { NULL },
795 };
796
797 int main(int argc, char **argv)
798 {
799         GOptionContext *context;
800         GError *error = NULL;
801         DBusError err;
802         guint watch;
803         struct sigaction sa;
804
805         context = g_option_context_new(NULL);
806         g_option_context_add_main_entries(context, options, NULL);
807
808         if (g_option_context_parse(context, &argc, &argv, &error) == FALSE) {
809                 if (error != NULL) {
810                         g_printerr("%s\n", error->message);
811                         g_error_free(error);
812                 } else
813                         g_printerr("An unknown error occurred\n");
814                 exit(1);
815         }
816
817         g_option_context_free(context);
818
819         if (option_version == TRUE) {
820                 printf("%s\n", VERSION);
821                 exit(0);
822         }
823
824         main_loop = g_main_loop_new(NULL, FALSE);
825
826         dbus_error_init(&err);
827
828         conn = g_dbus_setup_bus(DBUS_BUS_SYSTEM, NULL, &err);
829         if (conn == NULL) {
830                 if (dbus_error_is_set(&err) == TRUE) {
831                         fprintf(stderr, "%s\n", err.message);
832                         dbus_error_free(&err);
833                 } else
834                         fprintf(stderr, "Can't register with system bus\n");
835                 exit(1);
836         }
837
838         g_dbus_set_disconnect_function(conn, disconnect_callback, NULL, NULL);
839
840         memset(&sa, 0, sizeof(sa));
841         sa.sa_handler = sig_term;
842         sigaction(SIGINT, &sa, NULL);
843         sigaction(SIGTERM, &sa, NULL);
844
845         watch = g_dbus_add_service_watch(conn, OFONO_SERVICE,
846                                 ofono_connect, ofono_disconnect, NULL, NULL);
847
848         g_main_loop_run(main_loop);
849
850         g_dbus_remove_watch(conn, watch);
851
852         if (ofono_running == TRUE)
853                 ofono_disconnect(conn, NULL);
854
855         dbus_connection_unref(conn);
856
857         g_main_loop_unref(main_loop);
858
859         return 0;
860 }