Merge branch 'issue-699' into 'master'
[glib.git] / gio / gdbusauth.c
blob1f8ea80570cf910a45f3c7f4bb678789145b5d33
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.1 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, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
21 #include "config.h"
23 #include "gdbusauth.h"
25 #include "gdbusauthmechanismanon.h"
26 #include "gdbusauthmechanismexternal.h"
27 #include "gdbusauthmechanismsha1.h"
28 #include "gdbusauthobserver.h"
30 #include "gdbuserror.h"
31 #include "gdbusutils.h"
32 #include "gioenumtypes.h"
33 #include "gcredentials.h"
34 #include "gdbusprivate.h"
35 #include "giostream.h"
36 #include "gdatainputstream.h"
37 #include "gdataoutputstream.h"
39 #ifdef G_OS_UNIX
40 #include "gnetworking.h"
41 #include "gunixconnection.h"
42 #include "gunixcredentialsmessage.h"
43 #endif
45 #include "glibintl.h"
47 G_GNUC_PRINTF(1, 2)
48 static void
49 debug_print (const gchar *message, ...)
51 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
53 gchar *s;
54 GString *str;
55 va_list var_args;
56 guint n;
58 _g_dbus_debug_print_lock ();
60 va_start (var_args, message);
61 s = g_strdup_vprintf (message, var_args);
62 va_end (var_args);
64 str = g_string_new (NULL);
65 for (n = 0; s[n] != '\0'; n++)
67 if (G_UNLIKELY (s[n] == '\r'))
68 g_string_append (str, "\\r");
69 else if (G_UNLIKELY (s[n] == '\n'))
70 g_string_append (str, "\\n");
71 else
72 g_string_append_c (str, s[n]);
74 g_print ("GDBus-debug:Auth: %s\n", str->str);
75 g_string_free (str, TRUE);
76 g_free (s);
78 _g_dbus_debug_print_unlock ();
82 typedef struct
84 const gchar *name;
85 gint priority;
86 GType gtype;
87 } Mechanism;
89 static void mechanism_free (Mechanism *m);
91 struct _GDBusAuthPrivate
93 GIOStream *stream;
95 /* A list of available Mechanism, sorted according to priority */
96 GList *available_mechanisms;
99 enum
101 PROP_0,
102 PROP_STREAM
105 G_DEFINE_TYPE_WITH_PRIVATE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT)
107 /* ---------------------------------------------------------------------------------------------------- */
109 static void
110 _g_dbus_auth_finalize (GObject *object)
112 GDBusAuth *auth = G_DBUS_AUTH (object);
114 if (auth->priv->stream != NULL)
115 g_object_unref (auth->priv->stream);
116 g_list_free_full (auth->priv->available_mechanisms, (GDestroyNotify) mechanism_free);
118 if (G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize != NULL)
119 G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize (object);
122 static void
123 _g_dbus_auth_get_property (GObject *object,
124 guint prop_id,
125 GValue *value,
126 GParamSpec *pspec)
128 GDBusAuth *auth = G_DBUS_AUTH (object);
130 switch (prop_id)
132 case PROP_STREAM:
133 g_value_set_object (value, auth->priv->stream);
134 break;
136 default:
137 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
138 break;
142 static void
143 _g_dbus_auth_set_property (GObject *object,
144 guint prop_id,
145 const GValue *value,
146 GParamSpec *pspec)
148 GDBusAuth *auth = G_DBUS_AUTH (object);
150 switch (prop_id)
152 case PROP_STREAM:
153 auth->priv->stream = g_value_dup_object (value);
154 break;
156 default:
157 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
158 break;
162 static void
163 _g_dbus_auth_class_init (GDBusAuthClass *klass)
165 GObjectClass *gobject_class;
167 gobject_class = G_OBJECT_CLASS (klass);
168 gobject_class->get_property = _g_dbus_auth_get_property;
169 gobject_class->set_property = _g_dbus_auth_set_property;
170 gobject_class->finalize = _g_dbus_auth_finalize;
172 g_object_class_install_property (gobject_class,
173 PROP_STREAM,
174 g_param_spec_object ("stream",
175 P_("IO Stream"),
176 P_("The underlying GIOStream used for I/O"),
177 G_TYPE_IO_STREAM,
178 G_PARAM_READABLE |
179 G_PARAM_WRITABLE |
180 G_PARAM_CONSTRUCT_ONLY |
181 G_PARAM_STATIC_NAME |
182 G_PARAM_STATIC_BLURB |
183 G_PARAM_STATIC_NICK));
186 static void
187 mechanism_free (Mechanism *m)
189 g_free (m);
192 static void
193 add_mechanism (GDBusAuth *auth,
194 GDBusAuthObserver *observer,
195 GType mechanism_type)
197 const gchar *name;
199 name = _g_dbus_auth_mechanism_get_name (mechanism_type);
200 if (observer == NULL || g_dbus_auth_observer_allow_mechanism (observer, name))
202 Mechanism *m;
203 m = g_new0 (Mechanism, 1);
204 m->name = name;
205 m->priority = _g_dbus_auth_mechanism_get_priority (mechanism_type);
206 m->gtype = mechanism_type;
207 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_dbus_auth_get_instance_private (auth);
228 static void
229 _g_dbus_auth_add_mechs (GDBusAuth *auth,
230 GDBusAuthObserver *observer)
232 /* TODO: trawl extension points */
233 add_mechanism (auth, observer, G_TYPE_DBUS_AUTH_MECHANISM_ANON);
234 add_mechanism (auth, observer, G_TYPE_DBUS_AUTH_MECHANISM_SHA1);
235 add_mechanism (auth, observer, G_TYPE_DBUS_AUTH_MECHANISM_EXTERNAL);
237 auth->priv->available_mechanisms = g_list_sort (auth->priv->available_mechanisms,
238 (GCompareFunc) mech_compare_func);
241 static GType
242 find_mech_by_name (GDBusAuth *auth,
243 const gchar *name)
245 GType ret;
246 GList *l;
248 ret = (GType) 0;
250 for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
252 Mechanism *m = l->data;
253 if (g_strcmp0 (name, m->name) == 0)
255 ret = m->gtype;
256 goto out;
260 out:
261 return ret;
264 GDBusAuth *
265 _g_dbus_auth_new (GIOStream *stream)
267 return g_object_new (G_TYPE_DBUS_AUTH,
268 "stream", stream,
269 NULL);
272 /* ---------------------------------------------------------------------------------------------------- */
273 /* like g_data_input_stream_read_line() but sets error if there's no content to read */
274 static gchar *
275 _my_g_data_input_stream_read_line (GDataInputStream *dis,
276 gsize *out_line_length,
277 GCancellable *cancellable,
278 GError **error)
280 gchar *ret;
282 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
284 ret = g_data_input_stream_read_line (dis,
285 out_line_length,
286 cancellable,
287 error);
288 if (ret == NULL && error != NULL && *error == NULL)
290 g_set_error_literal (error,
291 G_IO_ERROR,
292 G_IO_ERROR_FAILED,
293 _("Unexpected lack of content trying to read a line"));
296 return ret;
299 /* This function is to avoid situations like this
301 * BEGIN\r\nl\0\0\1...
303 * e.g. where we read into the first D-Bus message while waiting for
304 * the final line from the client (TODO: file bug against gio for
305 * this)
307 static gchar *
308 _my_g_input_stream_read_line_safe (GInputStream *i,
309 gsize *out_line_length,
310 GCancellable *cancellable,
311 GError **error)
313 GString *str;
314 gchar c;
315 gssize num_read;
316 gboolean last_was_cr;
318 str = g_string_new (NULL);
320 last_was_cr = FALSE;
321 while (TRUE)
323 num_read = g_input_stream_read (i,
326 cancellable,
327 error);
328 if (num_read == -1)
329 goto fail;
330 if (num_read == 0)
332 if (error != NULL && *error == NULL)
334 g_set_error_literal (error,
335 G_IO_ERROR,
336 G_IO_ERROR_FAILED,
337 _("Unexpected lack of content trying to (safely) read a line"));
339 goto fail;
342 g_string_append_c (str, (gint) c);
343 if (last_was_cr)
345 if (c == 0x0a)
347 g_assert (str->len >= 2);
348 g_string_set_size (str, str->len - 2);
349 goto out;
352 last_was_cr = (c == 0x0d);
355 out:
356 if (out_line_length != NULL)
357 *out_line_length = str->len;
358 return g_string_free (str, FALSE);
360 fail:
361 g_assert (error == NULL || *error != NULL);
362 g_string_free (str, TRUE);
363 return NULL;
366 /* ---------------------------------------------------------------------------------------------------- */
368 static gchar *
369 hexdecode (const gchar *str,
370 gsize *out_len,
371 GError **error)
373 gchar *ret;
374 GString *s;
375 guint n;
377 ret = NULL;
378 s = g_string_new (NULL);
380 for (n = 0; str[n] != '\0'; n += 2)
382 gint upper_nibble;
383 gint lower_nibble;
384 guint value;
386 upper_nibble = g_ascii_xdigit_value (str[n]);
387 lower_nibble = g_ascii_xdigit_value (str[n + 1]);
388 if (upper_nibble == -1 || lower_nibble == -1)
390 g_set_error (error,
391 G_IO_ERROR,
392 G_IO_ERROR_FAILED,
393 "Error hexdecoding string '%s' around position %d",
394 str, n);
395 goto out;
397 value = (upper_nibble<<4) | lower_nibble;
398 g_string_append_c (s, value);
401 *out_len = s->len;
402 ret = g_string_free (s, FALSE);
403 s = NULL;
405 out:
406 if (s != NULL)
408 *out_len = 0;
409 g_string_free (s, TRUE);
411 return ret;
414 /* ---------------------------------------------------------------------------------------------------- */
416 static GDBusAuthMechanism *
417 client_choose_mech_and_send_initial_response (GDBusAuth *auth,
418 GCredentials *credentials_that_were_sent,
419 const gchar* const *supported_auth_mechs,
420 GPtrArray *attempted_auth_mechs,
421 GDataOutputStream *dos,
422 GCancellable *cancellable,
423 GError **error)
425 GDBusAuthMechanism *mech;
426 GType auth_mech_to_use_gtype;
427 guint n;
428 guint m;
429 gchar *initial_response;
430 gsize initial_response_len;
431 gchar *encoded;
432 gchar *s;
434 again:
435 mech = NULL;
437 debug_print ("CLIENT: Trying to choose mechanism");
439 /* find an authentication mechanism to try, if any */
440 auth_mech_to_use_gtype = (GType) 0;
441 for (n = 0; supported_auth_mechs[n] != NULL; n++)
443 gboolean attempted_already;
444 attempted_already = FALSE;
445 for (m = 0; m < attempted_auth_mechs->len; m++)
447 if (g_strcmp0 (supported_auth_mechs[n], attempted_auth_mechs->pdata[m]) == 0)
449 attempted_already = TRUE;
450 break;
453 if (!attempted_already)
455 auth_mech_to_use_gtype = find_mech_by_name (auth, supported_auth_mechs[n]);
456 if (auth_mech_to_use_gtype != (GType) 0)
457 break;
461 if (auth_mech_to_use_gtype == (GType) 0)
463 guint n;
464 gchar *available;
465 GString *tried_str;
467 debug_print ("CLIENT: Exhausted all available mechanisms");
469 available = g_strjoinv (", ", (gchar **) supported_auth_mechs);
471 tried_str = g_string_new (NULL);
472 for (n = 0; n < attempted_auth_mechs->len; n++)
474 if (n > 0)
475 g_string_append (tried_str, ", ");
476 g_string_append (tried_str, attempted_auth_mechs->pdata[n]);
478 g_set_error (error,
479 G_IO_ERROR,
480 G_IO_ERROR_FAILED,
481 _("Exhausted all available authentication mechanisms (tried: %s) (available: %s)"),
482 tried_str->str,
483 available);
484 g_string_free (tried_str, TRUE);
485 g_free (available);
486 goto out;
489 /* OK, decided on a mechanism - let's do this thing */
490 mech = g_object_new (auth_mech_to_use_gtype,
491 "stream", auth->priv->stream,
492 "credentials", credentials_that_were_sent,
493 NULL);
494 debug_print ("CLIENT: Trying mechanism '%s'", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
495 g_ptr_array_add (attempted_auth_mechs, (gpointer) _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
497 /* the auth mechanism may not be supported
498 * (for example, EXTERNAL only works if credentials were exchanged)
500 if (!_g_dbus_auth_mechanism_is_supported (mech))
502 debug_print ("CLIENT: Mechanism '%s' says it is not supported", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
503 g_object_unref (mech);
504 mech = NULL;
505 goto again;
508 initial_response_len = 0;
509 initial_response = _g_dbus_auth_mechanism_client_initiate (mech,
510 &initial_response_len);
511 #if 0
512 g_printerr ("using auth mechanism with name '%s' of type '%s' with initial response '%s'\n",
513 _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
514 g_type_name (G_TYPE_FROM_INSTANCE (mech)),
515 initial_response);
516 #endif
517 if (initial_response != NULL)
519 //g_printerr ("initial_response = '%s'\n", initial_response);
520 encoded = _g_dbus_hexencode (initial_response, initial_response_len);
521 s = g_strdup_printf ("AUTH %s %s\r\n",
522 _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
523 encoded);
524 g_free (initial_response);
525 g_free (encoded);
527 else
529 s = g_strdup_printf ("AUTH %s\r\n", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
531 debug_print ("CLIENT: writing '%s'", s);
532 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
534 g_object_unref (mech);
535 mech = NULL;
536 g_free (s);
537 goto out;
539 g_free (s);
541 out:
542 return mech;
546 /* ---------------------------------------------------------------------------------------------------- */
548 typedef enum
550 CLIENT_STATE_WAITING_FOR_DATA,
551 CLIENT_STATE_WAITING_FOR_OK,
552 CLIENT_STATE_WAITING_FOR_REJECT,
553 CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD
554 } ClientState;
556 gchar *
557 _g_dbus_auth_run_client (GDBusAuth *auth,
558 GDBusAuthObserver *observer,
559 GDBusCapabilityFlags offered_capabilities,
560 GDBusCapabilityFlags *out_negotiated_capabilities,
561 GCancellable *cancellable,
562 GError **error)
564 gchar *s;
565 GDataInputStream *dis;
566 GDataOutputStream *dos;
567 GCredentials *credentials;
568 gchar *ret_guid;
569 gchar *line;
570 gsize line_length;
571 gchar **supported_auth_mechs;
572 GPtrArray *attempted_auth_mechs;
573 GDBusAuthMechanism *mech;
574 ClientState state;
575 GDBusCapabilityFlags negotiated_capabilities;
577 debug_print ("CLIENT: initiating");
579 _g_dbus_auth_add_mechs (auth, observer);
581 ret_guid = NULL;
582 supported_auth_mechs = NULL;
583 attempted_auth_mechs = g_ptr_array_new ();
584 mech = NULL;
585 negotiated_capabilities = 0;
586 credentials = NULL;
588 dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
589 dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
590 g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
591 g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
593 g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
595 #ifdef G_OS_UNIX
596 if (G_IS_UNIX_CONNECTION (auth->priv->stream))
598 credentials = g_credentials_new ();
599 if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
600 cancellable,
601 error))
602 goto out;
604 else
606 if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
607 goto out;
609 #else
610 if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
611 goto out;
612 #endif
614 if (credentials != NULL)
616 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
618 s = g_credentials_to_string (credentials);
619 debug_print ("CLIENT: sent credentials '%s'", s);
620 g_free (s);
623 else
625 debug_print ("CLIENT: didn't send any credentials");
628 /* TODO: to reduce roundtrips, try to pick an auth mechanism to start with */
630 /* Get list of supported authentication mechanisms */
631 s = "AUTH\r\n";
632 debug_print ("CLIENT: writing '%s'", s);
633 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
634 goto out;
635 state = CLIENT_STATE_WAITING_FOR_REJECT;
637 while (TRUE)
639 switch (state)
641 case CLIENT_STATE_WAITING_FOR_REJECT:
642 debug_print ("CLIENT: WaitingForReject");
643 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
644 if (line == NULL)
645 goto out;
646 debug_print ("CLIENT: WaitingForReject, read '%s'", line);
648 choose_mechanism:
649 if (!g_str_has_prefix (line, "REJECTED "))
651 g_set_error (error,
652 G_IO_ERROR,
653 G_IO_ERROR_FAILED,
654 "In WaitingForReject: Expected 'REJECTED am1 am2 ... amN', got '%s'",
655 line);
656 g_free (line);
657 goto out;
659 if (supported_auth_mechs == NULL)
661 supported_auth_mechs = g_strsplit (line + sizeof ("REJECTED ") - 1, " ", 0);
662 #if 0
663 for (n = 0; supported_auth_mechs != NULL && supported_auth_mechs[n] != NULL; n++)
664 g_printerr ("supported_auth_mechs[%d] = '%s'\n", n, supported_auth_mechs[n]);
665 #endif
667 g_free (line);
668 mech = client_choose_mech_and_send_initial_response (auth,
669 credentials,
670 (const gchar* const *) supported_auth_mechs,
671 attempted_auth_mechs,
672 dos,
673 cancellable,
674 error);
675 if (mech == NULL)
676 goto out;
677 if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA)
678 state = CLIENT_STATE_WAITING_FOR_DATA;
679 else
680 state = CLIENT_STATE_WAITING_FOR_OK;
681 break;
683 case CLIENT_STATE_WAITING_FOR_OK:
684 debug_print ("CLIENT: WaitingForOK");
685 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
686 if (line == NULL)
687 goto out;
688 debug_print ("CLIENT: WaitingForOK, read '%s'", line);
689 if (g_str_has_prefix (line, "OK "))
691 if (!g_dbus_is_guid (line + 3))
693 g_set_error (error,
694 G_IO_ERROR,
695 G_IO_ERROR_FAILED,
696 "Invalid OK response '%s'",
697 line);
698 g_free (line);
699 goto out;
701 ret_guid = g_strdup (line + 3);
702 g_free (line);
704 if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
706 s = "NEGOTIATE_UNIX_FD\r\n";
707 debug_print ("CLIENT: writing '%s'", s);
708 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
709 goto out;
710 state = CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD;
712 else
714 s = "BEGIN\r\n";
715 debug_print ("CLIENT: writing '%s'", s);
716 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
717 goto out;
718 /* and we're done! */
719 goto out;
722 else if (g_str_has_prefix (line, "REJECTED "))
724 goto choose_mechanism;
726 else
728 /* TODO: handle other valid responses */
729 g_set_error (error,
730 G_IO_ERROR,
731 G_IO_ERROR_FAILED,
732 "In WaitingForOk: unexpected response '%s'",
733 line);
734 g_free (line);
735 goto out;
737 break;
739 case CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD:
740 debug_print ("CLIENT: WaitingForAgreeUnixFD");
741 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
742 if (line == NULL)
743 goto out;
744 debug_print ("CLIENT: WaitingForAgreeUnixFD, read='%s'", line);
745 if (g_strcmp0 (line, "AGREE_UNIX_FD") == 0)
747 g_free (line);
748 negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
749 s = "BEGIN\r\n";
750 debug_print ("CLIENT: writing '%s'", s);
751 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
752 goto out;
753 /* and we're done! */
754 goto out;
756 else if (g_str_has_prefix (line, "ERROR") && (line[5] == 0 || g_ascii_isspace (line[5])))
758 //g_strstrip (line + 5); g_debug ("bah, no unix_fd: '%s'", line + 5);
759 g_free (line);
760 s = "BEGIN\r\n";
761 debug_print ("CLIENT: writing '%s'", s);
762 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
763 goto out;
764 /* and we're done! */
765 goto out;
767 else
769 /* TODO: handle other valid responses */
770 g_set_error (error,
771 G_IO_ERROR,
772 G_IO_ERROR_FAILED,
773 "In WaitingForAgreeUnixFd: unexpected response '%s'",
774 line);
775 g_free (line);
776 goto out;
778 break;
780 case CLIENT_STATE_WAITING_FOR_DATA:
781 debug_print ("CLIENT: WaitingForData");
782 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
783 if (line == NULL)
784 goto out;
785 debug_print ("CLIENT: WaitingForData, read='%s'", line);
786 if (g_str_has_prefix (line, "DATA "))
788 gchar *encoded;
789 gchar *decoded_data;
790 gsize decoded_data_len = 0;
792 encoded = g_strdup (line + 5);
793 g_free (line);
794 g_strstrip (encoded);
795 decoded_data = hexdecode (encoded, &decoded_data_len, error);
796 g_free (encoded);
797 if (decoded_data == NULL)
799 g_prefix_error (error, "DATA response is malformed: ");
800 /* invalid encoding, disconnect! */
801 goto out;
803 _g_dbus_auth_mechanism_client_data_receive (mech, decoded_data, decoded_data_len);
804 g_free (decoded_data);
806 if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND)
808 gchar *data;
809 gsize data_len;
810 gchar *encoded_data;
811 data = _g_dbus_auth_mechanism_client_data_send (mech, &data_len);
812 encoded_data = _g_dbus_hexencode (data, data_len);
813 s = g_strdup_printf ("DATA %s\r\n", encoded_data);
814 g_free (encoded_data);
815 g_free (data);
816 debug_print ("CLIENT: writing '%s'", s);
817 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
819 g_free (s);
820 goto out;
822 g_free (s);
824 state = CLIENT_STATE_WAITING_FOR_OK;
826 else if (g_str_has_prefix (line, "REJECTED "))
828 /* could be the chosen authentication method just doesn't work. Try
829 * another one...
831 goto choose_mechanism;
833 else
835 g_set_error (error,
836 G_IO_ERROR,
837 G_IO_ERROR_FAILED,
838 "In WaitingForData: unexpected response '%s'",
839 line);
840 g_free (line);
841 goto out;
843 break;
845 default:
846 g_assert_not_reached ();
847 break;
850 }; /* main authentication client loop */
852 out:
853 if (mech != NULL)
854 g_object_unref (mech);
855 g_ptr_array_unref (attempted_auth_mechs);
856 g_strfreev (supported_auth_mechs);
857 g_object_unref (dis);
858 g_object_unref (dos);
860 /* ensure return value is NULL if error is set */
861 if (error != NULL && *error != NULL)
863 g_free (ret_guid);
864 ret_guid = NULL;
867 if (ret_guid != NULL)
869 if (out_negotiated_capabilities != NULL)
870 *out_negotiated_capabilities = negotiated_capabilities;
873 if (credentials != NULL)
874 g_object_unref (credentials);
876 debug_print ("CLIENT: Done, authenticated=%d", ret_guid != NULL);
878 return ret_guid;
881 /* ---------------------------------------------------------------------------------------------------- */
883 static gchar *
884 get_auth_mechanisms (GDBusAuth *auth,
885 gboolean allow_anonymous,
886 const gchar *prefix,
887 const gchar *suffix,
888 const gchar *separator)
890 GList *l;
891 GString *str;
892 gboolean need_sep;
894 str = g_string_new (prefix);
895 need_sep = FALSE;
896 for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
898 Mechanism *m = l->data;
900 if (!allow_anonymous && g_strcmp0 (m->name, "ANONYMOUS") == 0)
901 continue;
903 if (need_sep)
904 g_string_append (str, separator);
905 g_string_append (str, m->name);
906 need_sep = TRUE;
909 g_string_append (str, suffix);
910 return g_string_free (str, FALSE);
914 typedef enum
916 SERVER_STATE_WAITING_FOR_AUTH,
917 SERVER_STATE_WAITING_FOR_DATA,
918 SERVER_STATE_WAITING_FOR_BEGIN
919 } ServerState;
921 gboolean
922 _g_dbus_auth_run_server (GDBusAuth *auth,
923 GDBusAuthObserver *observer,
924 const gchar *guid,
925 gboolean allow_anonymous,
926 GDBusCapabilityFlags offered_capabilities,
927 GDBusCapabilityFlags *out_negotiated_capabilities,
928 GCredentials **out_received_credentials,
929 GCancellable *cancellable,
930 GError **error)
932 gboolean ret;
933 ServerState state;
934 GDataInputStream *dis;
935 GDataOutputStream *dos;
936 GError *local_error;
937 gchar *line;
938 gsize line_length;
939 GDBusAuthMechanism *mech;
940 gchar *s;
941 GDBusCapabilityFlags negotiated_capabilities;
942 GCredentials *credentials;
944 debug_print ("SERVER: initiating");
946 _g_dbus_auth_add_mechs (auth, observer);
948 ret = FALSE;
949 dis = NULL;
950 dos = NULL;
951 mech = NULL;
952 negotiated_capabilities = 0;
953 credentials = NULL;
955 if (!g_dbus_is_guid (guid))
957 g_set_error (error,
958 G_IO_ERROR,
959 G_IO_ERROR_FAILED,
960 "The given guid '%s' is not valid",
961 guid);
962 goto out;
965 dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
966 dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
967 g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
968 g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
970 g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
972 /* first read the NUL-byte */
973 #ifdef G_OS_UNIX
974 if (G_IS_UNIX_CONNECTION (auth->priv->stream))
976 local_error = NULL;
977 credentials = g_unix_connection_receive_credentials (G_UNIX_CONNECTION (auth->priv->stream),
978 cancellable,
979 &local_error);
980 if (credentials == NULL && !g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED))
982 g_propagate_error (error, local_error);
983 goto out;
986 else
988 local_error = NULL;
989 (void)g_data_input_stream_read_byte (dis, cancellable, &local_error);
990 if (local_error != NULL)
992 g_propagate_error (error, local_error);
993 goto out;
996 #else
997 local_error = NULL;
998 (void)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;
1004 #endif
1005 if (credentials != NULL)
1007 if (G_UNLIKELY (_g_dbus_debug_authentication ()))
1009 s = g_credentials_to_string (credentials);
1010 debug_print ("SERVER: received credentials '%s'", s);
1011 g_free (s);
1014 else
1016 debug_print ("SERVER: didn't receive any credentials");
1019 state = SERVER_STATE_WAITING_FOR_AUTH;
1020 while (TRUE)
1022 switch (state)
1024 case SERVER_STATE_WAITING_FOR_AUTH:
1025 debug_print ("SERVER: WaitingForAuth");
1026 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1027 debug_print ("SERVER: WaitingForAuth, read '%s'", line);
1028 if (line == NULL)
1029 goto out;
1030 if (g_strcmp0 (line, "AUTH") == 0)
1032 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1033 debug_print ("SERVER: writing '%s'", s);
1034 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1036 g_free (s);
1037 g_free (line);
1038 goto out;
1040 g_free (s);
1041 g_free (line);
1043 else if (g_str_has_prefix (line, "AUTH "))
1045 gchar **tokens;
1046 const gchar *encoded;
1047 const gchar *mech_name;
1048 GType auth_mech_to_use_gtype;
1050 tokens = g_strsplit (line, " ", 0);
1052 switch (g_strv_length (tokens))
1054 case 2:
1055 /* no initial response */
1056 mech_name = tokens[1];
1057 encoded = NULL;
1058 break;
1060 case 3:
1061 /* initial response */
1062 mech_name = tokens[1];
1063 encoded = tokens[2];
1064 break;
1066 default:
1067 g_set_error (error,
1068 G_IO_ERROR,
1069 G_IO_ERROR_FAILED,
1070 "Unexpected line '%s' while in WaitingForAuth state",
1071 line);
1072 g_strfreev (tokens);
1073 g_free (line);
1074 goto out;
1077 g_free (line);
1079 /* TODO: record that the client has attempted to use this mechanism */
1080 //g_debug ("client is trying '%s'", mech_name);
1082 auth_mech_to_use_gtype = find_mech_by_name (auth, mech_name);
1083 if ((auth_mech_to_use_gtype == (GType) 0) ||
1084 (!allow_anonymous && g_strcmp0 (mech_name, "ANONYMOUS") == 0))
1086 /* We don't support this auth mechanism */
1087 g_strfreev (tokens);
1088 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1089 debug_print ("SERVER: writing '%s'", s);
1090 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1092 g_free (s);
1093 goto out;
1095 g_free (s);
1097 /* stay in WAITING FOR AUTH */
1098 state = SERVER_STATE_WAITING_FOR_AUTH;
1100 else
1102 gchar *initial_response;
1103 gsize initial_response_len;
1105 g_clear_object (&mech);
1106 mech = g_object_new (auth_mech_to_use_gtype,
1107 "stream", auth->priv->stream,
1108 "credentials", credentials,
1109 NULL);
1111 initial_response = NULL;
1112 initial_response_len = 0;
1113 if (encoded != NULL)
1115 initial_response = hexdecode (encoded, &initial_response_len, error);
1116 if (initial_response == NULL)
1118 g_prefix_error (error, "Initial response is malformed: ");
1119 /* invalid encoding, disconnect! */
1120 g_strfreev (tokens);
1121 goto out;
1125 _g_dbus_auth_mechanism_server_initiate (mech,
1126 initial_response,
1127 initial_response_len);
1128 g_free (initial_response);
1129 g_strfreev (tokens);
1131 change_state:
1132 switch (_g_dbus_auth_mechanism_server_get_state (mech))
1134 case G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED:
1135 if (observer != NULL &&
1136 !g_dbus_auth_observer_authorize_authenticated_peer (observer,
1137 auth->priv->stream,
1138 credentials))
1140 /* disconnect */
1141 g_set_error_literal (error,
1142 G_IO_ERROR,
1143 G_IO_ERROR_FAILED,
1144 _("Cancelled via GDBusAuthObserver::authorize-authenticated-peer"));
1145 goto out;
1147 else
1149 s = g_strdup_printf ("OK %s\r\n", guid);
1150 debug_print ("SERVER: writing '%s'", s);
1151 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1153 g_free (s);
1154 goto out;
1156 g_free (s);
1157 state = SERVER_STATE_WAITING_FOR_BEGIN;
1159 break;
1161 case G_DBUS_AUTH_MECHANISM_STATE_REJECTED:
1162 s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1163 debug_print ("SERVER: writing '%s'", s);
1164 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1166 g_free (s);
1167 goto out;
1169 g_free (s);
1170 state = SERVER_STATE_WAITING_FOR_AUTH;
1171 break;
1173 case G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA:
1174 state = SERVER_STATE_WAITING_FOR_DATA;
1175 break;
1177 case G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND:
1179 gchar *data;
1180 gsize data_len;
1182 data = _g_dbus_auth_mechanism_server_data_send (mech, &data_len);
1183 if (data != NULL)
1185 gchar *encoded_data;
1187 encoded_data = _g_dbus_hexencode (data, data_len);
1188 s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1189 g_free (encoded_data);
1190 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);
1201 goto change_state;
1202 break;
1204 default:
1205 /* TODO */
1206 g_assert_not_reached ();
1207 break;
1211 else
1213 g_set_error (error,
1214 G_IO_ERROR,
1215 G_IO_ERROR_FAILED,
1216 "Unexpected line '%s' while in WaitingForAuth state",
1217 line);
1218 g_free (line);
1219 goto out;
1221 break;
1223 case SERVER_STATE_WAITING_FOR_DATA:
1224 debug_print ("SERVER: WaitingForData");
1225 line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1226 debug_print ("SERVER: WaitingForData, read '%s'", line);
1227 if (line == NULL)
1228 goto out;
1229 if (g_str_has_prefix (line, "DATA "))
1231 gchar *encoded;
1232 gchar *decoded_data;
1233 gsize decoded_data_len = 0;
1235 encoded = g_strdup (line + 5);
1236 g_free (line);
1237 g_strstrip (encoded);
1238 decoded_data = hexdecode (encoded, &decoded_data_len, error);
1239 g_free (encoded);
1240 if (decoded_data == NULL)
1242 g_prefix_error (error, "DATA response is malformed: ");
1243 /* invalid encoding, disconnect! */
1244 goto out;
1246 _g_dbus_auth_mechanism_server_data_receive (mech, decoded_data, decoded_data_len);
1247 g_free (decoded_data);
1248 /* oh man, this goto-crap is so ugly.. really need to rewrite the state machine */
1249 goto change_state;
1251 else
1253 g_set_error (error,
1254 G_IO_ERROR,
1255 G_IO_ERROR_FAILED,
1256 "Unexpected line '%s' while in WaitingForData state",
1257 line);
1258 g_free (line);
1260 goto out;
1262 case SERVER_STATE_WAITING_FOR_BEGIN:
1263 debug_print ("SERVER: WaitingForBegin");
1264 /* Use extremely slow (but reliable) line reader - this basically
1265 * does a recvfrom() system call per character
1267 * (the problem with using GDataInputStream's read_line is that because of
1268 * buffering it might start reading into the first D-Bus message that
1269 * appears after "BEGIN\r\n"....)
1271 line = _my_g_input_stream_read_line_safe (g_io_stream_get_input_stream (auth->priv->stream),
1272 &line_length,
1273 cancellable,
1274 error);
1275 debug_print ("SERVER: WaitingForBegin, read '%s'", line);
1276 if (line == NULL)
1277 goto out;
1278 if (g_strcmp0 (line, "BEGIN") == 0)
1280 /* YAY, done! */
1281 ret = TRUE;
1282 g_free (line);
1283 goto out;
1285 else if (g_strcmp0 (line, "NEGOTIATE_UNIX_FD") == 0)
1287 g_free (line);
1288 if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
1290 negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1291 s = "AGREE_UNIX_FD\r\n";
1292 debug_print ("SERVER: writing '%s'", s);
1293 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1294 goto out;
1296 else
1298 s = "ERROR \"fd passing not offered\"\r\n";
1299 debug_print ("SERVER: writing '%s'", s);
1300 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1301 goto out;
1304 else
1306 g_debug ("Unexpected line '%s' while in WaitingForBegin state", line);
1307 g_free (line);
1308 s = "ERROR \"Unknown Command\"\r\n";
1309 debug_print ("SERVER: writing '%s'", s);
1310 if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1311 goto out;
1313 break;
1315 default:
1316 g_assert_not_reached ();
1317 break;
1322 g_set_error_literal (error,
1323 G_IO_ERROR,
1324 G_IO_ERROR_FAILED,
1325 "Not implemented (server)");
1327 out:
1328 if (mech != NULL)
1329 g_object_unref (mech);
1330 if (dis != NULL)
1331 g_object_unref (dis);
1332 if (dos != NULL)
1333 g_object_unref (dos);
1335 /* ensure return value is FALSE if error is set */
1336 if (error != NULL && *error != NULL)
1338 ret = FALSE;
1341 if (ret)
1343 if (out_negotiated_capabilities != NULL)
1344 *out_negotiated_capabilities = negotiated_capabilities;
1345 if (out_received_credentials != NULL)
1346 *out_received_credentials = credentials != NULL ? g_object_ref (credentials) : NULL;
1349 if (credentials != NULL)
1350 g_object_unref (credentials);
1352 debug_print ("SERVER: Done, authenticated=%d", ret);
1354 return ret;
1357 /* ---------------------------------------------------------------------------------------------------- */