Rework the GSettings keyfile backend
[platform/upstream/glib.git] / gio / gkeyfilesettingsbackend.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  * Copyright © 2010 Novell, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the licence, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Authors: Vincent Untz <vuntz@gnome.org>
21  *          Ryan Lortie <desrt@desrt.ca>
22  */
23
24 #include "config.h"
25
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "gfile.h"
30 #include "gfileinfo.h"
31 #include "gfilemonitor.h"
32 #include "gsimplepermission.h"
33 #include "gsettingsbackend.h"
34
35 #include "gioalias.h"
36
37 #define G_TYPE_KEYFILE_SETTINGS_BACKEND      (g_keyfile_settings_backend_get_type ())
38 #define G_KEYFILE_SETTINGS_BACKEND(inst)     (G_TYPE_CHECK_INSTANCE_CAST ((inst),      \
39                                               G_TYPE_KEYFILE_SETTINGS_BACKEND,         \
40                                               GKeyfileSettingsBackend))
41 #define G_IS_KEYFILE_SETTINGS_BACKEND(inst)  (G_TYPE_CHECK_INSTANCE_TYPE ((inst),      \
42                                               G_TYPE_KEYFILE_SETTINGS_BACKEND))
43
44
45 typedef GSettingsBackendClass GKeyfileSettingsBackendClass;
46
47 typedef struct
48 {
49   GSettingsBackend   parent_instance;
50
51   GKeyFile          *keyfile;
52   GPermission       *permission;
53   gboolean           writable;
54
55   gchar             *prefix;
56   gint               prefix_len;
57   gchar             *root_group;
58   gint               root_group_len;
59
60   GFile             *file;
61   GFileMonitor      *file_monitor;
62   guint8             digest[32];
63   GFile             *dir;
64   GFileMonitor      *dir_monitor;
65 } GKeyfileSettingsBackend;
66
67 G_DEFINE_TYPE (GKeyfileSettingsBackend,
68                g_keyfile_settings_backend,
69                G_TYPE_SETTINGS_BACKEND)
70
71 static void
72 compute_checksum (guint8        *digest,
73                   gconstpointer  contents,
74                   gsize          length)
75 {
76   GChecksum *checksum;
77   gsize len = 32;
78
79   checksum = g_checksum_new (G_CHECKSUM_SHA256);
80   g_checksum_update (checksum, contents, length);
81   g_checksum_get_digest (checksum, digest, &len);
82   g_checksum_free (checksum);
83   g_assert (len == 32);
84 }
85
86 static void
87 g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend *kfsb)
88 {
89   gchar *contents;
90   gsize length;
91
92   contents = g_key_file_to_data (kfsb->keyfile, &length, NULL);
93   g_file_replace_contents (kfsb->file, contents, length, NULL, FALSE,
94                            G_FILE_CREATE_REPLACE_DESTINATION,
95                            NULL, NULL, NULL);
96
97   compute_checksum (kfsb->digest, contents, length);
98   g_free (contents);
99 }
100
101 static gboolean
102 group_name_matches (const gchar *group_name,
103                     const gchar *prefix)
104 {
105   /* sort of like g_str_has_prefix() except that it must be an exact
106    * match or the prefix followed by '/'.
107    *
108    * for example 'a' is a prefix of 'a' and 'a/b' but not 'ab'.
109    */
110   gint i;
111
112   for (i = 0; prefix[i]; i++)
113     if (prefix[i] != group_name[i])
114       return FALSE;
115
116   return group_name[i] == '\0' || group_name[i] == '/';
117 }
118
119 static gboolean
120 convert_path (GKeyfileSettingsBackend  *kfsb,
121               const gchar              *key,
122               gchar                   **group,
123               gchar                   **basename)
124 {
125   gint key_len = strlen (key);
126   gint i;
127
128   if (key_len < kfsb->prefix_len ||
129       memcmp (key, kfsb->prefix, kfsb->prefix_len) != 0)
130     return FALSE;
131
132   key_len -= kfsb->prefix_len;
133   key += kfsb->prefix_len;
134
135   for (i = key_len; i >= 0; i--)
136     if (key[i] == '/')
137       break;
138
139   if (kfsb->root_group)
140     {
141       /* if a root_group was specified, make sure the user hasn't given
142        * a path that ghosts that group name
143        */
144       if (i == kfsb->root_group_len && memcmp (key, kfsb->root_group, i) == 0)
145         return FALSE;
146     }
147   else
148     {
149       /* if no root_group was given, ensure that the user gave a path */
150       if (i == -1)
151         return FALSE;
152     }
153
154   if (group)
155     {
156       if (i >= 0)
157         {
158           *group = g_memdup (key, i + 1);
159           (*group)[i] = '\0';
160         }
161       else
162         *group = g_strdup (kfsb->root_group);
163     }
164
165   if (basename)
166     *basename = g_memdup (key + i + 1, key_len - i);
167
168   return TRUE;
169 }
170
171 gboolean
172 path_is_valid (GKeyfileSettingsBackend *kfsb,
173                const gchar             *path)
174 {
175   return convert_path (kfsb, path, NULL, NULL);
176 }
177
178 static GVariant *
179 get_from_keyfile (GKeyfileSettingsBackend *kfsb,
180                   const GVariantType      *type,
181                   const gchar             *key)
182 {
183   GVariant *return_value = NULL;
184   gchar *group, *name;
185
186   if (convert_path (kfsb, key, &group, &name))
187     {
188       gchar *str;
189
190       g_assert (*name);
191
192       str = g_key_file_get_value (kfsb->keyfile, group, name, NULL);
193
194       if (str)
195         {
196           return_value = g_variant_parse (type, str, NULL, NULL, NULL);
197           g_free (str);
198         }
199
200       g_free (group);
201       g_free (name);
202     }
203
204   return return_value;
205 }
206
207 static gboolean
208 set_to_keyfile (GKeyfileSettingsBackend *kfsb,
209                 const gchar             *key,
210                 GVariant                *value)
211 {
212   gchar *group, *name;
213
214   if (convert_path (kfsb, key, &group, &name))
215     {
216       if (value)
217         {
218           gchar *str = g_variant_print (value, FALSE);
219           g_key_file_set_value (kfsb->keyfile, group, name, str);
220           g_variant_unref (g_variant_ref_sink (value));
221           g_free (str);
222         }
223       else
224         {
225           if (*name == '\0')
226             {
227               gchar **groups;
228               gint i;
229
230               groups = g_key_file_get_groups (kfsb->keyfile, NULL);
231
232               for (i = 0; groups[i]; i++)
233                 if (group_name_matches (groups[i], group))
234                   g_key_file_remove_group (kfsb->keyfile, groups[i], NULL);
235
236               g_strfreev (groups);
237             }
238           else
239             g_key_file_remove_key (kfsb->keyfile, group, name, NULL);
240         }
241
242       g_free (group);
243       g_free (name);
244
245       return TRUE;
246     }
247
248   return FALSE;
249 }
250
251 static GVariant *
252 g_keyfile_settings_backend_read (GSettingsBackend   *backend,
253                                  const gchar        *key,
254                                  const GVariantType *expected_type,
255                                  gboolean            default_value)
256 {
257   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
258
259   if (default_value)
260     return NULL;
261
262   return get_from_keyfile (kfsb, expected_type, key);
263 }
264
265 typedef struct
266 {
267   GKeyfileSettingsBackend *kfsb;
268   gboolean failed;
269 } WriteManyData;
270
271 static gboolean
272 g_keyfile_settings_backend_write_one (gpointer key,
273                                       gpointer value,
274                                       gpointer user_data)
275 {
276   WriteManyData *data = user_data;
277   gboolean success;
278
279   success = set_to_keyfile (data->kfsb, key, value);
280   g_assert (success);
281
282   return FALSE;
283 }
284
285 static gboolean
286 g_keyfile_settings_backend_check_one (gpointer key,
287                                       gpointer value,
288                                       gpointer user_data)
289 {
290   WriteManyData *data = user_data;
291
292   return data->failed = !path_is_valid (data->kfsb, key);
293 }
294
295 static gboolean
296 g_keyfile_settings_backend_write_many (GSettingsBackend *backend,
297                                        GTree            *tree,
298                                        gpointer          origin_tag)
299 {
300   WriteManyData data = { G_KEYFILE_SETTINGS_BACKEND (backend) };
301
302   if (!data.kfsb->writable)
303     return FALSE;
304
305   g_tree_foreach (tree, g_keyfile_settings_backend_check_one, &data);
306
307   if (data.failed)
308     return FALSE;
309
310   g_tree_foreach (tree, g_keyfile_settings_backend_write_one, &data);
311   g_keyfile_settings_backend_keyfile_write (data.kfsb);
312
313   g_settings_backend_changed_tree (backend, tree, origin_tag);
314
315   return TRUE;
316 }
317
318 static gboolean
319 g_keyfile_settings_backend_write (GSettingsBackend *backend,
320                                   const gchar      *key,
321                                   GVariant         *value,
322                                   gpointer          origin_tag)
323 {
324   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
325   gboolean success;
326
327   if (!kfsb->writable)
328     return FALSE;
329
330   success = set_to_keyfile (kfsb, key, value);
331
332   if (success)
333     {
334       g_settings_backend_changed (backend, key, origin_tag);
335       g_keyfile_settings_backend_keyfile_write (kfsb);
336     }
337
338   return success;
339 }
340
341 static void
342 g_keyfile_settings_backend_reset_path (GSettingsBackend *backend,
343                                        const gchar      *path,
344                                        gpointer          origin_tag)
345 {
346   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
347
348   if (set_to_keyfile (kfsb, path, NULL))
349     g_keyfile_settings_backend_keyfile_write (kfsb);
350
351   g_settings_backend_path_changed (backend, path, origin_tag);
352 }
353
354 static void
355 g_keyfile_settings_backend_reset (GSettingsBackend *backend,
356                                   const gchar      *key,
357                                   gpointer          origin_tag)
358 {
359   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
360
361   if (set_to_keyfile (kfsb, key, NULL))
362     g_keyfile_settings_backend_keyfile_write (kfsb);
363
364   g_settings_backend_changed (backend, key, origin_tag);
365 }
366
367 static gboolean
368 g_keyfile_settings_backend_get_writable (GSettingsBackend *backend,
369                                          const gchar      *name)
370 {
371   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
372
373   return kfsb->writable && path_is_valid (kfsb, name);
374 }
375
376 static GPermission *
377 g_keyfile_settings_backend_get_permission (GSettingsBackend *backend,
378                                            const gchar      *path)
379 {
380   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
381
382   return g_object_ref (kfsb->permission);
383 }
384
385 static void
386 keyfile_to_tree (GKeyfileSettingsBackend *kfsb,
387                  GTree                   *tree,
388                  GKeyFile                *keyfile,
389                  gboolean                 dup_check)
390 {
391   gchar **groups;
392   gint i;
393
394   groups = g_key_file_get_groups (keyfile, NULL);
395   for (i = 0; groups[i]; i++)
396     {
397       gboolean is_root_group;
398       gchar **keys;
399       gint j;
400
401       is_root_group = g_strcmp0 (kfsb->root_group, groups[i]) == 0;
402       keys = g_key_file_get_keys (keyfile, groups[i], NULL, NULL);
403
404       for (j = 0; keys[j]; j++)
405         {
406           gchar *path, *value;
407
408           if (is_root_group)
409             path = g_strdup_printf ("%s%s", kfsb->prefix, keys[j]);
410           else
411             path = g_strdup_printf ("%s%s/%s", kfsb->prefix, groups[i], keys[j]);
412
413           value = g_key_file_get_value (keyfile, groups[i], keys[j], NULL);
414
415           if (dup_check && g_strcmp0 (g_tree_lookup (tree, path), value) == 0)
416             {
417               g_tree_remove (tree, path);
418               g_free (value);
419               g_free (path);
420             }
421           else
422             g_tree_insert (tree, path, value);
423         }
424
425       g_strfreev (keys);
426     }
427   g_strfreev (groups);
428 }
429
430 static void
431 g_keyfile_settings_backend_keyfile_reload (GKeyfileSettingsBackend *kfsb)
432 {
433   guint8 digest[32];
434   gchar *contents;
435   gsize length;
436
437   contents = NULL;
438   length = 0;
439
440   g_file_load_contents (kfsb->file, NULL, &contents, &length, NULL, NULL);
441   compute_checksum (digest, contents, length);
442
443   if (memcmp (kfsb->digest, digest, sizeof digest) != 0)
444     {
445       GKeyFile *keyfiles[2];
446       GTree *tree;
447
448       tree = g_tree_new_full ((GCompareDataFunc) strcmp, NULL,
449                               g_free, g_free);
450
451       keyfiles[0] = kfsb->keyfile;
452       keyfiles[1] = g_key_file_new ();
453
454       if (length > 0)
455         g_key_file_load_from_data (keyfiles[1], contents, length,
456                                    G_KEY_FILE_KEEP_COMMENTS |
457                                    G_KEY_FILE_KEEP_TRANSLATIONS, NULL);
458
459       keyfile_to_tree (kfsb, tree, keyfiles[0], FALSE);
460       keyfile_to_tree (kfsb, tree, keyfiles[1], TRUE);
461       g_key_file_free (keyfiles[0]);
462       kfsb->keyfile = keyfiles[1];
463
464       if (g_tree_nnodes (tree) > 0)
465         g_settings_backend_changed_tree (&kfsb->parent_instance, tree, NULL);
466
467       g_tree_unref (tree);
468
469       memcpy (kfsb->digest, digest, sizeof digest);
470     }
471
472   g_free (contents);
473 }
474
475 static void
476 g_keyfile_settings_backend_keyfile_writable (GKeyfileSettingsBackend *kfsb)
477 {
478   GFileInfo *fileinfo;
479   gboolean writable;
480
481   fileinfo = g_file_query_info (kfsb->dir, "access::*", 0, NULL, NULL);
482
483   if (fileinfo)
484     {
485       writable =
486         g_file_info_get_attribute_boolean (fileinfo, G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE) &&
487         g_file_info_get_attribute_boolean (fileinfo, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE);
488       g_object_unref (fileinfo);
489     }
490   else
491     writable = FALSE;
492
493   if (writable != kfsb->writable)
494     {
495       kfsb->writable = writable;
496       g_settings_backend_path_writable_changed (&kfsb->parent_instance, "/");
497     }
498 }
499
500 static void
501 g_keyfile_settings_backend_finalize (GObject *object)
502 {
503   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (object);
504
505   g_key_file_free (kfsb->keyfile);
506   g_object_unref (kfsb->permission);
507
508   g_file_monitor_cancel (kfsb->file_monitor);
509   g_object_unref (kfsb->file_monitor);
510   g_object_unref (kfsb->file);
511
512   g_file_monitor_cancel (kfsb->dir_monitor);
513   g_object_unref (kfsb->dir_monitor);
514   g_object_unref (kfsb->dir);
515
516   g_free (kfsb->root_group);
517   g_free (kfsb->prefix);
518
519   G_OBJECT_CLASS (g_keyfile_settings_backend_parent_class)
520     ->finalize (object);
521 }
522
523 static void
524 g_keyfile_settings_backend_init (GKeyfileSettingsBackend *kfsb)
525 {
526 }
527
528 static void
529 g_keyfile_settings_backend_class_init (GKeyfileSettingsBackendClass *class)
530 {
531   GObjectClass *object_class = G_OBJECT_CLASS (class);
532
533   object_class->finalize = g_keyfile_settings_backend_finalize;
534
535   class->read = g_keyfile_settings_backend_read;
536   class->write = g_keyfile_settings_backend_write;
537   class->write_keys = g_keyfile_settings_backend_write_many;
538   class->reset = g_keyfile_settings_backend_reset;
539   class->reset_path = g_keyfile_settings_backend_reset_path;
540   class->get_writable = g_keyfile_settings_backend_get_writable;
541   class->get_permission = g_keyfile_settings_backend_get_permission;
542   /* No need to implement subscribed/unsubscribe: the only point would be to
543    * stop monitoring the file when there's no GSettings anymore, which is no
544    * big win. */
545 }
546
547 static void
548 file_changed (GFileMonitor      *monitor,
549               GFile             *file,
550               GFile             *other_file,
551               GFileMonitorEvent  event_type,
552               gpointer           user_data)
553 {
554   GKeyfileSettingsBackend *kfsb = user_data;
555
556   g_keyfile_settings_backend_keyfile_reload (kfsb);
557 }
558
559 static void
560 dir_changed (GFileMonitor       *monitor,
561               GFile             *file,
562               GFile             *other_file,
563               GFileMonitorEvent  event_type,
564               gpointer           user_data)
565 {
566   GKeyfileSettingsBackend *kfsb = user_data;
567
568   g_keyfile_settings_backend_keyfile_writable (kfsb);
569 }
570
571 /**
572  * g_keyfile_settings_backend_new:
573  * @filename: the filename of the keyfile
574  * @root_path: the path under which all settings keys appear
575  * @root_group: (allow-none): the group name corresponding to
576  *              @root_path, or %NULL
577  * Returns: a keyfile-backed #GSettingsBackend
578  *
579  * Creates a keyfile-backed #GSettingsBackend.
580  *
581  * The filename of the keyfile to use is given by @filename.
582  *
583  * All settings read to or written from the backend must fall under the
584  * path given in @root_path (which must start and end with a slash and
585  * not contain two consecutive slashes).  @root_path may be "/".
586  *
587  * If @root_group is non-%NULL then it specifies the name of the keyfile
588  * group used for keys that are written directly below @root_path.  For
589  * example, if @root_path is "/apps/example/" and @root_group is
590  * "toplevel", then settings the key "/apps/example/enabled" to a value
591  * of %TRUE will cause the following to appear in the keyfile:
592  *
593  * <programlisting>
594  *   [toplevel]
595  *   foo=true
596  * </programlisting>
597  *
598  * If @root_group is %NULL then it is not permitted to store keys
599  * directly below the @root_path.
600  *
601  * For keys not stored directly below @root_path (ie: in a sub-path),
602  * the name of the subpath (with the final slash stripped) is used as
603  * the name of the keyfile group.  To continue the example, if
604  * were stored in "/apps/example/profiles/default/font-size" were set to
605  * 12 then the following would appear in the keyfile:
606  *
607  * <programlisting>
608  *   [profiles/default]
609  *   font-size=12
610  * </programlisting>
611  *
612  * The backend will refuse writes (and return writability as being
613  * %FALSE) for keys outside of @root_path and, in the event that
614  * @root_group is %NULL, also for keys directly under @root_path.
615  * Writes will also be refused if the backend detects that it has the
616  * inability to rewrite the keyfile (ie: the containing directory is not
617  * writable).
618  **/
619 GSettingsBackend *
620 g_keyfile_settings_backend_new (const gchar *filename,
621                                 const gchar *root_path,
622                                 const gchar *root_group)
623 {
624   GKeyfileSettingsBackend *kfsb;
625
626   g_return_val_if_fail (filename != NULL, NULL);
627   g_return_val_if_fail (root_path != NULL, NULL);
628   g_return_val_if_fail (g_str_has_prefix (root_path, "/"), NULL);
629   g_return_val_if_fail (g_str_has_suffix (root_path, "/"), NULL);
630   g_return_val_if_fail (strstr (root_path, "//") == NULL, NULL);
631
632   kfsb = g_object_new (G_TYPE_KEYFILE_SETTINGS_BACKEND, NULL);
633   kfsb->keyfile = g_key_file_new ();
634   kfsb->permission = g_simple_permission_new (TRUE);
635
636   kfsb->file = g_file_new_for_path (filename);
637   kfsb->dir = g_file_get_parent (kfsb->file);
638   g_file_make_directory_with_parents (kfsb->dir, NULL, NULL);
639
640   kfsb->file_monitor = g_file_monitor_file (kfsb->file, 0, NULL, NULL);
641   kfsb->dir_monitor = g_file_monitor_file (kfsb->dir, 0, NULL, NULL);
642
643   kfsb->prefix_len = strlen (root_path);
644   kfsb->prefix = g_strdup (root_path);
645
646   if (root_group)
647     {
648       kfsb->root_group_len = strlen (root_group);
649       kfsb->root_group = g_strdup (root_group);
650     }
651
652   compute_checksum (kfsb->digest, NULL, 0);
653
654   g_signal_connect (kfsb->file_monitor, "changed",
655                     G_CALLBACK (file_changed), kfsb);
656   g_signal_connect (kfsb->dir_monitor, "changed",
657                     G_CALLBACK (dir_changed), kfsb);
658
659   g_keyfile_settings_backend_keyfile_writable (kfsb);
660   g_keyfile_settings_backend_keyfile_reload (kfsb);
661
662   return G_SETTINGS_BACKEND (kfsb);
663 }
664
665 #define __G_KEYFILE_SETTINGS_BACKEND_C__
666 #include "gioaliasdef.c"