Add some more test about gdbus_error apis
[glib.git] / gio / gdbusauth.c
blob7f19ace8740392748bdd0bbf596fbf3fc9916779
1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
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.
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.
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.
20 * Author: David Zeuthen <davidz@redhat.com>
23 #include "config.h"
25 #include "gdbusauth.h"
27 #include "gdbusauthmechanismanon.h"
28 #include "gdbusauthmechanismexternal.h"
29 #include "gdbusauthmechanismsha1.h"
30 #include "gdbusauthobserver.h"
32 #include "gdbuserror.h"
33 #include "gdbusutils.h"
34 #include "gioenumtypes.h"
35 #include "gcredentials.h"
36 #include "gdbusprivate.h"
37 #include "giostream.h"
38 #include "gdatainputstream.h"
39 #include "gdataoutputstream.h"
41 #ifdef G_OS_UNIX
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include "gunixconnection.h"
45 #include "gunixcredentialsmessage.h"
46 #endif
48 #include "glibintl.h"
50 static void
51 debug_print (const gchar *message, ...)
53 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
55 gchar *s;
56 GString *str;
57 va_list var_args;
58 guint n;
60 _g_dbus_debug_print_lock ();
62 va_start (var_args, message);
63 s = g_strdup_vprintf (message, var_args);
64 va_end (var_args);
66 str = g_string_new (NULL);
67 for (n = 0; s[n] != '\0'; n++)
69 if (G_UNLIKELY (s[n] == '\r'))
70 g_string_append (str, "\\r");
71 else if (G_UNLIKELY (s[n] == '\n'))
72 g_string_append (str, "\\n");
73 else
74 g_string_append_c (str, s[n]);
76 g_print ("GDBus-debug:Auth: %s\n", str->str);
77 g_string_free (str, TRUE);
78 g_free (s);
80 _g_dbus_debug_print_unlock ();
84 typedef struct
86 const gchar *name;
87 gint priority;
88 GType gtype;
89 } Mechanism;
91 static void mechanism_free (Mechanism *m);
93 struct _GDBusAuthPrivate
95 GIOStream *stream;
97 /* A list of available Mechanism, sorted according to priority */
98 GList *available_mechanisms;
101 enum
103 PROP_0,
104 PROP_STREAM
107 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
109 /* ---------------------------------------------------------------------------------------------------- */
111 static void
112 _g_dbus_auth_finalize (GObject *object)
114 GDBusAuth *auth = G_DBUS_AUTH (object);
116 if (auth->priv->stream != NULL)
117 g_object_unref (auth->priv->stream);
118 g_list_foreach (auth->priv->available_mechanisms, (GFunc) mechanism_free, NULL);
119 g_list_free (auth->priv->available_mechanisms);
121 if (G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize != NULL)
122 G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize (object);
125 static void
126 _g_dbus_auth_get_property (GObject *object,
127 guint prop_id,
128 GValue *value,
129 GParamSpec *pspec)
131 GDBusAuth *auth = G_DBUS_AUTH (object);
133 switch (prop_id)
135 case PROP_STREAM:
136 g_value_set_object (value, auth->priv->stream);
137 break;
139 default:
140 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
141 break;
145 static void
146 _g_dbus_auth_set_property (GObject *object,
147 guint prop_id,
148 const GValue *value,
149 GParamSpec *pspec)
151 GDBusAuth *auth = G_DBUS_AUTH (object);
153 switch (prop_id)
155 case PROP_STREAM:
156 auth->priv->stream = g_value_dup_object (value);
157 break;
159 default:
160 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
161 break;
165 static void
166 _g_dbus_auth_class_init (GDBusAuthClass *klass)
168 GObjectClass *gobject_class;
170 g_type_class_add_private (klass, sizeof (GDBusAuthPrivate));
172 gobject_class = G_OBJECT_CLASS (klass);
173 gobject_class->get_property = _g_dbus_auth_get_property;
174 gobject_class->set_property = _g_dbus_auth_set_property;
175 gobject_class->finalize = _g_dbus_auth_finalize;
177 g_object_class_install_property (gobject_class,
178 PROP_STREAM,
179 g_param_spec_object ("stream",
180 P_("IO Stream"),
181 P_("The underlying GIOStream used for I/O"),
182 G_TYPE_IO_STREAM,
183 G_PARAM_READABLE |
184 G_PARAM_WRITABLE |
185 G_PARAM_CONSTRUCT_ONLY |
186 G_PARAM_STATIC_NAME |
187 G_PARAM_STATIC_BLURB |
188 G_PARAM_STATIC_NICK));
191 static void
192 mechanism_free (Mechanism *m)
194 g_free (m);
197 static void
198 add_mechanism (GDBusAuth *auth,
199 GType mechanism_type)
201 Mechanism *m;
203 m = g_new0 (Mechanism, 1);
204 m->name = _g_dbus_auth_mechanism_get_name (mechanism_type);
205 m->priority = _g_dbus_auth_mechanism_get_priority (mechanism_type);
206 m->gtype = mechanism_type;
208 auth->priv->available_mechanisms = g_list_prepend (auth->priv->available_mechanisms, m);
211 static gint
212 mech_compare_func (Mechanism *a, Mechanism *b)
214 gint ret;
215 /* ensure deterministic order */
216 ret = b->priority - a->priority;
217 if (ret == 0)
218 ret = g_strcmp0 (b->name, a->name);
219 return ret;
222 static void
223 _g_dbus_auth_init (GDBusAuth *auth)
225 auth->priv = G_TYPE_INSTANCE_GET_PRIVATE (auth, G_TYPE_DBUS_AUTH, GDBusAuthPrivate);
227 /* TODO: trawl extension points */
228 add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_ANON);
229 add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_SHA1);
230 add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_EXTERNAL);
232 auth->priv->available_mechanisms = g_list_sort (auth->priv->available_mechanisms,
233 (GCompareFunc) mech_compare_func);
236 static GType
237 find_mech_by_name (GDBusAuth *auth,
238 const gchar *name)
240 GType ret;
241 GList *l;
243 ret = (GType) 0;
245 for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
247 Mechanism *m = l->data;
248 if (g_strcmp0 (name, m->name) == 0)
250 ret = m->gtype;
251 goto out;
255 out:
256 return ret;
259 GDBusAuth *
260 _g_dbus_auth_new (GIOStream *stream)
262 return g_object_new (G_TYPE_DBUS_AUTH,
263 "stream", stream,
264 NULL);
267 /* ---------------------------------------------------------------------------------------------------- */
268 /* like g_data_input_stream_read_line() but sets error if there's no content to read */
269 static gchar *
270 _my_g_data_input_stream_read_line (GDataInputStream *dis,
271 gsize *out_line_length,
272 GCancellable *cancellable,
273 GError **error)
275 gchar *ret;
277 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
279 ret = g_data_input_stream_read_line (dis,
280 out_line_length,
281 cancellable,
282 error);
283 if (ret == NULL && error != NULL && *error == NULL)
285 g_set_error_literal (error,
286 G_IO_ERROR,
287 G_IO_ERROR_FAILED,
288 _("Unexpected lack of content trying to read a line"));
291 return ret;
294 /* This function is to avoid situations like this
296 * BEGIN\r\nl\0\0\1...
298 * e.g. where we read into the first D-Bus message while waiting for
299 * the final line from the client (TODO: file bug against gio for
300 * this)
302 static gchar *
303 _my_g_input_stream_read_line_safe (GInputStream *i,
304 gsize *out_line_length,
305 GCancellable *cancellable,
306 GError **error)
308 GString *str;
309 gchar c;
310 gssize num_read;
311 gboolean last_was_cr;
313 str = g_string_new (NULL);
315 last_was_cr = FALSE;
316 while (TRUE)
318 num_read = g_input_stream_read (i,
321 cancellable,
322 error);
323 if (num_read == -1)
324 goto fail;
325 if (num_read == 0)
327 if (error != NULL && *error == NULL)
329 g_set_error_literal (error,
330 G_IO_ERROR,
331 G_IO_ERROR_FAILED,
332 _("Unexpected lack of content trying to (safely) read a line"));
334 goto fail;
337 g_string_append_c (str, (gint) c);
338 if (last_was_cr)
340 if (c == 0x0a)
342 g_assert (str->len >= 2);
343 g_string_set_size (str, str->len - 2);
344 goto out;
347 last_was_cr = (c == 0x0d);
350 out:
351 if (out_line_length != NULL)
352 *out_line_length = str->len;
353 return g_string_free (str, FALSE);
355 fail:
356 g_assert (error == NULL || *error != NULL);
357 g_string_free (str, TRUE);
358 return NULL;
361 /* ---------------------------------------------------------------------------------------------------- */
363 static void
364 append_nibble (GString *s, gint val)
366 g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
369 static gchar *
370 hexdecode (const gchar *str,
371 gsize *out_len,
372 GError **error)
374 gchar *ret;
375 GString *s;
376 guint n;
378 ret = NULL;
379 s = g_string_new (NULL);
381 for (n = 0; str[n] != '\0'; n += 2)
383 gint upper_nibble;
384 gint lower_nibble;
385 guint value;
387 upper_nibble = g_ascii_xdigit_value (str[n]);
388 lower_nibble = g_ascii_xdigit_value (str[n + 1]);
389 if (upper_nibble == -1 || lower_nibble == -1)
391 g_set_error (error,
392 G_IO_ERROR,
393 G_IO_ERROR_FAILED,
394 "Error hexdecoding string `%s' around position %d",
395 str, n);
396 goto out;
398 value = (upper_nibble<<4) | lower_nibble;
399 g_string_append_c (s, value);
402 ret = g_string_free (s, FALSE);
403 s = NULL;
405 out:
406 if (s != NULL)
407 g_string_free (s, TRUE);
408 return ret;
411 /* TODO: take len */
412 static gchar *
413 hexencode (const gchar *str)
415 guint n;
416 GString *s;
418 s = g_string_new (NULL);
419 for (n = 0; str[n] != '\0'; n++)
421 gint val;
422 gint upper_nibble;
423 gint lower_nibble;
425 val = ((const guchar *) str)[n];
426 upper_nibble = val >> 4;
427 lower_nibble = val & 0x0f;
429 append_nibble (s, upper_nibble);
430 append_nibble (s, lower_nibble);
433 return g_string_free (s, FALSE);
436 /* ---------------------------------------------------------------------------------------------------- */
438 static GDBusAuthMechanism *
439 client_choose_mech_and_send_initial_response (GDBusAuth *auth,
440 GCredentials *credentials_that_were_sent,
441 const gchar* const *supported_auth_mechs,
442 GPtrArray *attempted_auth_mechs,
443 GDataOutputStream *dos,
444 GCancellable *cancellable,
445 GError **error)
447 GDBusAuthMechanism *mech;
448 GType auth_mech_to_use_gtype;
449 guint n;
450 guint m;
451 gchar *initial_response;
452 gsize initial_response_len;
453 gchar *encoded;
454 gchar *s;
456 again:
457 mech = NULL;
459 debug_print ("CLIENT: Trying to choose mechanism");
461 /* find an authentication mechanism to try, if any */
462 auth_mech_to_use_gtype = (GType) 0;
463 for (n = 0; supported_auth_mechs[n] != NULL; n++)
465 gboolean attempted_already;
466 attempted_already = FALSE;
467 for (m = 0; m < attempted_auth_mechs->len; m++)
469 if (g_strcmp0 (supported_auth_mechs[n], attempted_auth_mechs->pdata[m]) == 0)
471 attempted_already = TRUE;
472 break;
475 if (!attempted_already)
477 auth_mech_to_use_gtype = find_mech_by_name (auth, supported_auth_mechs[n]);
478 if (auth_mech_to_use_gtype != (GType) 0)
479 break;
483 if (auth_mech_to_use_gtype == (GType) 0)
485 guint n;
486 gchar *available;
487 GString *tried_str;
489 debug_print ("CLIENT: Exhausted all available mechanisms");
491 available = g_strjoinv (", ", (gchar **) supported_auth_mechs);
493 tried_str = g_string_new (NULL);
494 for (n = 0; n < attempted_auth_mechs->len; n++)
496 if (n > 0)
497 g_string_append (tried_str, ", ");
498 g_string_append (tried_str, attempted_auth_mechs->pdata[n]);
500 g_set_error (error,
501 G_IO_ERROR,
502 G_IO_ERROR_FAILED,
503 _("Exhausted all available authentication mechanisms (tried: %s) (available: %s)"),
504 tried_str->str,
505 available);
506 g_string_free (tried_str, TRUE);
507 g_free (available);
508 goto out;
511 /* OK, decided on a mechanism - let's do this thing */
512 mech = g_object_new (auth_mech_to_use_gtype,
513 "stream", auth->priv->stream,
514 "credentials", credentials_that_were_sent,
515 NULL);
516 debug_print ("CLIENT: Trying mechanism `%s'", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
517 g_ptr_array_add (attempted_auth_mechs, (gpointer) _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
519 /* the auth mechanism may not be supported
520 * (for example, EXTERNAL only works if credentials were exchanged)
522 if (!_g_dbus_auth_mechanism_is_supported (mech))
524 debug_print ("CLIENT: Mechanism `%s' says it is not supported", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
525 g_object_unref (mech);
526 mech = NULL;
527 goto again;
530 initial_response_len = -1;
531 initial_response = _g_dbus_auth_mechanism_client_initiate (mech,
532 &initial_response_len);
533 #if 0
534 g_printerr ("using auth mechanism with name `%s' of type `%s' with initial response `%s'\n",
535 _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
536 g_type_name (G_TYPE_FROM_INSTANCE (mech)),
537 initial_response);
538 #endif
539 if (initial_response != NULL)
541 //g_printerr ("initial_response = `%s'\n", initial_response);
542 encoded = hexencode (initial_response);
543 s = g_strdup_printf ("AUTH %s %s\r\n",
544 _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
545 encoded);
546 g_free (initial_response);
547 g_free (encoded);
549 else
551 s = g_strdup_printf ("AUTH %s\r\n", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
553 debug_print ("CLIENT: writing `%s'", s);
554 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
556 g_object_unref (mech);
557 mech = NULL;
558 g_free (s);
559 goto out;
561 g_free (s);
563 out:
564 return mech;
568 /* ---------------------------------------------------------------------------------------------------- */
570 typedef enum
572 CLIENT_STATE_WAITING_FOR_DATA,
573 CLIENT_STATE_WAITING_FOR_OK,
574 CLIENT_STATE_WAITING_FOR_REJECT,
575 CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD
576 } ClientState;
578 gchar *
579 _g_dbus_auth_run_client (GDBusAuth *auth,
580 GDBusCapabilityFlags offered_capabilities,
581 GDBusCapabilityFlags *out_negotiated_capabilities,
582 GCancellable *cancellable,
583 GError **error)
585 gchar *s;
586 GDataInputStream *dis;
587 GDataOutputStream *dos;
588 GCredentials *credentials;
589 gchar *ret_guid;
590 gchar *line;
591 gsize line_length;
592 gchar **supported_auth_mechs;
593 GPtrArray *attempted_auth_mechs;
594 GDBusAuthMechanism *mech;
595 ClientState state;
596 GDBusCapabilityFlags negotiated_capabilities;
598 debug_print ("CLIENT: initiating");
600 ret_guid = NULL;
601 supported_auth_mechs = NULL;
602 attempted_auth_mechs = g_ptr_array_new ();
603 mech = NULL;
604 negotiated_capabilities = 0;
605 credentials = NULL;
607 dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
608 dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
609 g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
610 g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
612 g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
614 #ifdef G_OS_UNIX
615 if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
617 credentials = g_credentials_new ();
618 if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
619 cancellable,
620 error))
621 goto out;
623 else
625 if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
626 goto out;
628 #else
629 if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
630 goto out;
631 #endif
633 if (credentials != NULL)
635 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
637 s = g_credentials_to_string (credentials);
638 debug_print ("CLIENT: sent credentials `%s'", s);
639 g_free (s);
642 else
644 debug_print ("CLIENT: didn't send any credentials");
647 /* TODO: to reduce roundtrips, try to pick an auth mechanism to start with */
649 /* Get list of supported authentication mechanisms */
650 s = "AUTH\r\n";
651 debug_print ("CLIENT: writing `%s'", s);
652 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
653 goto out;
654 state = CLIENT_STATE_WAITING_FOR_REJECT;
656 while (TRUE)
658 switch (state)
660 case CLIENT_STATE_WAITING_FOR_REJECT:
661 debug_print ("CLIENT: WaitingForReject");
662 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
663 if (line == NULL)
664 goto out;
665 debug_print ("CLIENT: WaitingForReject, read '%s'", line);
666 foobar:
667 if (!g_str_has_prefix (line, "REJECTED "))
669 g_set_error (error,
670 G_IO_ERROR,
671 G_IO_ERROR_FAILED,
672 "In WaitingForReject: Expected `REJECTED am1 am2 ... amN', got `%s'",
673 line);
674 g_free (line);
675 goto out;
677 if (supported_auth_mechs == NULL)
679 supported_auth_mechs = g_strsplit (line + sizeof ("REJECTED ") - 1, " ", 0);
680 #if 0
681 for (n = 0; supported_auth_mechs != NULL && supported_auth_mechs[n] != NULL; n++)
682 g_printerr ("supported_auth_mechs[%d] = `%s'\n", n, supported_auth_mechs[n]);
683 #endif
685 g_free (line);
686 mech = client_choose_mech_and_send_initial_response (auth,
687 credentials,
688 (const gchar* const *) supported_auth_mechs,
689 attempted_auth_mechs,
690 dos,
691 cancellable,
692 error);
693 if (mech == NULL)
694 goto out;
695 if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA)
696 state = CLIENT_STATE_WAITING_FOR_DATA;
697 else
698 state = CLIENT_STATE_WAITING_FOR_OK;
699 break;
701 case CLIENT_STATE_WAITING_FOR_OK:
702 debug_print ("CLIENT: WaitingForOK");
703 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
704 if (line == NULL)
705 goto out;
706 debug_print ("CLIENT: WaitingForOK, read `%s'", line);
707 if (g_str_has_prefix (line, "OK "))
709 if (!g_dbus_is_guid (line + 3))
711 g_set_error (error,
712 G_IO_ERROR,
713 G_IO_ERROR_FAILED,
714 "Invalid OK response `%s'",
715 line);
716 g_free (line);
717 goto out;
719 ret_guid = g_strdup (line + 3);
720 g_free (line);
722 if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
724 s = "NEGOTIATE_UNIX_FD\r\n";
725 debug_print ("CLIENT: writing `%s'", s);
726 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
727 goto out;
728 state = CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD;
730 else
732 s = "BEGIN\r\n";
733 debug_print ("CLIENT: writing `%s'", s);
734 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
735 goto out;
736 /* and we're done! */
737 goto out;
740 else if (g_str_has_prefix (line, "REJECTED "))
742 goto foobar;
744 else
746 /* TODO: handle other valid responses */
747 g_set_error (error,
748 G_IO_ERROR,
749 G_IO_ERROR_FAILED,
750 "In WaitingForOk: unexpected response `%s'",
751 line);
752 g_free (line);
753 goto out;
755 break;
757 case CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD:
758 debug_print ("CLIENT: WaitingForAgreeUnixFD");
759 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
760 if (line == NULL)
761 goto out;
762 debug_print ("CLIENT: WaitingForAgreeUnixFD, read=`%s'", line);
763 if (g_strcmp0 (line, "AGREE_UNIX_FD") == 0)
765 negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
766 s = "BEGIN\r\n";
767 debug_print ("CLIENT: writing `%s'", s);
768 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
769 goto out;
770 /* and we're done! */
771 goto out;
773 else if (g_str_has_prefix (line, "ERROR") && (line[5] == 0 || g_ascii_isspace (line[5])))
775 //g_strstrip (line + 5); g_debug ("bah, no unix_fd: `%s'", line + 5);
776 g_free (line);
777 s = "BEGIN\r\n";
778 debug_print ("CLIENT: writing `%s'", s);
779 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
780 goto out;
781 /* and we're done! */
782 goto out;
784 else
786 /* TODO: handle other valid responses */
787 g_set_error (error,
788 G_IO_ERROR,
789 G_IO_ERROR_FAILED,
790 "In WaitingForAgreeUnixFd: unexpected response `%s'",
791 line);
792 g_free (line);
793 goto out;
795 break;
797 case CLIENT_STATE_WAITING_FOR_DATA:
798 debug_print ("CLIENT: WaitingForData");
799 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
800 if (line == NULL)
801 goto out;
802 debug_print ("CLIENT: WaitingForData, read=`%s'", line);
803 if (g_str_has_prefix (line, "DATA "))
805 gchar *encoded;
806 gchar *decoded_data;
807 gsize decoded_data_len;
809 encoded = g_strdup (line + 5);
810 g_free (line);
811 g_strstrip (encoded);
812 decoded_data = hexdecode (encoded, &decoded_data_len, error);
813 g_free (encoded);
814 if (decoded_data == NULL)
816 g_prefix_error (error, "DATA response is malformed: ");
817 /* invalid encoding, disconnect! */
818 goto out;
820 _g_dbus_auth_mechanism_client_data_receive (mech, decoded_data, decoded_data_len);
821 g_free (decoded_data);
823 if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND)
825 gchar *data;
826 gsize data_len;
827 gchar *encoded_data;
828 data = _g_dbus_auth_mechanism_client_data_send (mech, &data_len);
829 encoded_data = hexencode (data);
830 s = g_strdup_printf ("DATA %s\r\n", encoded_data);
831 g_free (encoded_data);
832 g_free (data);
833 debug_print ("CLIENT: writing `%s'", s);
834 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
836 g_free (s);
837 goto out;
839 g_free (s);
841 state = CLIENT_STATE_WAITING_FOR_OK;
843 else
845 g_set_error (error,
846 G_IO_ERROR,
847 G_IO_ERROR_FAILED,
848 "In WaitingForData: unexpected response `%s'",
849 line);
850 g_free (line);
851 goto out;
853 break;
855 default:
856 g_assert_not_reached ();
857 break;
860 }; /* main authentication client loop */
862 out:
863 if (mech != NULL)
864 g_object_unref (mech);
865 g_ptr_array_unref (attempted_auth_mechs);
866 g_strfreev (supported_auth_mechs);
867 g_object_unref (dis);
868 g_object_unref (dos);
870 /* ensure return value is NULL if error is set */
871 if (error != NULL && *error != NULL)
873 g_free (ret_guid);
874 ret_guid = NULL;
877 if (ret_guid != NULL)
879 if (out_negotiated_capabilities != NULL)
880 *out_negotiated_capabilities = negotiated_capabilities;
883 if (credentials != NULL)
884 g_object_unref (credentials);
886 debug_print ("CLIENT: Done, authenticated=%d", ret_guid != NULL);
888 return ret_guid;
891 /* ---------------------------------------------------------------------------------------------------- */
893 static gchar *
894 get_auth_mechanisms (GDBusAuth *auth,
895 gboolean allow_anonymous,
896 const gchar *prefix,
897 const gchar *suffix,
898 const gchar *separator)
900 GList *l;
901 GString *str;
902 gboolean need_sep;
904 str = g_string_new (prefix);
905 need_sep = FALSE;
906 for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
908 Mechanism *m = l->data;
910 if (!allow_anonymous && g_strcmp0 (m->name, "ANONYMOUS") == 0)
911 continue;
913 if (need_sep)
914 g_string_append (str, separator);
915 g_string_append (str, m->name);
916 need_sep = TRUE;
919 g_string_append (str, suffix);
920 return g_string_free (str, FALSE);
924 typedef enum
926 SERVER_STATE_WAITING_FOR_AUTH,
927 SERVER_STATE_WAITING_FOR_DATA,
928 SERVER_STATE_WAITING_FOR_BEGIN
929 } ServerState;
931 gboolean
932 _g_dbus_auth_run_server (GDBusAuth *auth,
933 GDBusAuthObserver *observer,
934 const gchar *guid,
935 gboolean allow_anonymous,
936 GDBusCapabilityFlags offered_capabilities,
937 GDBusCapabilityFlags *out_negotiated_capabilities,
938 GCredentials **out_received_credentials,
939 GCancellable *cancellable,
940 GError **error)
942 gboolean ret;
943 ServerState state;
944 GDataInputStream *dis;
945 GDataOutputStream *dos;
946 GError *local_error;
947 guchar byte;
948 gchar *line;
949 gsize line_length;
950 GDBusAuthMechanism *mech;
951 gchar *s;
952 GDBusCapabilityFlags negotiated_capabilities;
953 GCredentials *credentials;
955 debug_print ("SERVER: initiating");
957 ret = FALSE;
958 dis = NULL;
959 dos = NULL;
960 mech = NULL;
961 negotiated_capabilities = 0;
962 credentials = NULL;
964 if (!g_dbus_is_guid (guid))
966 g_set_error (error,
967 G_IO_ERROR,
968 G_IO_ERROR_FAILED,
969 "The given guid `%s' is not valid",
970 guid);
971 goto out;
974 dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
975 dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
976 g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
977 g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
979 g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
981 /* first read the NUL-byte (TODO: read credentials if using a unix domain socket) */
982 #ifdef G_OS_UNIX
983 if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
985 local_error = NULL;
986 credentials = g_unix_connection_receive_credentials (G_UNIX_CONNECTION (auth->priv->stream),
987 cancellable,
988 &local_error);
989 if (credentials == NULL)
991 g_propagate_error (error, local_error);
992 goto out;
995 else
997 local_error = NULL;
998 byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
999 if (local_error != NULL)
1001 g_propagate_error (error, local_error);
1002 goto out;
1005 #else
1006 local_error = NULL;
1007 byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
1008 if (local_error != NULL)
1010 g_propagate_error (error, local_error);
1011 goto out;
1013 #endif
1014 if (credentials != NULL)
1016 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
1018 s = g_credentials_to_string (credentials);
1019 debug_print ("SERVER: received credentials `%s'", s);
1020 g_free (s);
1023 else
1025 debug_print ("SERVER: didn't receive any credentials");
1028 state = SERVER_STATE_WAITING_FOR_AUTH;
1029 while (TRUE)
1031 switch (state)
1033 case SERVER_STATE_WAITING_FOR_AUTH:
1034 debug_print ("SERVER: WaitingForAuth");
1035 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1036 debug_print ("SERVER: WaitingForAuth, read `%s'", line);
1037 if (line == NULL)
1038 goto out;
1039 if (g_strcmp0 (line, "AUTH") == 0)
1041 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1042 debug_print ("SERVER: writing `%s'", s);
1043 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1045 g_free (s);
1046 goto out;
1048 g_free (s);
1049 g_free (line);
1051 else if (g_str_has_prefix (line, "AUTH "))
1053 gchar **tokens;
1054 const gchar *encoded;
1055 const gchar *mech_name;
1056 GType auth_mech_to_use_gtype;
1058 tokens = g_strsplit (line, " ", 0);
1059 g_free (line);
1061 switch (g_strv_length (tokens))
1063 case 2:
1064 /* no initial response */
1065 mech_name = tokens[1];
1066 encoded = NULL;
1067 break;
1069 case 3:
1070 /* initial response */
1071 mech_name = tokens[1];
1072 encoded = tokens[2];
1073 break;
1075 default:
1076 g_set_error (error,
1077 G_IO_ERROR,
1078 G_IO_ERROR_FAILED,
1079 "Unexpected line `%s' while in WaitingForAuth state",
1080 line);
1081 g_strfreev (tokens);
1082 goto out;
1085 /* TODO: record that the client has attempted to use this mechanism */
1086 //g_debug ("client is trying `%s'", mech_name);
1088 auth_mech_to_use_gtype = find_mech_by_name (auth, mech_name);
1089 if ((auth_mech_to_use_gtype == (GType) 0) ||
1090 (!allow_anonymous && g_strcmp0 (mech_name, "ANONYMOUS") == 0))
1092 /* We don't support this auth mechanism */
1093 g_strfreev (tokens);
1094 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1095 debug_print ("SERVER: writing `%s'", s);
1096 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1098 g_free (s);
1099 goto out;
1101 g_free (s);
1103 /* stay in WAITING FOR AUTH */
1104 state = SERVER_STATE_WAITING_FOR_AUTH;
1106 else
1108 gchar *initial_response;
1109 gsize initial_response_len;
1111 mech = g_object_new (auth_mech_to_use_gtype,
1112 "stream", auth->priv->stream,
1113 "credentials", credentials,
1114 NULL);
1116 initial_response = NULL;
1117 initial_response_len = 0;
1118 if (encoded != NULL)
1120 initial_response = hexdecode (encoded, &initial_response_len, error);
1121 if (initial_response == NULL)
1123 g_prefix_error (error, "Initial response is malformed: ");
1124 /* invalid encoding, disconnect! */
1125 g_strfreev (tokens);
1126 goto out;
1130 _g_dbus_auth_mechanism_server_initiate (mech,
1131 initial_response,
1132 initial_response_len);
1133 g_free (initial_response);
1134 g_strfreev (tokens);
1136 change_state:
1137 switch (_g_dbus_auth_mechanism_server_get_state (mech))
1139 case G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED:
1140 if (observer != NULL &&
1141 !g_dbus_auth_observer_authorize_authenticated_peer (observer,
1142 auth->priv->stream,
1143 credentials))
1145 /* disconnect */
1146 g_set_error_literal (error,
1147 G_IO_ERROR,
1148 G_IO_ERROR_FAILED,
1149 _("Cancelled via GDBusAuthObserver::authorize-authenticated-peer"));
1150 goto out;
1152 else
1154 s = g_strdup_printf ("OK %s\r\n", guid);
1155 debug_print ("SERVER: writing `%s'", s);
1156 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1158 g_free (s);
1159 goto out;
1161 g_free (s);
1162 state = SERVER_STATE_WAITING_FOR_BEGIN;
1164 break;
1166 case G_DBUS_AUTH_MECHANISM_STATE_REJECTED:
1167 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1168 debug_print ("SERVER: writing `%s'", s);
1169 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1171 g_free (s);
1172 goto out;
1174 g_free (s);
1175 state = SERVER_STATE_WAITING_FOR_AUTH;
1176 break;
1178 case G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA:
1179 state = SERVER_STATE_WAITING_FOR_DATA;
1180 break;
1182 case G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND:
1184 gchar *data;
1185 gsize data_len;
1186 gchar *encoded_data;
1187 data = _g_dbus_auth_mechanism_server_data_send (mech, &data_len);
1188 encoded_data = hexencode (data);
1189 s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1190 g_free (encoded_data);
1191 g_free (data);
1192 debug_print ("SERVER: writing `%s'", s);
1193 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1195 g_free (s);
1196 goto out;
1198 g_free (s);
1200 goto change_state;
1201 break;
1203 default:
1204 /* TODO */
1205 g_assert_not_reached ();
1206 break;
1210 else
1212 g_set_error (error,
1213 G_IO_ERROR,
1214 G_IO_ERROR_FAILED,
1215 "Unexpected line `%s' while in WaitingForAuth state",
1216 line);
1217 g_free (line);
1218 goto out;
1220 break;
1222 case SERVER_STATE_WAITING_FOR_DATA:
1223 debug_print ("SERVER: WaitingForData");
1224 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1225 debug_print ("SERVER: WaitingForData, read `%s'", line);
1226 if (line == NULL)
1227 goto out;
1228 if (g_str_has_prefix (line, "DATA "))
1230 gchar *encoded;
1231 gchar *decoded_data;
1232 gsize decoded_data_len;
1234 encoded = g_strdup (line + 5);
1235 g_free (line);
1236 g_strstrip (encoded);
1237 decoded_data = hexdecode (encoded, &decoded_data_len, error);
1238 g_free (encoded);
1239 if (decoded_data == NULL)
1241 g_prefix_error (error, "DATA response is malformed: ");
1242 /* invalid encoding, disconnect! */
1243 goto out;
1245 _g_dbus_auth_mechanism_server_data_receive (mech, decoded_data, decoded_data_len);
1246 g_free (decoded_data);
1247 /* oh man, this goto-crap is so ugly.. really need to rewrite the state machine */
1248 goto change_state;
1250 else
1252 g_set_error (error,
1253 G_IO_ERROR,
1254 G_IO_ERROR_FAILED,
1255 "Unexpected line `%s' while in WaitingForData state",
1256 line);
1257 g_free (line);
1259 goto out;
1261 case SERVER_STATE_WAITING_FOR_BEGIN:
1262 debug_print ("SERVER: WaitingForBegin");
1263 /* Use extremely slow (but reliable) line reader - this basically
1264 * does a recvfrom() system call per character
1266 * (the problem with using GDataInputStream's read_line is that because of
1267 * buffering it might start reading into the first D-Bus message that
1268 * appears after "BEGIN\r\n"....)
1270 line = _my_g_input_stream_read_line_safe (g_io_stream_get_input_stream (auth->priv->stream),
1271 &line_length,
1272 cancellable,
1273 error);
1274 debug_print ("SERVER: WaitingForBegin, read `%s'", line);
1275 if (line == NULL)
1276 goto out;
1277 if (g_strcmp0 (line, "BEGIN") == 0)
1279 /* YAY, done! */
1280 ret = TRUE;
1281 g_free (line);
1282 goto out;
1284 else if (g_strcmp0 (line, "NEGOTIATE_UNIX_FD") == 0)
1286 g_free (line);
1287 if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
1289 negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1290 s = "AGREE_UNIX_FD\r\n";
1291 debug_print ("SERVER: writing `%s'", s);
1292 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1293 goto out;
1295 else
1297 s = "ERROR \"fd passing not offered\"\r\n";
1298 debug_print ("SERVER: writing `%s'", s);
1299 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1300 goto out;
1303 else
1305 g_debug ("Unexpected line `%s' while in WaitingForBegin state", line);
1306 g_free (line);
1307 s = "ERROR \"Unknown Command\"\r\n";
1308 debug_print ("SERVER: writing `%s'", s);
1309 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1310 goto out;
1312 break;
1314 default:
1315 g_assert_not_reached ();
1316 break;
1321 g_set_error_literal (error,
1322 G_IO_ERROR,
1323 G_IO_ERROR_FAILED,
1324 "Not implemented (server)");
1326 out:
1327 if (mech != NULL)
1328 g_object_unref (mech);
1329 if (dis != NULL)
1330 g_object_unref (dis);
1331 if (dos != NULL)
1332 g_object_unref (dos);
1334 /* ensure return value is FALSE if error is set */
1335 if (error != NULL && *error != NULL)
1337 ret = FALSE;
1340 if (ret)
1342 if (out_negotiated_capabilities != NULL)
1343 *out_negotiated_capabilities = negotiated_capabilities;
1344 if (out_received_credentials != NULL)
1345 *out_received_credentials = credentials != NULL ? g_object_ref (credentials) : NULL;
1348 if (credentials != NULL)
1349 g_object_unref (credentials);
1351 debug_print ("SERVER: Done, authenticated=%d", ret);
1353 return ret;
1356 /* ---------------------------------------------------------------------------------------------------- */