GDBus: make G_DBUS_DEBUG=authentication work again
[platform/upstream/glib.git] / gio / gdbusauth.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 "gdbusauth.h"
26
27 #include "gdbusauthmechanismanon.h"
28 #include "gdbusauthmechanismexternal.h"
29 #include "gdbusauthmechanismsha1.h"
30 #include "gdbusauthobserver.h"
31
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"
40
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
47
48 #include "glibintl.h"
49 #include "gioalias.h"
50
51 static void
52 debug_print (const gchar *message, ...)
53 {
54   if (G_UNLIKELY (_g_dbus_debug_authentication ()))
55     {
56       gchar *s;
57       GString *str;
58       va_list var_args;
59       guint n;
60
61       va_start (var_args, message);
62       s = g_strdup_vprintf (message, var_args);
63       va_end (var_args);
64
65       str = g_string_new (NULL);
66       for (n = 0; s[n] != '\0'; n++)
67         {
68           if (G_UNLIKELY (s[n] == '\r'))
69             g_string_append (str, "\\r");
70           else if (G_UNLIKELY (s[n] == '\n'))
71             g_string_append (str, "\\n");
72           else
73             g_string_append_c (str, s[n]);
74         }
75       g_print ("GDBus-debug:Auth: %s\n", str->str);
76       g_string_free (str, TRUE);
77       g_free (s);
78     }
79 }
80
81 typedef struct
82 {
83   const gchar *name;
84   gint priority;
85   GType gtype;
86 } Mechanism;
87
88 static void mechanism_free (Mechanism *m);
89
90 struct _GDBusAuthPrivate
91 {
92   GIOStream *stream;
93
94   /* A list of available Mechanism, sorted according to priority  */
95   GList *available_mechanisms;
96 };
97
98 enum
99 {
100   PROP_0,
101   PROP_STREAM
102 };
103
104 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
105
106 /* ---------------------------------------------------------------------------------------------------- */
107
108 static void
109 _g_dbus_auth_finalize (GObject *object)
110 {
111   GDBusAuth *auth = G_DBUS_AUTH (object);
112
113   if (auth->priv->stream != NULL)
114     g_object_unref (auth->priv->stream);
115   g_list_foreach (auth->priv->available_mechanisms, (GFunc) mechanism_free, NULL);
116   g_list_free (auth->priv->available_mechanisms);
117
118   if (G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize != NULL)
119     G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize (object);
120 }
121
122 static void
123 _g_dbus_auth_get_property (GObject    *object,
124                            guint       prop_id,
125                            GValue     *value,
126                            GParamSpec *pspec)
127 {
128   GDBusAuth *auth = G_DBUS_AUTH (object);
129
130   switch (prop_id)
131     {
132     case PROP_STREAM:
133       g_value_set_object (value, auth->priv->stream);
134       break;
135
136     default:
137       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
138       break;
139     }
140 }
141
142 static void
143 _g_dbus_auth_set_property (GObject      *object,
144                            guint         prop_id,
145                            const GValue *value,
146                            GParamSpec   *pspec)
147 {
148   GDBusAuth *auth = G_DBUS_AUTH (object);
149
150   switch (prop_id)
151     {
152     case PROP_STREAM:
153       auth->priv->stream = g_value_dup_object (value);
154       break;
155
156     default:
157       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
158       break;
159     }
160 }
161
162 static void
163 _g_dbus_auth_class_init (GDBusAuthClass *klass)
164 {
165   GObjectClass *gobject_class;
166
167   g_type_class_add_private (klass, sizeof (GDBusAuthPrivate));
168
169   gobject_class = G_OBJECT_CLASS (klass);
170   gobject_class->get_property = _g_dbus_auth_get_property;
171   gobject_class->set_property = _g_dbus_auth_set_property;
172   gobject_class->finalize     = _g_dbus_auth_finalize;
173
174   g_object_class_install_property (gobject_class,
175                                    PROP_STREAM,
176                                    g_param_spec_object ("stream",
177                                                         P_("IO Stream"),
178                                                         P_("The underlying GIOStream used for I/O"),
179                                                         G_TYPE_IO_STREAM,
180                                                         G_PARAM_READABLE |
181                                                         G_PARAM_WRITABLE |
182                                                         G_PARAM_CONSTRUCT_ONLY |
183                                                         G_PARAM_STATIC_NAME |
184                                                         G_PARAM_STATIC_BLURB |
185                                                         G_PARAM_STATIC_NICK));
186 }
187
188 static void
189 mechanism_free (Mechanism *m)
190 {
191   g_free (m);
192 }
193
194 static void
195 add_mechanism (GDBusAuth *auth,
196                GType      mechanism_type)
197 {
198   Mechanism *m;
199
200   m = g_new0 (Mechanism, 1);
201   m->name = _g_dbus_auth_mechanism_get_name (mechanism_type);
202   m->priority = _g_dbus_auth_mechanism_get_priority (mechanism_type);
203   m->gtype = mechanism_type;
204
205   auth->priv->available_mechanisms = g_list_prepend (auth->priv->available_mechanisms, m);
206 }
207
208 static gint
209 mech_compare_func (Mechanism *a, Mechanism *b)
210 {
211   gint ret;
212   /* ensure deterministic order */
213   ret = b->priority - a->priority;
214   if (ret == 0)
215     ret = g_strcmp0 (b->name, a->name);
216   return ret;
217 }
218
219 static void
220 _g_dbus_auth_init (GDBusAuth *auth)
221 {
222   auth->priv = G_TYPE_INSTANCE_GET_PRIVATE (auth, G_TYPE_DBUS_AUTH, GDBusAuthPrivate);
223
224   /* TODO: trawl extension points */
225   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_ANON);
226   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_SHA1);
227   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_EXTERNAL);
228
229   auth->priv->available_mechanisms = g_list_sort (auth->priv->available_mechanisms,
230                                                   (GCompareFunc) mech_compare_func);
231 }
232
233 static GType
234 find_mech_by_name (GDBusAuth *auth,
235                    const gchar *name)
236 {
237   GType ret;
238   GList *l;
239
240   ret = (GType) 0;
241
242   for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
243     {
244       Mechanism *m = l->data;
245       if (g_strcmp0 (name, m->name) == 0)
246         {
247           ret = m->gtype;
248           goto out;
249         }
250     }
251
252  out:
253   return ret;
254 }
255
256 GDBusAuth  *
257 _g_dbus_auth_new (GIOStream *stream)
258 {
259   return g_object_new (G_TYPE_DBUS_AUTH,
260                        "stream", stream,
261                        NULL);
262 }
263
264 /* ---------------------------------------------------------------------------------------------------- */
265 /* like g_data_input_stream_read_line() but sets error if there's no content to read */
266 static gchar *
267 _my_g_data_input_stream_read_line (GDataInputStream  *dis,
268                                    gsize             *out_line_length,
269                                    GCancellable      *cancellable,
270                                    GError           **error)
271 {
272   gchar *ret;
273
274   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
275
276   ret = g_data_input_stream_read_line (dis,
277                                        out_line_length,
278                                        cancellable,
279                                        error);
280   if (ret == NULL && error != NULL && *error == NULL)
281     {
282       g_set_error_literal (error,
283                            G_IO_ERROR,
284                            G_IO_ERROR_FAILED,
285                            _("Unexpected lack of content trying to read a line"));
286     }
287
288   return ret;
289 }
290
291 /* This function is to avoid situations like this
292  *
293  * BEGIN\r\nl\0\0\1...
294  *
295  * e.g. where we read into the first D-Bus message while waiting for
296  * the final line from the client (TODO: file bug against gio for
297  * this)
298  */
299 static gchar *
300 _my_g_input_stream_read_line_safe (GInputStream  *i,
301                                    gsize         *out_line_length,
302                                    GCancellable  *cancellable,
303                                    GError       **error)
304 {
305   GString *str;
306   gchar c;
307   gssize num_read;
308   gboolean last_was_cr;
309
310   str = g_string_new (NULL);
311
312   last_was_cr = FALSE;
313   while (TRUE)
314     {
315       num_read = g_input_stream_read (i,
316                                       &c,
317                                       1,
318                                       cancellable,
319                                       error);
320       if (num_read == -1)
321         goto fail;
322       if (num_read == 0)
323         {
324           if (error != NULL && *error == NULL)
325             {
326               g_set_error_literal (error,
327                                    G_IO_ERROR,
328                                    G_IO_ERROR_FAILED,
329                                    _("Unexpected lack of content trying to (safely) read a line"));
330             }
331           goto fail;
332         }
333
334       g_string_append_c (str, (gint) c);
335       if (last_was_cr)
336         {
337           if (c == 0x0a)
338             {
339               g_assert (str->len >= 2);
340               g_string_set_size (str, str->len - 2);
341               goto out;
342             }
343         }
344       last_was_cr = (c == 0x0d);
345     }
346
347  out:
348   if (out_line_length != NULL)
349     *out_line_length = str->len;
350   return g_string_free (str, FALSE);
351
352  fail:
353   g_assert (error == NULL || *error != NULL);
354   g_string_free (str, TRUE);
355   return NULL;
356 }
357
358 /* ---------------------------------------------------------------------------------------------------- */
359
360 static void
361 append_nibble (GString *s, gint val)
362 {
363   g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
364 }
365
366 static gchar *
367 hexdecode (const gchar  *str,
368            gsize        *out_len,
369            GError      **error)
370 {
371   gchar *ret;
372   GString *s;
373   guint n;
374
375   ret = NULL;
376   s = g_string_new (NULL);
377
378   for (n = 0; str[n] != '\0'; n += 2)
379     {
380       gint upper_nibble;
381       gint lower_nibble;
382       guint value;
383
384       upper_nibble = g_ascii_xdigit_value (str[n]);
385       lower_nibble = g_ascii_xdigit_value (str[n + 1]);
386       if (upper_nibble == -1 || lower_nibble == -1)
387         {
388           g_set_error (error,
389                        G_IO_ERROR,
390                        G_IO_ERROR_FAILED,
391                        "Error hexdecoding string `%s' around position %d",
392                        str, n);
393           goto out;
394         }
395       value = (upper_nibble<<4) | lower_nibble;
396       g_string_append_c (s, value);
397     }
398
399   ret = g_string_free (s, FALSE);
400   s = NULL;
401
402  out:
403   if (s != NULL)
404     g_string_free (s, TRUE);
405   return ret;
406 }
407
408 /* TODO: take len */
409 static gchar *
410 hexencode (const gchar *str)
411 {
412   guint n;
413   GString *s;
414
415   s = g_string_new (NULL);
416   for (n = 0; str[n] != '\0'; n++)
417     {
418       gint val;
419       gint upper_nibble;
420       gint lower_nibble;
421
422       val = ((const guchar *) str)[n];
423       upper_nibble = val >> 4;
424       lower_nibble = val & 0x0f;
425
426       append_nibble (s, upper_nibble);
427       append_nibble (s, lower_nibble);
428     }
429
430   return g_string_free (s, FALSE);
431 }
432
433 /* ---------------------------------------------------------------------------------------------------- */
434
435 static GDBusAuthMechanism *
436 client_choose_mech_and_send_initial_response (GDBusAuth           *auth,
437                                               GCredentials        *credentials_that_were_sent,
438                                               const gchar* const  *supported_auth_mechs,
439                                               GPtrArray           *attempted_auth_mechs,
440                                               GDataOutputStream   *dos,
441                                               GCancellable        *cancellable,
442                                               GError             **error)
443 {
444   GDBusAuthMechanism *mech;
445   GType auth_mech_to_use_gtype;
446   guint n;
447   guint m;
448   gchar *initial_response;
449   gsize initial_response_len;
450   gchar *encoded;
451   gchar *s;
452
453  again:
454   mech = NULL;
455
456   debug_print ("CLIENT: Trying to choose mechanism");
457
458   /* find an authentication mechanism to try, if any */
459   auth_mech_to_use_gtype = (GType) 0;
460   for (n = 0; supported_auth_mechs[n] != NULL; n++)
461     {
462       gboolean attempted_already;
463       attempted_already = FALSE;
464       for (m = 0; m < attempted_auth_mechs->len; m++)
465         {
466           if (g_strcmp0 (supported_auth_mechs[n], attempted_auth_mechs->pdata[m]) == 0)
467             {
468               attempted_already = TRUE;
469               break;
470             }
471         }
472       if (!attempted_already)
473         {
474           auth_mech_to_use_gtype = find_mech_by_name (auth, supported_auth_mechs[n]);
475           if (auth_mech_to_use_gtype != (GType) 0)
476             break;
477         }
478     }
479
480   if (auth_mech_to_use_gtype == (GType) 0)
481     {
482       guint n;
483       gchar *available;
484       GString *tried_str;
485
486       debug_print ("CLIENT: Exhausted all available mechanisms");
487
488       available = g_strjoinv (", ", (gchar **) supported_auth_mechs);
489
490       tried_str = g_string_new (NULL);
491       for (n = 0; n < attempted_auth_mechs->len; n++)
492         {
493           if (n > 0)
494             g_string_append (tried_str, ", ");
495           g_string_append (tried_str, attempted_auth_mechs->pdata[n]);
496         }
497       g_set_error (error,
498                    G_IO_ERROR,
499                    G_IO_ERROR_FAILED,
500                    _("Exhausted all available authentication mechanisms (tried: %s) (available: %s)"),
501                    tried_str->str,
502                    available);
503       g_string_free (tried_str, TRUE);
504       g_free (available);
505       goto out;
506     }
507
508   /* OK, decided on a mechanism - let's do this thing */
509   mech = g_object_new (auth_mech_to_use_gtype,
510                        "stream", auth->priv->stream,
511                        "credentials", credentials_that_were_sent,
512                        NULL);
513   debug_print ("CLIENT: Trying mechanism `%s'", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
514   g_ptr_array_add (attempted_auth_mechs, (gpointer) _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
515
516   /* the auth mechanism may not be supported
517    * (for example, EXTERNAL only works if credentials were exchanged)
518    */
519   if (!_g_dbus_auth_mechanism_is_supported (mech))
520     {
521       debug_print ("CLIENT: Mechanism `%s' says it is not supported", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
522       g_object_unref (mech);
523       mech = NULL;
524       goto again;
525     }
526
527   initial_response_len = -1;
528   initial_response = _g_dbus_auth_mechanism_client_initiate (mech,
529                                                              &initial_response_len);
530 #if 0
531   g_printerr ("using auth mechanism with name `%s' of type `%s' with initial response `%s'\n",
532               _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
533               g_type_name (G_TYPE_FROM_INSTANCE (mech)),
534               initial_response);
535 #endif
536   if (initial_response != NULL)
537     {
538       //g_printerr ("initial_response = `%s'\n", initial_response);
539       encoded = hexencode (initial_response);
540       s = g_strdup_printf ("AUTH %s %s\r\n",
541                            _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
542                            encoded);
543       g_free (initial_response);
544       g_free (encoded);
545     }
546   else
547     {
548       s = g_strdup_printf ("AUTH %s\r\n", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
549     }
550   debug_print ("CLIENT: writing `%s'", s);
551   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
552     {
553       g_object_unref (mech);
554       mech = NULL;
555       g_free (s);
556       goto out;
557     }
558   g_free (s);
559
560  out:
561   return mech;
562 }
563
564
565 /* ---------------------------------------------------------------------------------------------------- */
566
567 typedef enum
568 {
569   CLIENT_STATE_WAITING_FOR_DATA,
570   CLIENT_STATE_WAITING_FOR_OK,
571   CLIENT_STATE_WAITING_FOR_REJECT,
572   CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD
573 } ClientState;
574
575 gchar *
576 _g_dbus_auth_run_client (GDBusAuth     *auth,
577                          GDBusCapabilityFlags offered_capabilities,
578                          GDBusCapabilityFlags *out_negotiated_capabilities,
579                          GCancellable  *cancellable,
580                          GError       **error)
581 {
582   gchar *s;
583   GDataInputStream *dis;
584   GDataOutputStream *dos;
585   GCredentials *credentials;
586   gchar *ret_guid;
587   gchar *line;
588   gsize line_length;
589   gchar **supported_auth_mechs;
590   GPtrArray *attempted_auth_mechs;
591   GDBusAuthMechanism *mech;
592   ClientState state;
593   GDBusCapabilityFlags negotiated_capabilities;
594
595   debug_print ("CLIENT: initiating");
596
597   ret_guid = NULL;
598   supported_auth_mechs = NULL;
599   attempted_auth_mechs = g_ptr_array_new ();
600   mech = NULL;
601   negotiated_capabilities = 0;
602   credentials = NULL;
603
604   dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
605   dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
606   g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
607   g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
608
609   g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
610
611 #ifdef G_OS_UNIX
612   if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
613     {
614       credentials = g_credentials_new ();
615       if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
616                                                cancellable,
617                                                error))
618         goto out;
619     }
620   else
621     {
622       if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
623         goto out;
624     }
625 #else
626   if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
627     goto out;
628 #endif
629
630   if (credentials != NULL)
631     {
632       if (G_UNLIKELY (_g_dbus_debug_authentication ()))
633         {
634           s = g_credentials_to_string (credentials);
635           debug_print ("CLIENT: sent credentials `%s'", s);
636           g_free (s);
637         }
638     }
639   else
640     {
641       debug_print ("CLIENT: didn't send any credentials");
642     }
643
644   /* TODO: to reduce roundtrips, try to pick an auth mechanism to start with */
645
646   /* Get list of supported authentication mechanisms */
647   s = "AUTH\r\n";
648   debug_print ("CLIENT: writing `%s'", s);
649   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
650     goto out;
651   state = CLIENT_STATE_WAITING_FOR_REJECT;
652
653   while (TRUE)
654     {
655       switch (state)
656         {
657         case CLIENT_STATE_WAITING_FOR_REJECT:
658           debug_print ("CLIENT: WaitingForReject");
659           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
660           if (line == NULL)
661             goto out;
662           debug_print ("CLIENT: WaitingForReject, read '%s'", line);
663         foobar:
664           if (!g_str_has_prefix (line, "REJECTED "))
665             {
666               g_set_error (error,
667                            G_IO_ERROR,
668                            G_IO_ERROR_FAILED,
669                            "In WaitingForReject: Expected `REJECTED am1 am2 ... amN', got `%s'",
670                            line);
671               g_free (line);
672               goto out;
673             }
674           if (supported_auth_mechs == NULL)
675             {
676               supported_auth_mechs = g_strsplit (line + sizeof ("REJECTED ") - 1, " ", 0);
677 #if 0
678               for (n = 0; supported_auth_mechs != NULL && supported_auth_mechs[n] != NULL; n++)
679                 g_printerr ("supported_auth_mechs[%d] = `%s'\n", n, supported_auth_mechs[n]);
680 #endif
681             }
682           g_free (line);
683           mech = client_choose_mech_and_send_initial_response (auth,
684                                                                credentials,
685                                                                (const gchar* const *) supported_auth_mechs,
686                                                                attempted_auth_mechs,
687                                                                dos,
688                                                                cancellable,
689                                                                error);
690           if (mech == NULL)
691             goto out;
692           if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA)
693             state = CLIENT_STATE_WAITING_FOR_DATA;
694           else
695             state = CLIENT_STATE_WAITING_FOR_OK;
696           break;
697
698         case CLIENT_STATE_WAITING_FOR_OK:
699           debug_print ("CLIENT: WaitingForOK");
700           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
701           if (line == NULL)
702             goto out;
703           debug_print ("CLIENT: WaitingForOK, read `%s'", line);
704           if (g_str_has_prefix (line, "OK "))
705             {
706               if (!g_dbus_is_guid (line + 3))
707                 {
708                   g_set_error (error,
709                                G_IO_ERROR,
710                                G_IO_ERROR_FAILED,
711                                "Invalid OK response `%s'",
712                                line);
713                   g_free (line);
714                   goto out;
715                 }
716               ret_guid = g_strdup (line + 3);
717               g_free (line);
718
719               if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
720                 {
721                   s = "NEGOTIATE_UNIX_FD\r\n";
722                   debug_print ("CLIENT: writing `%s'", s);
723                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
724                     goto out;
725                   state = CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD;
726                 }
727               else
728                 {
729                   s = "BEGIN\r\n";
730                   debug_print ("CLIENT: writing `%s'", s);
731                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
732                     goto out;
733                   /* and we're done! */
734                   goto out;
735                 }
736             }
737           else if (g_str_has_prefix (line, "REJECTED "))
738             {
739               goto foobar;
740             }
741           else
742             {
743               /* TODO: handle other valid responses */
744               g_set_error (error,
745                            G_IO_ERROR,
746                            G_IO_ERROR_FAILED,
747                            "In WaitingForOk: unexpected response `%s'",
748                            line);
749               g_free (line);
750               goto out;
751             }
752           break;
753
754         case CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD:
755           debug_print ("CLIENT: WaitingForAgreeUnixFD");
756           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
757           if (line == NULL)
758             goto out;
759           debug_print ("CLIENT: WaitingForAgreeUnixFD, read=`%s'", line);
760           if (g_strcmp0 (line, "AGREE_UNIX_FD") == 0)
761             {
762               negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
763               s = "BEGIN\r\n";
764               debug_print ("CLIENT: writing `%s'", s);
765               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
766                 goto out;
767               /* and we're done! */
768               goto out;
769             }
770           else if (g_str_has_prefix (line, "ERROR") && (line[5] == 0 || g_ascii_isspace (line[5])))
771             {
772               //g_strstrip (line + 5); g_debug ("bah, no unix_fd: `%s'", line + 5);
773               g_free (line);
774               s = "BEGIN\r\n";
775               debug_print ("CLIENT: writing `%s'", s);
776               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
777                 goto out;
778               /* and we're done! */
779               goto out;
780             }
781           else
782             {
783               /* TODO: handle other valid responses */
784               g_set_error (error,
785                            G_IO_ERROR,
786                            G_IO_ERROR_FAILED,
787                            "In WaitingForAgreeUnixFd: unexpected response `%s'",
788                            line);
789               g_free (line);
790               goto out;
791             }
792           break;
793
794         case CLIENT_STATE_WAITING_FOR_DATA:
795           debug_print ("CLIENT: WaitingForData");
796           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
797           if (line == NULL)
798             goto out;
799           debug_print ("CLIENT: WaitingForData, read=`%s'", line);
800           if (g_str_has_prefix (line, "DATA "))
801             {
802               gchar *encoded;
803               gchar *decoded_data;
804               gsize decoded_data_len;
805
806               encoded = g_strdup (line + 5);
807               g_free (line);
808               g_strstrip (encoded);
809               decoded_data = hexdecode (encoded, &decoded_data_len, error);
810               g_free (encoded);
811               if (decoded_data == NULL)
812                 {
813                   g_prefix_error (error, "DATA response is malformed: ");
814                   /* invalid encoding, disconnect! */
815                   goto out;
816                 }
817               _g_dbus_auth_mechanism_client_data_receive (mech, decoded_data, decoded_data_len);
818               g_free (decoded_data);
819
820               if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND)
821                 {
822                   gchar *data;
823                   gsize data_len;
824                   gchar *encoded_data;
825                   data = _g_dbus_auth_mechanism_client_data_send (mech, &data_len);
826                   encoded_data = hexencode (data);
827                   s = g_strdup_printf ("DATA %s\r\n", encoded_data);
828                   g_free (encoded_data);
829                   g_free (data);
830                   debug_print ("CLIENT: writing `%s'", s);
831                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
832                     {
833                       g_free (s);
834                       goto out;
835                     }
836                   g_free (s);
837                 }
838               state = CLIENT_STATE_WAITING_FOR_OK;
839             }
840           else
841             {
842               g_set_error (error,
843                            G_IO_ERROR,
844                            G_IO_ERROR_FAILED,
845                            "In WaitingForData: unexpected response `%s'",
846                            line);
847               g_free (line);
848               goto out;
849             }
850           break;
851
852         default:
853           g_assert_not_reached ();
854           break;
855         }
856
857     }; /* main authentication client loop */
858
859  out:
860   if (mech != NULL)
861     g_object_unref (mech);
862   g_ptr_array_unref (attempted_auth_mechs);
863   g_strfreev (supported_auth_mechs);
864   g_object_unref (dis);
865   g_object_unref (dos);
866
867   /* ensure return value is NULL if error is set */
868   if (error != NULL && *error != NULL)
869     {
870       g_free (ret_guid);
871       ret_guid = NULL;
872     }
873
874   if (ret_guid != NULL)
875     {
876       if (out_negotiated_capabilities != NULL)
877         *out_negotiated_capabilities = negotiated_capabilities;
878     }
879
880   if (credentials != NULL)
881     g_object_unref (credentials);
882
883   debug_print ("CLIENT: Done, authenticated=%d", ret_guid != NULL);
884
885   return ret_guid;
886 }
887
888 /* ---------------------------------------------------------------------------------------------------- */
889
890 static gchar *
891 get_auth_mechanisms (GDBusAuth     *auth,
892                      gboolean       allow_anonymous,
893                      const gchar   *prefix,
894                      const gchar   *suffix,
895                      const gchar   *separator)
896 {
897   GList *l;
898   GString *str;
899   gboolean need_sep;
900
901   str = g_string_new (prefix);
902   need_sep = FALSE;
903   for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
904     {
905       Mechanism *m = l->data;
906
907       if (!allow_anonymous && g_strcmp0 (m->name, "ANONYMOUS") == 0)
908         continue;
909
910       if (need_sep)
911         g_string_append (str, separator);
912       g_string_append (str, m->name);
913       need_sep = TRUE;
914     }
915
916   g_string_append (str, suffix);
917   return g_string_free (str, FALSE);
918 }
919
920
921 typedef enum
922 {
923   SERVER_STATE_WAITING_FOR_AUTH,
924   SERVER_STATE_WAITING_FOR_DATA,
925   SERVER_STATE_WAITING_FOR_BEGIN
926 } ServerState;
927
928 gboolean
929 _g_dbus_auth_run_server (GDBusAuth              *auth,
930                          GDBusAuthObserver      *observer,
931                          const gchar            *guid,
932                          gboolean                allow_anonymous,
933                          GDBusCapabilityFlags    offered_capabilities,
934                          GDBusCapabilityFlags   *out_negotiated_capabilities,
935                          GCredentials          **out_received_credentials,
936                          GCancellable           *cancellable,
937                          GError                **error)
938 {
939   gboolean ret;
940   ServerState state;
941   GDataInputStream *dis;
942   GDataOutputStream *dos;
943   GError *local_error;
944   guchar byte;
945   gchar *line;
946   gsize line_length;
947   GDBusAuthMechanism *mech;
948   gchar *s;
949   GDBusCapabilityFlags negotiated_capabilities;
950   GCredentials *credentials;
951
952   debug_print ("SERVER: initiating");
953
954   ret = FALSE;
955   dis = NULL;
956   dos = NULL;
957   mech = NULL;
958   negotiated_capabilities = 0;
959   credentials = NULL;
960
961   if (!g_dbus_is_guid (guid))
962     {
963       g_set_error (error,
964                    G_IO_ERROR,
965                    G_IO_ERROR_FAILED,
966                    "The given guid `%s' is not valid",
967                    guid);
968       goto out;
969     }
970
971   dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
972   dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
973   g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
974   g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
975
976   g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
977
978   /* first read the NUL-byte (TODO: read credentials if using a unix domain socket) */
979 #ifdef G_OS_UNIX
980   if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
981     {
982       local_error = NULL;
983       credentials = g_unix_connection_receive_credentials (G_UNIX_CONNECTION (auth->priv->stream),
984                                                            cancellable,
985                                                            &local_error);
986       if (credentials == NULL)
987         {
988           g_propagate_error (error, local_error);
989           goto out;
990         }
991     }
992   else
993     {
994       local_error = NULL;
995       byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
996       if (local_error != NULL)
997         {
998           g_propagate_error (error, local_error);
999           goto out;
1000         }
1001     }
1002 #else
1003   local_error = NULL;
1004   byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
1005   if (local_error != NULL)
1006     {
1007       g_propagate_error (error, local_error);
1008       goto out;
1009     }
1010 #endif
1011   if (credentials != NULL)
1012     {
1013       if (G_UNLIKELY (_g_dbus_debug_authentication ()))
1014         {
1015           s = g_credentials_to_string (credentials);
1016           debug_print ("SERVER: received credentials `%s'", s);
1017           g_free (s);
1018         }
1019     }
1020   else
1021     {
1022       debug_print ("SERVER: didn't receive any credentials");
1023     }
1024
1025   state = SERVER_STATE_WAITING_FOR_AUTH;
1026   while (TRUE)
1027     {
1028       switch (state)
1029         {
1030         case SERVER_STATE_WAITING_FOR_AUTH:
1031           debug_print ("SERVER: WaitingForAuth");
1032           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1033           debug_print ("SERVER: WaitingForAuth, read `%s'", line);
1034           if (line == NULL)
1035             goto out;
1036           if (g_strcmp0 (line, "AUTH") == 0)
1037             {
1038               s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1039               debug_print ("SERVER: writing `%s'", s);
1040               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1041                 {
1042                   g_free (s);
1043                   goto out;
1044                 }
1045               g_free (s);
1046               g_free (line);
1047             }
1048           else if (g_str_has_prefix (line, "AUTH "))
1049             {
1050               gchar **tokens;
1051               const gchar *encoded;
1052               const gchar *mech_name;
1053               GType auth_mech_to_use_gtype;
1054
1055               tokens = g_strsplit (line, " ", 0);
1056               g_free (line);
1057
1058               switch (g_strv_length (tokens))
1059                 {
1060                 case 2:
1061                   /* no initial response */
1062                   mech_name = tokens[1];
1063                   encoded = NULL;
1064                   break;
1065
1066                 case 3:
1067                   /* initial response */
1068                   mech_name = tokens[1];
1069                   encoded = tokens[2];
1070                   break;
1071
1072                 default:
1073                   g_set_error (error,
1074                                G_IO_ERROR,
1075                                G_IO_ERROR_FAILED,
1076                                "Unexpected line `%s' while in WaitingForAuth state",
1077                                line);
1078                   g_strfreev (tokens);
1079                   goto out;
1080                 }
1081
1082               /* TODO: record that the client has attempted to use this mechanism */
1083               //g_debug ("client is trying `%s'", mech_name);
1084
1085               auth_mech_to_use_gtype = find_mech_by_name (auth, mech_name);
1086               if ((auth_mech_to_use_gtype == (GType) 0) ||
1087                   (!allow_anonymous && g_strcmp0 (mech_name, "ANONYMOUS") == 0))
1088                 {
1089                   /* We don't support this auth mechanism */
1090                   g_strfreev (tokens);
1091                   s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1092                   debug_print ("SERVER: writing `%s'", s);
1093                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1094                     {
1095                       g_free (s);
1096                       goto out;
1097                     }
1098                   g_free (s);
1099
1100                   /* stay in WAITING FOR AUTH */
1101                   state = SERVER_STATE_WAITING_FOR_AUTH;
1102                 }
1103               else
1104                 {
1105                   gchar *initial_response;
1106                   gsize initial_response_len;
1107
1108                   mech = g_object_new (auth_mech_to_use_gtype,
1109                                        "stream", auth->priv->stream,
1110                                        "credentials", credentials,
1111                                        NULL);
1112
1113                   initial_response = NULL;
1114                   initial_response_len = 0;
1115                   if (encoded != NULL)
1116                     {
1117                       initial_response = hexdecode (encoded, &initial_response_len, error);
1118                       if (initial_response == NULL)
1119                         {
1120                           g_prefix_error (error, "Initial response is malformed: ");
1121                           /* invalid encoding, disconnect! */
1122                           g_strfreev (tokens);
1123                           goto out;
1124                         }
1125                     }
1126
1127                   _g_dbus_auth_mechanism_server_initiate (mech,
1128                                                           initial_response,
1129                                                           initial_response_len);
1130                   g_free (initial_response);
1131                   g_strfreev (tokens);
1132
1133                 change_state:
1134                   switch (_g_dbus_auth_mechanism_server_get_state (mech))
1135                     {
1136                     case G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED:
1137                       if (observer != NULL &&
1138                           !g_dbus_auth_observer_authorize_authenticated_peer (observer,
1139                                                                               auth->priv->stream,
1140                                                                               credentials))
1141                         {
1142                           /* disconnect */
1143                           g_set_error_literal (error,
1144                                                G_IO_ERROR,
1145                                                G_IO_ERROR_FAILED,
1146                                                _("Cancelled via GDBusAuthObserver::authorize-authenticated-peer"));
1147                           goto out;
1148                         }
1149                       else
1150                         {
1151                           s = g_strdup_printf ("OK %s\r\n", guid);
1152                           debug_print ("SERVER: writing `%s'", s);
1153                           if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1154                             {
1155                               g_free (s);
1156                               goto out;
1157                             }
1158                           g_free (s);
1159                           state = SERVER_STATE_WAITING_FOR_BEGIN;
1160                         }
1161                       break;
1162
1163                     case G_DBUS_AUTH_MECHANISM_STATE_REJECTED:
1164                       s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1165                       debug_print ("SERVER: writing `%s'", s);
1166                       if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1167                         {
1168                           g_free (s);
1169                           goto out;
1170                         }
1171                       g_free (s);
1172                       state = SERVER_STATE_WAITING_FOR_AUTH;
1173                       break;
1174
1175                     case G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA:
1176                       state = SERVER_STATE_WAITING_FOR_DATA;
1177                       break;
1178
1179                     case G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND:
1180                       {
1181                         gchar *data;
1182                         gsize data_len;
1183                         gchar *encoded_data;
1184                         data = _g_dbus_auth_mechanism_server_data_send (mech, &data_len);
1185                         encoded_data = hexencode (data);
1186                         s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1187                         g_free (encoded_data);
1188                         g_free (data);
1189                         debug_print ("SERVER: writing `%s'", s);
1190                         if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1191                           {
1192                             g_free (s);
1193                             goto out;
1194                           }
1195                         g_free (s);
1196                       }
1197                       goto change_state;
1198                       break;
1199
1200                     default:
1201                       /* TODO */
1202                       g_assert_not_reached ();
1203                       break;
1204                     }
1205                 }
1206             }
1207           else
1208             {
1209               g_set_error (error,
1210                            G_IO_ERROR,
1211                            G_IO_ERROR_FAILED,
1212                            "Unexpected line `%s' while in WaitingForAuth state",
1213                            line);
1214               g_free (line);
1215               goto out;
1216             }
1217           break;
1218
1219         case SERVER_STATE_WAITING_FOR_DATA:
1220           debug_print ("SERVER: WaitingForData");
1221           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1222           debug_print ("SERVER: WaitingForData, read `%s'", line);
1223           if (line == NULL)
1224             goto out;
1225           if (g_str_has_prefix (line, "DATA "))
1226             {
1227               gchar *encoded;
1228               gchar *decoded_data;
1229               gsize decoded_data_len;
1230
1231               encoded = g_strdup (line + 5);
1232               g_free (line);
1233               g_strstrip (encoded);
1234               decoded_data = hexdecode (encoded, &decoded_data_len, error);
1235               g_free (encoded);
1236               if (decoded_data == NULL)
1237                 {
1238                   g_prefix_error (error, "DATA response is malformed: ");
1239                   /* invalid encoding, disconnect! */
1240                   goto out;
1241                 }
1242               _g_dbus_auth_mechanism_server_data_receive (mech, decoded_data, decoded_data_len);
1243               g_free (decoded_data);
1244               /* oh man, this goto-crap is so ugly.. really need to rewrite the state machine */
1245               goto change_state;
1246             }
1247           else
1248             {
1249               g_set_error (error,
1250                            G_IO_ERROR,
1251                            G_IO_ERROR_FAILED,
1252                            "Unexpected line `%s' while in WaitingForData state",
1253                            line);
1254               g_free (line);
1255             }
1256           goto out;
1257
1258         case SERVER_STATE_WAITING_FOR_BEGIN:
1259           debug_print ("SERVER: WaitingForBegin");
1260           /* Use extremely slow (but reliable) line reader - this basically
1261            * does a recvfrom() system call per character
1262            *
1263            * (the problem with using GDataInputStream's read_line is that because of
1264            * buffering it might start reading into the first D-Bus message that
1265            * appears after "BEGIN\r\n"....)
1266            */
1267           line = _my_g_input_stream_read_line_safe (g_io_stream_get_input_stream (auth->priv->stream),
1268                                                     &line_length,
1269                                                     cancellable,
1270                                                     error);
1271           debug_print ("SERVER: WaitingForBegin, read `%s'", line);
1272           if (line == NULL)
1273             goto out;
1274           if (g_strcmp0 (line, "BEGIN") == 0)
1275             {
1276               /* YAY, done! */
1277               ret = TRUE;
1278               g_free (line);
1279               goto out;
1280             }
1281           else if (g_strcmp0 (line, "NEGOTIATE_UNIX_FD") == 0)
1282             {
1283               g_free (line);
1284               if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
1285                 {
1286                   negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1287                   s = "AGREE_UNIX_FD\r\n";
1288                   debug_print ("SERVER: writing `%s'", s);
1289                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1290                     goto out;
1291                 }
1292               else
1293                 {
1294                   s = "ERROR \"fd passing not offered\"\r\n";
1295                   debug_print ("SERVER: writing `%s'", s);
1296                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1297                     goto out;
1298                 }
1299             }
1300           else
1301             {
1302               g_debug ("Unexpected line `%s' while in WaitingForBegin state", line);
1303               g_free (line);
1304               s = "ERROR \"Unknown Command\"\r\n";
1305               debug_print ("SERVER: writing `%s'", s);
1306               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1307                 goto out;
1308             }
1309           break;
1310
1311         default:
1312           g_assert_not_reached ();
1313           break;
1314         }
1315     }
1316
1317
1318   g_set_error_literal (error,
1319                        G_IO_ERROR,
1320                        G_IO_ERROR_FAILED,
1321                        "Not implemented (server)");
1322
1323  out:
1324   if (mech != NULL)
1325     g_object_unref (mech);
1326   if (dis != NULL)
1327     g_object_unref (dis);
1328   if (dos != NULL)
1329     g_object_unref (dos);
1330
1331   /* ensure return value is FALSE if error is set */
1332   if (error != NULL && *error != NULL)
1333     {
1334       ret = FALSE;
1335     }
1336
1337   if (ret)
1338     {
1339       if (out_negotiated_capabilities != NULL)
1340         *out_negotiated_capabilities = negotiated_capabilities;
1341       if (out_received_credentials != NULL)
1342         *out_received_credentials = credentials != NULL ? g_object_ref (credentials) : NULL;
1343     }
1344
1345   if (credentials != NULL)
1346     g_object_unref (credentials);
1347
1348   debug_print ("SERVER: Done, authenticated=%d", ret);
1349
1350   return ret;
1351 }
1352
1353 /* ---------------------------------------------------------------------------------------------------- */
1354
1355 #define __G_DBUS_AUTH_C__
1356 #include "gioaliasdef.c"