Added sudo scripts for enabling and disabling USB networking
[mtetherd] / status.c
index 52efb5e..7ca2364 100644 (file)
--- a/status.c
+++ b/status.c
@@ -19,6 +19,7 @@
 */
 
 #include <stdio.h>
+#include <string.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <pwd.h>
@@ -43,6 +44,25 @@ static void mtetherd_status_plugin_class_init(MTetherDStatusPluginClass *klass)
        g_type_class_add_private(klass, sizeof(MTetherDStatusPluginPrivate));
 }
 
+static gboolean get_usbnet_enabled(MTetherDStatusPlugin *plugin) {
+       FILE *fp = fopen("/proc/modules", "r");
+       if (!fp) {
+               // fallback (useless?)
+               return plugin->priv->neton;
+       }
+       gboolean found = FALSE;
+       char *line = NULL;
+       while (!found && getline(&line, NULL, fp) != -1) {
+               if (strncmp(line, "g_ether", 7) == 0) {
+                       found = TRUE;
+               }
+               free(line);
+               line = NULL;
+       }
+       fclose(fp);
+       return found;
+}
+
 static void set_button_text(GtkWidget *button, gboolean enabled) {
        if (enabled) {
                gtk_button_set_label(GTK_BUTTON(button), "Disable USB Networking");
@@ -51,16 +71,42 @@ static void set_button_text(GtkWidget *button, gboolean enabled) {
        }
 }
 
+static gboolean launch_usbnet_script(gboolean enable) {
+       const char *arg;
+       if (enable) {
+               arg = "/usr/sbin/mtetherd-usbnet-enable.sh";
+       } else {
+               arg = "/usr/sbin/mtetherd-usbnet-disable.sh";
+       }
+       const char *command[] = { "/usr/bin/sudo", arg, NULL };
+       pid_t pid = fork();
+       if (pid == 0) {
+               if (execv(command[0], (char **const) command) == -1) {
+                       exit(1);
+               }
+       } else if (pid == -1) {
+               // error forking
+               return FALSE;
+       }
+       // launch ok
+       return TRUE;
+}
+
 static void enable_usb_net_clicked(GtkWidget *button, gpointer user) {
        MTetherDStatusPlugin *plugin = MTETHERD_STATUS_PLUGIN(user);
 
        if (button == plugin->priv->button) {
-               plugin->priv->neton = !plugin->priv->neton;
-               set_button_text(plugin->priv->button, plugin->priv->neton);
-               if (plugin->priv->neton) {
-                       // enable
+               gboolean enabled = get_usbnet_enabled(plugin);
+               set_button_text(plugin->priv->button, enabled);
+               if (enabled) {
+                       if (launch_usbnet_script(FALSE)) {
+                               // launch ok
+                               plugin->priv->neton = FALSE;
+                       }
                } else {
-                       // disable
+                       if (launch_usbnet_script(TRUE)) {
+                               plugin->priv->neton = TRUE;
+                       }
                }
        }
 }