gio/tests/file: skip the file monitor tests if using GPollFileMonitor
[platform/upstream/glib.git] / gio / gdbusauth.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include "gdbusauth.h"
26
27 #include "gdbusauthmechanismanon.h"
28 #include "gdbusauthmechanismexternal.h"
29 #include "gdbusauthmechanismsha1.h"
30 #include "gdbusauthobserver.h"
31
32 #include "gdbuserror.h"
33 #include "gdbusutils.h"
34 #include "gioenumtypes.h"
35 #include "gcredentials.h"
36 #include "gdbusprivate.h"
37 #include "giostream.h"
38 #include "gdatainputstream.h"
39 #include "gdataoutputstream.h"
40
41 #ifdef G_OS_UNIX
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include "gunixconnection.h"
45 #include "gunixcredentialsmessage.h"
46 #endif
47
48 #include "glibintl.h"
49
50 static void
51 debug_print (const gchar *message, ...)
52 {
53   if (G_UNLIKELY (_g_dbus_debug_authentication ()))
54     {
55       gchar *s;
56       GString *str;
57       va_list var_args;
58       guint n;
59
60       _g_dbus_debug_print_lock ();
61
62       va_start (var_args, message);
63       s = g_strdup_vprintf (message, var_args);
64       va_end (var_args);
65
66       str = g_string_new (NULL);
67       for (n = 0; s[n] != '\0'; n++)
68         {
69           if (G_UNLIKELY (s[n] == '\r'))
70             g_string_append (str, "\\r");
71           else if (G_UNLIKELY (s[n] == '\n'))
72             g_string_append (str, "\\n");
73           else
74             g_string_append_c (str, s[n]);
75         }
76       g_print ("GDBus-debug:Auth: %s\n", str->str);
77       g_string_free (str, TRUE);
78       g_free (s);
79
80       _g_dbus_debug_print_unlock ();
81     }
82 }
83
84 typedef struct
85 {
86   const gchar *name;
87   gint priority;
88   GType gtype;
89 } Mechanism;
90
91 static void mechanism_free (Mechanism *m);
92
93 struct _GDBusAuthPrivate
94 {
95   GIOStream *stream;
96
97   /* A list of available Mechanism, sorted according to priority  */
98   GList *available_mechanisms;
99 };
100
101 enum
102 {
103   PROP_0,
104   PROP_STREAM
105 };
106
107 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
108
109 /* ---------------------------------------------------------------------------------------------------- */
110
111 static void
112 _g_dbus_auth_finalize (GObject *object)
113 {
114   GDBusAuth *auth = G_DBUS_AUTH (object);
115
116   if (auth->priv->stream != NULL)
117     g_object_unref (auth->priv->stream);
118   g_list_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   if (local_error != NULL)
1034     {
1035       g_propagate_error (error, local_error);
1036       goto out;
1037     }
1038 #endif
1039   if (credentials != NULL)
1040     {
1041       if (G_UNLIKELY (_g_dbus_debug_authentication ()))
1042         {
1043           s = g_credentials_to_string (credentials);
1044           debug_print ("SERVER: received credentials `%s'", s);
1045           g_free (s);
1046         }
1047     }
1048   else
1049     {
1050       debug_print ("SERVER: didn't receive any credentials");
1051     }
1052
1053   state = SERVER_STATE_WAITING_FOR_AUTH;
1054   while (TRUE)
1055     {
1056       switch (state)
1057         {
1058         case SERVER_STATE_WAITING_FOR_AUTH:
1059           debug_print ("SERVER: WaitingForAuth");
1060           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1061           debug_print ("SERVER: WaitingForAuth, read `%s'", line);
1062           if (line == NULL)
1063             goto out;
1064           if (g_strcmp0 (line, "AUTH") == 0)
1065             {
1066               s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1067               debug_print ("SERVER: writing `%s'", s);
1068               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1069                 {
1070                   g_free (s);
1071                   goto out;
1072                 }
1073               g_free (s);
1074               g_free (line);
1075             }
1076           else if (g_str_has_prefix (line, "AUTH "))
1077             {
1078               gchar **tokens;
1079               const gchar *encoded;
1080               const gchar *mech_name;
1081               GType auth_mech_to_use_gtype;
1082
1083               tokens = g_strsplit (line, " ", 0);
1084               g_free (line);
1085
1086               switch (g_strv_length (tokens))
1087                 {
1088                 case 2:
1089                   /* no initial response */
1090                   mech_name = tokens[1];
1091                   encoded = NULL;
1092                   break;
1093
1094                 case 3:
1095                   /* initial response */
1096                   mech_name = tokens[1];
1097                   encoded = tokens[2];
1098                   break;
1099
1100                 default:
1101                   g_set_error (error,
1102                                G_IO_ERROR,
1103                                G_IO_ERROR_FAILED,
1104                                "Unexpected line `%s' while in WaitingForAuth state",
1105                                line);
1106                   g_strfreev (tokens);
1107                   goto out;
1108                 }
1109
1110               /* TODO: record that the client has attempted to use this mechanism */
1111               //g_debug ("client is trying `%s'", mech_name);
1112
1113               auth_mech_to_use_gtype = find_mech_by_name (auth, mech_name);
1114               if ((auth_mech_to_use_gtype == (GType) 0) ||
1115                   (!allow_anonymous && g_strcmp0 (mech_name, "ANONYMOUS") == 0))
1116                 {
1117                   /* We don't support this auth mechanism */
1118                   g_strfreev (tokens);
1119                   s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1120                   debug_print ("SERVER: writing `%s'", s);
1121                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1122                     {
1123                       g_free (s);
1124                       goto out;
1125                     }
1126                   g_free (s);
1127
1128                   /* stay in WAITING FOR AUTH */
1129                   state = SERVER_STATE_WAITING_FOR_AUTH;
1130                 }
1131               else
1132                 {
1133                   gchar *initial_response;
1134                   gsize initial_response_len;
1135
1136                   mech = g_object_new (auth_mech_to_use_gtype,
1137                                        "stream", auth->priv->stream,
1138                                        "credentials", credentials,
1139                                        NULL);
1140
1141                   initial_response = NULL;
1142                   initial_response_len = 0;
1143                   if (encoded != NULL)
1144                     {
1145                       initial_response = hexdecode (encoded, &initial_response_len, error);
1146                       if (initial_response == NULL)
1147                         {
1148                           g_prefix_error (error, "Initial response is malformed: ");
1149                           /* invalid encoding, disconnect! */
1150                           g_strfreev (tokens);
1151                           goto out;
1152                         }
1153                     }
1154
1155                   _g_dbus_auth_mechanism_server_initiate (mech,
1156                                                           initial_response,
1157                                                           initial_response_len);
1158                   g_free (initial_response);
1159                   g_strfreev (tokens);
1160
1161                 change_state:
1162                   switch (_g_dbus_auth_mechanism_server_get_state (mech))
1163                     {
1164                     case G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED:
1165                       if (observer != NULL &&
1166                           !g_dbus_auth_observer_authorize_authenticated_peer (observer,
1167                                                                               auth->priv->stream,
1168                                                                               credentials))
1169                         {
1170                           /* disconnect */
1171                           g_set_error_literal (error,
1172                                                G_IO_ERROR,
1173                                                G_IO_ERROR_FAILED,
1174                                                _("Cancelled via GDBusAuthObserver::authorize-authenticated-peer"));
1175                           goto out;
1176                         }
1177                       else
1178                         {
1179                           s = g_strdup_printf ("OK %s\r\n", guid);
1180                           debug_print ("SERVER: writing `%s'", s);
1181                           if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1182                             {
1183                               g_free (s);
1184                               goto out;
1185                             }
1186                           g_free (s);
1187                           state = SERVER_STATE_WAITING_FOR_BEGIN;
1188                         }
1189                       break;
1190
1191                     case G_DBUS_AUTH_MECHANISM_STATE_REJECTED:
1192                       s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1193                       debug_print ("SERVER: writing `%s'", s);
1194                       if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1195                         {
1196                           g_free (s);
1197                           goto out;
1198                         }
1199                       g_free (s);
1200                       state = SERVER_STATE_WAITING_FOR_AUTH;
1201                       break;
1202
1203                     case G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA:
1204                       state = SERVER_STATE_WAITING_FOR_DATA;
1205                       break;
1206
1207                     case G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND:
1208                       {
1209                         gchar *data;
1210                         gsize data_len;
1211                         gchar *encoded_data;
1212                         data = _g_dbus_auth_mechanism_server_data_send (mech, &data_len);
1213                         encoded_data = hexencode (data);
1214                         s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1215                         g_free (encoded_data);
1216                         g_free (data);
1217                         debug_print ("SERVER: writing `%s'", s);
1218                         if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1219                           {
1220                             g_free (s);
1221                             goto out;
1222                           }
1223                         g_free (s);
1224                       }
1225                       goto change_state;
1226                       break;
1227
1228                     default:
1229                       /* TODO */
1230                       g_assert_not_reached ();
1231                       break;
1232                     }
1233                 }
1234             }
1235           else
1236             {
1237               g_set_error (error,
1238                            G_IO_ERROR,
1239                            G_IO_ERROR_FAILED,
1240                            "Unexpected line `%s' while in WaitingForAuth state",
1241                            line);
1242               g_free (line);
1243               goto out;
1244             }
1245           break;
1246
1247         case SERVER_STATE_WAITING_FOR_DATA:
1248           debug_print ("SERVER: WaitingForData");
1249           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1250           debug_print ("SERVER: WaitingForData, read `%s'", line);
1251           if (line == NULL)
1252             goto out;
1253           if (g_str_has_prefix (line, "DATA "))
1254             {
1255               gchar *encoded;
1256               gchar *decoded_data;
1257               gsize decoded_data_len = 0;
1258
1259               encoded = g_strdup (line + 5);
1260               g_free (line);
1261               g_strstrip (encoded);
1262               decoded_data = hexdecode (encoded, &decoded_data_len, error);
1263               g_free (encoded);
1264               if (decoded_data == NULL)
1265                 {
1266                   g_prefix_error (error, "DATA response is malformed: ");
1267                   /* invalid encoding, disconnect! */
1268                   goto out;
1269                 }
1270               _g_dbus_auth_mechanism_server_data_receive (mech, decoded_data, decoded_data_len);
1271               g_free (decoded_data);
1272               /* oh man, this goto-crap is so ugly.. really need to rewrite the state machine */
1273               goto change_state;
1274             }
1275           else
1276             {
1277               g_set_error (error,
1278                            G_IO_ERROR,
1279                            G_IO_ERROR_FAILED,
1280                            "Unexpected line `%s' while in WaitingForData state",
1281                            line);
1282               g_free (line);
1283             }
1284           goto out;
1285
1286         case SERVER_STATE_WAITING_FOR_BEGIN:
1287           debug_print ("SERVER: WaitingForBegin");
1288           /* Use extremely slow (but reliable) line reader - this basically
1289            * does a recvfrom() system call per character
1290            *
1291            * (the problem with using GDataInputStream's read_line is that because of
1292            * buffering it might start reading into the first D-Bus message that
1293            * appears after "BEGIN\r\n"....)
1294            */
1295           line = _my_g_input_stream_read_line_safe (g_io_stream_get_input_stream (auth->priv->stream),
1296                                                     &line_length,
1297                                                     cancellable,
1298                                                     error);
1299           debug_print ("SERVER: WaitingForBegin, read `%s'", line);
1300           if (line == NULL)
1301             goto out;
1302           if (g_strcmp0 (line, "BEGIN") == 0)
1303             {
1304               /* YAY, done! */
1305               ret = TRUE;
1306               g_free (line);
1307               goto out;
1308             }
1309           else if (g_strcmp0 (line, "NEGOTIATE_UNIX_FD") == 0)
1310             {
1311               g_free (line);
1312               if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
1313                 {
1314                   negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1315                   s = "AGREE_UNIX_FD\r\n";
1316                   debug_print ("SERVER: writing `%s'", s);
1317                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1318                     goto out;
1319                 }
1320               else
1321                 {
1322                   s = "ERROR \"fd passing not offered\"\r\n";
1323                   debug_print ("SERVER: writing `%s'", s);
1324                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1325                     goto out;
1326                 }
1327             }
1328           else
1329             {
1330               g_debug ("Unexpected line `%s' while in WaitingForBegin state", line);
1331               g_free (line);
1332               s = "ERROR \"Unknown Command\"\r\n";
1333               debug_print ("SERVER: writing `%s'", s);
1334               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1335                 goto out;
1336             }
1337           break;
1338
1339         default:
1340           g_assert_not_reached ();
1341           break;
1342         }
1343     }
1344
1345
1346   g_set_error_literal (error,
1347                        G_IO_ERROR,
1348                        G_IO_ERROR_FAILED,
1349                        "Not implemented (server)");
1350
1351  out:
1352   if (mech != NULL)
1353     g_object_unref (mech);
1354   if (dis != NULL)
1355     g_object_unref (dis);
1356   if (dos != NULL)
1357     g_object_unref (dos);
1358
1359   /* ensure return value is FALSE if error is set */
1360   if (error != NULL && *error != NULL)
1361     {
1362       ret = FALSE;
1363     }
1364
1365   if (ret)
1366     {
1367       if (out_negotiated_capabilities != NULL)
1368         *out_negotiated_capabilities = negotiated_capabilities;
1369       if (out_received_credentials != NULL)
1370         *out_received_credentials = credentials != NULL ? g_object_ref (credentials) : NULL;
1371     }
1372
1373   if (credentials != NULL)
1374     g_object_unref (credentials);
1375
1376   debug_print ("SERVER: Done, authenticated=%d", ret);
1377
1378   return ret;
1379 }
1380
1381 /* ---------------------------------------------------------------------------------------------------- */