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