eeced636fb707038ba761c2da1e0d0c9940d78e9
[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 #define DEBUG_ENABLED 0
52
53 static void
54 debug_print (const gchar *message, ...)
55 {
56 #if DEBUG_ENABLED
57   if (G_UNLIKELY (_g_dbus_debug_authentication ()))
58     {
59       gchar *s;
60       GString *str;
61       va_list var_args;
62       guint n;
63
64       va_start (var_args, message);
65       s = g_strdup_vprintf (message, var_args);
66       va_end (var_args);
67
68       str = g_string_new (NULL);
69       for (n = 0; s[n] != '\0'; n++)
70         {
71           if (G_UNLIKELY (s[n] == '\r'))
72             g_string_append (str, "\\r");
73           else if (G_UNLIKELY (s[n] == '\n'))
74             g_string_append (str, "\\n");
75           else
76             g_string_append_c (str, s[n]);
77         }
78       g_print ("GDBus-debug:Auth: %s\n", str->str);
79       g_string_free (str, TRUE);
80       g_free (s);
81     }
82 #endif
83 }
84
85 typedef struct
86 {
87   const gchar *name;
88   gint priority;
89   GType gtype;
90 } Mechanism;
91
92 static void mechanism_free (Mechanism *m);
93
94 struct _GDBusAuthPrivate
95 {
96   GIOStream *stream;
97
98   /* A list of available Mechanism, sorted according to priority  */
99   GList *available_mechanisms;
100 };
101
102 enum
103 {
104   PROP_0,
105   PROP_STREAM
106 };
107
108 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
109
110 /* ---------------------------------------------------------------------------------------------------- */
111
112 static void
113 _g_dbus_auth_finalize (GObject *object)
114 {
115   GDBusAuth *auth = G_DBUS_AUTH (object);
116
117   if (auth->priv->stream != NULL)
118     g_object_unref (auth->priv->stream);
119   g_list_foreach (auth->priv->available_mechanisms, (GFunc) mechanism_free, NULL);
120   g_list_free (auth->priv->available_mechanisms);
121
122   if (G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize != NULL)
123     G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize (object);
124 }
125
126 static void
127 _g_dbus_auth_get_property (GObject    *object,
128                            guint       prop_id,
129                            GValue     *value,
130                            GParamSpec *pspec)
131 {
132   GDBusAuth *auth = G_DBUS_AUTH (object);
133
134   switch (prop_id)
135     {
136     case PROP_STREAM:
137       g_value_set_object (value, auth->priv->stream);
138       break;
139
140     default:
141       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
142       break;
143     }
144 }
145
146 static void
147 _g_dbus_auth_set_property (GObject      *object,
148                            guint         prop_id,
149                            const GValue *value,
150                            GParamSpec   *pspec)
151 {
152   GDBusAuth *auth = G_DBUS_AUTH (object);
153
154   switch (prop_id)
155     {
156     case PROP_STREAM:
157       auth->priv->stream = g_value_dup_object (value);
158       break;
159
160     default:
161       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
162       break;
163     }
164 }
165
166 static void
167 _g_dbus_auth_class_init (GDBusAuthClass *klass)
168 {
169   GObjectClass *gobject_class;
170
171   g_type_class_add_private (klass, sizeof (GDBusAuthPrivate));
172
173   gobject_class = G_OBJECT_CLASS (klass);
174   gobject_class->get_property = _g_dbus_auth_get_property;
175   gobject_class->set_property = _g_dbus_auth_set_property;
176   gobject_class->finalize     = _g_dbus_auth_finalize;
177
178   g_object_class_install_property (gobject_class,
179                                    PROP_STREAM,
180                                    g_param_spec_object ("stream",
181                                                         P_("IO Stream"),
182                                                         P_("The underlying GIOStream used for I/O"),
183                                                         G_TYPE_IO_STREAM,
184                                                         G_PARAM_READABLE |
185                                                         G_PARAM_WRITABLE |
186                                                         G_PARAM_CONSTRUCT_ONLY |
187                                                         G_PARAM_STATIC_NAME |
188                                                         G_PARAM_STATIC_BLURB |
189                                                         G_PARAM_STATIC_NICK));
190 }
191
192 static void
193 mechanism_free (Mechanism *m)
194 {
195   g_free (m);
196 }
197
198 static void
199 add_mechanism (GDBusAuth *auth,
200                GType      mechanism_type)
201 {
202   Mechanism *m;
203
204   m = g_new0 (Mechanism, 1);
205   m->name = _g_dbus_auth_mechanism_get_name (mechanism_type);
206   m->priority = _g_dbus_auth_mechanism_get_priority (mechanism_type);
207   m->gtype = mechanism_type;
208
209   auth->priv->available_mechanisms = g_list_prepend (auth->priv->available_mechanisms, m);
210 }
211
212 static gint
213 mech_compare_func (Mechanism *a, Mechanism *b)
214 {
215   gint ret;
216   /* ensure deterministic order */
217   ret = b->priority - a->priority;
218   if (ret == 0)
219     ret = g_strcmp0 (b->name, a->name);
220   return ret;
221 }
222
223 static void
224 _g_dbus_auth_init (GDBusAuth *auth)
225 {
226   auth->priv = G_TYPE_INSTANCE_GET_PRIVATE (auth, G_TYPE_DBUS_AUTH, GDBusAuthPrivate);
227
228   /* TODO: trawl extension points */
229   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_ANON);
230   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_SHA1);
231   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_EXTERNAL);
232
233   auth->priv->available_mechanisms = g_list_sort (auth->priv->available_mechanisms,
234                                                   (GCompareFunc) mech_compare_func);
235 }
236
237 static GType
238 find_mech_by_name (GDBusAuth *auth,
239                    const gchar *name)
240 {
241   GType ret;
242   GList *l;
243
244   ret = (GType) 0;
245
246   for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
247     {
248       Mechanism *m = l->data;
249       if (g_strcmp0 (name, m->name) == 0)
250         {
251           ret = m->gtype;
252           goto out;
253         }
254     }
255
256  out:
257   return ret;
258 }
259
260 GDBusAuth  *
261 _g_dbus_auth_new (GIOStream *stream)
262 {
263   return g_object_new (G_TYPE_DBUS_AUTH,
264                        "stream", stream,
265                        NULL);
266 }
267
268 /* ---------------------------------------------------------------------------------------------------- */
269 /* like g_data_input_stream_read_line() but sets error if there's no content to read */
270 static gchar *
271 _my_g_data_input_stream_read_line (GDataInputStream  *dis,
272                                    gsize             *out_line_length,
273                                    GCancellable      *cancellable,
274                                    GError           **error)
275 {
276   gchar *ret;
277
278   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
279
280   ret = g_data_input_stream_read_line (dis,
281                                        out_line_length,
282                                        cancellable,
283                                        error);
284   if (ret == NULL && error != NULL && *error == NULL)
285     {
286       g_set_error_literal (error,
287                            G_IO_ERROR,
288                            G_IO_ERROR_FAILED,
289                            _("Unexpected lack of content trying to read a line"));
290     }
291
292   return ret;
293 }
294
295 /* This function is to avoid situations like this
296  *
297  * BEGIN\r\nl\0\0\1...
298  *
299  * e.g. where we read into the first D-Bus message while waiting for
300  * the final line from the client (TODO: file bug against gio for
301  * this)
302  */
303 static gchar *
304 _my_g_input_stream_read_line_safe (GInputStream  *i,
305                                    gsize         *out_line_length,
306                                    GCancellable  *cancellable,
307                                    GError       **error)
308 {
309   GString *str;
310   gchar c;
311   gssize num_read;
312   gboolean last_was_cr;
313
314   str = g_string_new (NULL);
315
316   last_was_cr = FALSE;
317   while (TRUE)
318     {
319       num_read = g_input_stream_read (i,
320                                       &c,
321                                       1,
322                                       cancellable,
323                                       error);
324       if (num_read == -1)
325         goto fail;
326       if (num_read == 0)
327         {
328           if (error != NULL && *error == NULL)
329             {
330               g_set_error_literal (error,
331                                    G_IO_ERROR,
332                                    G_IO_ERROR_FAILED,
333                                    _("Unexpected lack of content trying to (safely) read a line"));
334             }
335           goto fail;
336         }
337
338       g_string_append_c (str, (gint) c);
339       if (last_was_cr)
340         {
341           if (c == 0x0a)
342             {
343               g_assert (str->len >= 2);
344               g_string_set_size (str, str->len - 2);
345               goto out;
346             }
347         }
348       last_was_cr = (c == 0x0d);
349     }
350
351  out:
352   if (out_line_length != NULL)
353     *out_line_length = str->len;
354   return g_string_free (str, FALSE);
355
356  fail:
357   g_assert (error == NULL || *error != NULL);
358   g_string_free (str, TRUE);
359   return NULL;
360 }
361
362 /* ---------------------------------------------------------------------------------------------------- */
363
364 static void
365 append_nibble (GString *s, gint val)
366 {
367   g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
368 }
369
370 static gchar *
371 hexdecode (const gchar  *str,
372            gsize        *out_len,
373            GError      **error)
374 {
375   gchar *ret;
376   GString *s;
377   guint n;
378
379   ret = NULL;
380   s = g_string_new (NULL);
381
382   for (n = 0; str[n] != '\0'; n += 2)
383     {
384       gint upper_nibble;
385       gint lower_nibble;
386       guint value;
387
388       upper_nibble = g_ascii_xdigit_value (str[n]);
389       lower_nibble = g_ascii_xdigit_value (str[n + 1]);
390       if (upper_nibble == -1 || lower_nibble == -1)
391         {
392           g_set_error (error,
393                        G_IO_ERROR,
394                        G_IO_ERROR_FAILED,
395                        "Error hexdecoding string `%s' around position %d",
396                        str, n);
397           goto out;
398         }
399       value = (upper_nibble<<4) | lower_nibble;
400       g_string_append_c (s, value);
401     }
402
403   ret = g_string_free (s, FALSE);
404   s = NULL;
405
406  out:
407   if (s != NULL)
408     g_string_free (s, TRUE);
409   return ret;
410 }
411
412 /* TODO: take len */
413 static gchar *
414 hexencode (const gchar *str)
415 {
416   guint n;
417   GString *s;
418
419   s = g_string_new (NULL);
420   for (n = 0; str[n] != '\0'; n++)
421     {
422       gint val;
423       gint upper_nibble;
424       gint lower_nibble;
425
426       val = ((const guchar *) str)[n];
427       upper_nibble = val >> 4;
428       lower_nibble = val & 0x0f;
429
430       append_nibble (s, upper_nibble);
431       append_nibble (s, lower_nibble);
432     }
433
434   return g_string_free (s, FALSE);
435 }
436
437 /* ---------------------------------------------------------------------------------------------------- */
438
439 static GDBusAuthMechanism *
440 client_choose_mech_and_send_initial_response (GDBusAuth           *auth,
441                                               GCredentials        *credentials_that_were_sent,
442                                               const gchar* const  *supported_auth_mechs,
443                                               GPtrArray           *attempted_auth_mechs,
444                                               GDataOutputStream   *dos,
445                                               GCancellable        *cancellable,
446                                               GError             **error)
447 {
448   GDBusAuthMechanism *mech;
449   GType auth_mech_to_use_gtype;
450   guint n;
451   guint m;
452   gchar *initial_response;
453   gsize initial_response_len;
454   gchar *encoded;
455   gchar *s;
456
457  again:
458   mech = NULL;
459
460   debug_print ("CLIENT: Trying to choose mechanism");
461
462   /* find an authentication mechanism to try, if any */
463   auth_mech_to_use_gtype = (GType) 0;
464   for (n = 0; supported_auth_mechs[n] != NULL; n++)
465     {
466       gboolean attempted_already;
467       attempted_already = FALSE;
468       for (m = 0; m < attempted_auth_mechs->len; m++)
469         {
470           if (g_strcmp0 (supported_auth_mechs[n], attempted_auth_mechs->pdata[m]) == 0)
471             {
472               attempted_already = TRUE;
473               break;
474             }
475         }
476       if (!attempted_already)
477         {
478           auth_mech_to_use_gtype = find_mech_by_name (auth, supported_auth_mechs[n]);
479           if (auth_mech_to_use_gtype != (GType) 0)
480             break;
481         }
482     }
483
484   if (auth_mech_to_use_gtype == (GType) 0)
485     {
486       guint n;
487       gchar *available;
488       GString *tried_str;
489
490       debug_print ("CLIENT: Exhausted all available mechanisms");
491
492       available = g_strjoinv (", ", (gchar **) supported_auth_mechs);
493
494       tried_str = g_string_new (NULL);
495       for (n = 0; n < attempted_auth_mechs->len; n++)
496         {
497           if (n > 0)
498             g_string_append (tried_str, ", ");
499           g_string_append (tried_str, attempted_auth_mechs->pdata[n]);
500         }
501       g_set_error (error,
502                    G_IO_ERROR,
503                    G_IO_ERROR_FAILED,
504                    _("Exhausted all available authentication mechanisms (tried: %s) (available: %s)"),
505                    tried_str->str,
506                    available);
507       g_string_free (tried_str, TRUE);
508       g_free (available);
509       goto out;
510     }
511
512   /* OK, decided on a mechanism - let's do this thing */
513   mech = g_object_new (auth_mech_to_use_gtype,
514                        "stream", auth->priv->stream,
515                        "credentials", credentials_that_were_sent,
516                        NULL);
517   debug_print ("CLIENT: Trying mechanism `%s'", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
518   g_ptr_array_add (attempted_auth_mechs, (gpointer) _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
519
520   /* the auth mechanism may not be supported
521    * (for example, EXTERNAL only works if credentials were exchanged)
522    */
523   if (!_g_dbus_auth_mechanism_is_supported (mech))
524     {
525       debug_print ("CLIENT: Mechanism `%s' says it is not supported", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
526       g_object_unref (mech);
527       mech = NULL;
528       goto again;
529     }
530
531   initial_response_len = -1;
532   initial_response = _g_dbus_auth_mechanism_client_initiate (mech,
533                                                              &initial_response_len);
534 #if 0
535   g_printerr ("using auth mechanism with name `%s' of type `%s' with initial response `%s'\n",
536               _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
537               g_type_name (G_TYPE_FROM_INSTANCE (mech)),
538               initial_response);
539 #endif
540   if (initial_response != NULL)
541     {
542       //g_printerr ("initial_response = `%s'\n", initial_response);
543       encoded = hexencode (initial_response);
544       s = g_strdup_printf ("AUTH %s %s\r\n",
545                            _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
546                            encoded);
547       g_free (initial_response);
548       g_free (encoded);
549     }
550   else
551     {
552       s = g_strdup_printf ("AUTH %s\r\n", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
553     }
554   debug_print ("CLIENT: writing `%s'", s);
555   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
556     {
557       g_object_unref (mech);
558       mech = NULL;
559       g_free (s);
560       goto out;
561     }
562   g_free (s);
563
564  out:
565   return mech;
566 }
567
568
569 /* ---------------------------------------------------------------------------------------------------- */
570
571 typedef enum
572 {
573   CLIENT_STATE_WAITING_FOR_DATA,
574   CLIENT_STATE_WAITING_FOR_OK,
575   CLIENT_STATE_WAITING_FOR_REJECT,
576   CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD
577 } ClientState;
578
579 gchar *
580 _g_dbus_auth_run_client (GDBusAuth     *auth,
581                          GDBusCapabilityFlags offered_capabilities,
582                          GDBusCapabilityFlags *out_negotiated_capabilities,
583                          GCancellable  *cancellable,
584                          GError       **error)
585 {
586   gchar *s;
587   GDataInputStream *dis;
588   GDataOutputStream *dos;
589   GCredentials *credentials;
590   gchar *ret_guid;
591   gchar *line;
592   gsize line_length;
593   gchar **supported_auth_mechs;
594   GPtrArray *attempted_auth_mechs;
595   GDBusAuthMechanism *mech;
596   ClientState state;
597   GDBusCapabilityFlags negotiated_capabilities;
598
599   debug_print ("CLIENT: initiating");
600
601   ret_guid = NULL;
602   supported_auth_mechs = NULL;
603   attempted_auth_mechs = g_ptr_array_new ();
604   mech = NULL;
605   negotiated_capabilities = 0;
606   credentials = NULL;
607
608   dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
609   dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
610
611   g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
612
613 #ifdef G_OS_UNIX
614   if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
615     {
616       credentials = g_credentials_new ();
617       if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
618                                                cancellable,
619                                                error))
620         goto out;
621     }
622   else
623     {
624       if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
625         goto out;
626     }
627 #else
628   if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
629     goto out;
630 #endif
631
632   if (credentials != NULL)
633     {
634       if (G_UNLIKELY (_g_dbus_debug_authentication ()))
635         {
636           s = g_credentials_to_string (credentials);
637           debug_print ("CLIENT: sent credentials `%s'", s);
638           g_free (s);
639         }
640     }
641   else
642     {
643       debug_print ("CLIENT: didn't send any credentials");
644     }
645
646   /* TODO: to reduce roundtrips, try to pick an auth mechanism to start with */
647
648   /* Get list of supported authentication mechanisms */
649   s = "AUTH\r\n";
650   debug_print ("CLIENT: writing `%s'", s);
651   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
652     goto out;
653   state = CLIENT_STATE_WAITING_FOR_REJECT;
654
655   while (TRUE)
656     {
657       switch (state)
658         {
659         case CLIENT_STATE_WAITING_FOR_REJECT:
660           debug_print ("CLIENT: WaitingForReject");
661           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
662           if (line == NULL)
663             goto out;
664           debug_print ("CLIENT: WaitingForReject, read '%s'", line);
665         foobar:
666           if (!g_str_has_prefix (line, "REJECTED "))
667             {
668               g_set_error (error,
669                            G_IO_ERROR,
670                            G_IO_ERROR_FAILED,
671                            "In WaitingForReject: Expected `REJECTED am1 am2 ... amN', got `%s'",
672                            line);
673               g_free (line);
674               goto out;
675             }
676           if (supported_auth_mechs == NULL)
677             {
678               supported_auth_mechs = g_strsplit (line + sizeof ("REJECTED ") - 1, " ", 0);
679 #if 0
680               for (n = 0; supported_auth_mechs != NULL && supported_auth_mechs[n] != NULL; n++)
681                 g_printerr ("supported_auth_mechs[%d] = `%s'\n", n, supported_auth_mechs[n]);
682 #endif
683             }
684           g_free (line);
685           mech = client_choose_mech_and_send_initial_response (auth,
686                                                                credentials,
687                                                                (const gchar* const *) supported_auth_mechs,
688                                                                attempted_auth_mechs,
689                                                                dos,
690                                                                cancellable,
691                                                                error);
692           if (mech == NULL)
693             goto out;
694           if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA)
695             state = CLIENT_STATE_WAITING_FOR_DATA;
696           else
697             state = CLIENT_STATE_WAITING_FOR_OK;
698           break;
699
700         case CLIENT_STATE_WAITING_FOR_OK:
701           debug_print ("CLIENT: WaitingForOK");
702           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
703           if (line == NULL)
704             goto out;
705           debug_print ("CLIENT: WaitingForOK, read `%s'", line);
706           if (g_str_has_prefix (line, "OK "))
707             {
708               if (!g_dbus_is_guid (line + 3))
709                 {
710                   g_set_error (error,
711                                G_IO_ERROR,
712                                G_IO_ERROR_FAILED,
713                                "Invalid OK response `%s'",
714                                line);
715                   g_free (line);
716                   goto out;
717                 }
718               ret_guid = g_strdup (line + 3);
719               g_free (line);
720
721               if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
722                 {
723                   s = "NEGOTIATE_UNIX_FD\r\n";
724                   debug_print ("CLIENT: writing `%s'", s);
725                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
726                     goto out;
727                   state = CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD;
728                 }
729               else
730                 {
731                   s = "BEGIN\r\n";
732                   debug_print ("CLIENT: writing `%s'", s);
733                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
734                     goto out;
735                   /* and we're done! */
736                   goto out;
737                 }
738             }
739           else if (g_str_has_prefix (line, "REJECTED "))
740             {
741               goto foobar;
742             }
743           else
744             {
745               /* TODO: handle other valid responses */
746               g_set_error (error,
747                            G_IO_ERROR,
748                            G_IO_ERROR_FAILED,
749                            "In WaitingForOk: unexpected response `%s'",
750                            line);
751               g_free (line);
752               goto out;
753             }
754           break;
755
756         case CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD:
757           debug_print ("CLIENT: WaitingForAgreeUnixFD");
758           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
759           if (line == NULL)
760             goto out;
761           debug_print ("CLIENT: WaitingForAgreeUnixFD, read=`%s'", line);
762           if (g_strcmp0 (line, "AGREE_UNIX_FD") == 0)
763             {
764               negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
765               s = "BEGIN\r\n";
766               debug_print ("CLIENT: writing `%s'", s);
767               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
768                 goto out;
769               /* and we're done! */
770               goto out;
771             }
772           else if (g_str_has_prefix (line, "ERROR") && (line[5] == 0 || g_ascii_isspace (line[5])))
773             {
774               //g_strstrip (line + 5); g_debug ("bah, no unix_fd: `%s'", line + 5);
775               g_free (line);
776               s = "BEGIN\r\n";
777               debug_print ("CLIENT: writing `%s'", s);
778               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
779                 goto out;
780               /* and we're done! */
781               goto out;
782             }
783           else
784             {
785               /* TODO: handle other valid responses */
786               g_set_error (error,
787                            G_IO_ERROR,
788                            G_IO_ERROR_FAILED,
789                            "In WaitingForAgreeUnixFd: unexpected response `%s'",
790                            line);
791               g_free (line);
792               goto out;
793             }
794           break;
795
796         case CLIENT_STATE_WAITING_FOR_DATA:
797           debug_print ("CLIENT: WaitingForData");
798           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
799           if (line == NULL)
800             goto out;
801           debug_print ("CLIENT: WaitingForData, read=`%s'", line);
802           if (g_str_has_prefix (line, "DATA "))
803             {
804               gchar *encoded;
805               gchar *decoded_data;
806               gsize decoded_data_len;
807
808               encoded = g_strdup (line + 5);
809               g_free (line);
810               g_strstrip (encoded);
811               decoded_data = hexdecode (encoded, &decoded_data_len, error);
812               g_free (encoded);
813               if (decoded_data == NULL)
814                 {
815                   g_prefix_error (error, "DATA response is malformed: ");
816                   /* invalid encoding, disconnect! */
817                   goto out;
818                 }
819               _g_dbus_auth_mechanism_client_data_receive (mech, decoded_data, decoded_data_len);
820               g_free (decoded_data);
821
822               if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND)
823                 {
824                   gchar *data;
825                   gsize data_len;
826                   gchar *encoded_data;
827                   data = _g_dbus_auth_mechanism_client_data_send (mech, &data_len);
828                   encoded_data = hexencode (data);
829                   s = g_strdup_printf ("DATA %s\r\n", encoded_data);
830                   g_free (encoded_data);
831                   g_free (data);
832                   debug_print ("CLIENT: writing `%s'", s);
833                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
834                     {
835                       g_free (s);
836                       goto out;
837                     }
838                   g_free (s);
839                 }
840               state = CLIENT_STATE_WAITING_FOR_OK;
841             }
842           else
843             {
844               g_set_error (error,
845                            G_IO_ERROR,
846                            G_IO_ERROR_FAILED,
847                            "In WaitingForData: unexpected response `%s'",
848                            line);
849               g_free (line);
850               goto out;
851             }
852           break;
853
854         default:
855           g_assert_not_reached ();
856           break;
857         }
858
859     }; /* main authentication client loop */
860
861  out:
862   if (mech != NULL)
863     g_object_unref (mech);
864   g_ptr_array_unref (attempted_auth_mechs);
865   g_strfreev (supported_auth_mechs);
866   g_object_ref (dis);
867   g_object_ref (dos);
868
869   /* ensure return value is NULL if error is set */
870   if (error != NULL && *error != NULL)
871     {
872       g_free (ret_guid);
873       ret_guid = NULL;
874     }
875
876   if (ret_guid != NULL)
877     {
878       if (out_negotiated_capabilities != NULL)
879         *out_negotiated_capabilities = negotiated_capabilities;
880     }
881
882   if (credentials != NULL)
883     g_object_unref (credentials);
884
885   debug_print ("CLIENT: Done, authenticated=%d", ret_guid != NULL);
886
887   return ret_guid;
888 }
889
890 /* ---------------------------------------------------------------------------------------------------- */
891
892 static gchar *
893 get_auth_mechanisms (GDBusAuth     *auth,
894                      gboolean       allow_anonymous,
895                      const gchar   *prefix,
896                      const gchar   *suffix,
897                      const gchar   *separator)
898 {
899   GList *l;
900   GString *str;
901   gboolean need_sep;
902
903   str = g_string_new (prefix);
904   need_sep = FALSE;
905   for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
906     {
907       Mechanism *m = l->data;
908
909       if (!allow_anonymous && g_strcmp0 (m->name, "ANONYMOUS") == 0)
910         continue;
911
912       if (need_sep)
913         g_string_append (str, separator);
914       g_string_append (str, m->name);
915       need_sep = TRUE;
916     }
917
918   g_string_append (str, suffix);
919   return g_string_free (str, FALSE);
920 }
921
922
923 typedef enum
924 {
925   SERVER_STATE_WAITING_FOR_AUTH,
926   SERVER_STATE_WAITING_FOR_DATA,
927   SERVER_STATE_WAITING_FOR_BEGIN
928 } ServerState;
929
930 gboolean
931 _g_dbus_auth_run_server (GDBusAuth              *auth,
932                          GDBusAuthObserver      *observer,
933                          const gchar            *guid,
934                          gboolean                allow_anonymous,
935                          GDBusCapabilityFlags    offered_capabilities,
936                          GDBusCapabilityFlags   *out_negotiated_capabilities,
937                          GCredentials          **out_received_credentials,
938                          GCancellable           *cancellable,
939                          GError                **error)
940 {
941   gboolean ret;
942   ServerState state;
943   GDataInputStream *dis;
944   GDataOutputStream *dos;
945   GError *local_error;
946   guchar byte;
947   gchar *line;
948   gsize line_length;
949   GDBusAuthMechanism *mech;
950   gchar *s;
951   GDBusCapabilityFlags negotiated_capabilities;
952   GCredentials *credentials;
953
954   debug_print ("SERVER: initiating");
955
956   ret = FALSE;
957   dis = NULL;
958   dos = NULL;
959   mech = NULL;
960   negotiated_capabilities = 0;
961   credentials = NULL;
962
963   if (!g_dbus_is_guid (guid))
964     {
965       g_set_error (error,
966                    G_IO_ERROR,
967                    G_IO_ERROR_FAILED,
968                    "The given guid `%s' is not valid",
969                    guid);
970       goto out;
971     }
972
973   dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
974   dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
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_ref (dis);
1328   if (dis != NULL)
1329     g_object_ref (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"