Fix animation a little.
[dhcpcd-ui] / main.c
1 /*
2  * dhcpcd-gtk
3  * Copyright 2009 Roy Marples <roy@marples.name>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 /* TODO: Animate the icon from carrier -> address
28  * maybe use network-idle -> network-transmit ->
29  * network-receive -> network-transmit-receive */
30
31 #include <locale.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include <libnotify/notify.h>
36
37 #include "dhcpcd-gtk.h"
38 #include "menu.h"
39
40 DBusGProxy *dbus = NULL;
41 GList *interfaces = NULL;
42
43 static GtkStatusIcon *status_icon;
44 static gint ani_timer;
45 static int ani_counter;
46 static gboolean online;
47 static gboolean carrier;
48 static char **interface_order;
49 static NotifyNotification *nn;
50
51 const char *const up_reasons[] = {
52         "BOUND",
53         "RENEW",
54         "REBIND",
55         "REBOOT",
56         "IPV4LL",
57         "INFORM",
58         "TIMEOUT",
59         NULL
60 };
61
62 const char *const down_reasons[] = {
63         "EXPIRE",
64         "FAIL",
65         "NAK",
66         "NOCARRIER",
67         "STOP",
68         NULL
69 };
70
71 static gboolean
72 ignore_if_msg(const struct if_msg *ifm)
73 {
74         if (g_strcmp0(ifm->reason, "STOP") == 0 ||
75             g_strcmp0(ifm->reason, "RELEASE") == 0)
76                 return TRUE;
77         return FALSE;
78 }
79
80 static void
81 free_if_msg(struct if_msg *ifm)
82 {
83         g_free(ifm->name);
84         g_free(ifm->reason);
85         g_free(ifm->ssid);
86         g_free(ifm);
87 }
88
89 static void
90 error_exit(const char *msg, GError *error)
91 {
92         GtkWidget *dialog;
93
94         if (error) {
95                 g_critical("%s: %s", msg, error->message);
96                 dialog = gtk_message_dialog_new(NULL,
97                                                 0,
98                                                 GTK_MESSAGE_ERROR,
99                                                 GTK_BUTTONS_CLOSE,
100                                                 "%s: %s",
101                                                 msg,
102                                                 error->message);
103         } else {
104                 g_critical("%s", msg);
105                 dialog = gtk_message_dialog_new(NULL,
106                                                 0,
107                                                 GTK_MESSAGE_ERROR,
108                                                 GTK_BUTTONS_CLOSE,
109                                                 "%s",
110                                                 msg);
111         }
112         gtk_dialog_run(GTK_DIALOG(dialog));
113         gtk_widget_destroy(dialog);
114         if (gtk_main_level())
115                 gtk_main_quit();
116         else
117                 exit(EXIT_FAILURE);
118 }
119
120 GList *
121 get_scan_results(const char *iface)
122 {
123         GType otype;
124         GPtrArray *array = NULL;
125         GValueArray *item;
126         GError *error = NULL;
127         GList *list = NULL;
128         struct if_ap *ifa;
129         guint i;
130         GValue *v;
131
132         /* Below code causes dbus to go belly up for some reason :/ */
133         return NULL;
134         otype = dbus_g_type_get_struct("GValueArray",
135                                        G_TYPE_STRING,
136                                        G_TYPE_UINT,
137                                        G_TYPE_UINT,
138                                        G_TYPE_STRING,
139                                        G_TYPE_STRING,
140                                        G_TYPE_INVALID);
141         otype = dbus_g_type_get_collection("GPtrArray", otype);
142         if (!dbus_g_proxy_call(dbus, "GetScanResults", &error,
143                                G_TYPE_STRING, &iface, G_TYPE_INVALID,
144                                otype, &array, G_TYPE_INVALID)) {
145                 g_message("GetScanResults: %s\n", error->message);
146                 g_clear_error(&error);
147                 return NULL;
148         }
149
150         printf ("got %d\n", array->len);
151         for (i = 0; i < array->len; i++) {
152                 ifa = g_malloc(sizeof(*ifa));
153                 item = g_ptr_array_index(array, i);
154                 v = g_value_array_get_nth(item, 0);
155                 ifa->bssid = g_strdup(g_value_get_string(v));
156                 v = g_value_array_get_nth(item, 1);
157                 ifa->freq = g_value_get_uint(v);
158                 v = g_value_array_get_nth(item, 2);
159                 ifa->level = g_value_get_uint(v);
160                 v = g_value_array_get_nth(item, 3);
161                 ifa->flags = g_strdup(g_value_get_string(v));
162                 v = g_value_array_get_nth(item, 3);
163                 ifa->ssid = g_strdup(g_value_get_string(v));
164                 list = g_list_append(list, ifa);
165         }
166         g_ptr_array_free(array, TRUE);
167         return list;
168 }
169
170 static struct if_msg *
171 make_if_msg(GHashTable *config)
172 {
173         GValue *val;
174         struct if_msg *ifm;
175
176         val = g_hash_table_lookup(config, "Interface");
177         if (val == NULL)
178                 return NULL;
179         ifm = g_malloc0(sizeof(*ifm));
180         ifm->name = g_strdup(g_value_get_string(val));
181         val = g_hash_table_lookup(config, "Reason");
182         if (val)
183                 ifm->reason = g_strdup(g_value_get_string(val));
184         val = g_hash_table_lookup(config, "Wireless");
185         if (val)
186                 ifm->wireless = g_value_get_boolean(val);
187         if (ifm->wireless) {
188                 val = g_hash_table_lookup(config, "SSID");
189                 if (val)
190                         ifm->ssid = g_strdup(g_value_get_string(val));
191         }
192         val = g_hash_table_lookup(config, "IPAddress");
193         if (val)
194                 ifm->ip.s_addr = g_value_get_uint(val);
195         val = g_hash_table_lookup(config, "SubnetCIDR");
196         if (val)
197                 ifm->cidr = g_value_get_uchar(val);
198         val = g_hash_table_lookup(config, "InterfaceOrder");
199         if (val) {
200                 g_strfreev(interface_order);
201                 interface_order = g_strsplit(g_value_get_string(val), " ", 0);
202         }
203         if (ifm->wireless)
204                 ifm->scan_results = get_scan_results(ifm->name);
205         return ifm;
206 }
207
208 static gboolean
209 if_up(const struct if_msg *ifm)
210 {
211         const char *const *r;
212
213         for (r = up_reasons; *r; r++)
214                 if (g_strcmp0(*r, ifm->reason) == 0)
215                         return TRUE;
216         return FALSE;
217 }
218
219 static char *
220 print_if_msg(const struct if_msg *ifm)
221 {
222         char *msg, *p;
223         const char *reason = NULL;
224         size_t len;
225         gboolean showip, showssid;
226     
227         showip = TRUE;
228         showssid = FALSE;
229         if (if_up(ifm))
230                 reason = N_("Acquired address");
231         else {
232                 if (g_strcmp0(ifm->reason, "EXPIRE") == 0)
233                         reason = N_("Failed to renew");
234                 else if (g_strcmp0(ifm->reason, "CARRIER") == 0) {
235                         if (ifm->wireless) {
236                                 reason = N_("Asssociated with");
237                                 if (ifm->ssid != NULL)
238                                         showssid = TRUE;
239                         } else
240                                 reason = N_("Cable plugged in");
241                         showip = FALSE;
242                 } else if (g_strcmp0(ifm->reason, "NOCARRIER") == 0) {
243                         if (ifm->wireless) {
244                                 if (ifm->ssid != NULL || ifm->ip.s_addr != 0) {
245                                         reason = N_("Disassociated from");
246                                         showssid = TRUE;
247                                 } else
248                                     reason = N_("Not associated");
249                         } else
250                                 reason = N_("Cable unplugged");
251                         showip = FALSE;
252                 }
253         }
254         if (reason == NULL)
255                 reason = ifm->reason;
256         
257         len = strlen(ifm->name) + 3;
258         len += strlen(reason) + 1;
259         if (ifm->ip.s_addr != 0) {
260                 len += 16; /* 000. * 4 */
261                 if (ifm->cidr != 0)
262                         len += 3; /* /32 */
263         }
264         if (showssid)
265                 len += strlen(ifm->ssid) + 1;
266         msg = p = g_malloc(len);
267         p += g_snprintf(msg, len, "%s: %s", ifm->name, reason);
268         if (showssid)
269                 p += g_snprintf(p, len - (p - msg), " %s", ifm->ssid);
270         if (ifm->ip.s_addr != 0 && showip) {
271                 p += g_snprintf(p, len - (p - msg), " %s", inet_ntoa(ifm->ip));
272                 if (ifm->cidr != 0)
273                         g_snprintf(p, len - (p - msg), "/%d", ifm->cidr);
274         }
275         return msg;
276 }
277
278 static gint
279 if_msg_comparer(gconstpointer a, gconstpointer b)
280 {
281         const struct if_msg *ifa, *ifb;
282         const char *const *order;
283
284         ifa = (const struct if_msg *)a;
285         ifb = (const struct if_msg *)b;
286         for (order = (const char *const *)interface_order; *order; order++) {
287                 if (g_strcmp0(*order, ifa->name) == 0)
288                         return -1;
289                 if (g_strcmp0(*order, ifb->name) == 0)
290                         return 1;
291         }
292         return 0;
293 }
294
295 static gboolean
296 animate_carrier(_unused gpointer data)
297 {
298         if (ani_timer == 0)
299                 return FALSE;
300
301         switch(ani_counter++) {
302         case 0:
303                 gtk_status_icon_set_from_icon_name(status_icon, "network-transmit");
304                 break;
305         case 1:
306                 gtk_status_icon_set_from_icon_name(status_icon, "network-receive");
307                 break;
308         default:
309                 gtk_status_icon_set_from_icon_name(status_icon, "network-idle");
310                 ani_counter = 0;
311                 break;
312         }
313         return TRUE;
314 }
315
316 static gboolean
317 animate_online(_unused gpointer data)
318 {
319         if (ani_timer == 0)
320                 return FALSE;
321
322         if (ani_counter++ > 6) {
323                 ani_timer = 0;
324                 ani_counter = 0;
325                 return FALSE;
326         }
327
328         if (ani_counter % 2 == 0)
329                 gtk_status_icon_set_from_icon_name(status_icon, "network-idle");
330         else
331                 gtk_status_icon_set_from_icon_name(status_icon, "network-transmit-receive");
332         return TRUE;
333 }
334
335 static void
336 update_online(char **buffer)
337 {
338         gboolean ison, iscarrier;
339         char *msg, *msgs, *tmp;
340         const GList *gl;
341         const struct if_msg *ifm;
342
343         ison = iscarrier = FALSE;
344         msgs = NULL;
345         for (gl = interfaces; gl; gl = gl->next) {
346                 ifm = (const struct if_msg *)gl->data;
347                 if (if_up(ifm))
348                         ison = iscarrier = TRUE;
349                 if (!iscarrier && g_strcmp0(ifm->reason, "CARRIER") == 0)
350                         iscarrier = TRUE;
351                 msg = print_if_msg(ifm);
352                 if (msgs) {
353                         tmp = g_strconcat(msgs, "\n", msg, NULL);
354                         g_free(msgs);
355                         g_free(msg);
356                         msgs = tmp;
357                 } else
358                         msgs = msg;
359         }
360
361         if (online != ison || carrier != iscarrier) {
362                 online = ison;
363                 if (ani_timer != 0) {
364                         g_source_remove(ani_timer);
365                         ani_timer = 0;
366                         ani_counter = 0;
367                 }
368                 if (ison) {
369                         animate_online(NULL);
370                         ani_timer = g_timeout_add(300, animate_online, NULL);
371                 } else if (iscarrier) {
372                         animate_carrier(NULL);
373                         ani_timer = g_timeout_add(500, animate_carrier, NULL);
374                 } else {
375                         gtk_status_icon_set_from_icon_name(status_icon,
376                                                            "network-offline");
377                 }
378         }
379         gtk_status_icon_set_tooltip(status_icon, msgs);
380         if (buffer)
381                 *buffer = msgs;
382         else
383                 g_free(msgs);
384 }
385
386 void
387 notify_close(void)
388 {
389         if (nn != NULL)
390                 notify_notification_close(nn, NULL);
391 }
392
393 static void
394 notify_closed(void)
395 {
396         nn = NULL;
397 }
398
399 static void
400 notify(const char *title, const char *msg, const char *icon)
401 {
402         char **msgs, **m;
403
404         msgs = g_strsplit(msg, "\n", 0);
405         for (m = msgs; *m; m++)
406                 g_message("%s", *m);
407         g_strfreev(msgs);
408         if (nn != NULL)
409                 notify_notification_close(nn, NULL);
410         if (gtk_status_icon_get_visible(status_icon))
411                 nn = notify_notification_new_with_status_icon(title,
412                                                               msg,
413                                                               icon,
414                                                               status_icon);
415         else
416                 nn = notify_notification_new(title, msg, icon, NULL);
417         notify_notification_set_timeout(nn, 5000);
418         g_signal_connect(nn, "closed", G_CALLBACK(notify_closed), NULL);
419         notify_notification_show(nn, NULL);
420 }
421
422 static void
423 dhcpcd_event(_unused DBusGProxy *proxy, GHashTable *config, _unused void *data)
424 {
425         struct if_msg *ifm, *ifp;
426         gboolean rem;
427         GList *gl;
428         char *msg, *title;
429         const char *act, *net;
430         const char *const *r;
431         in_addr_t ipn;
432
433         ifm = make_if_msg(config);
434         if (ifm == NULL)
435                 return;
436
437         rem = ignore_if_msg(ifm);
438         ifp = NULL;
439         for (gl = interfaces; gl; gl = gl->next) {
440                 ifp = (struct if_msg *)gl->data;
441                 if (g_strcmp0(ifp->name, ifm->name) == 0) {
442                         free_if_msg(ifp);
443                         if (rem)
444                                 interfaces = g_list_delete_link(interfaces, gl);
445                         else
446                                 gl->data = ifm;
447                         break;
448                 }
449         }
450         if (ifp == NULL && !rem)
451                 interfaces = g_list_prepend(interfaces, ifm);
452         interfaces = g_list_sort(interfaces, if_msg_comparer);
453         update_online(NULL);
454
455         /* We should ignore renew and stop so we don't annoy the user */
456         if (g_strcmp0(ifm->reason, "RENEW") == 0 ||
457             g_strcmp0(ifm->reason, "STOP") == 0)
458                 return;
459
460         msg = print_if_msg(ifm);
461         title = NULL;
462         if (if_up(ifm))
463                 act = N_("Connected to ");
464         else
465                 act = NULL;
466         for (r = down_reasons; *r; r++) {
467                 if (g_strcmp0(*r, ifm->reason) == 0) {
468                         act = N_("Disconnected from ");
469                         break;
470                 }
471         }
472         if (act && ifm->ip.s_addr) {
473                 ipn = htonl(ifm->ip.s_addr);
474                 if (IN_LINKLOCAL(ipn))
475                         net = N_("private network");
476                 else if (IN_PRIVATE(ipn))
477                         net = N_("LAN");
478                 else
479                         net = N_("internet");
480                 title = g_strconcat(act, net, NULL);
481         }
482
483         if (title) {
484                 notify(title, msg, GTK_STOCK_NETWORK);
485                 g_free(title);
486         } else
487                 notify("Interface event", msg, GTK_STOCK_NETWORK);
488         g_free(msg);
489 }
490
491 static void
492 foreach_make_ifm(_unused gpointer key, gpointer value, _unused gpointer data)
493 {
494         struct if_msg *ifm;
495
496         ifm = make_if_msg((GHashTable *)value);
497         if (ignore_if_msg(ifm))
498                 g_free(ifm);
499         else if (ifm)
500                 interfaces = g_list_prepend(interfaces, ifm);
501 }
502
503 static void
504 dhcpcd_get_interfaces()
505 {
506         GHashTable *ifs;
507         GError *error = NULL;
508         GType otype;
509         char *msg;
510
511         otype = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE);
512         otype = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, otype);
513         if (!dbus_g_proxy_call(dbus, "GetInterfaces", &error,
514                                G_TYPE_INVALID,
515                                otype, &ifs, G_TYPE_INVALID))
516                 error_exit("GetInterfaces", error);
517         g_hash_table_foreach(ifs, foreach_make_ifm, NULL);
518         g_hash_table_unref(ifs);
519
520         /* Each interface config only remembers the last order when
521          * that interface was configured, so get the real order now. */
522         g_strfreev(interface_order);
523         interface_order = NULL;
524         if (!dbus_g_proxy_call(dbus, "ListInterfaces", &error,
525                                G_TYPE_INVALID,
526                                G_TYPE_STRV, &interface_order, G_TYPE_INVALID))
527                 error_exit("ListInterfaces", error);
528         interfaces = g_list_sort(interfaces, if_msg_comparer);
529         msg = NULL;
530         update_online(&msg);
531         // GTK+ 2.16 msg = gtk_status_icon_get_tooltip_text(status_icon);
532         if (msg != NULL) {
533                 notify("Interface status", msg, GTK_STOCK_NETWORK);
534                 g_free(msg);
535         }
536 }
537
538 static void
539 check_status(const char *status)
540 {
541         static char *last = NULL;
542         GList *gl;
543         char *version;
544         const char *msg;
545         gboolean refresh;
546         GError *error = NULL;
547
548         g_message("Status changed to %s", status);
549         if (g_strcmp0(status, "down") == 0) {
550                 for (gl = interfaces; gl; gl = gl->next)
551                         free_if_msg((struct if_msg *)gl->data);
552                 g_list_free(interfaces);
553                 interfaces = NULL;
554                 update_online(NULL);
555                 msg = N_(last? "Connection to dhcpcd lost" : "dhcpcd not running");
556                 gtk_status_icon_set_tooltip(status_icon, msg);
557                 notify(_("No network"), msg, GTK_STOCK_NETWORK);
558         }
559
560         refresh = FALSE;
561         if (last == NULL) {
562                 if (g_strcmp0(status, "down") != 0)
563                         refresh = TRUE;
564         } else {
565                 if (g_strcmp0(status, last) == 0)
566                         return;
567                 if (g_strcmp0(last, "down") == 0)
568                         refresh = TRUE;
569                 g_free(last);
570         }
571         last = g_strdup(status);
572
573         if (!refresh)
574                 return;
575         if (!dbus_g_proxy_call(dbus, "GetDhcpcdVersion", &error,
576                                G_TYPE_INVALID,
577                                G_TYPE_STRING, &version, G_TYPE_INVALID))
578                 error_exit(_("GetDhcpcdVersion"), error);
579         g_message(_("Connected to %s-%s"), "dhcpcd", version);
580         g_free(version);
581         dhcpcd_get_interfaces();
582 }
583
584 static void
585 dhcpcd_status(_unused DBusGProxy *proxy, const char *status, _unused void *data)
586 {
587         check_status(status);
588 }
589
590 int
591 main(int argc, char *argv[])
592 {
593         DBusGConnection *bus;
594         GError *error = NULL;
595         char *version = NULL;
596         GType otype;
597         int tries = 5;
598
599                 
600         setlocale(LC_ALL, "");
601         bindtextdomain(PACKAGE, NULL);
602         bind_textdomain_codeset(PACKAGE, "UTF-8");
603         textdomain(PACKAGE); 
604
605         gtk_init(&argc, &argv);
606         g_set_application_name("dhcpcd Monitor");
607         status_icon = gtk_status_icon_new_from_icon_name("network-offline");
608         if (status_icon == NULL)
609                 status_icon = gtk_status_icon_new_from_stock(GTK_STOCK_DISCONNECT);
610         //network_offline = gtk_status_icon_get_pixbuf(status_icon);
611         
612         gtk_status_icon_set_tooltip(status_icon, _("Connecting to dhcpcd ..."));
613         gtk_status_icon_set_visible(status_icon, TRUE);
614
615         notify_init(PACKAGE);
616
617         g_message(_("Connecting to dbus ..."));
618         bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
619         if (bus == NULL || error != NULL)
620                 error_exit(_("Could not connect to system bus"), error);
621         dbus = dbus_g_proxy_new_for_name(bus,
622                                               DHCPCD_SERVICE,
623                                               DHCPCD_PATH,
624                                               DHCPCD_SERVICE);
625
626         g_message(_("Connecting to dhcpcd-dbus ..."));
627         while (--tries > 0) {
628                 g_clear_error(&error);
629                 if (dbus_g_proxy_call_with_timeout(dbus,
630                                                    "GetVersion",
631                                                    500,
632                                                    &error,
633                                                    G_TYPE_INVALID,
634                                                    G_TYPE_STRING,
635                                                    &version,
636                                                    G_TYPE_INVALID))
637                         break;
638         }
639         if (tries == 0)
640                 error_exit(_("GetVersion"), error);
641         g_message(_("Connected to %s-%s"), "dhcpcd-dbus", version);
642         g_free(version);
643
644         gtk_status_icon_set_tooltip(status_icon, _("Triggering dhcpcd ..."));
645         online = FALSE;
646         menu_init(status_icon);
647
648         if (!dbus_g_proxy_call(dbus, "GetStatus", &error,
649                                G_TYPE_INVALID,
650                                G_TYPE_STRING, &version, G_TYPE_INVALID))
651                 error_exit(_("GetStatus"), error);
652         check_status(version);
653         g_free(version);
654
655         otype = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE);
656         dbus_g_proxy_add_signal(dbus, "Event",
657                                 otype, G_TYPE_INVALID);
658         dbus_g_proxy_connect_signal(dbus, "Event",
659                                     G_CALLBACK(dhcpcd_event),
660                                     NULL, NULL);
661         dbus_g_proxy_add_signal(dbus, "StatusChanged",
662                                 G_TYPE_STRING, G_TYPE_INVALID);
663         dbus_g_proxy_connect_signal(dbus, "StatusChanged",
664                                     G_CALLBACK(dhcpcd_status),
665                                     NULL, NULL);
666
667         gtk_main();
668         return 0;
669 }