Imported Upstream version 2.67.4
[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.1 of the License, 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, see <http://www.gnu.org/licenses/>.
17  *
18  * Authors: Vincent Untz <vuntz@gnome.org>
19  *          Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include <glib.h>
25 #include <glibintl.h>
26
27 #include <stdio.h>
28 #include <string.h>
29
30 #include "gfile.h"
31 #include "gfileinfo.h"
32 #include "gfileenumerator.h"
33 #include "gfilemonitor.h"
34 #include "gsimplepermission.h"
35 #include "gsettingsbackendinternal.h"
36 #include "giomodule-priv.h"
37 #include "gportalsupport.h"
38
39
40 #define G_TYPE_KEYFILE_SETTINGS_BACKEND      (g_keyfile_settings_backend_get_type ())
41 #define G_KEYFILE_SETTINGS_BACKEND(inst)     (G_TYPE_CHECK_INSTANCE_CAST ((inst),      \
42                                               G_TYPE_KEYFILE_SETTINGS_BACKEND,         \
43                                               GKeyfileSettingsBackend))
44 #define G_IS_KEYFILE_SETTINGS_BACKEND(inst)  (G_TYPE_CHECK_INSTANCE_TYPE ((inst),      \
45                                               G_TYPE_KEYFILE_SETTINGS_BACKEND))
46
47
48 typedef GSettingsBackendClass GKeyfileSettingsBackendClass;
49
50 typedef enum {
51   PROP_FILENAME = 1,
52   PROP_ROOT_PATH,
53   PROP_ROOT_GROUP,
54   PROP_DEFAULTS_DIR
55 } GKeyfileSettingsBackendProperty;
56
57 typedef struct
58 {
59   GSettingsBackend   parent_instance;
60
61   GKeyFile          *keyfile;
62   GPermission       *permission;
63   gboolean           writable;
64   char              *defaults_dir;
65   GKeyFile          *system_keyfile;
66   GHashTable        *system_locks; /* Used as a set, owning the strings it contains */
67
68   gchar             *prefix;
69   gint               prefix_len;
70   gchar             *root_group;
71   gint               root_group_len;
72
73   GFile             *file;
74   GFileMonitor      *file_monitor;
75   guint8             digest[32];
76   GFile             *dir;
77   GFileMonitor      *dir_monitor;
78 } GKeyfileSettingsBackend;
79
80 #ifdef G_OS_WIN32
81 #define EXTENSION_PRIORITY 10
82 #else
83 #define EXTENSION_PRIORITY (glib_should_use_portal () && !glib_has_dconf_access_in_sandbox () ? 110 : 10)
84 #endif
85
86 G_DEFINE_TYPE_WITH_CODE (GKeyfileSettingsBackend,
87                          g_keyfile_settings_backend,
88                          G_TYPE_SETTINGS_BACKEND,
89                          _g_io_modules_ensure_extension_points_registered ();
90                          g_io_extension_point_implement (G_SETTINGS_BACKEND_EXTENSION_POINT_NAME,
91                                                          g_define_type_id, "keyfile", EXTENSION_PRIORITY))
92
93 static void
94 compute_checksum (guint8        *digest,
95                   gconstpointer  contents,
96                   gsize          length)
97 {
98   GChecksum *checksum;
99   gsize len = 32;
100
101   checksum = g_checksum_new (G_CHECKSUM_SHA256);
102   g_checksum_update (checksum, contents, length);
103   g_checksum_get_digest (checksum, digest, &len);
104   g_checksum_free (checksum);
105   g_assert (len == 32);
106 }
107
108 static gboolean
109 g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend  *kfsb,
110                                           GError                  **error)
111 {
112   gchar *contents;
113   gsize length;
114   gboolean success;
115
116   contents = g_key_file_to_data (kfsb->keyfile, &length, NULL);
117   success = g_file_replace_contents (kfsb->file, contents, length, NULL, FALSE,
118                                      G_FILE_CREATE_REPLACE_DESTINATION |
119                                      G_FILE_CREATE_PRIVATE,
120                                      NULL, NULL, error);
121
122   compute_checksum (kfsb->digest, contents, length);
123   g_free (contents);
124
125   return success;
126 }
127
128 static gboolean
129 group_name_matches (const gchar *group_name,
130                     const gchar *prefix)
131 {
132   /* sort of like g_str_has_prefix() except that it must be an exact
133    * match or the prefix followed by '/'.
134    *
135    * for example 'a' is a prefix of 'a' and 'a/b' but not 'ab'.
136    */
137   gint i;
138
139   for (i = 0; prefix[i]; i++)
140     if (prefix[i] != group_name[i])
141       return FALSE;
142
143   return group_name[i] == '\0' || group_name[i] == '/';
144 }
145
146 static gboolean
147 convert_path (GKeyfileSettingsBackend  *kfsb,
148               const gchar              *key,
149               gchar                   **group,
150               gchar                   **basename)
151 {
152   gsize key_len = strlen (key);
153   const gchar *last_slash;
154
155   if (key_len < kfsb->prefix_len ||
156       memcmp (key, kfsb->prefix, kfsb->prefix_len) != 0)
157     return FALSE;
158
159   key_len -= kfsb->prefix_len;
160   key += kfsb->prefix_len;
161
162   last_slash = strrchr (key, '/');
163
164   /* Disallow empty group names or key names */
165   if (key_len == 0 ||
166       (last_slash != NULL &&
167        (*(last_slash + 1) == '\0' ||
168         last_slash == key)))
169     return FALSE;
170
171   if (kfsb->root_group)
172     {
173       /* if a root_group was specified, make sure the user hasn't given
174        * a path that ghosts that group name
175        */
176       if (last_slash != NULL && (last_slash - key) == kfsb->root_group_len && memcmp (key, kfsb->root_group, last_slash - key) == 0)
177         return FALSE;
178     }
179   else
180     {
181       /* if no root_group was given, ensure that the user gave a path */
182       if (last_slash == NULL)
183         return FALSE;
184     }
185
186   if (group)
187     {
188       if (last_slash != NULL)
189         {
190           *group = g_memdup2 (key, (last_slash - key) + 1);
191           (*group)[(last_slash - key)] = '\0';
192         }
193       else
194         *group = g_strdup (kfsb->root_group);
195     }
196
197   if (basename)
198     {
199       if (last_slash != NULL)
200         *basename = g_memdup2 (last_slash + 1, key_len - (last_slash - key));
201       else
202         *basename = g_strdup (key);
203     }
204
205   return TRUE;
206 }
207
208 static gboolean
209 path_is_valid (GKeyfileSettingsBackend *kfsb,
210                const gchar             *path)
211 {
212   return convert_path (kfsb, path, NULL, NULL);
213 }
214
215 static GVariant *
216 get_from_keyfile (GKeyfileSettingsBackend *kfsb,
217                   const GVariantType      *type,
218                   const gchar             *key)
219 {
220   GVariant *return_value = NULL;
221   gchar *group, *name;
222
223   if (convert_path (kfsb, key, &group, &name))
224     {
225       gchar *str;
226       gchar *sysstr;
227
228       g_assert (*name);
229
230       sysstr = g_key_file_get_value (kfsb->system_keyfile, group, name, NULL);
231       str = g_key_file_get_value (kfsb->keyfile, group, name, NULL);
232       if (sysstr &&
233           (g_hash_table_contains (kfsb->system_locks, key) ||
234            str == NULL))
235         {
236           g_free (str);
237           str = g_steal_pointer (&sysstr);
238         }
239
240       if (str)
241         {
242           return_value = g_variant_parse (type, str, NULL, NULL, NULL);
243
244           /* As a special case, support values of type %G_VARIANT_TYPE_STRING
245            * not being quoted, since users keep forgetting to do it and then
246            * getting confused. */
247           if (return_value == NULL &&
248               g_variant_type_equal (type, G_VARIANT_TYPE_STRING) &&
249               str[0] != '\"')
250             {
251               GString *s = g_string_sized_new (strlen (str) + 2);
252               char *p = str;
253
254               g_string_append_c (s, '\"');
255               while (*p)
256                 {
257                   if (*p == '\"')
258                     g_string_append_c (s, '\\');
259                   g_string_append_c (s, *p);
260                   p++;
261                 }
262               g_string_append_c (s, '\"');
263               return_value = g_variant_parse (type, s->str, NULL, NULL, NULL);
264               g_string_free (s, TRUE);
265             }
266           g_free (str);
267         }
268
269       g_free (sysstr);
270
271       g_free (group);
272       g_free (name);
273     }
274
275   return return_value;
276 }
277
278 static gboolean
279 set_to_keyfile (GKeyfileSettingsBackend *kfsb,
280                 const gchar             *key,
281                 GVariant                *value)
282 {
283   gchar *group, *name;
284
285   if (g_hash_table_contains (kfsb->system_locks, key))
286     return FALSE;
287
288   if (convert_path (kfsb, key, &group, &name))
289     {
290       if (value)
291         {
292           gchar *str = g_variant_print (value, FALSE);
293           g_key_file_set_value (kfsb->keyfile, group, name, str);
294           g_variant_unref (g_variant_ref_sink (value));
295           g_free (str);
296         }
297       else
298         {
299           if (*name == '\0')
300             {
301               gchar **groups;
302               gint i;
303
304               groups = g_key_file_get_groups (kfsb->keyfile, NULL);
305
306               for (i = 0; groups[i]; i++)
307                 if (group_name_matches (groups[i], group))
308                   g_key_file_remove_group (kfsb->keyfile, groups[i], NULL);
309
310               g_strfreev (groups);
311             }
312           else
313             g_key_file_remove_key (kfsb->keyfile, group, name, NULL);
314         }
315
316       g_free (group);
317       g_free (name);
318
319       return TRUE;
320     }
321
322   return FALSE;
323 }
324
325 static GVariant *
326 g_keyfile_settings_backend_read (GSettingsBackend   *backend,
327                                  const gchar        *key,
328                                  const GVariantType *expected_type,
329                                  gboolean            default_value)
330 {
331   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
332
333   if (default_value)
334     return NULL;
335
336   return get_from_keyfile (kfsb, expected_type, key);
337 }
338
339 typedef struct
340 {
341   GKeyfileSettingsBackend *kfsb;
342   gboolean failed;
343 } WriteManyData;
344
345 static gboolean
346 g_keyfile_settings_backend_write_one (gpointer key,
347                                       gpointer value,
348                                       gpointer user_data)
349 {
350   WriteManyData *data = user_data;
351   gboolean success G_GNUC_UNUSED  /* when compiling with G_DISABLE_ASSERT */;
352
353   success = set_to_keyfile (data->kfsb, key, value);
354   g_assert (success);
355
356   return FALSE;
357 }
358
359 static gboolean
360 g_keyfile_settings_backend_check_one (gpointer key,
361                                       gpointer value,
362                                       gpointer user_data)
363 {
364   WriteManyData *data = user_data;
365
366   return data->failed = g_hash_table_contains (data->kfsb->system_locks, key) ||
367                         !path_is_valid (data->kfsb, key);
368 }
369
370 static gboolean
371 g_keyfile_settings_backend_write_tree (GSettingsBackend *backend,
372                                        GTree            *tree,
373                                        gpointer          origin_tag)
374 {
375   WriteManyData data = { G_KEYFILE_SETTINGS_BACKEND (backend), 0 };
376   gboolean success;
377   GError *error = NULL;
378
379   if (!data.kfsb->writable)
380     return FALSE;
381
382   g_tree_foreach (tree, g_keyfile_settings_backend_check_one, &data);
383
384   if (data.failed)
385     return FALSE;
386
387   g_tree_foreach (tree, g_keyfile_settings_backend_write_one, &data);
388   success = g_keyfile_settings_backend_keyfile_write (data.kfsb, &error);
389   if (error)
390     {
391       g_warning ("Failed to write keyfile to %s: %s", g_file_peek_path (data.kfsb->file), error->message);
392       g_error_free (error);
393     }
394
395   g_settings_backend_changed_tree (backend, tree, origin_tag);
396
397   return success;
398 }
399
400 static gboolean
401 g_keyfile_settings_backend_write (GSettingsBackend *backend,
402                                   const gchar      *key,
403                                   GVariant         *value,
404                                   gpointer          origin_tag)
405 {
406   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
407   gboolean success;
408   GError *error = NULL;
409
410   if (!kfsb->writable)
411     return FALSE;
412
413   success = set_to_keyfile (kfsb, key, value);
414
415   if (success)
416     {
417       g_settings_backend_changed (backend, key, origin_tag);
418       success = g_keyfile_settings_backend_keyfile_write (kfsb, &error);
419       if (error)
420         {
421           g_warning ("Failed to write keyfile to %s: %s", g_file_peek_path (kfsb->file), error->message);
422           g_error_free (error);
423         }
424     }
425
426   return success;
427 }
428
429 static void
430 g_keyfile_settings_backend_reset (GSettingsBackend *backend,
431                                   const gchar      *key,
432                                   gpointer          origin_tag)
433 {
434   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
435   GError *error = NULL;
436
437   if (set_to_keyfile (kfsb, key, NULL))
438     {
439       g_keyfile_settings_backend_keyfile_write (kfsb, &error);
440       if (error)
441         {
442           g_warning ("Failed to write keyfile to %s: %s", g_file_peek_path (kfsb->file), error->message);
443           g_error_free (error);
444         }
445     }
446
447   g_settings_backend_changed (backend, key, origin_tag);
448 }
449
450 static gboolean
451 g_keyfile_settings_backend_get_writable (GSettingsBackend *backend,
452                                          const gchar      *name)
453 {
454   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
455
456   return kfsb->writable &&
457          !g_hash_table_contains (kfsb->system_locks, name) &&
458          path_is_valid (kfsb, name);
459 }
460
461 static GPermission *
462 g_keyfile_settings_backend_get_permission (GSettingsBackend *backend,
463                                            const gchar      *path)
464 {
465   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (backend);
466
467   return g_object_ref (kfsb->permission);
468 }
469
470 static void
471 keyfile_to_tree (GKeyfileSettingsBackend *kfsb,
472                  GTree                   *tree,
473                  GKeyFile                *keyfile,
474                  gboolean                 dup_check)
475 {
476   gchar **groups;
477   gint i;
478
479   groups = g_key_file_get_groups (keyfile, NULL);
480   for (i = 0; groups[i]; i++)
481     {
482       gboolean is_root_group;
483       gchar **keys;
484       gint j;
485
486       is_root_group = g_strcmp0 (kfsb->root_group, groups[i]) == 0;
487
488       /* reject group names that will form invalid key names */
489       if (!is_root_group &&
490           (g_str_has_prefix (groups[i], "/") ||
491            g_str_has_suffix (groups[i], "/") || strstr (groups[i], "//")))
492         continue;
493
494       keys = g_key_file_get_keys (keyfile, groups[i], NULL, NULL);
495       g_assert (keys != NULL);
496
497       for (j = 0; keys[j]; j++)
498         {
499           gchar *path, *value;
500
501           /* reject key names with slashes in them */
502           if (strchr (keys[j], '/'))
503             continue;
504
505           if (is_root_group)
506             path = g_strdup_printf ("%s%s", kfsb->prefix, keys[j]);
507           else
508             path = g_strdup_printf ("%s%s/%s", kfsb->prefix, groups[i], keys[j]);
509
510           value = g_key_file_get_value (keyfile, groups[i], keys[j], NULL);
511
512           if (dup_check && g_strcmp0 (g_tree_lookup (tree, path), value) == 0)
513             {
514               g_tree_remove (tree, path);
515               g_free (value);
516               g_free (path);
517             }
518           else
519             g_tree_insert (tree, path, value);
520         }
521
522       g_strfreev (keys);
523     }
524   g_strfreev (groups);
525 }
526
527 static void
528 g_keyfile_settings_backend_keyfile_reload (GKeyfileSettingsBackend *kfsb)
529 {
530   guint8 digest[32];
531   gchar *contents;
532   gsize length;
533
534   contents = NULL;
535   length = 0;
536
537   g_file_load_contents (kfsb->file, NULL, &contents, &length, NULL, NULL);
538   compute_checksum (digest, contents, length);
539
540   if (memcmp (kfsb->digest, digest, sizeof digest) != 0)
541     {
542       GKeyFile *keyfiles[2];
543       GTree *tree;
544
545       tree = g_tree_new_full ((GCompareDataFunc) strcmp, NULL,
546                               g_free, g_free);
547
548       keyfiles[0] = kfsb->keyfile;
549       keyfiles[1] = g_key_file_new ();
550
551       if (length > 0)
552         g_key_file_load_from_data (keyfiles[1], contents, length,
553                                    G_KEY_FILE_KEEP_COMMENTS |
554                                    G_KEY_FILE_KEEP_TRANSLATIONS, NULL);
555
556       keyfile_to_tree (kfsb, tree, keyfiles[0], FALSE);
557       keyfile_to_tree (kfsb, tree, keyfiles[1], TRUE);
558       g_key_file_free (keyfiles[0]);
559       kfsb->keyfile = keyfiles[1];
560
561       if (g_tree_nnodes (tree) > 0)
562         g_settings_backend_changed_tree (&kfsb->parent_instance, tree, NULL);
563
564       g_tree_unref (tree);
565
566       memcpy (kfsb->digest, digest, sizeof digest);
567     }
568
569   g_free (contents);
570 }
571
572 static void
573 g_keyfile_settings_backend_keyfile_writable (GKeyfileSettingsBackend *kfsb)
574 {
575   GFileInfo *fileinfo;
576   gboolean writable;
577
578   fileinfo = g_file_query_info (kfsb->dir, "access::*", 0, NULL, NULL);
579
580   if (fileinfo)
581     {
582       writable =
583         g_file_info_get_attribute_boolean (fileinfo, G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE) &&
584         g_file_info_get_attribute_boolean (fileinfo, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE);
585       g_object_unref (fileinfo);
586     }
587   else
588     writable = FALSE;
589
590   if (writable != kfsb->writable)
591     {
592       kfsb->writable = writable;
593       g_settings_backend_path_writable_changed (&kfsb->parent_instance, "/");
594     }
595 }
596
597 static void
598 g_keyfile_settings_backend_finalize (GObject *object)
599 {
600   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (object);
601
602   g_key_file_free (kfsb->keyfile);
603   g_object_unref (kfsb->permission);
604   g_key_file_unref (kfsb->system_keyfile);
605   g_hash_table_unref (kfsb->system_locks);
606   g_free (kfsb->defaults_dir);
607
608   g_file_monitor_cancel (kfsb->file_monitor);
609   g_object_unref (kfsb->file_monitor);
610   g_object_unref (kfsb->file);
611
612   g_file_monitor_cancel (kfsb->dir_monitor);
613   g_object_unref (kfsb->dir_monitor);
614   g_object_unref (kfsb->dir);
615
616   g_free (kfsb->root_group);
617   g_free (kfsb->prefix);
618
619   G_OBJECT_CLASS (g_keyfile_settings_backend_parent_class)
620     ->finalize (object);
621 }
622
623 static void
624 g_keyfile_settings_backend_init (GKeyfileSettingsBackend *kfsb)
625 {
626 }
627
628 static void
629 file_changed (GFileMonitor      *monitor,
630               GFile             *file,
631               GFile             *other_file,
632               GFileMonitorEvent  event_type,
633               gpointer           user_data)
634 {
635   GKeyfileSettingsBackend *kfsb = user_data;
636
637   /* Ignore file deletions, let the GKeyFile content remain in tact. */
638   if (event_type != G_FILE_MONITOR_EVENT_DELETED)
639     g_keyfile_settings_backend_keyfile_reload (kfsb);
640 }
641
642 static void
643 dir_changed (GFileMonitor       *monitor,
644               GFile             *file,
645               GFile             *other_file,
646               GFileMonitorEvent  event_type,
647               gpointer           user_data)
648 {
649   GKeyfileSettingsBackend *kfsb = user_data;
650
651   g_keyfile_settings_backend_keyfile_writable (kfsb);
652 }
653
654 static void
655 load_system_settings (GKeyfileSettingsBackend *kfsb)
656 {
657   GError *error = NULL;
658   const char *dir = "/etc/glib-2.0/settings";
659   char *path;
660   char *contents;
661
662   kfsb->system_keyfile = g_key_file_new ();
663   kfsb->system_locks = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
664
665   if (kfsb->defaults_dir)
666     dir = kfsb->defaults_dir;
667
668   path = g_build_filename (dir, "defaults", NULL);
669
670   /* The defaults are in the same keyfile format that we use for the settings.
671    * It can be produced from a dconf database using: dconf dump
672    */
673   if (!g_key_file_load_from_file (kfsb->system_keyfile, path, G_KEY_FILE_NONE, &error))
674     {
675       if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
676         g_warning ("Failed to read %s: %s", path, error->message);
677       g_clear_error (&error);
678     }
679   else
680     g_debug ("Loading default settings from %s", path);
681
682   g_free (path);
683
684   path = g_build_filename (dir, "locks", NULL);
685
686   /* The locks file is a text file containing a list paths to lock, one per line.
687    * It can be produced from a dconf database using: dconf list-locks
688    */
689   if (!g_file_get_contents (path, &contents, NULL, &error))
690     {
691       if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
692         g_warning ("Failed to read %s: %s", path, error->message);
693       g_clear_error (&error);
694     }
695   else
696     {
697       char **lines;
698       gsize i;
699
700       g_debug ("Loading locks from %s", path);
701
702       lines = g_strsplit (contents, "\n", 0);
703       for (i = 0; lines[i]; i++)
704         {
705           char *line = lines[i];
706           if (line[0] == '#' || line[0] == '\0')
707             {
708               g_free (line);
709               continue;
710             }
711
712           g_debug ("Locking key %s", line);
713           g_hash_table_add (kfsb->system_locks, g_steal_pointer (&line));
714         }
715
716       g_free (lines);
717     }
718   g_free (contents);
719
720   g_free (path);
721 }
722
723 static void
724 g_keyfile_settings_backend_constructed (GObject *object)
725 {
726   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (object);
727   const char *path;
728
729   if (kfsb->file == NULL)
730     {
731       char *filename = g_build_filename (g_get_user_config_dir (),
732                                          "glib-2.0", "settings", "keyfile",
733                                          NULL);
734       kfsb->file = g_file_new_for_path (filename);
735       g_free (filename);
736     }
737
738   if (kfsb->prefix == NULL)
739     {
740       kfsb->prefix = g_strdup ("/");
741       kfsb->prefix_len = 1;
742     }
743   
744   kfsb->keyfile = g_key_file_new ();
745   kfsb->permission = g_simple_permission_new (TRUE);
746
747   kfsb->dir = g_file_get_parent (kfsb->file);
748   path = g_file_peek_path (kfsb->dir);
749   if (g_mkdir_with_parents (path, 0700) == -1)
750     g_warning ("Failed to create %s: %s", path, g_strerror (errno));
751
752   kfsb->file_monitor = g_file_monitor (kfsb->file, G_FILE_MONITOR_NONE, NULL, NULL);
753   kfsb->dir_monitor = g_file_monitor (kfsb->dir, G_FILE_MONITOR_NONE, NULL, NULL);
754
755   compute_checksum (kfsb->digest, NULL, 0);
756
757   g_signal_connect (kfsb->file_monitor, "changed",
758                     G_CALLBACK (file_changed), kfsb);
759   g_signal_connect (kfsb->dir_monitor, "changed",
760                     G_CALLBACK (dir_changed), kfsb);
761
762   g_keyfile_settings_backend_keyfile_writable (kfsb);
763   g_keyfile_settings_backend_keyfile_reload (kfsb);
764
765   load_system_settings (kfsb);
766 }
767
768 static void
769 g_keyfile_settings_backend_set_property (GObject      *object,
770                                          guint         prop_id,
771                                          const GValue *value,
772                                          GParamSpec   *pspec)
773 {
774   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (object);
775
776   switch ((GKeyfileSettingsBackendProperty)prop_id)
777     {
778     case PROP_FILENAME:
779       /* Construct only. */
780       g_assert (kfsb->file == NULL);
781       if (g_value_get_string (value))
782         kfsb->file = g_file_new_for_path (g_value_get_string (value));
783       break;
784
785     case PROP_ROOT_PATH:
786       /* Construct only. */
787       g_assert (kfsb->prefix == NULL);
788       kfsb->prefix = g_value_dup_string (value);
789       if (kfsb->prefix)
790         kfsb->prefix_len = strlen (kfsb->prefix);
791       break;
792
793     case PROP_ROOT_GROUP:
794       /* Construct only. */
795       g_assert (kfsb->root_group == NULL);
796       kfsb->root_group = g_value_dup_string (value);
797       if (kfsb->root_group)
798         kfsb->root_group_len = strlen (kfsb->root_group);
799       break;
800
801     case PROP_DEFAULTS_DIR:
802       /* Construct only. */
803       g_assert (kfsb->defaults_dir == NULL);
804       kfsb->defaults_dir = g_value_dup_string (value);
805       break;
806
807     default:
808       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
809       break;
810     }
811 }
812
813 static void
814 g_keyfile_settings_backend_get_property (GObject    *object,
815                                          guint       prop_id,
816                                          GValue     *value,
817                                          GParamSpec *pspec)
818 {
819   GKeyfileSettingsBackend *kfsb = G_KEYFILE_SETTINGS_BACKEND (object);
820
821   switch ((GKeyfileSettingsBackendProperty)prop_id)
822     {
823     case PROP_FILENAME:
824       g_value_set_string (value, g_file_peek_path (kfsb->file));
825       break;
826
827     case PROP_ROOT_PATH:
828       g_value_set_string (value, kfsb->prefix);
829       break;
830
831     case PROP_ROOT_GROUP:
832       g_value_set_string (value, kfsb->root_group);
833       break;
834
835     case PROP_DEFAULTS_DIR:
836       g_value_set_string (value, kfsb->defaults_dir);
837       break;
838
839     default:
840       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
841       break;
842     }
843 }
844
845 static void
846 g_keyfile_settings_backend_class_init (GKeyfileSettingsBackendClass *class)
847 {
848   GObjectClass *object_class = G_OBJECT_CLASS (class);
849
850   object_class->finalize = g_keyfile_settings_backend_finalize;
851   object_class->constructed = g_keyfile_settings_backend_constructed;
852   object_class->get_property = g_keyfile_settings_backend_get_property;
853   object_class->set_property = g_keyfile_settings_backend_set_property;
854
855   class->read = g_keyfile_settings_backend_read;
856   class->write = g_keyfile_settings_backend_write;
857   class->write_tree = g_keyfile_settings_backend_write_tree;
858   class->reset = g_keyfile_settings_backend_reset;
859   class->get_writable = g_keyfile_settings_backend_get_writable;
860   class->get_permission = g_keyfile_settings_backend_get_permission;
861   /* No need to implement subscribed/unsubscribe: the only point would be to
862    * stop monitoring the file when there's no GSettings anymore, which is no
863    * big win.
864    */
865
866   /**
867    * GKeyfileSettingsBackend:filename:
868    *
869    * The location where the settings are stored on disk.
870    *
871    * Defaults to `$XDG_CONFIG_HOME/glib-2.0/settings/keyfile`.
872    */
873   g_object_class_install_property (object_class,
874                                    PROP_FILENAME,
875                                    g_param_spec_string ("filename",
876                                                         P_("Filename"),
877                                                         P_("The filename"),
878                                                         NULL,
879                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
880                                                         G_PARAM_STATIC_STRINGS));
881
882   /**
883    * GKeyfileSettingsBackend:root-path:
884    *
885    * All settings read to or written from the backend must fall under the
886    * path given in @root_path (which must start and end with a slash and
887    * not contain two consecutive slashes).  @root_path may be "/".
888    * 
889    * Defaults to "/".
890    */
891   g_object_class_install_property (object_class,
892                                    PROP_ROOT_PATH,
893                                    g_param_spec_string ("root-path",
894                                                         P_("Root path"),
895                                                         P_("The root path"),
896                                                         NULL,
897                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
898                                                         G_PARAM_STATIC_STRINGS));
899
900   /**
901    * GKeyfileSettingsBackend:root-group:
902    *
903    * If @root_group is non-%NULL then it specifies the name of the keyfile
904    * group used for keys that are written directly below the root path.
905    *
906    * Defaults to NULL.
907    */
908   g_object_class_install_property (object_class,
909                                    PROP_ROOT_GROUP,
910                                    g_param_spec_string ("root-group",
911                                                         P_("Root group"),
912                                                         P_("The root group"),
913                                                         NULL,
914                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
915                                                         G_PARAM_STATIC_STRINGS));
916
917   /**
918    * GKeyfileSettingsBackend:default-dir:
919    *
920    * The directory where the system defaults and locks are located.
921    *
922    * Defaults to `/etc/glib-2.0/settings`.
923    */
924   g_object_class_install_property (object_class,
925                                    PROP_DEFAULTS_DIR,
926                                    g_param_spec_string ("defaults-dir",
927                                                         P_("Default dir"),
928                                                         P_("Defaults dir"),
929                                                         NULL,
930                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
931                                                         G_PARAM_STATIC_STRINGS));
932 }
933
934 /**
935  * g_keyfile_settings_backend_new:
936  * @filename: the filename of the keyfile
937  * @root_path: the path under which all settings keys appear
938  * @root_group: (nullable): the group name corresponding to
939  *              @root_path, or %NULL
940  *
941  * Creates a keyfile-backed #GSettingsBackend.
942  *
943  * The filename of the keyfile to use is given by @filename.
944  *
945  * All settings read to or written from the backend must fall under the
946  * path given in @root_path (which must start and end with a slash and
947  * not contain two consecutive slashes).  @root_path may be "/".
948  *
949  * If @root_group is non-%NULL then it specifies the name of the keyfile
950  * group used for keys that are written directly below @root_path.  For
951  * example, if @root_path is "/apps/example/" and @root_group is
952  * "toplevel", then settings the key "/apps/example/enabled" to a value
953  * of %TRUE will cause the following to appear in the keyfile:
954  *
955  * |[
956  *   [toplevel]
957  *   enabled=true
958  * ]|
959  *
960  * If @root_group is %NULL then it is not permitted to store keys
961  * directly below the @root_path.
962  *
963  * For keys not stored directly below @root_path (ie: in a sub-path),
964  * the name of the subpath (with the final slash stripped) is used as
965  * the name of the keyfile group.  To continue the example, if
966  * "/apps/example/profiles/default/font-size" were set to
967  * 12 then the following would appear in the keyfile:
968  *
969  * |[
970  *   [profiles/default]
971  *   font-size=12
972  * ]|
973  *
974  * The backend will refuse writes (and return writability as being
975  * %FALSE) for keys outside of @root_path and, in the event that
976  * @root_group is %NULL, also for keys directly under @root_path.
977  * Writes will also be refused if the backend detects that it has the
978  * inability to rewrite the keyfile (ie: the containing directory is not
979  * writable).
980  *
981  * There is no checking done for your key namespace clashing with the
982  * syntax of the key file format.  For example, if you have '[' or ']'
983  * characters in your path names or '=' in your key names you may be in
984  * trouble.
985  *
986  * The backend reads default values from a keyfile called `defaults` in
987  * the directory specified by the #GKeyfileSettingsBackend:defaults-dir property,
988  * and a list of locked keys from a text file with the name `locks` in
989  * the same location.
990  *
991  * Returns: (transfer full): a keyfile-backed #GSettingsBackend
992  **/
993 GSettingsBackend *
994 g_keyfile_settings_backend_new (const gchar *filename,
995                                 const gchar *root_path,
996                                 const gchar *root_group)
997 {
998   g_return_val_if_fail (filename != NULL, NULL);
999   g_return_val_if_fail (root_path != NULL, NULL);
1000   g_return_val_if_fail (g_str_has_prefix (root_path, "/"), NULL);
1001   g_return_val_if_fail (g_str_has_suffix (root_path, "/"), NULL);
1002   g_return_val_if_fail (strstr (root_path, "//") == NULL, NULL);
1003
1004   return G_SETTINGS_BACKEND (g_object_new (G_TYPE_KEYFILE_SETTINGS_BACKEND,
1005                                            "filename", filename,
1006                                            "root-path", root_path,
1007                                            "root-group", root_group,
1008                                            NULL));
1009 }