Docs: don't use <footnote>
[platform/upstream/glib.git] / gio / gdbuserror.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, 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 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
16  * Public 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  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "gdbuserror.h"
29 #include "gioenums.h"
30 #include "gioenumtypes.h"
31 #include "gioerror.h"
32 #include "gdbusprivate.h"
33
34 #include "glibintl.h"
35
36 /**
37  * SECTION:gdbuserror
38  * @title: GDBusError
39  * @short_description: Mapping D-Bus errors to and from GError
40  * @include: gio/gio.h
41  *
42  * All facilities that return errors from remote methods (such as
43  * g_dbus_connection_call_sync()) use #GError to represent both D-Bus
44  * errors (e.g. errors returned from the other peer) and locally
45  * in-process generated errors.
46  *
47  * To check if a returned #GError is an error from a remote peer, use
48  * g_dbus_error_is_remote_error(). To get the actual D-Bus error name,
49  * use g_dbus_error_get_remote_error(). Before presenting an error,
50  * always use g_dbus_error_strip_remote_error().
51  *
52  * In addition, facilities used to return errors to a remote peer also
53  * use #GError. See g_dbus_method_invocation_return_error() for
54  * discussion about how the D-Bus error name is set.
55  *
56  * Applications can associate a #GError error domain with a set of D-Bus errors in order to
57  * automatically map from D-Bus errors to #GError and back. This
58  * is typically done in the function returning the #GQuark for the
59  * error domain:
60  * <example id="error-registration"><title>Error Registration</title><programlisting>
61  * /<!-- -->* foo-bar-error.h: *<!-- -->/
62  *
63  * #define FOO_BAR_ERROR (foo_bar_error_quark ())
64  * GQuark foo_bar_error_quark (void);
65  *
66  * typedef enum
67  * {
68  *   FOO_BAR_ERROR_FAILED,
69  *   FOO_BAR_ERROR_ANOTHER_ERROR,
70  *   FOO_BAR_ERROR_SOME_THIRD_ERROR,
71  *   FOO_BAR_N_ERRORS /<!-- -->*< skip >*<!-- -->/
72  * } FooBarError;
73  *
74  * /<!-- -->* foo-bar-error.c: *<!-- -->/
75  *
76  * static const GDBusErrorEntry foo_bar_error_entries[] =
77  * {
78  *   {FOO_BAR_ERROR_FAILED,           "org.project.Foo.Bar.Error.Failed"},
79  *   {FOO_BAR_ERROR_ANOTHER_ERROR,    "org.project.Foo.Bar.Error.AnotherError"},
80  *   {FOO_BAR_ERROR_SOME_THIRD_ERROR, "org.project.Foo.Bar.Error.SomeThirdError"},
81  * };
82  *
83  * /<!-- -->* Ensure that every error code has an associated D-Bus error name *<!-- -->/
84  * G_STATIC_ASSERT (G_N_ELEMENTS (foo_bar_error_entries) == FOO_BAR_N_ERRORS);
85  *
86  * GQuark
87  * foo_bar_error_quark (void)
88  * {
89  *   static volatile gsize quark_volatile = 0;
90  *   g_dbus_error_register_error_domain ("foo-bar-error-quark",
91  *                                       &quark_volatile,
92  *                                       foo_bar_error_entries,
93  *                                       G_N_ELEMENTS (foo_bar_error_entries));
94  *   return (GQuark) quark_volatile;
95  * }
96  * </programlisting></example>
97  * With this setup, a D-Bus peer can transparently pass e.g. %FOO_BAR_ERROR_ANOTHER_ERROR and
98  * other peers will see the D-Bus error name <literal>org.project.Foo.Bar.Error.AnotherError</literal>.
99  *
100  * If the other peer is using GDBus, and has registered the association with
101  * g_dbus_error_register_error_domain() in advance (e.g. by invoking the %FOO_BAR_ERROR quark
102  * generation itself in the previous example) the peer will see also %FOO_BAR_ERROR_ANOTHER_ERROR instead
103  * of %G_IO_ERROR_DBUS_ERROR. Note that GDBus clients can still recover
104  * <literal>org.project.Foo.Bar.Error.AnotherError</literal> using g_dbus_error_get_remote_error().
105  *
106  * Note that errors in the %G_DBUS_ERROR error domain is intended only
107  * for returning errors from a remote message bus process. Errors
108  * generated locally in-process by e.g. #GDBusConnection is from the
109  * %G_IO_ERROR domain.
110  */
111
112 static const GDBusErrorEntry g_dbus_error_entries[] =
113 {
114   {G_DBUS_ERROR_FAILED,                           "org.freedesktop.DBus.Error.Failed"},
115   {G_DBUS_ERROR_NO_MEMORY,                        "org.freedesktop.DBus.Error.NoMemory"},
116   {G_DBUS_ERROR_SERVICE_UNKNOWN,                  "org.freedesktop.DBus.Error.ServiceUnknown"},
117   {G_DBUS_ERROR_NAME_HAS_NO_OWNER,                "org.freedesktop.DBus.Error.NameHasNoOwner"},
118   {G_DBUS_ERROR_NO_REPLY,                         "org.freedesktop.DBus.Error.NoReply"},
119   {G_DBUS_ERROR_IO_ERROR,                         "org.freedesktop.DBus.Error.IOError"},
120   {G_DBUS_ERROR_BAD_ADDRESS,                      "org.freedesktop.DBus.Error.BadAddress"},
121   {G_DBUS_ERROR_NOT_SUPPORTED,                    "org.freedesktop.DBus.Error.NotSupported"},
122   {G_DBUS_ERROR_LIMITS_EXCEEDED,                  "org.freedesktop.DBus.Error.LimitsExceeded"},
123   {G_DBUS_ERROR_ACCESS_DENIED,                    "org.freedesktop.DBus.Error.AccessDenied"},
124   {G_DBUS_ERROR_AUTH_FAILED,                      "org.freedesktop.DBus.Error.AuthFailed"},
125   {G_DBUS_ERROR_NO_SERVER,                        "org.freedesktop.DBus.Error.NoServer"},
126   {G_DBUS_ERROR_TIMEOUT,                          "org.freedesktop.DBus.Error.Timeout"},
127   {G_DBUS_ERROR_NO_NETWORK,                       "org.freedesktop.DBus.Error.NoNetwork"},
128   {G_DBUS_ERROR_ADDRESS_IN_USE,                   "org.freedesktop.DBus.Error.AddressInUse"},
129   {G_DBUS_ERROR_DISCONNECTED,                     "org.freedesktop.DBus.Error.Disconnected"},
130   {G_DBUS_ERROR_INVALID_ARGS,                     "org.freedesktop.DBus.Error.InvalidArgs"},
131   {G_DBUS_ERROR_FILE_NOT_FOUND,                   "org.freedesktop.DBus.Error.FileNotFound"},
132   {G_DBUS_ERROR_FILE_EXISTS,                      "org.freedesktop.DBus.Error.FileExists"},
133   {G_DBUS_ERROR_UNKNOWN_METHOD,                   "org.freedesktop.DBus.Error.UnknownMethod"},
134   {G_DBUS_ERROR_TIMED_OUT,                        "org.freedesktop.DBus.Error.TimedOut"},
135   {G_DBUS_ERROR_MATCH_RULE_NOT_FOUND,             "org.freedesktop.DBus.Error.MatchRuleNotFound"},
136   {G_DBUS_ERROR_MATCH_RULE_INVALID,               "org.freedesktop.DBus.Error.MatchRuleInvalid"},
137   {G_DBUS_ERROR_SPAWN_EXEC_FAILED,                "org.freedesktop.DBus.Error.Spawn.ExecFailed"},
138   {G_DBUS_ERROR_SPAWN_FORK_FAILED,                "org.freedesktop.DBus.Error.Spawn.ForkFailed"},
139   {G_DBUS_ERROR_SPAWN_CHILD_EXITED,               "org.freedesktop.DBus.Error.Spawn.ChildExited"},
140   {G_DBUS_ERROR_SPAWN_CHILD_SIGNALED,             "org.freedesktop.DBus.Error.Spawn.ChildSignaled"},
141   {G_DBUS_ERROR_SPAWN_FAILED,                     "org.freedesktop.DBus.Error.Spawn.Failed"},
142   {G_DBUS_ERROR_SPAWN_SETUP_FAILED,               "org.freedesktop.DBus.Error.Spawn.FailedToSetup"},
143   {G_DBUS_ERROR_SPAWN_CONFIG_INVALID,             "org.freedesktop.DBus.Error.Spawn.ConfigInvalid"},
144   {G_DBUS_ERROR_SPAWN_SERVICE_INVALID,            "org.freedesktop.DBus.Error.Spawn.ServiceNotValid"},
145   {G_DBUS_ERROR_SPAWN_SERVICE_NOT_FOUND,          "org.freedesktop.DBus.Error.Spawn.ServiceNotFound"},
146   {G_DBUS_ERROR_SPAWN_PERMISSIONS_INVALID,        "org.freedesktop.DBus.Error.Spawn.PermissionsInvalid"},
147   {G_DBUS_ERROR_SPAWN_FILE_INVALID,               "org.freedesktop.DBus.Error.Spawn.FileInvalid"},
148   {G_DBUS_ERROR_SPAWN_NO_MEMORY,                  "org.freedesktop.DBus.Error.Spawn.NoMemory"},
149   {G_DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN,          "org.freedesktop.DBus.Error.UnixProcessIdUnknown"},
150   {G_DBUS_ERROR_INVALID_SIGNATURE,                "org.freedesktop.DBus.Error.InvalidSignature"},
151   {G_DBUS_ERROR_INVALID_FILE_CONTENT,             "org.freedesktop.DBus.Error.InvalidFileContent"},
152   {G_DBUS_ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN, "org.freedesktop.DBus.Error.SELinuxSecurityContextUnknown"},
153   {G_DBUS_ERROR_ADT_AUDIT_DATA_UNKNOWN,           "org.freedesktop.DBus.Error.AdtAuditDataUnknown"},
154   {G_DBUS_ERROR_OBJECT_PATH_IN_USE,               "org.freedesktop.DBus.Error.ObjectPathInUse"},
155 };
156
157 GQuark
158 g_dbus_error_quark (void)
159 {
160   G_STATIC_ASSERT (G_N_ELEMENTS (g_dbus_error_entries) - 1 == G_DBUS_ERROR_OBJECT_PATH_IN_USE);
161   static volatile gsize quark_volatile = 0;
162   g_dbus_error_register_error_domain ("g-dbus-error-quark",
163                                       &quark_volatile,
164                                       g_dbus_error_entries,
165                                       G_N_ELEMENTS (g_dbus_error_entries));
166   return (GQuark) quark_volatile;
167 }
168
169 /**
170  * g_dbus_error_register_error_domain:
171  * @error_domain_quark_name: The error domain name.
172  * @quark_volatile: A pointer where to store the #GQuark.
173  * @entries: A pointer to @num_entries #GDBusErrorEntry struct items.
174  * @num_entries: Number of items to register.
175  *
176  * Helper function for associating a #GError error domain with D-Bus error names.
177  *
178  * Since: 2.26
179  */
180 void
181 g_dbus_error_register_error_domain (const gchar           *error_domain_quark_name,
182                                     volatile gsize        *quark_volatile,
183                                     const GDBusErrorEntry *entries,
184                                     guint                  num_entries)
185 {
186   g_return_if_fail (error_domain_quark_name != NULL);
187   g_return_if_fail (quark_volatile != NULL);
188   g_return_if_fail (entries != NULL);
189   g_return_if_fail (num_entries > 0);
190
191   if (g_once_init_enter (quark_volatile))
192     {
193       guint n;
194       GQuark quark;
195
196       quark = g_quark_from_static_string (error_domain_quark_name);
197
198       for (n = 0; n < num_entries; n++)
199         {
200           g_warn_if_fail (g_dbus_error_register_error (quark,
201                                                        entries[n].error_code,
202                                                        entries[n].dbus_error_name));
203         }
204       g_once_init_leave (quark_volatile, quark);
205     }
206 }
207
208 static gboolean
209 _g_dbus_error_decode_gerror (const gchar *dbus_name,
210                              GQuark      *out_error_domain,
211                              gint        *out_error_code)
212 {
213   gboolean ret;
214   guint n;
215   GString *s;
216   gchar *domain_quark_string;
217
218   ret = FALSE;
219   s = NULL;
220
221   if (g_str_has_prefix (dbus_name, "org.gtk.GDBus.UnmappedGError.Quark._"))
222     {
223       s = g_string_new (NULL);
224
225       for (n = sizeof "org.gtk.GDBus.UnmappedGError.Quark._" - 1;
226            dbus_name[n] != '.' && dbus_name[n] != '\0';
227            n++)
228         {
229           if (g_ascii_isalnum (dbus_name[n]))
230             {
231               g_string_append_c (s, dbus_name[n]);
232             }
233           else if (dbus_name[n] == '_')
234             {
235               guint nibble_top;
236               guint nibble_bottom;
237
238               n++;
239
240               nibble_top = dbus_name[n];
241               if (nibble_top >= '0' && nibble_top <= '9')
242                 nibble_top -= '0';
243               else if (nibble_top >= 'a' && nibble_top <= 'f')
244                 nibble_top -= ('a' - 10);
245               else
246                 goto not_mapped;
247
248               n++;
249
250               nibble_bottom = dbus_name[n];
251               if (nibble_bottom >= '0' && nibble_bottom <= '9')
252                 nibble_bottom -= '0';
253               else if (nibble_bottom >= 'a' && nibble_bottom <= 'f')
254                 nibble_bottom -= ('a' - 10);
255               else
256                 goto not_mapped;
257
258               g_string_append_c (s, (nibble_top<<4) | nibble_bottom);
259             }
260           else
261             {
262               goto not_mapped;
263             }
264         }
265
266       if (!g_str_has_prefix (dbus_name + n, ".Code"))
267         goto not_mapped;
268
269       domain_quark_string = g_string_free (s, FALSE);
270       s = NULL;
271
272       if (out_error_domain != NULL)
273         *out_error_domain = g_quark_from_string (domain_quark_string);
274       g_free (domain_quark_string);
275
276       if (out_error_code != NULL)
277         *out_error_code = atoi (dbus_name + n + sizeof ".Code" - 1);
278
279       ret = TRUE;
280     }
281
282  not_mapped:
283
284   if (s != NULL)
285     g_string_free (s, TRUE);
286
287   return ret;
288 }
289
290 /* ---------------------------------------------------------------------------------------------------- */
291
292 typedef struct
293 {
294   GQuark error_domain;
295   gint   error_code;
296 } QuarkCodePair;
297
298 static guint
299 quark_code_pair_hash_func (const QuarkCodePair *pair)
300 {
301   gint val;
302   val = pair->error_domain + pair->error_code;
303   return g_int_hash (&val);
304 }
305
306 static gboolean
307 quark_code_pair_equal_func (const QuarkCodePair *a,
308                             const QuarkCodePair *b)
309 {
310   return (a->error_domain == b->error_domain) && (a->error_code == b->error_code);
311 }
312
313 typedef struct
314 {
315   QuarkCodePair pair;
316   gchar *dbus_error_name;
317 } RegisteredError;
318
319 static void
320 registered_error_free (RegisteredError *re)
321 {
322   g_free (re->dbus_error_name);
323   g_free (re);
324 }
325
326 G_LOCK_DEFINE_STATIC (error_lock);
327
328 /* maps from QuarkCodePair* -> RegisteredError* */
329 static GHashTable *quark_code_pair_to_re = NULL;
330
331 /* maps from gchar* -> RegisteredError* */
332 static GHashTable *dbus_error_name_to_re = NULL;
333
334 /**
335  * g_dbus_error_register_error:
336  * @error_domain: A #GQuark for a error domain.
337  * @error_code: An error code.
338  * @dbus_error_name: A D-Bus error name.
339  *
340  * Creates an association to map between @dbus_error_name and
341  * #GError<!-- -->s specified by @error_domain and @error_code.
342  *
343  * This is typically done in the routine that returns the #GQuark for
344  * an error domain.
345  *
346  * Returns: %TRUE if the association was created, %FALSE if it already
347  * exists.
348  *
349  * Since: 2.26
350  */
351 gboolean
352 g_dbus_error_register_error (GQuark       error_domain,
353                              gint         error_code,
354                              const gchar *dbus_error_name)
355 {
356   gboolean ret;
357   QuarkCodePair pair;
358   RegisteredError *re;
359
360   g_return_val_if_fail (dbus_error_name != NULL, FALSE);
361
362   ret = FALSE;
363
364   G_LOCK (error_lock);
365
366   if (quark_code_pair_to_re == NULL)
367     {
368       g_assert (dbus_error_name_to_re == NULL); /* check invariant */
369       quark_code_pair_to_re = g_hash_table_new ((GHashFunc) quark_code_pair_hash_func,
370                                                 (GEqualFunc) quark_code_pair_equal_func);
371       dbus_error_name_to_re = g_hash_table_new_full (g_str_hash,
372                                                      g_str_equal,
373                                                      NULL,
374                                                      (GDestroyNotify) registered_error_free);
375     }
376
377   if (g_hash_table_lookup (dbus_error_name_to_re, dbus_error_name) != NULL)
378     goto out;
379
380   pair.error_domain = error_domain;
381   pair.error_code = error_code;
382
383   if (g_hash_table_lookup (quark_code_pair_to_re, &pair) != NULL)
384     goto out;
385
386   re = g_new0 (RegisteredError, 1);
387   re->pair = pair;
388   re->dbus_error_name = g_strdup (dbus_error_name);
389
390   g_hash_table_insert (quark_code_pair_to_re, &(re->pair), re);
391   g_hash_table_insert (dbus_error_name_to_re, re->dbus_error_name, re);
392
393   ret = TRUE;
394
395  out:
396   G_UNLOCK (error_lock);
397   return ret;
398 }
399
400 /**
401  * g_dbus_error_unregister_error:
402  * @error_domain: A #GQuark for a error domain.
403  * @error_code: An error code.
404  * @dbus_error_name: A D-Bus error name.
405  *
406  * Destroys an association previously set up with g_dbus_error_register_error().
407  *
408  * Returns: %TRUE if the association was destroyed, %FALSE if it wasn't found.
409  *
410  * Since: 2.26
411  */
412 gboolean
413 g_dbus_error_unregister_error (GQuark       error_domain,
414                                gint         error_code,
415                                const gchar *dbus_error_name)
416 {
417   gboolean ret;
418   RegisteredError *re;
419   guint hash_size;
420
421   g_return_val_if_fail (dbus_error_name != NULL, FALSE);
422
423   ret = FALSE;
424
425   G_LOCK (error_lock);
426
427   if (dbus_error_name_to_re == NULL)
428     {
429       g_assert (quark_code_pair_to_re == NULL); /* check invariant */
430       goto out;
431     }
432
433   re = g_hash_table_lookup (dbus_error_name_to_re, dbus_error_name);
434   if (re == NULL)
435     {
436       QuarkCodePair pair;
437       pair.error_domain = error_domain;
438       pair.error_code = error_code;
439       g_warn_if_fail (g_hash_table_lookup (quark_code_pair_to_re, &pair) == NULL); /* check invariant */
440       goto out;
441     }
442
443   ret = TRUE;
444
445   g_warn_if_fail (g_hash_table_lookup (quark_code_pair_to_re, &(re->pair)) == re); /* check invariant */
446
447   g_warn_if_fail (g_hash_table_remove (quark_code_pair_to_re, &(re->pair)));
448   g_warn_if_fail (g_hash_table_remove (dbus_error_name_to_re, re->dbus_error_name));
449
450   /* destroy hashes if empty */
451   hash_size = g_hash_table_size (dbus_error_name_to_re);
452   if (hash_size == 0)
453     {
454       g_warn_if_fail (g_hash_table_size (quark_code_pair_to_re) == 0); /* check invariant */
455
456       g_hash_table_unref (dbus_error_name_to_re);
457       dbus_error_name_to_re = NULL;
458       g_hash_table_unref (quark_code_pair_to_re);
459       quark_code_pair_to_re = NULL;
460     }
461   else
462     {
463       g_warn_if_fail (g_hash_table_size (quark_code_pair_to_re) == hash_size); /* check invariant */
464     }
465
466  out:
467   G_UNLOCK (error_lock);
468   return ret;
469 }
470
471 /* ---------------------------------------------------------------------------------------------------- */
472
473 /**
474  * g_dbus_error_is_remote_error:
475  * @error: A #GError.
476  *
477  * Checks if @error represents an error received via D-Bus from a remote peer. If so,
478  * use g_dbus_error_get_remote_error() to get the name of the error.
479  *
480  * Returns: %TRUE if @error represents an error from a remote peer,
481  * %FALSE otherwise.
482  *
483  * Since: 2.26
484  */
485 gboolean
486 g_dbus_error_is_remote_error (const GError *error)
487 {
488   g_return_val_if_fail (error != NULL, FALSE);
489   return g_str_has_prefix (error->message, "GDBus.Error:");
490 }
491
492
493 /**
494  * g_dbus_error_get_remote_error:
495  * @error: A #GError.
496  *
497  * Gets the D-Bus error name used for @error, if any.
498  *
499  * This function is guaranteed to return a D-Bus error name for all
500  * #GError<!-- -->s returned from functions handling remote method
501  * calls (e.g. g_dbus_connection_call_finish()) unless
502  * g_dbus_error_strip_remote_error() has been used on @error.
503  *
504  * Returns: An allocated string or %NULL if the D-Bus error name could not be found. Free with g_free().
505  *
506  * Since: 2.26
507  */
508 gchar *
509 g_dbus_error_get_remote_error (const GError *error)
510 {
511   RegisteredError *re;
512   gchar *ret;
513
514   g_return_val_if_fail (error != NULL, NULL);
515
516   /* Ensure that e.g. G_DBUS_ERROR is registered using g_dbus_error_register_error() */
517   _g_dbus_initialize ();
518
519   ret = NULL;
520
521   G_LOCK (error_lock);
522
523   re = NULL;
524   if (quark_code_pair_to_re != NULL)
525     {
526       QuarkCodePair pair;
527       pair.error_domain = error->domain;
528       pair.error_code = error->code;
529       g_assert (dbus_error_name_to_re != NULL); /* check invariant */
530       re = g_hash_table_lookup (quark_code_pair_to_re, &pair);
531     }
532
533   if (re != NULL)
534     {
535       ret = g_strdup (re->dbus_error_name);
536     }
537   else
538     {
539       if (g_str_has_prefix (error->message, "GDBus.Error:"))
540         {
541           const gchar *begin;
542           const gchar *end;
543           begin = error->message + sizeof ("GDBus.Error:") -1;
544           end = strstr (begin, ":");
545           if (end != NULL && end[1] == ' ')
546             {
547               ret = g_strndup (begin, end - begin);
548             }
549         }
550     }
551
552   G_UNLOCK (error_lock);
553
554   return ret;
555 }
556
557 /* ---------------------------------------------------------------------------------------------------- */
558
559 /**
560  * g_dbus_error_new_for_dbus_error:
561  * @dbus_error_name: D-Bus error name.
562  * @dbus_error_message: D-Bus error message.
563  *
564  * Creates a #GError based on the contents of @dbus_error_name and
565  * @dbus_error_message.
566  *
567  * Errors registered with g_dbus_error_register_error() will be looked
568  * up using @dbus_error_name and if a match is found, the error domain
569  * and code is used. Applications can use g_dbus_error_get_remote_error()
570  * to recover @dbus_error_name.
571  *
572  * If a match against a registered error is not found and the D-Bus
573  * error name is in a form as returned by g_dbus_error_encode_gerror()
574  * the error domain and code encoded in the name is used to
575  * create the #GError. Also, @dbus_error_name is added to the error message
576  * such that it can be recovered with g_dbus_error_get_remote_error().
577  *
578  * Otherwise, a #GError with the error code %G_IO_ERROR_DBUS_ERROR
579  * in the #G_IO_ERROR error domain is returned. Also, @dbus_error_name is
580  * added to the error message such that it can be recovered with
581  * g_dbus_error_get_remote_error().
582  *
583  * In all three cases, @dbus_error_name can always be recovered from the
584  * returned #GError using the g_dbus_error_get_remote_error() function
585  * (unless g_dbus_error_strip_remote_error() hasn't been used on the returned error).
586  *
587  * This function is typically only used in object mappings to prepare
588  * #GError instances for applications. Regular applications should not use
589  * it.
590  *
591  * Returns: An allocated #GError. Free with g_error_free().
592  *
593  * Since: 2.26
594  */
595 GError *
596 g_dbus_error_new_for_dbus_error (const gchar *dbus_error_name,
597                                  const gchar *dbus_error_message)
598 {
599   GError *error;
600   RegisteredError *re;
601
602   g_return_val_if_fail (dbus_error_name != NULL, NULL);
603   g_return_val_if_fail (dbus_error_message != NULL, NULL);
604
605   /* Ensure that e.g. G_DBUS_ERROR is registered using g_dbus_error_register_error() */
606   _g_dbus_initialize ();
607
608   G_LOCK (error_lock);
609
610   re = NULL;
611   if (dbus_error_name_to_re != NULL)
612     {
613       g_assert (quark_code_pair_to_re != NULL); /* check invariant */
614       re = g_hash_table_lookup (dbus_error_name_to_re, dbus_error_name);
615     }
616
617   if (re != NULL)
618     {
619       error = g_error_new (re->pair.error_domain,
620                            re->pair.error_code,
621                            "GDBus.Error:%s: %s",
622                            dbus_error_name,
623                            dbus_error_message);
624     }
625   else
626     {
627       GQuark error_domain = 0;
628       gint error_code = 0;
629
630       if (_g_dbus_error_decode_gerror (dbus_error_name,
631                                        &error_domain,
632                                        &error_code))
633         {
634           error = g_error_new (error_domain,
635                                error_code,
636                                "GDBus.Error:%s: %s",
637                                dbus_error_name,
638                                dbus_error_message);
639         }
640       else
641         {
642           error = g_error_new (G_IO_ERROR,
643                                G_IO_ERROR_DBUS_ERROR,
644                                "GDBus.Error:%s: %s",
645                                dbus_error_name,
646                                dbus_error_message);
647         }
648     }
649
650   G_UNLOCK (error_lock);
651   return error;
652 }
653
654 /**
655  * g_dbus_error_set_dbus_error:
656  * @error: A pointer to a #GError or %NULL.
657  * @dbus_error_name: D-Bus error name.
658  * @dbus_error_message: D-Bus error message.
659  * @format: (allow-none): printf()-style format to prepend to @dbus_error_message or %NULL.
660  * @...: Arguments for @format.
661  *
662  * Does nothing if @error is %NULL. Otherwise sets *@error to
663  * a new #GError created with g_dbus_error_new_for_dbus_error()
664  * with @dbus_error_message prepend with @format (unless %NULL).
665  *
666  * Since: 2.26
667  */
668 void
669 g_dbus_error_set_dbus_error (GError      **error,
670                              const gchar  *dbus_error_name,
671                              const gchar  *dbus_error_message,
672                              const gchar  *format,
673                              ...)
674 {
675   g_return_if_fail (error == NULL || *error == NULL);
676   g_return_if_fail (dbus_error_name != NULL);
677   g_return_if_fail (dbus_error_message != NULL);
678
679   if (error == NULL)
680     return;
681
682   if (format == NULL)
683     {
684       *error = g_dbus_error_new_for_dbus_error (dbus_error_name, dbus_error_message);
685     }
686   else
687     {
688       va_list var_args;
689       va_start (var_args, format);
690       g_dbus_error_set_dbus_error_valist (error,
691                                           dbus_error_name,
692                                           dbus_error_message,
693                                           format,
694                                           var_args);
695       va_end (var_args);
696     }
697 }
698
699 /**
700  * g_dbus_error_set_dbus_error_valist:
701  * @error: A pointer to a #GError or %NULL.
702  * @dbus_error_name: D-Bus error name.
703  * @dbus_error_message: D-Bus error message.
704  * @format: (allow-none): printf()-style format to prepend to @dbus_error_message or %NULL.
705  * @var_args: Arguments for @format.
706  *
707  * Like g_dbus_error_set_dbus_error() but intended for language bindings.
708  *
709  * Since: 2.26
710  */
711 void
712 g_dbus_error_set_dbus_error_valist (GError      **error,
713                                     const gchar  *dbus_error_name,
714                                     const gchar  *dbus_error_message,
715                                     const gchar  *format,
716                                     va_list       var_args)
717 {
718   g_return_if_fail (error == NULL || *error == NULL);
719   g_return_if_fail (dbus_error_name != NULL);
720   g_return_if_fail (dbus_error_message != NULL);
721
722   if (error == NULL)
723     return;
724
725   if (format != NULL)
726     {
727       gchar *message;
728       gchar *s;
729       message = g_strdup_vprintf (format, var_args);
730       s = g_strdup_printf ("%s: %s", message, dbus_error_message);
731       *error = g_dbus_error_new_for_dbus_error (dbus_error_name, s);
732       g_free (s);
733       g_free (message);
734     }
735   else
736     {
737       *error = g_dbus_error_new_for_dbus_error (dbus_error_name, dbus_error_message);
738     }
739 }
740
741 /**
742  * g_dbus_error_strip_remote_error:
743  * @error: A #GError.
744  *
745  * Looks for extra information in the error message used to recover
746  * the D-Bus error name and strips it if found. If stripped, the
747  * message field in @error will correspond exactly to what was
748  * received on the wire.
749  *
750  * This is typically used when presenting errors to the end user.
751  *
752  * Returns: %TRUE if information was stripped, %FALSE otherwise.
753  *
754  * Since: 2.26
755  */
756 gboolean
757 g_dbus_error_strip_remote_error (GError *error)
758 {
759   gboolean ret;
760
761   g_return_val_if_fail (error != NULL, FALSE);
762
763   ret = FALSE;
764
765   if (g_str_has_prefix (error->message, "GDBus.Error:"))
766     {
767       const gchar *begin;
768       const gchar *end;
769       gchar *new_message;
770
771       begin = error->message + sizeof ("GDBus.Error:") -1;
772       end = strstr (begin, ":");
773       if (end != NULL && end[1] == ' ')
774         {
775           new_message = g_strdup (end + 2);
776           g_free (error->message);
777           error->message = new_message;
778           ret = TRUE;
779         }
780     }
781
782   return ret;
783 }
784
785 /**
786  * g_dbus_error_encode_gerror:
787  * @error: A #GError.
788  *
789  * Creates a D-Bus error name to use for @error. If @error matches
790  * a registered error (cf. g_dbus_error_register_error()), the corresponding
791  * D-Bus error name will be returned.
792  *
793  * Otherwise the a name of the form
794  * <literal>org.gtk.GDBus.UnmappedGError.Quark._ESCAPED_QUARK_NAME.Code_ERROR_CODE</literal>
795  * will be used. This allows other GDBus applications to map the error
796  * on the wire back to a #GError using g_dbus_error_new_for_dbus_error().
797  *
798  * This function is typically only used in object mappings to put a
799  * #GError on the wire. Regular applications should not use it.
800  *
801  * Returns: A D-Bus error name (never %NULL). Free with g_free().
802  *
803  * Since: 2.26
804  */
805 gchar *
806 g_dbus_error_encode_gerror (const GError *error)
807 {
808   RegisteredError *re;
809   gchar *error_name;
810
811   g_return_val_if_fail (error != NULL, NULL);
812
813   /* Ensure that e.g. G_DBUS_ERROR is registered using g_dbus_error_register_error() */
814   _g_dbus_initialize ();
815
816   error_name = NULL;
817
818   G_LOCK (error_lock);
819   re = NULL;
820   if (quark_code_pair_to_re != NULL)
821     {
822       QuarkCodePair pair;
823       pair.error_domain = error->domain;
824       pair.error_code = error->code;
825       g_assert (dbus_error_name_to_re != NULL); /* check invariant */
826       re = g_hash_table_lookup (quark_code_pair_to_re, &pair);
827     }
828   if (re != NULL)
829     {
830       error_name = g_strdup (re->dbus_error_name);
831       G_UNLOCK (error_lock);
832     }
833   else
834     {
835       const gchar *domain_as_string;
836       GString *s;
837       guint n;
838
839       G_UNLOCK (error_lock);
840
841       /* We can't make a lot of assumptions about what domain_as_string
842        * looks like and D-Bus is extremely picky about error names so
843        * hex-encode it for transport across the wire.
844        */
845       domain_as_string = g_quark_to_string (error->domain);
846
847       /* 0 is not a domain; neither are non-quark integers */
848       g_return_val_if_fail (domain_as_string != NULL, NULL);
849
850       s = g_string_new ("org.gtk.GDBus.UnmappedGError.Quark._");
851       for (n = 0; domain_as_string[n] != 0; n++)
852         {
853           gint c = domain_as_string[n];
854           if (g_ascii_isalnum (c))
855             {
856               g_string_append_c (s, c);
857             }
858           else
859             {
860               guint nibble_top;
861               guint nibble_bottom;
862               g_string_append_c (s, '_');
863               nibble_top = ((int) domain_as_string[n]) >> 4;
864               nibble_bottom = ((int) domain_as_string[n]) & 0x0f;
865               if (nibble_top < 10)
866                 nibble_top += '0';
867               else
868                 nibble_top += 'a' - 10;
869               if (nibble_bottom < 10)
870                 nibble_bottom += '0';
871               else
872                 nibble_bottom += 'a' - 10;
873               g_string_append_c (s, nibble_top);
874               g_string_append_c (s, nibble_bottom);
875             }
876         }
877       g_string_append_printf (s, ".Code%d", error->code);
878       error_name = g_string_free (s, FALSE);
879     }
880
881   return error_name;
882 }