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