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