Cleanups
[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 <sys/types.h>
26 #include <sys/socket.h>
27
28 #include "gdbusauth.h"
29
30 #include "gdbusauthmechanismanon.h"
31 #include "gdbusauthmechanismexternal.h"
32 #include "gdbusauthmechanismsha1.h"
33 #include "gdbusauthobserver.h"
34
35 #include "gdbuserror.h"
36 #include "gdbusutils.h"
37 #include "gioenumtypes.h"
38 #include "gcredentials.h"
39 #include "gdbusprivate.h"
40
41 #ifdef G_OS_UNIX
42 #include "gunixconnection.h"
43 #include "gunixcredentialsmessage.h"
44 #endif
45
46 #include "glibintl.h"
47 #include "gioalias.h"
48
49 #define DEBUG_ENABLED 0
50
51 static void
52 debug_print (const gchar *message, ...)
53 {
54 #if DEBUG_ENABLED
55   if (G_UNLIKELY (_g_dbus_debug_authentication ()))
56     {
57       gchar *s;
58       GString *str;
59       va_list var_args;
60       guint n;
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 #endif
81 }
82
83 typedef struct
84 {
85   const gchar *name;
86   gint priority;
87   GType gtype;
88 } Mechanism;
89
90 static void mechanism_free (Mechanism *m);
91
92 struct _GDBusAuthPrivate
93 {
94   GIOStream *stream;
95
96   /* A list of available Mechanism, sorted according to priority  */
97   GList *available_mechanisms;
98 };
99
100 enum
101 {
102   PROP_0,
103   PROP_STREAM
104 };
105
106 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
107
108 /* ---------------------------------------------------------------------------------------------------- */
109
110 static void
111 _g_dbus_auth_finalize (GObject *object)
112 {
113   GDBusAuth *auth = G_DBUS_AUTH (object);
114
115   if (auth->priv->stream != NULL)
116     g_object_unref (auth->priv->stream);
117   g_list_foreach (auth->priv->available_mechanisms, (GFunc) mechanism_free, NULL);
118   g_list_free (auth->priv->available_mechanisms);
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                GType      mechanism_type)
199 {
200   Mechanism *m;
201
202   m = g_new0 (Mechanism, 1);
203   m->name = _g_dbus_auth_mechanism_get_name (mechanism_type);
204   m->priority = _g_dbus_auth_mechanism_get_priority (mechanism_type);
205   m->gtype = mechanism_type;
206
207   auth->priv->available_mechanisms = g_list_prepend (auth->priv->available_mechanisms, m);
208 }
209
210 static gint
211 mech_compare_func (Mechanism *a, Mechanism *b)
212 {
213   gint ret;
214   /* ensure deterministic order */
215   ret = b->priority - a->priority;
216   if (ret == 0)
217     ret = g_strcmp0 (b->name, a->name);
218   return ret;
219 }
220
221 static void
222 _g_dbus_auth_init (GDBusAuth *auth)
223 {
224   auth->priv = G_TYPE_INSTANCE_GET_PRIVATE (auth, G_TYPE_DBUS_AUTH, GDBusAuthPrivate);
225
226   /* TODO: trawl extension points */
227   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_ANON);
228   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_SHA1);
229   add_mechanism (auth, G_TYPE_DBUS_AUTH_MECHANISM_EXTERNAL);
230
231   auth->priv->available_mechanisms = g_list_sort (auth->priv->available_mechanisms,
232                                                   (GCompareFunc) mech_compare_func);
233 }
234
235 static GType
236 find_mech_by_name (GDBusAuth *auth,
237                    const gchar *name)
238 {
239   GType ret;
240   GList *l;
241
242   ret = (GType) 0;
243
244   for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
245     {
246       Mechanism *m = l->data;
247       if (g_strcmp0 (name, m->name) == 0)
248         {
249           ret = m->gtype;
250           goto out;
251         }
252     }
253
254  out:
255   return ret;
256 }
257
258 GDBusAuth  *
259 _g_dbus_auth_new (GIOStream *stream)
260 {
261   return g_object_new (G_TYPE_DBUS_AUTH,
262                        "stream", stream,
263                        NULL);
264 }
265
266 /* ---------------------------------------------------------------------------------------------------- */
267 /* like g_data_input_stream_read_line() but sets error if there's no content to read */
268 static gchar *
269 _my_g_data_input_stream_read_line (GDataInputStream  *dis,
270                                    gsize             *out_line_length,
271                                    GCancellable      *cancellable,
272                                    GError           **error)
273 {
274   gchar *ret;
275
276   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
277
278   ret = g_data_input_stream_read_line (dis,
279                                        out_line_length,
280                                        cancellable,
281                                        error);
282   if (ret == NULL && error != NULL && *error == NULL)
283     {
284       g_set_error_literal (error,
285                            G_IO_ERROR,
286                            G_IO_ERROR_FAILED,
287                            _("Unexpected lack of content trying to read a line"));
288     }
289
290   return ret;
291 }
292
293 /* This function is to avoid situations like this
294  *
295  * BEGIN\r\nl\0\0\1...
296  *
297  * e.g. where we read into the first D-Bus message while waiting for
298  * the final line from the client (TODO: file bug against gio for
299  * this)
300  */
301 static gchar *
302 _my_g_input_stream_read_line_safe (GInputStream  *i,
303                                    gsize         *out_line_length,
304                                    GCancellable  *cancellable,
305                                    GError       **error)
306 {
307   GString *str;
308   gchar c;
309   gssize num_read;
310   gboolean last_was_cr;
311
312   str = g_string_new (NULL);
313
314   last_was_cr = FALSE;
315   while (TRUE)
316     {
317       num_read = g_input_stream_read (i,
318                                       &c,
319                                       1,
320                                       cancellable,
321                                       error);
322       if (num_read == -1)
323         goto fail;
324       if (num_read == 0)
325         {
326           if (error != NULL && *error == NULL)
327             {
328               g_set_error_literal (error,
329                                    G_IO_ERROR,
330                                    G_IO_ERROR_FAILED,
331                                    _("Unexpected lack of content trying to (safely) read a line"));
332             }
333           goto fail;
334         }
335
336       g_string_append_c (str, (gint) c);
337       if (last_was_cr)
338         {
339           if (c == 0x0a)
340             {
341               g_assert (str->len >= 2);
342               g_string_set_size (str, str->len - 2);
343               goto out;
344             }
345         }
346       last_was_cr = (c == 0x0d);
347     }
348
349  out:
350   if (out_line_length != NULL)
351     *out_line_length = str->len;
352   return g_string_free (str, FALSE);
353
354  fail:
355   g_assert (error == NULL || *error != NULL);
356   g_string_free (str, TRUE);
357   return NULL;
358 }
359
360 /* ---------------------------------------------------------------------------------------------------- */
361
362 static void
363 append_nibble (GString *s, gint val)
364 {
365   g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
366 }
367
368 static gchar *
369 hexdecode (const gchar  *str,
370            gsize        *out_len,
371            GError      **error)
372 {
373   gchar *ret;
374   GString *s;
375   guint n;
376
377   ret = NULL;
378   s = g_string_new (NULL);
379
380   for (n = 0; str[n] != '\0'; n += 2)
381     {
382       gint upper_nibble;
383       gint lower_nibble;
384       guint value;
385
386       upper_nibble = g_ascii_xdigit_value (str[n]);
387       lower_nibble = g_ascii_xdigit_value (str[n + 1]);
388       if (upper_nibble == -1 || lower_nibble == -1)
389         {
390           g_set_error (error,
391                        G_IO_ERROR,
392                        G_IO_ERROR_FAILED,
393                        "Error hexdecoding string `%s' around position %d",
394                        str, n);
395           goto out;
396         }
397       value = (upper_nibble<<4) | lower_nibble;
398       g_string_append_c (s, value);
399     }
400
401   ret = g_string_free (s, FALSE);
402   s = NULL;
403
404  out:
405   if (s != NULL)
406     g_string_free (s, TRUE);
407   return ret;
408 }
409
410 /* TODO: take len */
411 static gchar *
412 hexencode (const gchar *str)
413 {
414   guint n;
415   GString *s;
416
417   s = g_string_new (NULL);
418   for (n = 0; str[n] != '\0'; n++)
419     {
420       gint val;
421       gint upper_nibble;
422       gint lower_nibble;
423
424       val = ((const guchar *) str)[n];
425       upper_nibble = val >> 4;
426       lower_nibble = val & 0x0f;
427
428       append_nibble (s, upper_nibble);
429       append_nibble (s, lower_nibble);
430     }
431
432   return g_string_free (s, FALSE);
433 }
434
435 /* ---------------------------------------------------------------------------------------------------- */
436
437 static GDBusAuthMechanism *
438 client_choose_mech_and_send_initial_response (GDBusAuth           *auth,
439                                               GCredentials        *credentials_that_were_sent,
440                                               const gchar* const  *supported_auth_mechs,
441                                               GPtrArray           *attempted_auth_mechs,
442                                               GDataOutputStream   *dos,
443                                               GCancellable        *cancellable,
444                                               GError             **error)
445 {
446   GDBusAuthMechanism *mech;
447   GType auth_mech_to_use_gtype;
448   guint n;
449   guint m;
450   gchar *initial_response;
451   gsize initial_response_len;
452   gchar *encoded;
453   gchar *s;
454
455  again:
456   mech = NULL;
457
458   debug_print ("CLIENT: Trying to choose mechanism");
459
460   /* find an authentication mechanism to try, if any */
461   auth_mech_to_use_gtype = (GType) 0;
462   for (n = 0; supported_auth_mechs[n] != NULL; n++)
463     {
464       gboolean attempted_already;
465       attempted_already = FALSE;
466       for (m = 0; m < attempted_auth_mechs->len; m++)
467         {
468           if (g_strcmp0 (supported_auth_mechs[n], attempted_auth_mechs->pdata[m]) == 0)
469             {
470               attempted_already = TRUE;
471               break;
472             }
473         }
474       if (!attempted_already)
475         {
476           auth_mech_to_use_gtype = find_mech_by_name (auth, supported_auth_mechs[n]);
477           if (auth_mech_to_use_gtype != (GType) 0)
478             break;
479         }
480     }
481
482   if (auth_mech_to_use_gtype == (GType) 0)
483     {
484       guint n;
485       gchar *available;
486       GString *tried_str;
487
488       debug_print ("CLIENT: Exhausted all available mechanisms");
489
490       available = g_strjoinv (", ", (gchar **) supported_auth_mechs);
491
492       tried_str = g_string_new (NULL);
493       for (n = 0; n < attempted_auth_mechs->len; n++)
494         {
495           if (n > 0)
496             g_string_append (tried_str, ", ");
497           g_string_append (tried_str, attempted_auth_mechs->pdata[n]);
498         }
499       g_set_error (error,
500                    G_IO_ERROR,
501                    G_IO_ERROR_FAILED,
502                    _("Exhausted all available authentication mechanisms (tried: %s) (available: %s)"),
503                    tried_str->str,
504                    available);
505       g_string_free (tried_str, TRUE);
506       g_free (available);
507       goto out;
508     }
509
510   /* OK, decided on a mechanism - let's do this thing */
511   mech = g_object_new (auth_mech_to_use_gtype,
512                        "stream", auth->priv->stream,
513                        "credentials", credentials_that_were_sent,
514                        NULL);
515   debug_print ("CLIENT: Trying mechanism `%s'", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
516   g_ptr_array_add (attempted_auth_mechs, (gpointer) _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
517
518   /* the auth mechanism may not be supported
519    * (for example, EXTERNAL only works if credentials were exchanged)
520    */
521   if (!_g_dbus_auth_mechanism_is_supported (mech))
522     {
523       debug_print ("CLIENT: Mechanism `%s' says it is not supported", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
524       g_object_unref (mech);
525       mech = NULL;
526       goto again;
527     }
528
529   initial_response_len = -1;
530   initial_response = _g_dbus_auth_mechanism_client_initiate (mech,
531                                                              &initial_response_len);
532 #if 0
533   g_printerr ("using auth mechanism with name `%s' of type `%s' with initial response `%s'\n",
534               _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
535               g_type_name (G_TYPE_FROM_INSTANCE (mech)),
536               initial_response);
537 #endif
538   if (initial_response != NULL)
539     {
540       //g_printerr ("initial_response = `%s'\n", initial_response);
541       encoded = hexencode (initial_response);
542       s = g_strdup_printf ("AUTH %s %s\r\n",
543                            _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype),
544                            encoded);
545       g_free (initial_response);
546       g_free (encoded);
547     }
548   else
549     {
550       s = g_strdup_printf ("AUTH %s\r\n", _g_dbus_auth_mechanism_get_name (auth_mech_to_use_gtype));
551     }
552   debug_print ("CLIENT: writing `%s'", s);
553   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
554     {
555       g_object_unref (mech);
556       mech = NULL;
557       g_free (s);
558       goto out;
559     }
560   g_free (s);
561
562  out:
563   return mech;
564 }
565
566
567 /* ---------------------------------------------------------------------------------------------------- */
568
569 typedef enum
570 {
571   CLIENT_STATE_WAITING_FOR_DATA,
572   CLIENT_STATE_WAITING_FOR_OK,
573   CLIENT_STATE_WAITING_FOR_REJECT,
574   CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD
575 } ClientState;
576
577 gchar *
578 _g_dbus_auth_run_client (GDBusAuth     *auth,
579                          GDBusCapabilityFlags offered_capabilities,
580                          GDBusCapabilityFlags *out_negotiated_capabilities,
581                          GCancellable  *cancellable,
582                          GError       **error)
583 {
584   gchar *s;
585   GDataInputStream *dis;
586   GDataOutputStream *dos;
587   GCredentials *credentials;
588   gchar *ret_guid;
589   gchar *line;
590   gsize line_length;
591   gchar **supported_auth_mechs;
592   GPtrArray *attempted_auth_mechs;
593   GDBusAuthMechanism *mech;
594   ClientState state;
595   GDBusCapabilityFlags negotiated_capabilities;
596
597   debug_print ("CLIENT: initiating");
598
599   ret_guid = NULL;
600   supported_auth_mechs = NULL;
601   attempted_auth_mechs = g_ptr_array_new ();
602   mech = NULL;
603   negotiated_capabilities = 0;
604   credentials = NULL;
605
606   dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
607   dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
608
609   g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
610
611 #ifdef G_OS_UNIX
612   if (G_IS_UNIX_CONNECTION (auth->priv->stream) && g_unix_credentials_message_is_supported ())
613     {
614       credentials = g_credentials_new ();
615       if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
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 roundtrips, 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_authorize_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::authorize-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"