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