1 /* Required for strdup, snprintf, getopt */
2 #define _XOPEN_SOURCE 500
13 #include <sys/select.h>
14 #include <sys/inotify.h>
16 #include <gdk/gdkkeysyms.h>
18 typedef struct sProperty
24 typedef struct sDevice
34 typedef struct sGuiContext
42 char *post_mount_command;
45 GIOChannel *inotify_channel;
52 Parses a string of the form name=value and places the components in a Property
53 structure. Returns 0 on success, or -1 if the string wasn't a valid property.
55 int parse_property(char *str, int size, Property *prop)
60 for(i=0; (equals<0 && i<size); ++i)
67 prop->name = malloc(equals+1);
68 strncpy(prop->name, str, equals);
69 prop->name[equals] = 0;
71 prop->value = malloc(size-equals);
72 strncpy(prop->value, str+equals+1, size-equals-1);
73 prop->value[size-equals-1] = 0;
79 Retrieves all properties associated with a /dev node. The returned array is
80 terminated with an entry containing NULL values. Use free_properties to free
83 Property *get_device_properties(char *node)
91 Property *props = NULL;
101 printf("Running udevadm info -q property -n \"%s\"\n", node);
106 execl("/sbin/udevadm", "udevadm", "info", "-q", "property", "-n", node, NULL);
121 buf = (char *)malloc(bufsize);
133 len = read(pipe_fd[0], buf+pos, bufsize-pos);
142 for(i=0; (newline<0 && i<pos); ++i)
151 /* There was no newline in the buffer but there is more output to
152 be read. Try again with a larger buffer. */
154 buf = (char *)realloc(buf, bufsize);
158 if(parse_property(buf, newline, &prop)==0)
160 /* Reserve space for a sentinel value as well. */
161 props = (Property *)realloc(props, (n_props+2)*sizeof(Property));
162 props[n_props] = prop;
165 memmove(buf, buf+newline+1, pos-newline-1);
176 /* Terminate the array with NULL pointers. */
177 props[n_props].name = NULL;
178 props[n_props].value = NULL;
181 waitpid(pid, NULL, 0);
188 Looks for a property in an array of properties and returns its value. Returns
189 NULL if the property was not found.
191 char *get_property_value(Property *props, char *name)
194 for(i=0; props[i].name; ++i)
195 if(strcmp(props[i].name, name)==0)
196 return props[i].value;
201 Checks if a property has a specific value. A NULL value is matched if the
202 property does not exist.
204 int match_property_value(Property *props, char *name, char *value)
206 char *v = get_property_value(props, name);
209 return strcmp(v, value)==0;
213 Frees an array of properties and all strings contained in it.
215 void free_properties(Property *props)
220 for(i=0; props[i].name; ++i)
223 free(props[i].value);
229 Returns an array of user-mountable devices listed in fstab.
231 char **get_fstab_devices(void)
235 char **devices = NULL;
238 file = setmntent("/etc/fstab", "r");
242 while((me = getmntent(file)))
243 if(hasmntopt(me, "user")!=NULL)
245 devices = (char **)realloc(devices, (n_devices+2)*sizeof(char *));
246 devices[n_devices] = strdup(me->mnt_fsname);
252 devices[n_devices] = NULL;
258 Checks if an array of strings contains the specified string.
260 int is_in_array(char **array, char *str)
265 for(i=0; array[i]; ++i)
266 if(!strcmp(str, array[i]))
272 Frees an array of strings.
274 void free_string_array(char **array)
279 for(i=0; array[i]; ++i)
285 Checks if a partition identified by a sysfs path is on a removable device.
287 int is_removable(char *devpath)
294 len = snprintf(fnbuf, sizeof(fnbuf), "/sys%s", devpath);
295 /* Default to not removable if the path was too long. */
296 if(len+10>=(int)sizeof(fnbuf))
299 /* We got a partition as a parameter, but the removable property is on the
300 disk. Replace the last component with "removable". */
301 for(ptr=fnbuf+len; (ptr>fnbuf && *ptr!='/'); --ptr) ;
302 strcpy(ptr, "/removable");
304 fd = open(fnbuf, O_RDONLY);
313 printf(" Removable\n");
317 printf(" Not removable\n");
324 Checks if a partition's disk or any of its parent devices are connected to any
325 of a set of buses. The device is identified by a sysfs path. The bus array
326 must be terminated with a NULL entry.
328 int check_buses(char *devpath, char **buses)
334 len = snprintf(fnbuf, sizeof(fnbuf), "/sys%s", devpath);
335 /* Default to no match if the path was too long. */
336 if(len+10>=(int)sizeof(fnbuf))
339 for(ptr=fnbuf+len; ptr>fnbuf+12; --ptr)
343 /* Replace the last component with "subsystem". */
344 strcpy(ptr, "/subsystem");
345 len = readlink(fnbuf, linkbuf, sizeof(linkbuf)-1);
350 /* Extract the last component of the subsystem symlink. */
351 for(; (len>0 && linkbuf[len-1]!='/'); --len) ;
356 printf(" Subsystem of %s is %s\n", fnbuf, linkbuf+len);
359 if(is_in_array(buses, linkbuf+len))
368 Check if an array of properties describes a device that can be mounted. An
369 array of explicitly allowed devices can be passed in as well. Both arrays must
370 be terminated by a NULL entry.
372 int can_mount(Property *props, char **allowed)
374 static char *removable_buses[] = { "usb", "firewire", 0 };
379 devname = get_property_value(props, "DEVNAME");
380 if(is_in_array(allowed, devname))
383 /* Special case for CD devices, since they are not partitions. Only allow
384 mounting if media is inserted. */
385 if(match_property_value(props, "ID_TYPE", "cd") && match_property_value(props, "ID_CDROM_MEDIA", "1"))
388 /* Only allow mounting partitions. */
389 if(!match_property_value(props, "DEVTYPE", "partition"))
392 devpath = get_property_value(props, "DEVPATH");
393 if(is_removable(devpath))
396 /* Certain buses are removable by nature, but devices only advertise
397 themselves as removable if they support removable media, e.g. memory card
399 bus = get_property_value(props, "ID_BUS");
400 if(is_in_array(removable_buses, bus))
403 return check_buses(devpath, removable_buses);
407 Returns an array of all device nodes in a directory. Symbolic links are
410 char **get_device_nodes(char *dirname)
419 char **checked = NULL;
423 dir = opendir(dirname);
427 while((de = readdir(dir)))
432 /* Ignore . and .. entries. */
433 if(de->d_name[0]=='.' && (de->d_name[1]==0 || (de->d_name[1]=='.' && de->d_name[2]==0)))
436 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", dirname, de->d_name);
440 if(S_ISLNK(st.st_mode))
443 len = readlink(fnbuf, linkbuf, sizeof(linkbuf)-1);
451 /* There may be multiple symlinks to the same device. Only include each
452 device once in the returned array. */
455 for(i=0; (!duplicate && i<n_checked); ++i)
456 if(strcmp(node, checked[i])==0)
462 printf("Device %s is a duplicate\n", fnbuf);
466 checked = (char **)realloc(checked, (n_checked+1)*sizeof(char *));
467 checked[n_checked] = strdup(node);
470 nodes = (char **)realloc(nodes, (n_nodes+2)*sizeof(char *));
471 nodes[n_nodes] = strdup(fnbuf);
478 for(i=0; i<n_checked; ++i)
484 nodes[n_nodes] = NULL;
490 Reads the list of mounted devices from /etc/mtab and records the mount points.
492 void check_mounts(Device *devices)
497 file = setmntent("/etc/mtab", "r");
501 while((me = getmntent(file)))
505 for(i=0; devices[i].node; ++i)
506 if(!strcmp(devices[i].devname, me->mnt_fsname))
508 devices[i].mount_point = strdup(me->mnt_dir);
511 printf("Device %s is mounted on %s\n", devices[i].node, devices[i].mount_point);
519 Returns an array of all mountable devices.
521 Device *get_devices(void)
524 Device *devices = NULL;
526 char **mounted = NULL;
530 nodes = get_device_nodes("/dev/disk/by-id");
531 fstab = get_fstab_devices();
533 for(i=0; nodes[i]; ++i)
538 printf("Examining device %s\n", nodes[i]);
540 props = get_device_properties(nodes[i]);
544 printf(" No properties\n");
551 for(j=0; props[j].name; ++j)
552 printf(" %s = %s\n", props[j].name, props[j].value);
555 if(can_mount(props, fstab))
566 printf(" Using device\n");
568 devname = get_property_value(props, "DEVNAME");
570 /* Get a human-readable label for the device. Use filesystem label,
571 filesystem UUID or device node name in order of preference. */
572 label = get_property_value(props, "ID_FS_LABEL");
574 label = get_property_value(props, "ID_FS_UUID");
580 for(ptr=label; *ptr; ++ptr)
585 vendor = get_property_value(props, "ID_VENDOR");
586 model = get_property_value(props, "ID_MODEL");
588 pos = snprintf(buf, sizeof(buf), "%s", label);
590 pos += snprintf(buf+pos, sizeof(buf)-pos, " (%s %s)", vendor, model);
594 /* Reserve space for a sentinel entry. */
595 devices = (Device *)realloc(devices, (n_devices+2)*sizeof(Device));
596 devices[n_devices].node = nodes[i];
597 devices[n_devices].devname = strdup(devname);
598 devices[n_devices].label = strdup(label);
599 devices[n_devices].description = strdup(buf);
600 devices[n_devices].mount_point = NULL;
601 devices[n_devices].time = st.st_mtime;
606 free_properties(props);
610 free_string_array(mounted);
614 /* Terminate the array with NULL pointers. */
615 devices[n_devices].node = NULL;
616 devices[n_devices].devname = NULL;
617 devices[n_devices].label = NULL;
618 devices[n_devices].description = NULL;
619 devices[n_devices].mount_point = NULL;
621 check_mounts(devices);
628 Frees an array of devices and all strings contained in it.
630 void free_devices(Device *devices)
635 for(i=0; devices[i].node; ++i)
637 free(devices[i].node);
638 free(devices[i].devname);
639 free(devices[i].label);
640 free(devices[i].description);
641 if(devices[i].mount_point)
642 free(devices[i].mount_point);
648 Mounts a device if it was not mounted, or unmounts if it was.
650 int toggle_device(Device *device, char *out_buf, int out_size)
652 int umount = !!device->mount_point;
653 char mount_point[1024];
657 struct timeval timeout;
664 /* Find a mount point that does not exist yet. */
669 len = snprintf(mount_point, sizeof(mount_point), "/media/%s", device->label);
670 if(len+2>=(int)sizeof(mount_point))
674 len += snprintf(mount_point+len, sizeof(mount_point)-len, "_%c", suffix);
676 if(access(mount_point, F_OK)<0 && errno==ENOENT)
696 printf("Running pumount %s\n", device->node);
698 printf("Running pmount %s %s\n", device->node, mount_point+7);
706 execl("/usr/bin/pumount", "pumount", device->node, NULL);
708 execl("/usr/bin/pmount", "pmount", device->node, mount_point+7, NULL);
718 FD_SET(pipe_fd[0], &fds);
720 timeout.tv_usec = 200000;
724 /* The write fd for the pipe may be inherited by a fuse server
725 process and stay open indefinitely. */
726 if(select(pipe_fd[0]+1, &fds, NULL, NULL, &timeout))
730 len = read(pipe_fd[0], out_buf+pos, out_size-pos-1);
735 else if(waitpid(pid, &status, 0))
744 waitpid(pid, &status, 0);
750 if(WIFEXITED(status))
752 if(WEXITSTATUS(status))
753 printf("Command exited successfully\n");
755 printf("Command exited with status %d\n", WEXITSTATUS(status));
757 else if(WIFSIGNALED(status))
758 printf("Command terminated with signal %d\n", WTERMSIG(status));
760 printf("Command exited with unknown result %04X\n", status);
763 if(!WIFEXITED(status) || WEXITSTATUS(status))
768 free(device->mount_point);
769 device->mount_point = NULL;
772 device->mount_point = strdup(mount_point);
778 Refreshes both the internal devices array and the GUI list.
780 int refresh_devices(GuiContext *context, int umount)
783 GtkTreeSelection *selection;
789 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(context->list)));
790 gtk_list_store_clear(store);
792 free_devices(context->devices);
794 context->devices = get_devices();
795 if(!context->devices)
798 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(context->list));
800 /* Populate the list with devices in appropriate state. */
803 for(i=0; context->devices[i].node; ++i)
807 dev = &context->devices[i];
808 if(umount<0 || !dev->mount_point==!umount)
810 gtk_list_store_append(store, &iter);
811 gtk_list_store_set(store, &iter,
814 2, !!dev->mount_point,
819 /* Pre-select the device that appeared on the system most recently. */
821 gtk_tree_selection_select_iter(selection, &iter);
832 Handles an automatic refresh of the device list in response to inotify events.
834 gboolean refresh_devices_idle(gpointer data)
836 GuiContext *context = (GuiContext *)data;
839 n_listed = refresh_devices(context, -1);
840 context->refresh_pending = 0;
842 if(context->autohide)
845 gtk_widget_show_all(context->window);
847 gtk_widget_hide(context->window);
854 Callback for selection in the device list changing. Updates the action button
855 label according to device status.
857 void selection_changed(GtkTreeSelection *selection, gpointer user_data)
859 GuiContext *context = (GuiContext *)user_data;
864 if(!gtk_tree_selection_get_selected(selection, &model, &iter))
867 gtk_tree_model_get(model, &iter, 1, &device, -1);
868 gtk_button_set_label(GTK_BUTTON(context->button), (device->mount_point ? "Unmount" : "Mount"));
872 Callback for activating a row in the device list. Mounts or unmounts the
873 device depending on operating mode.
875 void row_activated(GtkTreeView *list, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data)
877 GuiContext *context = (GuiContext *)user_data;
885 model = gtk_tree_view_get_model(list);
887 if(!gtk_tree_model_get_iter(model, &iter, path))
890 gtk_tree_model_get(model, &iter, 1, &device, -1);
891 ret = toggle_device(device, output, sizeof(output));
896 /* Pmount terminated with nonzero status or a signal. Display an
897 error to the user. */
898 dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "%s", output);
900 g_signal_connect(dialog, "response", G_CALLBACK(>k_widget_destroy), dialog);
902 g_signal_connect(dialog, "response", G_CALLBACK(>k_main_quit), NULL);
903 gtk_widget_show_all(dialog);
909 gtk_list_store_set(GTK_LIST_STORE(model), &iter,
910 2, !!device->mount_point,
911 3, device->mount_point,
914 gtk_button_set_label(GTK_BUTTON(context->button), (device->mount_point ? "Unmount" : "Mount"));
919 if(context->post_mount_command && device->mount_point)
922 printf("Running %s in %s\n", context->post_mount_command, device->mount_point);
927 chdir(device->mount_point);
928 execlp(context->post_mount_command, context->post_mount_command, NULL);
938 Callback for the mount/unmount button. Causes the selected row in the device
939 list to be activated.
941 void button_clicked(GtkButton *button, gpointer user_data)
943 GuiContext *context = (GuiContext *)user_data;
944 GtkTreeSelection *selection;
948 GtkTreeViewColumn *column;
950 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(context->list));
951 gtk_tree_selection_get_selected(selection, &model, &iter);
952 path = gtk_tree_model_get_path(model, &iter);
953 column = gtk_tree_view_get_column(GTK_TREE_VIEW(context->list), 0);
954 gtk_tree_view_row_activated(GTK_TREE_VIEW(context->list), path, column);
955 gtk_tree_path_free(path);
961 Global key press callback for the window.
963 gboolean key_press(GtkWidget *widget, GdkEvent *event, gpointer user_data)
965 if(event->key.keyval==GDK_KEY_Escape)
978 Callback for inotify events.
980 gboolean inotify_event_available(GIOChannel *source, GIOCondition condition, gpointer user_data)
982 GuiContext *context = (GuiContext *)user_data;
984 char eventbuf[sizeof(struct inotify_event)+NAME_MAX+1];
987 fd = g_io_channel_unix_get_fd(source);
988 len = read(fd, eventbuf, sizeof(eventbuf));
989 if(len>=(int)sizeof(struct inotify_event))
991 if(!context->refresh_pending)
993 g_timeout_add(500, &refresh_devices_idle, context);
994 context->refresh_pending = 1;
1003 void show_help(void)
1005 printf("pmount-gui\n"
1006 "Copyright (c) 2011-2015 Mikko Rasa, Mikkosoft Productions\n\n"
1007 "Usage: pmount-gui [-v] [-u] [-r <command>] [-m|-M] [-h]\n\n"
1009 " -v Increase verbosity\n"
1010 " -u Unmount a device (default is mount)\n"
1011 " -r Run a command after mounting\n"
1012 " -m Start a persistent mount manager\n"
1013 " -M Like -m, but hide the window if there are no devices\n"
1014 " -h Display this help\n");
1017 int main(int argc, char **argv)
1021 GtkWidget *viewport;
1022 GtkListStore *store;
1023 GtkTreeSelection *selection;
1024 GtkCellRenderer *mounted_toggle;
1029 context.manager = 0;
1030 context.autohide = 0;
1031 context.devices = NULL;
1032 context.post_mount_command = NULL;
1033 context.inotify_fd = -1;
1034 context.dev_wd = -1;
1035 context.inotify_channel = NULL;
1036 context.refresh_pending = 0;
1038 gtk_init(&argc, &argv);
1040 while((opt = getopt(argc, argv, "vur:mMh"))!=-1) switch(opt)
1049 context.post_mount_command = optarg;
1052 context.manager = 1;
1053 context.autohide = 0;
1056 context.manager = 1;
1057 context.autohide = 1;
1064 context.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1065 gtk_container_set_border_width(GTK_CONTAINER(context.window), 5);
1066 g_signal_connect(context.window, "destroy", G_CALLBACK(>k_main_quit), NULL);
1067 g_signal_connect(context.window, "key-press-event", G_CALLBACK(&key_press), NULL);
1069 box = gtk_vbox_new(FALSE, 5);
1070 gtk_container_add(GTK_CONTAINER(context.window), box);
1072 viewport = gtk_viewport_new(NULL, NULL);
1073 gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_IN);
1074 gtk_box_pack_start(GTK_BOX(box), viewport, TRUE, TRUE, 0);
1076 context.list = gtk_tree_view_new();
1077 gtk_container_add(GTK_CONTAINER(viewport), context.list);
1078 g_signal_connect(context.list, "row-activated", G_CALLBACK(&row_activated), &context);
1080 store = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_BOOLEAN, G_TYPE_STRING);
1081 gtk_tree_view_set_model(GTK_TREE_VIEW(context.list), GTK_TREE_MODEL(store));
1082 gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(context.list),
1083 -1, "Device", gtk_cell_renderer_text_new(), "text", 0, NULL);
1087 GtkTreeViewColumn *mounted_column;
1088 GtkCellRenderer *mount_point_renderer;
1090 mounted_column = gtk_tree_view_column_new();
1091 gtk_tree_view_column_set_title(mounted_column, "Mounted");
1093 mounted_toggle = gtk_cell_renderer_toggle_new();
1094 gtk_tree_view_column_pack_start(mounted_column, mounted_toggle, FALSE);
1095 gtk_tree_view_column_add_attribute(mounted_column, mounted_toggle, "active", 2);
1097 mount_point_renderer = gtk_cell_renderer_text_new();
1098 gtk_tree_view_column_pack_start(mounted_column, mount_point_renderer, TRUE);
1099 gtk_tree_view_column_add_attribute(mounted_column, mount_point_renderer, "text", 3);
1101 gtk_tree_view_insert_column(GTK_TREE_VIEW(context.list), mounted_column, -1);
1103 context.inotify_fd = inotify_init();
1104 if(context.inotify_fd>=0)
1106 context.dev_wd = inotify_add_watch(context.inotify_fd, "/dev/disk/by-id", IN_CREATE|IN_DELETE);
1108 context.inotify_channel = g_io_channel_unix_new(context.inotify_fd);
1109 g_io_add_watch(context.inotify_channel, G_IO_IN, &inotify_event_available, &context);
1112 printf("Warning: Unable to initialize inotify\n");
1117 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(context.list));
1118 g_signal_connect(selection, "changed", G_CALLBACK(&selection_changed), &context);
1120 context.button = gtk_button_new_with_label(umount ? "Unmount" : "Mount");
1121 g_signal_connect(context.button, "clicked", G_CALLBACK(&button_clicked), &context);
1122 gtk_box_pack_start(GTK_BOX(box), context.button, FALSE, TRUE, 0);
1124 n_listed = refresh_devices(&context, umount);
1126 if(n_listed || (context.manager && !context.autohide))
1127 gtk_widget_show_all(context.window);
1128 else if(!context.manager)
1132 /* Don't show the main window if no devices were listed. */
1133 dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_WARNING, GTK_BUTTONS_OK,
1134 "No devices to %s", (umount ? "unmount" : "mount"));
1135 g_signal_connect(dialog, "response", G_CALLBACK(>k_main_quit), NULL);
1136 gtk_widget_show_all(dialog);
1141 free_devices(context.devices);
1142 if(context.inotify_fd>=0)
1143 close(context.inotify_fd);