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