Improve the g_file_make_symbolic_link docs
[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 "gkeyfilesettingsbackend.h"
27
28 #include <stdio.h>
29 #include <string.h>
30 #include <errno.h>
31
32 #include "gioerror.h"
33 #include "giomodule.h"
34 #include "gfile.h"
35 #include "gfileinfo.h"
36 #include "gfilemonitor.h"
37
38 #include "gioalias.h"
39
40 G_DEFINE_TYPE (GKeyfileSettingsBackend,
41                g_keyfile_settings_backend,
42                G_TYPE_SETTINGS_BACKEND)
43
44 struct _GKeyfileSettingsBackendPrivate
45 {
46   GHashTable   *table;
47   GKeyFile     *keyfile;
48   gboolean      writable;
49   gchar        *file_path;
50   gchar        *checksum;
51   GFileMonitor *monitor;
52 };
53
54 static GVariant *
55 g_keyfile_settings_backend_read (GSettingsBackend   *backend,
56                                  const gchar        *key,
57                                  const GVariantType *expected_type,
58                                  gboolean            default_value)
59 {
60   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (backend);
61   GVariant *value;
62
63   if (default_value)
64     return NULL;
65
66   value = g_hash_table_lookup (kf_backend->priv->table, key);
67
68   if (value != NULL)
69     g_variant_ref (value);
70
71   return value;
72 }
73
74 static gboolean
75 g_keyfile_settings_backend_write_one (const gchar             *key,
76                                       GVariant                *value,
77                                       GKeyfileSettingsBackend *kf_backend)
78 {
79   const gchar *slash;
80   const gchar *base_key;
81   gchar       *path;
82
83   g_hash_table_replace (kf_backend->priv->table,
84                         g_strdup (key), g_variant_ref (value));
85
86   slash = strrchr (key, '/');
87   g_assert (slash != NULL);
88   base_key = (slash + 1);
89   path = g_strndup (key, slash - key + 1);
90
91   g_key_file_set_string (kf_backend->priv->keyfile,
92                          path, base_key, g_variant_print (value, TRUE));
93
94   g_free (path);
95
96   return FALSE;
97 }
98
99 static void
100 g_keyfile_settings_backend_keyfile_write (GKeyfileSettingsBackend *kf_backend)
101 {
102   gchar *dirname;
103   gchar *contents;
104   gsize  length;
105   GFile *file;
106
107   dirname = g_path_get_dirname (kf_backend->priv->file_path);
108   if (!g_file_test (dirname, G_FILE_TEST_IS_DIR))
109     g_mkdir_with_parents (dirname, 0700);
110   g_free (dirname);
111
112   contents = g_key_file_to_data (kf_backend->priv->keyfile, &length, NULL);
113
114   file = g_file_new_for_path (kf_backend->priv->file_path);
115   g_file_replace_contents (file, contents, length,
116                            NULL, FALSE, G_FILE_CREATE_REPLACE_DESTINATION,
117                            NULL, NULL, NULL);
118   g_object_unref (file);
119
120   g_free (kf_backend->priv->checksum);
121   kf_backend->priv->checksum = g_compute_checksum_for_string (G_CHECKSUM_SHA256, contents, length);
122
123   g_free (contents);
124 }
125
126 static gboolean
127 g_keyfile_settings_backend_write (GSettingsBackend *backend,
128                                   const gchar      *key,
129                                   GVariant         *value,
130                                   gpointer          origin_tag)
131 {
132   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (backend);
133
134   g_keyfile_settings_backend_write_one (key, value, kf_backend);
135   g_keyfile_settings_backend_keyfile_write (kf_backend);
136
137   g_settings_backend_changed (backend, key, origin_tag);
138
139   return TRUE;
140 }
141
142 static gboolean
143 g_keyfile_settings_backend_write_keys (GSettingsBackend *backend,
144                                        GTree            *tree,
145                                        gpointer          origin_tag)
146 {
147   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (backend);
148
149   g_tree_foreach (tree, (GTraverseFunc) g_keyfile_settings_backend_write_one, backend);
150   g_keyfile_settings_backend_keyfile_write (kf_backend);
151
152   g_settings_backend_changed_tree (backend, tree, origin_tag);
153
154   return TRUE;
155 }
156
157 static void
158 g_keyfile_settings_backend_reset_path (GSettingsBackend *backend,
159                                        const gchar      *path,
160                                        gpointer         origin_tag)
161 {
162   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (backend);
163   GPtrArray  *reset_array;
164   GList      *hash_keys;
165   GList      *l;
166   gboolean    changed;
167   gchar     **groups = NULL;
168   gsize       groups_nb = 0;
169   int         i;
170
171   reset_array = g_ptr_array_new_with_free_func (g_free);
172
173   hash_keys = g_hash_table_get_keys (kf_backend->priv->table);
174   for (l = hash_keys; l != NULL; l = l->next)
175     {
176       if (g_str_has_prefix (l->data, path))
177         {
178           g_hash_table_remove (kf_backend->priv->table, l->data);
179           g_ptr_array_add (reset_array, g_strdup (l->data));
180         }
181     }
182   g_list_free (hash_keys);
183
184   changed = FALSE;
185   groups = g_key_file_get_groups (kf_backend->priv->keyfile, &groups_nb);
186   for (i = 0; i < groups_nb; i++)
187     {
188       if (g_str_has_prefix (groups[i], path))
189         changed = g_key_file_remove_group (kf_backend->priv->keyfile, groups[i], NULL) || changed;
190     }
191   g_strfreev (groups);
192
193   if (changed)
194     g_keyfile_settings_backend_keyfile_write (kf_backend);
195
196   if (reset_array->len > 0)
197     {
198       /* the array has to be NULL-terminated */
199       g_ptr_array_add (reset_array, NULL);
200       g_settings_backend_keys_changed (G_SETTINGS_BACKEND (kf_backend),
201                                        "",
202                                        (const gchar **) reset_array->pdata,
203                                        origin_tag);
204     }
205
206   g_ptr_array_free (reset_array, TRUE);
207 }
208
209 static void
210 g_keyfile_settings_backend_reset (GSettingsBackend *backend,
211                                   const gchar      *key,
212                                   gpointer          origin_tag)
213 {
214   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (backend);
215   gboolean     had_key;
216   const gchar *slash;
217   const gchar *base_key;
218   gchar       *path;
219
220   had_key = g_hash_table_lookup_extended (kf_backend->priv->table, key, NULL, NULL);
221   if (had_key)
222     g_hash_table_remove (kf_backend->priv->table, key);
223
224   slash = strrchr (key, '/');
225   g_assert (slash != NULL);
226   base_key = (slash + 1);
227   path = g_strndup (key, slash - key + 1);
228
229   if (g_key_file_remove_key (kf_backend->priv->keyfile, path, base_key, NULL))
230     g_keyfile_settings_backend_keyfile_write (kf_backend);
231
232   g_free (path);
233
234   if (had_key)
235     g_settings_backend_changed (G_SETTINGS_BACKEND (kf_backend), key, origin_tag);
236 }
237
238 static gboolean
239 g_keyfile_settings_backend_get_writable (GSettingsBackend *backend,
240                                          const gchar      *name)
241 {
242   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (backend);
243
244   return kf_backend->priv->writable;
245 }
246
247 static void
248 g_keyfile_settings_backend_keyfile_reload (GKeyfileSettingsBackend *kf_backend)
249 {
250   gchar       *contents = NULL;
251   gsize        length = 0;
252   gchar       *new_checksum;
253   GHashTable  *loaded_keys;
254   GPtrArray   *changed_array;
255   gchar      **groups = NULL;
256   gsize        groups_nb = 0;
257   int          i;
258   GList       *keys_l = NULL;
259   GList       *l;
260
261   if (!g_file_get_contents (kf_backend->priv->file_path,
262                             &contents, &length, NULL))
263     {
264       contents = g_strdup ("");
265       length = 0;
266     }
267
268   new_checksum = g_compute_checksum_for_string (G_CHECKSUM_SHA256, contents, length);
269
270   if (g_strcmp0 (kf_backend->priv->checksum, new_checksum) == 0)
271     {
272       g_free (new_checksum);
273       return;
274     }
275
276   if (kf_backend->priv->checksum != NULL)
277     g_free (kf_backend->priv->checksum);
278   kf_backend->priv->checksum = new_checksum;
279
280   if (kf_backend->priv->keyfile != NULL)
281     g_key_file_free (kf_backend->priv->keyfile);
282
283   kf_backend->priv->keyfile = g_key_file_new ();
284
285   /* we just silently ignore errors: there's not much we can do about them */
286   if (length > 0)
287     g_key_file_load_from_data (kf_backend->priv->keyfile, contents, length,
288                                G_KEY_FILE_KEEP_COMMENTS|G_KEY_FILE_KEEP_TRANSLATIONS, NULL);
289
290   loaded_keys = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
291   changed_array = g_ptr_array_new_with_free_func (g_free);
292
293   /* Load keys from the keyfile */
294   groups = g_key_file_get_groups (kf_backend->priv->keyfile, &groups_nb);
295   for (i = 0; i < groups_nb; i++)
296     {
297       gchar **keys = NULL;
298       gsize   keys_nb = 0;
299       int     j;
300
301       keys = g_key_file_get_keys (kf_backend->priv->keyfile, groups[i], &keys_nb, NULL);
302       if (keys == NULL)
303         continue;
304
305       for (j = 0; j < keys_nb; j++)
306         {
307           gchar    *value;
308           gchar    *full_key;
309           GVariant *old_variant;
310           GVariant *variant;
311
312           value = g_key_file_get_string (kf_backend->priv->keyfile, groups[i], keys[j], NULL);
313           if (value == NULL)
314             continue;
315
316           variant = g_variant_new_parsed (value);
317           g_free (value);
318
319           if (variant == NULL)
320             continue;
321
322           full_key = g_strjoin ("", groups[i], keys[j], NULL),
323           g_hash_table_insert (loaded_keys, full_key, GINT_TO_POINTER(TRUE));
324
325           old_variant = g_hash_table_lookup (kf_backend->priv->table, full_key);
326
327           if (old_variant == NULL || !g_variant_equal (old_variant, variant))
328             {
329               g_ptr_array_add (changed_array, g_strdup (full_key));
330               g_hash_table_replace (kf_backend->priv->table,
331                                     g_strdup (full_key),
332                                     g_variant_ref_sink (variant));
333             }
334           else
335             g_variant_unref (variant);
336         }
337
338       g_strfreev (keys);
339     }
340   g_strfreev (groups);
341
342   /* Remove keys that were in the hashtable but not in the keyfile */
343   keys_l = g_hash_table_get_keys (kf_backend->priv->table);
344   for (l = keys_l; l != NULL; l = l->next)
345     {
346       gchar *key = l->data;
347
348       if (g_hash_table_lookup_extended (loaded_keys, key, NULL, NULL))
349         continue;
350
351       g_ptr_array_add (changed_array, g_strdup (key));
352       g_hash_table_remove (kf_backend->priv->table, key);
353     }
354   g_list_free (keys_l);
355
356   if (changed_array->len > 0)
357     {
358       /* the array has to be NULL-terminated */
359       g_ptr_array_add (changed_array, NULL);
360       g_settings_backend_keys_changed (G_SETTINGS_BACKEND (kf_backend),
361                                        "",
362                                        (const gchar **) changed_array->pdata,
363                                        NULL);
364     }
365
366   g_hash_table_unref (loaded_keys);
367   g_ptr_array_free (changed_array, TRUE);
368 }
369
370 static gboolean
371 g_keyfile_settings_backend_keyfile_writable (GFile *file)
372 {
373   GFileInfo *fileinfo;
374   GError    *error;
375   gboolean   writable = FALSE;
376
377   error = NULL;
378   fileinfo = g_file_query_info (file, "access::*",
379                                 G_FILE_QUERY_INFO_NONE, NULL, &error);
380
381   if (fileinfo == NULL)
382     {
383       if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))
384         {
385           GFile *parent;
386
387           parent = g_file_get_parent (file);
388           if (parent)
389             {
390               writable = g_keyfile_settings_backend_keyfile_writable (parent);
391               g_object_unref (parent);
392             }
393         }
394
395       g_error_free (error);
396
397       return writable;
398     }
399
400   /* We don't want to mark the backend as writable if the file is not readable,
401    * since it means we won't be able to load the content of the file, and we'll
402    * lose data. */
403   writable =
404         g_file_info_get_attribute_boolean (fileinfo, G_FILE_ATTRIBUTE_ACCESS_CAN_READ) &&
405         g_file_info_get_attribute_boolean (fileinfo, G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
406   g_object_unref (fileinfo);
407
408   return writable;
409 }
410
411 static void
412 g_keyfile_settings_backend_keyfile_changed (GFileMonitor      *monitor,
413                                             GFile             *file,
414                                             GFile             *other_file,
415                                             GFileMonitorEvent  event_type,
416                                             gpointer           user_data)
417 {
418   GKeyfileSettingsBackend *kf_backend;
419
420   if (event_type != G_FILE_MONITOR_EVENT_CHANGED &&
421       event_type != G_FILE_MONITOR_EVENT_CREATED &&
422       event_type != G_FILE_MONITOR_EVENT_DELETED &&
423       event_type != G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED)
424     return;
425
426   kf_backend = G_KEYFILE_SETTINGS_BACKEND (user_data);
427
428   if (event_type == G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED)
429     {
430       gboolean writable;
431
432       writable = g_keyfile_settings_backend_keyfile_writable (file);
433
434       if (kf_backend->priv->writable == writable)
435         return;
436
437       kf_backend->priv->writable = writable;
438       if (!writable)
439         return;
440       /* else: reload the file since it was possibly not readable before */
441     }
442
443   g_keyfile_settings_backend_keyfile_reload (kf_backend);
444 }
445
446 static void
447 g_keyfile_settings_backend_finalize (GObject *object)
448 {
449   GKeyfileSettingsBackend *kf_backend = G_KEYFILE_SETTINGS_BACKEND (object);
450
451   g_hash_table_unref (kf_backend->priv->table);
452   kf_backend->priv->table = NULL;
453
454   g_key_file_free (kf_backend->priv->keyfile);
455   kf_backend->priv->keyfile = NULL;
456
457   g_free (kf_backend->priv->file_path);
458   kf_backend->priv->file_path = NULL;
459
460   g_free (kf_backend->priv->checksum);
461   kf_backend->priv->checksum = NULL;
462
463   g_file_monitor_cancel (kf_backend->priv->monitor);
464   g_object_unref (kf_backend->priv->monitor);
465   kf_backend->priv->monitor = NULL;
466
467   G_OBJECT_CLASS (g_keyfile_settings_backend_parent_class)
468     ->finalize (object);
469 }
470
471 static void
472 g_keyfile_settings_backend_init (GKeyfileSettingsBackend *kf_backend)
473 {
474   kf_backend->priv = G_TYPE_INSTANCE_GET_PRIVATE (kf_backend,
475                                                   G_TYPE_KEYFILE_SETTINGS_BACKEND,
476                                                   GKeyfileSettingsBackendPrivate);
477   kf_backend->priv->table =
478     g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
479                            (GDestroyNotify) g_variant_unref);
480
481   kf_backend->priv->keyfile = NULL;
482   kf_backend->priv->writable = FALSE;
483   kf_backend->priv->file_path = NULL;
484   kf_backend->priv->checksum = NULL;
485   kf_backend->priv->monitor = NULL;
486 }
487
488 static void
489 g_keyfile_settings_backend_class_init (GKeyfileSettingsBackendClass *class)
490 {
491   GSettingsBackendClass *backend_class = G_SETTINGS_BACKEND_CLASS (class);
492   GObjectClass *object_class = G_OBJECT_CLASS (class);
493
494   object_class->finalize = g_keyfile_settings_backend_finalize;
495
496   backend_class->read = g_keyfile_settings_backend_read;
497   backend_class->write = g_keyfile_settings_backend_write;
498   backend_class->write_keys = g_keyfile_settings_backend_write_keys;
499   backend_class->reset = g_keyfile_settings_backend_reset;
500   backend_class->reset_path = g_keyfile_settings_backend_reset_path;
501   backend_class->get_writable = g_keyfile_settings_backend_get_writable;
502   /* No need to implement subscribed/unsubscribe: the only point would be to
503    * stop monitoring the file when there's no GSettings anymore, which is no
504    * big win. */
505
506   g_type_class_add_private (class, sizeof (GKeyfileSettingsBackendPrivate));
507 }
508
509 static GKeyfileSettingsBackend *
510 g_keyfile_settings_backend_new (const gchar *filename)
511 {
512   GKeyfileSettingsBackend *kf_backend;
513   GFile *file;
514
515   kf_backend = g_object_new (G_TYPE_KEYFILE_SETTINGS_BACKEND, NULL);
516   kf_backend->priv->file_path = g_strdup (filename);
517
518   file = g_file_new_for_path (kf_backend->priv->file_path);
519
520   kf_backend->priv->writable = g_keyfile_settings_backend_keyfile_writable (file);
521
522   kf_backend->priv->monitor = g_file_monitor_file (file, G_FILE_MONITOR_SEND_MOVED, NULL, NULL);
523   g_signal_connect (kf_backend->priv->monitor, "changed",
524                     (GCallback)g_keyfile_settings_backend_keyfile_changed, kf_backend);
525
526   g_object_unref (file);
527
528   g_keyfile_settings_backend_keyfile_reload (kf_backend);
529
530   return kf_backend;
531 }
532
533 /**
534  * g_settings_backend_setup_keyfile:
535  * @context: a context string (not %NULL or "")
536  * @filename: a filename
537  *
538  * Sets up a keyfile for use with #GSettings.
539  *
540  * If you create a #GSettings with its context property set to @context
541  * then the settings will be stored in the keyfile at @filename.  See
542  * g_settings_new_with_context().
543  *
544  * The keyfile must be setup before any settings objects are created
545  * for the named context.
546  *
547  * It is not possible to specify a keyfile for the default context.
548  *
549  * If the path leading up to @filename does not exist, it will be
550  * recursively created with user-only permissions.  If the keyfile is
551  * not writable, any #GSettings objects created using @context will
552  * return %FALSE for any calls to g_settings_is_writable() and any
553  * attempts to write will fail.
554  *
555  * Since: 2.26
556  */
557 void
558 g_settings_backend_setup_keyfile (const gchar *context,
559                                   const gchar *filename)
560 {
561   GKeyfileSettingsBackend *kf_backend;
562
563   kf_backend = g_keyfile_settings_backend_new (filename);
564   g_settings_backend_setup (context, G_SETTINGS_BACKEND (kf_backend));
565   g_object_unref (kf_backend);
566 }
567
568 #define __G_KEYFILE_SETTINGS_BACKEND_C__
569 #include "gioaliasdef.c"