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