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