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