Debian Codegraph @

lib/wp/state.c

raw
1 /* WirePlumber
2 *
3 * Copyright © 2020 Collabora Ltd.
4 * @author Julian Bouzas <[email protected]>
5 *
6 * SPDX-License-Identifier: MIT
7 */
8
9 #include <stdio.h>
10 #include <errno.h>
11
12 #include "log.h"
13 #include "state.h"
14 #include "wp.h"
15
16 WP_DEFINE_LOCAL_LOG_TOPIC ("wp-state")
17
18 #define DEFAULT_TIMEOUT_MS 1000
19 #define ESCAPED_CHARACTER '\\'
20
21 static char *
22 escape_string (const gchar *str)
23 {
24 char *res = NULL;
25 size_t str_size, i, j;
26
27 g_return_val_if_fail (str, NULL);
28 str_size = strlen (str);
29 g_return_val_if_fail (str_size > 0, NULL);
30
31 res = g_malloc_n ((str_size * 2) + 1, sizeof(gchar));
32
33 j = 0;
34 for (i = 0; i < str_size; i++) {
35 switch (str[i]) {
36 case ESCAPED_CHARACTER:
37 res[j++] = ESCAPED_CHARACTER;
38 res[j++] = ESCAPED_CHARACTER;
39 break;
40 case ' ':
41 res[j++] = ESCAPED_CHARACTER;
42 res[j++] = 's';
43 break;
44 case '=':
45 res[j++] = ESCAPED_CHARACTER;
46 res[j++] = 'e';
47 break;
48 case '[':
49 res[j++] = ESCAPED_CHARACTER;
50 res[j++] = 'o';
51 break;
52 case ']':
53 res[j++] = ESCAPED_CHARACTER;
54 res[j++] = 'c';
55 break;
56 default:
57 res[j++] = str[i];
58 break;
59 }
60 }
61 res[j++] = '\0';
62
63 return res;
64 }
65
66 static char *
67 compress_string (const gchar *str)
68 {
69 char *res = NULL;
70 size_t str_size, i, j;
71
72 g_return_val_if_fail (str, NULL);
73 str_size = strlen (str);
74 g_return_val_if_fail (str_size > 0, NULL);
75
76 res = g_malloc_n (str_size + 1, sizeof(gchar));
77
78 j = 0;
79 for (i = 0; i < str_size - 1; i++) {
80 if (str[i] == ESCAPED_CHARACTER) {
81 switch (str[i + 1]) {
82 case ESCAPED_CHARACTER:
83 res[j++] = ESCAPED_CHARACTER;
84 break;
85 case 's':
86 res[j++] = ' ';
87 break;
88 case 'e':
89 res[j++] = '=';
90 break;
91 case 'o':
92 res[j++] = '[';
93 break;
94 case 'c':
95 res[j++] = ']';
96 break;
97 default:
98 res[j++] = str[i];
99 break;
100 }
101 i++;
102 } else {
103 res[j++] = str[i];
104 }
105 }
106 if (i < str_size)
107 res[j++] = str[i];
108 res[j++] = '\0';
109
110 return res;
111 }
112
113 /*! \defgroup wpstate WpState */
114 /*!
115 * \struct WpState
116 *
117 * The WpState class saves and loads properties from a file
118 *
119 * \gproperties
120 * \gproperty{name, gchar *, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY,
121 * The file name where the state will be stored.}
122 */
123
124 enum {
125 PROP_0,
126 PROP_NAME,
127 PROP_TIMEOUT,
128 };
129
130 struct _WpState
131 {
132 GObject parent;
133
134 /* Props */
135 gchar *name;
136 guint timeout;
137
138 gchar *location;
139 GSource *timeout_source;
140 WpProperties *timeout_props;
141 };
142
143 G_DEFINE_TYPE (WpState, wp_state, G_TYPE_OBJECT)
144
145 /* Gets the full path to the WirePlumber XDG_STATE_HOME subdirectory */
146 static const gchar *
147 wp_get_xdg_state_dir (void)
148 {
149 static gchar xdg_dir[PATH_MAX] = {0};
150 if (xdg_dir[0] == '\0') {
151 g_autofree gchar *path = NULL;
152 g_autofree gchar *base = g_strdup (g_getenv ("XDG_STATE_HOME"));
153 if (!base)
154 base = g_build_filename (g_get_home_dir (), ".local", "state", NULL);
155
156 path = g_build_filename (base, "wireplumber", NULL);
157 (void) g_strlcpy (xdg_dir, path, sizeof (xdg_dir));
158 }
159 return xdg_dir;
160 }
161
162 static char *
163 get_new_location (const char *name)
164 {
165 const gchar *path = wp_get_xdg_state_dir ();
166
167 /* Create the directory if it doesn't exist */
168 if (g_mkdir_with_parents (path, 0700) < 0)
169 wp_warning ("failed to create directory %s: %s", path, g_strerror (errno));
170
171 return g_build_filename (path, name, NULL);
172 }
173
174 static void
175 wp_state_ensure_location (WpState *self)
176 {
177 if (!self->location)
178 self->location = get_new_location (self->name);
179 g_return_if_fail (self->location);
180 }
181
182 static void
183 wp_state_set_property (GObject * object, guint property_id,
184 const GValue * value, GParamSpec * pspec)
185 {
186 WpState *self = WP_STATE (object);
187
188 switch (property_id) {
189 case PROP_NAME:
190 g_clear_pointer (&self->name, g_free);
191 self->name = g_value_dup_string (value);
192 break;
193 case PROP_TIMEOUT:
194 self->timeout = g_value_get_uint (value);
195 break;
196 default:
197 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
198 break;
199 }
200 }
201
202 static void
203 wp_state_get_property (GObject * object, guint property_id, GValue * value,
204 GParamSpec * pspec)
205 {
206 WpState *self = WP_STATE (object);
207
208 switch (property_id) {
209 case PROP_NAME:
210 g_value_set_string (value, self->name);
211 break;
212 case PROP_TIMEOUT:
213 g_value_set_uint (value, self->timeout);
214 break;
215 default:
216 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
217 break;
218 }
219 }
220
221 static void
222 wp_state_finalize (GObject * object)
223 {
224 WpState * self = WP_STATE (object);
225
226 g_clear_pointer (&self->name, g_free);
227 g_clear_pointer (&self->location, g_free);
228 g_clear_pointer (&self->timeout_source, g_source_unref);
229 g_clear_pointer (&self->timeout_props, wp_properties_unref);
230
231 G_OBJECT_CLASS (wp_state_parent_class)->finalize (object);
232 }
233
234 static void
235 wp_state_init (WpState * self)
236 {
237 self->timeout = DEFAULT_TIMEOUT_MS;
238 }
239
240 static void
241 wp_state_class_init (WpStateClass * klass)
242 {
243 GObjectClass *object_class = (GObjectClass *) klass;
244
245 object_class->finalize = wp_state_finalize;
246 object_class->set_property = wp_state_set_property;
247 object_class->get_property = wp_state_get_property;
248
249 g_object_class_install_property (object_class, PROP_NAME,
250 g_param_spec_string ("name", "name",
251 "The file name where the state will be stored", NULL,
252 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
253
254 g_object_class_install_property (object_class, PROP_TIMEOUT,
255 g_param_spec_uint ("timeout", "timeout",
256 "The timeout in milliseconds to save the state", 0, G_MAXUINT,
257 DEFAULT_TIMEOUT_MS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
258 }
259
260 /*!
261 * \brief Constructs a new state object
262 * \ingroup wpstate
263 * \param name the state name
264 * \returns (transfer full): the new WpState
265 */
266 WpState *
267 wp_state_new (const gchar *name)
268 {
269 g_return_val_if_fail (name, NULL);
270 return g_object_new (wp_state_get_type (),
271 "name", name,
272 NULL);
273 }
274
275 /*!
276 * \brief Gets the name of a state object
277 * \ingroup wpstate
278 * \param self the state
279 * \returns the name of this state
280 */
281 const gchar *
282 wp_state_get_name (WpState *self)
283 {
284 g_return_val_if_fail (WP_IS_STATE (self), NULL);
285
286 return self->name;
287 }
288
289 /*!
290 * \brief Gets the location of a state object
291 * \ingroup wpstate
292 * \param self the state
293 * \returns the location of this state
294 */
295 const gchar *
296 wp_state_get_location (WpState *self)
297 {
298 g_return_val_if_fail (WP_IS_STATE (self), NULL);
299 wp_state_ensure_location (self);
300
301 return self->location;
302 }
303
304 /*!
305 * \brief Clears the state removing its file
306 * \ingroup wpstate
307 * \param self the state
308 */
309 void
310 wp_state_clear (WpState *self)
311 {
312 g_return_if_fail (WP_IS_STATE (self));
313 wp_state_ensure_location (self);
314 if (remove (self->location) < 0)
315 wp_warning ("failed to remove %s: %s", self->location, g_strerror (errno));
316 }
317
318 /*!
319 * \brief Saves new properties in the state, overwriting all previous data.
320 * \ingroup wpstate
321 * \param self the state
322 * \param props (transfer none): the properties to save
323 * \param error (out)(optional): return location for a GError, or NULL
324 * \returns TRUE if the properties could be saved, FALSE otherwise
325 */
326 gboolean
327 wp_state_save (WpState *self, WpProperties *props, GError ** error)
328 {
329 g_autoptr (GKeyFile) keyfile = g_key_file_new ();
330 g_autoptr (WpIterator) it = NULL;
331 g_auto (GValue) item = G_VALUE_INIT;
332 GError *err = NULL;
333
334 g_return_val_if_fail (WP_IS_STATE (self), FALSE);
335 g_return_val_if_fail (props, FALSE);
336 wp_state_ensure_location (self);
337
338 wp_info_object (self, "saving state into %s", self->location);
339
340 /* Set the properties */
341 for (it = wp_properties_new_iterator (props);
342 wp_iterator_next (it, &item);
343 g_value_unset (&item)) {
344 WpPropertiesItem *pi = g_value_get_boxed (&item);
345 const gchar *key = wp_properties_item_get_key (pi);
346 const gchar *val = wp_properties_item_get_value (pi);
347 g_autofree gchar *escaped_key = escape_string (key);
348 if (escaped_key)
349 g_key_file_set_string (keyfile, self->name, escaped_key, val);
350 }
351
352 if (!g_key_file_save_to_file (keyfile, self->location, &err)) {
353 g_propagate_prefixed_error (error, err, "could not save %s: ", self->name);
354 return FALSE;
355 }
356
357 return TRUE;
358 }
359
360 static gboolean
361 timeout_save_state_callback (WpState *self)
362 {
363 g_autoptr (GError) error = NULL;
364
365 if (!wp_state_save (self, self->timeout_props, &error))
366 wp_warning_object (self, "%s", error->message);
367
368 g_clear_pointer (&self->timeout_source, g_source_unref);
369 g_clear_pointer (&self->timeout_props, wp_properties_unref);
370
371 return G_SOURCE_REMOVE;
372 }
373
374 /*!
375 * \brief Saves new properties in the state, overwriting all previous data,
376 * after a timeout
377 *
378 * This is similar to wp_state_save() but it will save the state after a timeout
379 * has elapsed. If the state is saved again before the timeout elapses, the
380 * timeout is reset.
381 *
382 * This function is useful to avoid saving the state too often. When called
383 * consecutively, it will save the state only once. Every time it is called,
384 * it will cancel the previous timer and start a new one, resulting in timing
385 * out only after the last call.
386 *
387 * \ingroup wpstate
388 * \param self the state
389 * \param core the core, used to add the timeout callback to the main loop
390 * \param props (transfer none): the properties to save. This object will be
391 * referenced and kept alive until the timeout elapses, but not deep copied.
392 * \since 0.5.0
393 */
394 void
395 wp_state_save_after_timeout (WpState *self, WpCore *core, WpProperties *props)
396 {
397 /* Clear the current timeout callback */
398 if (self->timeout_source)
399 g_source_destroy (self->timeout_source);
400 g_clear_pointer (&self->timeout_source, g_source_unref);
401 g_clear_pointer (&self->timeout_props, wp_properties_unref);
402
403 self->timeout_props = wp_properties_ref (props);
404
405 /* Add the timeout callback */
406 wp_core_timeout_add_closure (core, &self->timeout_source, self->timeout,
407 g_cclosure_new_object (G_CALLBACK (timeout_save_state_callback),
408 G_OBJECT (self)));
409 }
410
411 /*!
412 * \brief Loads the state data from the file system
413 *
414 * This function will never fail. If it cannot load the state, for any reason,
415 * it will simply return an empty WpProperties, behaving as if there was no
416 * previous state stored.
417 *
418 * \ingroup wpstate
419 * \param self the state
420 * \returns (transfer full): a new WpProperties containing the state data
421 */
422 WpProperties *
423 wp_state_load (WpState *self)
424 {
425 g_autoptr (GKeyFile) keyfile = g_key_file_new ();
426 g_autoptr (WpProperties) props = wp_properties_new_empty ();
427 gchar ** keys = NULL;
428
429 g_return_val_if_fail (WP_IS_STATE (self), NULL);
430 wp_state_ensure_location (self);
431
432 /* Open */
433 if (!g_key_file_load_from_file (keyfile, self->location,
434 G_KEY_FILE_NONE, NULL))
435 return g_steal_pointer (&props);
436
437 /* Load all keys */
438 keys = g_key_file_get_keys (keyfile, self->name, NULL, NULL);
439 if (!keys)
440 return g_steal_pointer (&props);
441
442 for (guint i = 0; keys[i]; i++) {
443 g_autofree gchar *compressed_key = NULL;
444 const gchar *key = keys[i];
445 g_autofree gchar *val = NULL;
446 val = g_key_file_get_string (keyfile, self->name, key, NULL);
447 if (!val)
448 continue;
449 compressed_key = compress_string (key);
450 if (compressed_key)
451 wp_properties_set (props, compressed_key, val);
452 }
453
454 g_strfreev (keys);
455
456 return g_steal_pointer (&props);
457 }