gio/*: Use g_list_free_full() convenience function
[platform/upstream/glib.git] / gio / gdbusauth.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include "gdbusauth.h"
26
27 #include "gdbusauthmechanismanon.h"
28 #include "gdbusauthmechanismexternal.h"
29 #include "gdbusauthmechanismsha1.h"
30 #include "gdbusauthobserver.h"
31
32 #include "gdbuserror.h"
33 #include "gdbusutils.h"
34 #include "gioenumtypes.h"
35 #include "gcredentials.h"
36 #include "gdbusprivate.h"
37 #include "giostream.h"
38 #include "gdatainputstream.h"
39 #include "gdataoutputstream.h"
40
41 #ifdef G_OS_UNIX
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include "gunixconnection.h"
45 #include "gunixcredentialsmessage.h"
46 #endif
47
48 #include "glibintl.h"
49
50 static void
51 debug_print (const gchar *message, ...)
52 {
53   if (G_UNLIKELY (_g_dbus_debug_authentication ()))
54     {
55       gchar *s;
56       GString *str;
57       va_list var_args;
58       guint n;
59
60       _g_dbus_debug_print_lock ();
61
62       va_start (var_args, message);
63       s = g_strdup_vprintf (message, var_args);
64       va_end (var_args);
65
66       str = g_string_new (NULL);
67       for (n = 0; s[n] != '\0'; n++)
68         {
69           if (G_UNLIKELY (s[n] == '\r'))
70             g_string_append (str, "\\r");
71           else if (G_UNLIKELY (s[n] == '\n'))
72             g_string_append (str, "\\n");
73           else
74             g_string_append_c (str, s[n]);
75         }
76       g_print ("GDBus-debug:Auth: %s\n", str->str);
77       g_string_free (str, TRUE);
78       g_free (s);
79
80       _g_dbus_debug_print_unlock ();
81     }
82 }
83
84 typedef struct
85 {
86   const gchar *name;
87   gint priority;
88   GType gtype;
89 } Mechanism;
90
91 static void mechanism_free (Mechanism *m);
92
93 struct _GDBusAuthPrivate
94 {
95   GIOStream *stream;
96
97   /* A list of available Mechanism, sorted according to priority  */
98   GList *available_mechanisms;
99 };
100
101 enum
102 {
103   PROP_0,
104   PROP_STREAM
105 };
106
107 G_DEFINE_TYPE (GDBusAuth, _g_dbus_auth, G_TYPE_OBJECT);
108
109 /* ---------------------------------------------------------------------------------------------------- */
110
111 static void
112 _g_dbus_auth_finalize (GObject *object)
113 {
114   GDBusAuth *auth = G_DBUS_AUTH (object);
115
116   if (auth->priv->stream != NULL)
117     g_object_unref (auth->priv->stream);
118   g_list_free_full (auth->priv->available_mechanisms, (GDestroyNotify) mechanism_free);
119
120   if (G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize != NULL)
121     G_OBJECT_CLASS (_g_dbus_auth_parent_class)->finalize (object);
122 }
123
124 static void
125 _g_dbus_auth_get_property (GObject    *object,
126                            guint       prop_id,
127                            GValue     *value,
128                            GParamSpec *pspec)
129 {
130   GDBusAuth *auth = G_DBUS_AUTH (object);
131
132   switch (prop_id)
133     {
134     case PROP_STREAM:
135       g_value_set_object (value, auth->priv->stream);
136       break;
137
138     default:
139       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
140       break;
141     }
142 }
143
144 static void
145 _g_dbus_auth_set_property (GObject      *object,
146                            guint         prop_id,
147                            const GValue *value,
148                            GParamSpec   *pspec)
149 {
150   GDBusAuth *auth = G_DBUS_AUTH (object);
151
152   switch (prop_id)
153     {
154     case PROP_STREAM:
155       auth->priv->stream = g_value_dup_object (value);
156       break;
157
158     default:
159       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
160       break;
161     }
162 }
163
164 static void
165 _g_dbus_auth_class_init (GDBusAuthClass *klass)
166 {
167   GObjectClass *gobject_class;
168
169   g_type_class_add_private (klass, sizeof (GDBusAuthPrivate));
170
171   gobject_class = G_OBJECT_CLASS (klass);
172   gobject_class->get_property = _g_dbus_auth_get_property;
173   gobject_class->set_property = _g_dbus_auth_set_property;
174   gobject_class->finalize     = _g_dbus_auth_finalize;
175
176   g_object_class_install_property (gobject_class,
177                                    PROP_STREAM,
178                                    g_param_spec_object ("stream",
179                                                         P_("IO Stream"),
180                                                         P_("The underlying GIOStream used for I/O"),
181                                                         G_TYPE_IO_STREAM,
182                                                         G_PARAM_READABLE |
183                                                         G_PARAM_WRITABLE |
184                                                         G_PARAM_CONSTRUCT_ONLY |
185                                                         G_PARAM_STATIC_NAME |
186                                                         G_PARAM_STATIC_BLURB |
187                                                         G_PARAM_STATIC_NICK));
188 }
189
190 static void
191 mechanism_free (Mechanism *m)
192 {
193   g_free (m);
194 }
195
196 static void
197 add_mechanism (GDBusAuth *auth,
198                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   g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
609   g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
610
611   g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
612
613 #ifdef G_OS_UNIX
614   if (G_IS_UNIX_CONNECTION (auth->priv->stream))
615     {
616       credentials = g_credentials_new ();
617       if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (auth->priv->stream),
618                                                cancellable,
619                                                error))
620         goto out;
621     }
622   else
623     {
624       if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
625         goto out;
626     }
627 #else
628   if (!g_data_output_stream_put_byte (dos, '\0', cancellable, error))
629     goto out;
630 #endif
631
632   if (credentials != NULL)
633     {
634       if (G_UNLIKELY (_g_dbus_debug_authentication ()))
635         {
636           s = g_credentials_to_string (credentials);
637           debug_print ("CLIENT: sent credentials `%s'", s);
638           g_free (s);
639         }
640     }
641   else
642     {
643       debug_print ("CLIENT: didn't send any credentials");
644     }
645
646   /* TODO: to reduce roundtrips, try to pick an auth mechanism to start with */
647
648   /* Get list of supported authentication mechanisms */
649   s = "AUTH\r\n";
650   debug_print ("CLIENT: writing `%s'", s);
651   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
652     goto out;
653   state = CLIENT_STATE_WAITING_FOR_REJECT;
654
655   while (TRUE)
656     {
657       switch (state)
658         {
659         case CLIENT_STATE_WAITING_FOR_REJECT:
660           debug_print ("CLIENT: WaitingForReject");
661           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
662           if (line == NULL)
663             goto out;
664           debug_print ("CLIENT: WaitingForReject, read '%s'", line);
665
666         choose_mechanism:
667           if (!g_str_has_prefix (line, "REJECTED "))
668             {
669               g_set_error (error,
670                            G_IO_ERROR,
671                            G_IO_ERROR_FAILED,
672                            "In WaitingForReject: Expected `REJECTED am1 am2 ... amN', got `%s'",
673                            line);
674               g_free (line);
675               goto out;
676             }
677           if (supported_auth_mechs == NULL)
678             {
679               supported_auth_mechs = g_strsplit (line + sizeof ("REJECTED ") - 1, " ", 0);
680 #if 0
681               for (n = 0; supported_auth_mechs != NULL && supported_auth_mechs[n] != NULL; n++)
682                 g_printerr ("supported_auth_mechs[%d] = `%s'\n", n, supported_auth_mechs[n]);
683 #endif
684             }
685           g_free (line);
686           mech = client_choose_mech_and_send_initial_response (auth,
687                                                                credentials,
688                                                                (const gchar* const *) supported_auth_mechs,
689                                                                attempted_auth_mechs,
690                                                                dos,
691                                                                cancellable,
692                                                                error);
693           if (mech == NULL)
694             goto out;
695           if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA)
696             state = CLIENT_STATE_WAITING_FOR_DATA;
697           else
698             state = CLIENT_STATE_WAITING_FOR_OK;
699           break;
700
701         case CLIENT_STATE_WAITING_FOR_OK:
702           debug_print ("CLIENT: WaitingForOK");
703           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
704           if (line == NULL)
705             goto out;
706           debug_print ("CLIENT: WaitingForOK, read `%s'", line);
707           if (g_str_has_prefix (line, "OK "))
708             {
709               if (!g_dbus_is_guid (line + 3))
710                 {
711                   g_set_error (error,
712                                G_IO_ERROR,
713                                G_IO_ERROR_FAILED,
714                                "Invalid OK response `%s'",
715                                line);
716                   g_free (line);
717                   goto out;
718                 }
719               ret_guid = g_strdup (line + 3);
720               g_free (line);
721
722               if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
723                 {
724                   s = "NEGOTIATE_UNIX_FD\r\n";
725                   debug_print ("CLIENT: writing `%s'", s);
726                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
727                     goto out;
728                   state = CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD;
729                 }
730               else
731                 {
732                   s = "BEGIN\r\n";
733                   debug_print ("CLIENT: writing `%s'", s);
734                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
735                     goto out;
736                   /* and we're done! */
737                   goto out;
738                 }
739             }
740           else if (g_str_has_prefix (line, "REJECTED "))
741             {
742               goto choose_mechanism;
743             }
744           else
745             {
746               /* TODO: handle other valid responses */
747               g_set_error (error,
748                            G_IO_ERROR,
749                            G_IO_ERROR_FAILED,
750                            "In WaitingForOk: unexpected response `%s'",
751                            line);
752               g_free (line);
753               goto out;
754             }
755           break;
756
757         case CLIENT_STATE_WAITING_FOR_AGREE_UNIX_FD:
758           debug_print ("CLIENT: WaitingForAgreeUnixFD");
759           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
760           if (line == NULL)
761             goto out;
762           debug_print ("CLIENT: WaitingForAgreeUnixFD, read=`%s'", line);
763           if (g_strcmp0 (line, "AGREE_UNIX_FD") == 0)
764             {
765               g_free (line);
766               negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
767               s = "BEGIN\r\n";
768               debug_print ("CLIENT: writing `%s'", s);
769               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
770                 goto out;
771               /* and we're done! */
772               goto out;
773             }
774           else if (g_str_has_prefix (line, "ERROR") && (line[5] == 0 || g_ascii_isspace (line[5])))
775             {
776               //g_strstrip (line + 5); g_debug ("bah, no unix_fd: `%s'", line + 5);
777               g_free (line);
778               s = "BEGIN\r\n";
779               debug_print ("CLIENT: writing `%s'", s);
780               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
781                 goto out;
782               /* and we're done! */
783               goto out;
784             }
785           else
786             {
787               /* TODO: handle other valid responses */
788               g_set_error (error,
789                            G_IO_ERROR,
790                            G_IO_ERROR_FAILED,
791                            "In WaitingForAgreeUnixFd: unexpected response `%s'",
792                            line);
793               g_free (line);
794               goto out;
795             }
796           break;
797
798         case CLIENT_STATE_WAITING_FOR_DATA:
799           debug_print ("CLIENT: WaitingForData");
800           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
801           if (line == NULL)
802             goto out;
803           debug_print ("CLIENT: WaitingForData, read=`%s'", line);
804           if (g_str_has_prefix (line, "DATA "))
805             {
806               gchar *encoded;
807               gchar *decoded_data;
808               gsize decoded_data_len = 0;
809
810               encoded = g_strdup (line + 5);
811               g_free (line);
812               g_strstrip (encoded);
813               decoded_data = hexdecode (encoded, &decoded_data_len, error);
814               g_free (encoded);
815               if (decoded_data == NULL)
816                 {
817                   g_prefix_error (error, "DATA response is malformed: ");
818                   /* invalid encoding, disconnect! */
819                   goto out;
820                 }
821               _g_dbus_auth_mechanism_client_data_receive (mech, decoded_data, decoded_data_len);
822               g_free (decoded_data);
823
824               if (_g_dbus_auth_mechanism_client_get_state (mech) == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND)
825                 {
826                   gchar *data;
827                   gsize data_len;
828                   gchar *encoded_data;
829                   data = _g_dbus_auth_mechanism_client_data_send (mech, &data_len);
830                   encoded_data = hexencode (data);
831                   s = g_strdup_printf ("DATA %s\r\n", encoded_data);
832                   g_free (encoded_data);
833                   g_free (data);
834                   debug_print ("CLIENT: writing `%s'", s);
835                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
836                     {
837                       g_free (s);
838                       goto out;
839                     }
840                   g_free (s);
841                 }
842               state = CLIENT_STATE_WAITING_FOR_OK;
843             }
844           else if (g_str_has_prefix (line, "REJECTED "))
845             {
846               /* could be the chosen authentication method just doesn't work. Try
847                * another one...
848                */
849               goto choose_mechanism;
850             }
851           else
852             {
853               g_set_error (error,
854                            G_IO_ERROR,
855                            G_IO_ERROR_FAILED,
856                            "In WaitingForData: unexpected response `%s'",
857                            line);
858               g_free (line);
859               goto out;
860             }
861           break;
862
863         default:
864           g_assert_not_reached ();
865           break;
866         }
867
868     }; /* main authentication client loop */
869
870  out:
871   if (mech != NULL)
872     g_object_unref (mech);
873   g_ptr_array_unref (attempted_auth_mechs);
874   g_strfreev (supported_auth_mechs);
875   g_object_unref (dis);
876   g_object_unref (dos);
877
878   /* ensure return value is NULL if error is set */
879   if (error != NULL && *error != NULL)
880     {
881       g_free (ret_guid);
882       ret_guid = NULL;
883     }
884
885   if (ret_guid != NULL)
886     {
887       if (out_negotiated_capabilities != NULL)
888         *out_negotiated_capabilities = negotiated_capabilities;
889     }
890
891   if (credentials != NULL)
892     g_object_unref (credentials);
893
894   debug_print ("CLIENT: Done, authenticated=%d", ret_guid != NULL);
895
896   return ret_guid;
897 }
898
899 /* ---------------------------------------------------------------------------------------------------- */
900
901 static gchar *
902 get_auth_mechanisms (GDBusAuth     *auth,
903                      gboolean       allow_anonymous,
904                      const gchar   *prefix,
905                      const gchar   *suffix,
906                      const gchar   *separator)
907 {
908   GList *l;
909   GString *str;
910   gboolean need_sep;
911
912   str = g_string_new (prefix);
913   need_sep = FALSE;
914   for (l = auth->priv->available_mechanisms; l != NULL; l = l->next)
915     {
916       Mechanism *m = l->data;
917
918       if (!allow_anonymous && g_strcmp0 (m->name, "ANONYMOUS") == 0)
919         continue;
920
921       if (need_sep)
922         g_string_append (str, separator);
923       g_string_append (str, m->name);
924       need_sep = TRUE;
925     }
926
927   g_string_append (str, suffix);
928   return g_string_free (str, FALSE);
929 }
930
931
932 typedef enum
933 {
934   SERVER_STATE_WAITING_FOR_AUTH,
935   SERVER_STATE_WAITING_FOR_DATA,
936   SERVER_STATE_WAITING_FOR_BEGIN
937 } ServerState;
938
939 gboolean
940 _g_dbus_auth_run_server (GDBusAuth              *auth,
941                          GDBusAuthObserver      *observer,
942                          const gchar            *guid,
943                          gboolean                allow_anonymous,
944                          GDBusCapabilityFlags    offered_capabilities,
945                          GDBusCapabilityFlags   *out_negotiated_capabilities,
946                          GCredentials          **out_received_credentials,
947                          GCancellable           *cancellable,
948                          GError                **error)
949 {
950   gboolean ret;
951   ServerState state;
952   GDataInputStream *dis;
953   GDataOutputStream *dos;
954   GError *local_error;
955   guchar byte;
956   gchar *line;
957   gsize line_length;
958   GDBusAuthMechanism *mech;
959   gchar *s;
960   GDBusCapabilityFlags negotiated_capabilities;
961   GCredentials *credentials;
962
963   debug_print ("SERVER: initiating");
964
965   ret = FALSE;
966   dis = NULL;
967   dos = NULL;
968   mech = NULL;
969   negotiated_capabilities = 0;
970   credentials = NULL;
971
972   if (!g_dbus_is_guid (guid))
973     {
974       g_set_error (error,
975                    G_IO_ERROR,
976                    G_IO_ERROR_FAILED,
977                    "The given guid `%s' is not valid",
978                    guid);
979       goto out;
980     }
981
982   dis = G_DATA_INPUT_STREAM (g_data_input_stream_new (g_io_stream_get_input_stream (auth->priv->stream)));
983   dos = G_DATA_OUTPUT_STREAM (g_data_output_stream_new (g_io_stream_get_output_stream (auth->priv->stream)));
984   g_filter_input_stream_set_close_base_stream (G_FILTER_INPUT_STREAM (dis), FALSE);
985   g_filter_output_stream_set_close_base_stream (G_FILTER_OUTPUT_STREAM (dos), FALSE);
986
987   g_data_input_stream_set_newline_type (dis, G_DATA_STREAM_NEWLINE_TYPE_CR_LF);
988
989   /* first read the NUL-byte (TODO: read credentials if using a unix domain socket) */
990 #ifdef G_OS_UNIX
991   if (G_IS_UNIX_CONNECTION (auth->priv->stream))
992     {
993       local_error = NULL;
994       credentials = g_unix_connection_receive_credentials (G_UNIX_CONNECTION (auth->priv->stream),
995                                                            cancellable,
996                                                            &local_error);
997       if (credentials == NULL && !g_error_matches (local_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED))
998         {
999           g_propagate_error (error, local_error);
1000           goto out;
1001         }
1002     }
1003   else
1004     {
1005       local_error = NULL;
1006       byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
1007       byte = byte; /* To avoid -Wunused-but-set-variable */
1008       if (local_error != NULL)
1009         {
1010           g_propagate_error (error, local_error);
1011           goto out;
1012         }
1013     }
1014 #else
1015   local_error = NULL;
1016   byte = g_data_input_stream_read_byte (dis, cancellable, &local_error);
1017   if (local_error != NULL)
1018     {
1019       g_propagate_error (error, local_error);
1020       goto out;
1021     }
1022 #endif
1023   if (credentials != NULL)
1024     {
1025       if (G_UNLIKELY (_g_dbus_debug_authentication ()))
1026         {
1027           s = g_credentials_to_string (credentials);
1028           debug_print ("SERVER: received credentials `%s'", s);
1029           g_free (s);
1030         }
1031     }
1032   else
1033     {
1034       debug_print ("SERVER: didn't receive any credentials");
1035     }
1036
1037   state = SERVER_STATE_WAITING_FOR_AUTH;
1038   while (TRUE)
1039     {
1040       switch (state)
1041         {
1042         case SERVER_STATE_WAITING_FOR_AUTH:
1043           debug_print ("SERVER: WaitingForAuth");
1044           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1045           debug_print ("SERVER: WaitingForAuth, read `%s'", line);
1046           if (line == NULL)
1047             goto out;
1048           if (g_strcmp0 (line, "AUTH") == 0)
1049             {
1050               s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1051               debug_print ("SERVER: writing `%s'", s);
1052               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1053                 {
1054                   g_free (s);
1055                   goto out;
1056                 }
1057               g_free (s);
1058               g_free (line);
1059             }
1060           else if (g_str_has_prefix (line, "AUTH "))
1061             {
1062               gchar **tokens;
1063               const gchar *encoded;
1064               const gchar *mech_name;
1065               GType auth_mech_to_use_gtype;
1066
1067               tokens = g_strsplit (line, " ", 0);
1068               g_free (line);
1069
1070               switch (g_strv_length (tokens))
1071                 {
1072                 case 2:
1073                   /* no initial response */
1074                   mech_name = tokens[1];
1075                   encoded = NULL;
1076                   break;
1077
1078                 case 3:
1079                   /* initial response */
1080                   mech_name = tokens[1];
1081                   encoded = tokens[2];
1082                   break;
1083
1084                 default:
1085                   g_set_error (error,
1086                                G_IO_ERROR,
1087                                G_IO_ERROR_FAILED,
1088                                "Unexpected line `%s' while in WaitingForAuth state",
1089                                line);
1090                   g_strfreev (tokens);
1091                   goto out;
1092                 }
1093
1094               /* TODO: record that the client has attempted to use this mechanism */
1095               //g_debug ("client is trying `%s'", mech_name);
1096
1097               auth_mech_to_use_gtype = find_mech_by_name (auth, mech_name);
1098               if ((auth_mech_to_use_gtype == (GType) 0) ||
1099                   (!allow_anonymous && g_strcmp0 (mech_name, "ANONYMOUS") == 0))
1100                 {
1101                   /* We don't support this auth mechanism */
1102                   g_strfreev (tokens);
1103                   s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1104                   debug_print ("SERVER: writing `%s'", s);
1105                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1106                     {
1107                       g_free (s);
1108                       goto out;
1109                     }
1110                   g_free (s);
1111
1112                   /* stay in WAITING FOR AUTH */
1113                   state = SERVER_STATE_WAITING_FOR_AUTH;
1114                 }
1115               else
1116                 {
1117                   gchar *initial_response;
1118                   gsize initial_response_len;
1119
1120                   mech = g_object_new (auth_mech_to_use_gtype,
1121                                        "stream", auth->priv->stream,
1122                                        "credentials", credentials,
1123                                        NULL);
1124
1125                   initial_response = NULL;
1126                   initial_response_len = 0;
1127                   if (encoded != NULL)
1128                     {
1129                       initial_response = hexdecode (encoded, &initial_response_len, error);
1130                       if (initial_response == NULL)
1131                         {
1132                           g_prefix_error (error, "Initial response is malformed: ");
1133                           /* invalid encoding, disconnect! */
1134                           g_strfreev (tokens);
1135                           goto out;
1136                         }
1137                     }
1138
1139                   _g_dbus_auth_mechanism_server_initiate (mech,
1140                                                           initial_response,
1141                                                           initial_response_len);
1142                   g_free (initial_response);
1143                   g_strfreev (tokens);
1144
1145                 change_state:
1146                   switch (_g_dbus_auth_mechanism_server_get_state (mech))
1147                     {
1148                     case G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED:
1149                       if (observer != NULL &&
1150                           !g_dbus_auth_observer_authorize_authenticated_peer (observer,
1151                                                                               auth->priv->stream,
1152                                                                               credentials))
1153                         {
1154                           /* disconnect */
1155                           g_set_error_literal (error,
1156                                                G_IO_ERROR,
1157                                                G_IO_ERROR_FAILED,
1158                                                _("Cancelled via GDBusAuthObserver::authorize-authenticated-peer"));
1159                           goto out;
1160                         }
1161                       else
1162                         {
1163                           s = g_strdup_printf ("OK %s\r\n", guid);
1164                           debug_print ("SERVER: writing `%s'", s);
1165                           if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1166                             {
1167                               g_free (s);
1168                               goto out;
1169                             }
1170                           g_free (s);
1171                           state = SERVER_STATE_WAITING_FOR_BEGIN;
1172                         }
1173                       break;
1174
1175                     case G_DBUS_AUTH_MECHANISM_STATE_REJECTED:
1176                       s = get_auth_mechanisms (auth, allow_anonymous, "REJECTED ", "\r\n", " ");
1177                       debug_print ("SERVER: writing `%s'", s);
1178                       if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1179                         {
1180                           g_free (s);
1181                           goto out;
1182                         }
1183                       g_free (s);
1184                       state = SERVER_STATE_WAITING_FOR_AUTH;
1185                       break;
1186
1187                     case G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA:
1188                       state = SERVER_STATE_WAITING_FOR_DATA;
1189                       break;
1190
1191                     case G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND:
1192                       {
1193                         gchar *data;
1194                         gsize data_len;
1195                         gchar *encoded_data;
1196                         data = _g_dbus_auth_mechanism_server_data_send (mech, &data_len);
1197                         encoded_data = hexencode (data);
1198                         s = g_strdup_printf ("DATA %s\r\n", encoded_data);
1199                         g_free (encoded_data);
1200                         g_free (data);
1201                         debug_print ("SERVER: writing `%s'", s);
1202                         if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1203                           {
1204                             g_free (s);
1205                             goto out;
1206                           }
1207                         g_free (s);
1208                       }
1209                       goto change_state;
1210                       break;
1211
1212                     default:
1213                       /* TODO */
1214                       g_assert_not_reached ();
1215                       break;
1216                     }
1217                 }
1218             }
1219           else
1220             {
1221               g_set_error (error,
1222                            G_IO_ERROR,
1223                            G_IO_ERROR_FAILED,
1224                            "Unexpected line `%s' while in WaitingForAuth state",
1225                            line);
1226               g_free (line);
1227               goto out;
1228             }
1229           break;
1230
1231         case SERVER_STATE_WAITING_FOR_DATA:
1232           debug_print ("SERVER: WaitingForData");
1233           line = _my_g_data_input_stream_read_line (dis, &line_length, cancellable, error);
1234           debug_print ("SERVER: WaitingForData, read `%s'", line);
1235           if (line == NULL)
1236             goto out;
1237           if (g_str_has_prefix (line, "DATA "))
1238             {
1239               gchar *encoded;
1240               gchar *decoded_data;
1241               gsize decoded_data_len = 0;
1242
1243               encoded = g_strdup (line + 5);
1244               g_free (line);
1245               g_strstrip (encoded);
1246               decoded_data = hexdecode (encoded, &decoded_data_len, error);
1247               g_free (encoded);
1248               if (decoded_data == NULL)
1249                 {
1250                   g_prefix_error (error, "DATA response is malformed: ");
1251                   /* invalid encoding, disconnect! */
1252                   goto out;
1253                 }
1254               _g_dbus_auth_mechanism_server_data_receive (mech, decoded_data, decoded_data_len);
1255               g_free (decoded_data);
1256               /* oh man, this goto-crap is so ugly.. really need to rewrite the state machine */
1257               goto change_state;
1258             }
1259           else
1260             {
1261               g_set_error (error,
1262                            G_IO_ERROR,
1263                            G_IO_ERROR_FAILED,
1264                            "Unexpected line `%s' while in WaitingForData state",
1265                            line);
1266               g_free (line);
1267             }
1268           goto out;
1269
1270         case SERVER_STATE_WAITING_FOR_BEGIN:
1271           debug_print ("SERVER: WaitingForBegin");
1272           /* Use extremely slow (but reliable) line reader - this basically
1273            * does a recvfrom() system call per character
1274            *
1275            * (the problem with using GDataInputStream's read_line is that because of
1276            * buffering it might start reading into the first D-Bus message that
1277            * appears after "BEGIN\r\n"....)
1278            */
1279           line = _my_g_input_stream_read_line_safe (g_io_stream_get_input_stream (auth->priv->stream),
1280                                                     &line_length,
1281                                                     cancellable,
1282                                                     error);
1283           debug_print ("SERVER: WaitingForBegin, read `%s'", line);
1284           if (line == NULL)
1285             goto out;
1286           if (g_strcmp0 (line, "BEGIN") == 0)
1287             {
1288               /* YAY, done! */
1289               ret = TRUE;
1290               g_free (line);
1291               goto out;
1292             }
1293           else if (g_strcmp0 (line, "NEGOTIATE_UNIX_FD") == 0)
1294             {
1295               g_free (line);
1296               if (offered_capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING)
1297                 {
1298                   negotiated_capabilities |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1299                   s = "AGREE_UNIX_FD\r\n";
1300                   debug_print ("SERVER: writing `%s'", s);
1301                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1302                     goto out;
1303                 }
1304               else
1305                 {
1306                   s = "ERROR \"fd passing not offered\"\r\n";
1307                   debug_print ("SERVER: writing `%s'", s);
1308                   if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1309                     goto out;
1310                 }
1311             }
1312           else
1313             {
1314               g_debug ("Unexpected line `%s' while in WaitingForBegin state", line);
1315               g_free (line);
1316               s = "ERROR \"Unknown Command\"\r\n";
1317               debug_print ("SERVER: writing `%s'", s);
1318               if (!g_data_output_stream_put_string (dos, s, cancellable, error))
1319                 goto out;
1320             }
1321           break;
1322
1323         default:
1324           g_assert_not_reached ();
1325           break;
1326         }
1327     }
1328
1329
1330   g_set_error_literal (error,
1331                        G_IO_ERROR,
1332                        G_IO_ERROR_FAILED,
1333                        "Not implemented (server)");
1334
1335  out:
1336   if (mech != NULL)
1337     g_object_unref (mech);
1338   if (dis != NULL)
1339     g_object_unref (dis);
1340   if (dos != NULL)
1341     g_object_unref (dos);
1342
1343   /* ensure return value is FALSE if error is set */
1344   if (error != NULL && *error != NULL)
1345     {
1346       ret = FALSE;
1347     }
1348
1349   if (ret)
1350     {
1351       if (out_negotiated_capabilities != NULL)
1352         *out_negotiated_capabilities = negotiated_capabilities;
1353       if (out_received_credentials != NULL)
1354         *out_received_credentials = credentials != NULL ? g_object_ref (credentials) : NULL;
1355     }
1356
1357   if (credentials != NULL)
1358     g_object_unref (credentials);
1359
1360   debug_print ("SERVER: Done, authenticated=%d", ret);
1361
1362   return ret;
1363 }
1364
1365 /* ---------------------------------------------------------------------------------------------------- */