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