Add G_GNUC_PRINTF on all functions with format strings
[platform/upstream/glib.git] / gio / gdbusauthmechanismsha1.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 <string.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef _WIN32
33 #include <io.h>
34 #endif
35
36 #include <glib/gstdio.h>
37
38 #include "gdbusauthmechanismsha1.h"
39 #include "gcredentials.h"
40 #include "gdbuserror.h"
41 #include "gioenumtypes.h"
42 #include "gioerror.h"
43 #include "gdbusprivate.h"
44
45 #include "glibintl.h"
46
47 struct _GDBusAuthMechanismSha1Private
48 {
49   gboolean is_client;
50   gboolean is_server;
51   GDBusAuthMechanismState state;
52
53   /* used on the client side */
54   gchar *to_send;
55
56   /* used on the server side */
57   gchar *cookie;
58   gchar *server_challenge;
59 };
60
61 static gint                     mechanism_get_priority              (void);
62 static const gchar             *mechanism_get_name                  (void);
63
64 static gboolean                 mechanism_is_supported              (GDBusAuthMechanism   *mechanism);
65 static gchar                   *mechanism_encode_data               (GDBusAuthMechanism   *mechanism,
66                                                                      const gchar          *data,
67                                                                      gsize                 data_len,
68                                                                      gsize                *out_data_len);
69 static gchar                   *mechanism_decode_data               (GDBusAuthMechanism   *mechanism,
70                                                                      const gchar          *data,
71                                                                      gsize                 data_len,
72                                                                      gsize                *out_data_len);
73 static GDBusAuthMechanismState  mechanism_server_get_state          (GDBusAuthMechanism   *mechanism);
74 static void                     mechanism_server_initiate           (GDBusAuthMechanism   *mechanism,
75                                                                      const gchar          *initial_response,
76                                                                      gsize                 initial_response_len);
77 static void                     mechanism_server_data_receive       (GDBusAuthMechanism   *mechanism,
78                                                                      const gchar          *data,
79                                                                      gsize                 data_len);
80 static gchar                   *mechanism_server_data_send          (GDBusAuthMechanism   *mechanism,
81                                                                      gsize                *out_data_len);
82 static gchar                   *mechanism_server_get_reject_reason  (GDBusAuthMechanism   *mechanism);
83 static void                     mechanism_server_shutdown           (GDBusAuthMechanism   *mechanism);
84 static GDBusAuthMechanismState  mechanism_client_get_state          (GDBusAuthMechanism   *mechanism);
85 static gchar                   *mechanism_client_initiate           (GDBusAuthMechanism   *mechanism,
86                                                                      gsize                *out_initial_response_len);
87 static void                     mechanism_client_data_receive       (GDBusAuthMechanism   *mechanism,
88                                                                      const gchar          *data,
89                                                                      gsize                 data_len);
90 static gchar                   *mechanism_client_data_send          (GDBusAuthMechanism   *mechanism,
91                                                                      gsize                *out_data_len);
92 static void                     mechanism_client_shutdown           (GDBusAuthMechanism   *mechanism);
93
94 /* ---------------------------------------------------------------------------------------------------- */
95
96 G_DEFINE_TYPE (GDBusAuthMechanismSha1, _g_dbus_auth_mechanism_sha1, G_TYPE_DBUS_AUTH_MECHANISM);
97
98 /* ---------------------------------------------------------------------------------------------------- */
99
100 static void
101 _g_dbus_auth_mechanism_sha1_finalize (GObject *object)
102 {
103   GDBusAuthMechanismSha1 *mechanism = G_DBUS_AUTH_MECHANISM_SHA1 (object);
104
105   g_free (mechanism->priv->to_send);
106
107   g_free (mechanism->priv->cookie);
108   g_free (mechanism->priv->server_challenge);
109
110   if (G_OBJECT_CLASS (_g_dbus_auth_mechanism_sha1_parent_class)->finalize != NULL)
111     G_OBJECT_CLASS (_g_dbus_auth_mechanism_sha1_parent_class)->finalize (object);
112 }
113
114 static void
115 _g_dbus_auth_mechanism_sha1_class_init (GDBusAuthMechanismSha1Class *klass)
116 {
117   GObjectClass *gobject_class;
118   GDBusAuthMechanismClass *mechanism_class;
119
120   g_type_class_add_private (klass, sizeof (GDBusAuthMechanismSha1Private));
121
122   gobject_class = G_OBJECT_CLASS (klass);
123   gobject_class->finalize = _g_dbus_auth_mechanism_sha1_finalize;
124
125   mechanism_class = G_DBUS_AUTH_MECHANISM_CLASS (klass);
126   mechanism_class->get_priority              = mechanism_get_priority;
127   mechanism_class->get_name                  = mechanism_get_name;
128   mechanism_class->is_supported              = mechanism_is_supported;
129   mechanism_class->encode_data               = mechanism_encode_data;
130   mechanism_class->decode_data               = mechanism_decode_data;
131   mechanism_class->server_get_state          = mechanism_server_get_state;
132   mechanism_class->server_initiate           = mechanism_server_initiate;
133   mechanism_class->server_data_receive       = mechanism_server_data_receive;
134   mechanism_class->server_data_send          = mechanism_server_data_send;
135   mechanism_class->server_get_reject_reason  = mechanism_server_get_reject_reason;
136   mechanism_class->server_shutdown           = mechanism_server_shutdown;
137   mechanism_class->client_get_state          = mechanism_client_get_state;
138   mechanism_class->client_initiate           = mechanism_client_initiate;
139   mechanism_class->client_data_receive       = mechanism_client_data_receive;
140   mechanism_class->client_data_send          = mechanism_client_data_send;
141   mechanism_class->client_shutdown           = mechanism_client_shutdown;
142 }
143
144 static void
145 _g_dbus_auth_mechanism_sha1_init (GDBusAuthMechanismSha1 *mechanism)
146 {
147   mechanism->priv = G_TYPE_INSTANCE_GET_PRIVATE (mechanism,
148                                                  G_TYPE_DBUS_AUTH_MECHANISM_SHA1,
149                                                  GDBusAuthMechanismSha1Private);
150 }
151
152 /* ---------------------------------------------------------------------------------------------------- */
153
154 static gint
155 mechanism_get_priority (void)
156 {
157   return 0;
158 }
159
160 static const gchar *
161 mechanism_get_name (void)
162 {
163   return "DBUS_COOKIE_SHA1";
164 }
165
166 static gboolean
167 mechanism_is_supported (GDBusAuthMechanism *mechanism)
168 {
169   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), FALSE);
170   return TRUE;
171 }
172
173 static gchar *
174 mechanism_encode_data (GDBusAuthMechanism   *mechanism,
175                        const gchar          *data,
176                        gsize                 data_len,
177                        gsize                *out_data_len)
178 {
179   return NULL;
180 }
181
182
183 static gchar *
184 mechanism_decode_data (GDBusAuthMechanism   *mechanism,
185                        const gchar          *data,
186                        gsize                 data_len,
187                        gsize                *out_data_len)
188 {
189   return NULL;
190 }
191
192 /* ---------------------------------------------------------------------------------------------------- */
193
194 static gint
195 random_ascii (void)
196 {
197   gint ret;
198   ret = g_random_int_range (0, 60);
199   if (ret < 25)
200     ret += 'A';
201   else if (ret < 50)
202     ret += 'a' - 25;
203   else
204     ret += '0' - 50;
205   return ret;
206 }
207
208 static gchar *
209 random_ascii_string (guint len)
210 {
211   GString *challenge;
212   guint n;
213
214   challenge = g_string_new (NULL);
215   for (n = 0; n < len; n++)
216     g_string_append_c (challenge, random_ascii ());
217   return g_string_free (challenge, FALSE);
218 }
219
220 static gchar *
221 random_blob (guint len)
222 {
223   GString *challenge;
224   guint n;
225
226   challenge = g_string_new (NULL);
227   for (n = 0; n < len; n++)
228     g_string_append_c (challenge, g_random_int_range (0, 256));
229   return g_string_free (challenge, FALSE);
230 }
231
232 /* ---------------------------------------------------------------------------------------------------- */
233
234 /* ensure keyring dir exists and permissions are correct */
235 static gchar *
236 ensure_keyring_directory (GError **error)
237 {
238   gchar *path;
239   const gchar *e;
240
241   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
242
243   e = g_getenv ("G_DBUS_COOKIE_SHA1_KEYRING_DIR");
244   if (e != NULL)
245     {
246       path = g_strdup (e);
247     }
248   else
249     {
250       path = g_build_filename (g_get_home_dir (),
251                                ".dbus-keyrings",
252                                NULL);
253     }
254
255   if (g_file_test (path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))
256     {
257       if (g_getenv ("G_DBUS_COOKIE_SHA1_KEYRING_DIR_IGNORE_PERMISSION") == NULL)
258         {
259 #ifdef G_OS_UNIX
260           struct stat statbuf;
261           if (stat (path, &statbuf) != 0)
262             {
263               g_set_error (error,
264                            G_IO_ERROR,
265                            g_io_error_from_errno (errno),
266                            _("Error when getting information for directory `%s': %s"),
267                            path,
268                            strerror (errno));
269               g_free (path);
270               path = NULL;
271               goto out;
272             }
273           if ((statbuf.st_mode  & 0777) != 0700)
274             {
275               g_set_error (error,
276                            G_IO_ERROR,
277                            G_IO_ERROR_FAILED,
278                            _("Permissions on directory `%s' are malformed. Expected mode 0700, got 0%o"),
279                            path,
280                            statbuf.st_mode & 0777);
281               g_free (path);
282               path = NULL;
283               goto out;
284             }
285 #else
286 #ifdef __GNUC__
287 #warning Please implement permission checking on this non-UNIX platform
288 #endif
289 #endif
290         }
291         goto out;
292     }
293
294   if (g_mkdir (path, 0700) != 0)
295     {
296       g_set_error (error,
297                    G_IO_ERROR,
298                    g_io_error_from_errno (errno),
299                    _("Error creating directory `%s': %s"),
300                    path,
301                    strerror (errno));
302       g_free (path);
303       path = NULL;
304       goto out;
305     }
306
307 out:
308   return path;
309 }
310
311 /* ---------------------------------------------------------------------------------------------------- */
312
313 static void
314 append_nibble (GString *s, gint val)
315 {
316   g_string_append_c (s, val >= 10 ? ('a' + val - 10) : ('0' + val));
317 }
318
319 static gchar *
320 hexencode (const gchar *str,
321            gssize       len)
322 {
323   guint n;
324   GString *s;
325
326   if (len == -1)
327     len = strlen (str);
328
329   s = g_string_new (NULL);
330   for (n = 0; n < len; n++)
331     {
332       gint val;
333       gint upper_nibble;
334       gint lower_nibble;
335
336       val = ((const guchar *) str)[n];
337       upper_nibble = val >> 4;
338       lower_nibble = val & 0x0f;
339
340       append_nibble (s, upper_nibble);
341       append_nibble (s, lower_nibble);
342     }
343
344   return g_string_free (s, FALSE);
345 }
346
347 /* ---------------------------------------------------------------------------------------------------- */
348
349 /* looks up an entry in the keyring */
350 static gchar *
351 keyring_lookup_entry (const gchar  *cookie_context,
352                       gint          cookie_id,
353                       GError      **error)
354 {
355   gchar *ret;
356   gchar *keyring_dir;
357   gchar *contents;
358   gchar *path;
359   guint n;
360   gchar **lines;
361
362   g_return_val_if_fail (cookie_context != NULL, NULL);
363   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
364
365   ret = NULL;
366   path = NULL;
367   contents = NULL;
368   lines = NULL;
369
370   keyring_dir = ensure_keyring_directory (error);
371   if (keyring_dir == NULL)
372     goto out;
373
374   path = g_build_filename (keyring_dir, cookie_context, NULL);
375
376   if (!g_file_get_contents (path,
377                             &contents,
378                             NULL,
379                             error))
380     {
381       g_prefix_error (error,
382                       _("Error opening keyring `%s' for reading: "),
383                       path);
384       goto out;
385     }
386   g_assert (contents != NULL);
387
388   lines = g_strsplit (contents, "\n", 0);
389   for (n = 0; lines[n] != NULL; n++)
390     {
391       const gchar *line = lines[n];
392       gchar **tokens;
393       gchar *endp;
394       gint line_id;
395       guint64 line_when;
396
397       if (line[0] == '\0')
398         continue;
399
400       tokens = g_strsplit (line, " ", 0);
401       if (g_strv_length (tokens) != 3)
402         {
403           g_set_error (error,
404                        G_IO_ERROR,
405                        G_IO_ERROR_FAILED,
406                        _("Line %d of the keyring at `%s' with content `%s' is malformed"),
407                        n + 1,
408                        path,
409                        line);
410           g_strfreev (tokens);
411           goto out;
412         }
413
414       line_id = g_ascii_strtoll (tokens[0], &endp, 10);
415       if (*endp != '\0')
416         {
417           g_set_error (error,
418                        G_IO_ERROR,
419                        G_IO_ERROR_FAILED,
420                        _("First token of line %d of the keyring at `%s' with content `%s' is malformed"),
421                        n + 1,
422                        path,
423                        line);
424           g_strfreev (tokens);
425           goto out;
426         }
427
428       line_when = g_ascii_strtoll (tokens[1], &endp, 10);
429       line_when = line_when; /* To avoid -Wunused-but-set-variable */
430       if (*endp != '\0')
431         {
432           g_set_error (error,
433                        G_IO_ERROR,
434                        G_IO_ERROR_FAILED,
435                        _("Second token of line %d of the keyring at `%s' with content `%s' is malformed"),
436                        n + 1,
437                        path,
438                        line);
439           g_strfreev (tokens);
440           goto out;
441         }
442
443       if (line_id == cookie_id)
444         {
445           /* YAY, success */
446           ret = tokens[2]; /* steal pointer */
447           tokens[2] = NULL;
448           g_strfreev (tokens);
449           goto out;
450         }
451
452       g_strfreev (tokens);
453     }
454
455   /* BOOH, didn't find the cookie */
456   g_set_error (error,
457                G_IO_ERROR,
458                G_IO_ERROR_FAILED,
459                _("Didn't find cookie with id %d in the keyring at `%s'"),
460                cookie_id,
461                path);
462
463  out:
464   g_free (keyring_dir);
465   g_free (path);
466   g_free (contents);
467   g_strfreev (lines);
468   return ret;
469 }
470
471 /* function for logging important events that the system administrator should take notice of */
472 G_GNUC_PRINTF(1, 2)
473 static void
474 _log (const gchar *message,
475       ...)
476 {
477   gchar *s;
478   va_list var_args;
479
480   va_start (var_args, message);
481   s = g_strdup_vprintf (message, var_args);
482   va_end (var_args);
483
484   /* TODO: might want to send this to syslog instead */
485   g_printerr ("GDBus-DBUS_COOKIE_SHA1: %s\n", s);
486   g_free (s);
487 }
488
489 static gint
490 keyring_acquire_lock (const gchar  *path,
491                       GError      **error)
492 {
493   gchar *lock;
494   gint ret;
495   guint num_tries;
496   guint num_create_tries;
497
498   g_return_val_if_fail (path != NULL, FALSE);
499   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
500
501   ret = -1;
502   lock = g_strdup_printf ("%s.lock", path);
503
504   /* This is what the D-Bus spec says
505    *
506    *  Create a lockfile name by appending ".lock" to the name of the
507    *  cookie file. The server should attempt to create this file using
508    *  O_CREAT | O_EXCL. If file creation fails, the lock
509    *  fails. Servers should retry for a reasonable period of time,
510    *  then they may choose to delete an existing lock to keep users
511    *  from having to manually delete a stale lock. [1]
512    *
513    *  [1] : Lockfiles are used instead of real file locking fcntl() because
514    *         real locking implementations are still flaky on network filesystems
515    */
516
517   num_create_tries = 0;
518 #ifdef EEXISTS
519  again:
520 #endif
521   num_tries = 0;
522   while (g_file_test (lock, G_FILE_TEST_EXISTS))
523     {
524       /* sleep 10ms, then try again */
525       g_usleep (1000*10);
526       num_tries++;
527       if (num_tries == 50)
528         {
529           /* ok, we slept 50*10ms = 0.5 seconds. Conclude that the lock file must be
530            * stale (nuke the it from orbit)
531            */
532           if (g_unlink (lock) != 0)
533             {
534               g_set_error (error,
535                            G_IO_ERROR,
536                            g_io_error_from_errno (errno),
537                            _("Error deleting stale lock file `%s': %s"),
538                            lock,
539                            strerror (errno));
540               goto out;
541             }
542           _log ("Deleted stale lock file `%s'", lock);
543           break;
544         }
545     }
546
547   ret = g_open (lock, O_CREAT |
548 #ifdef O_EXCL
549                 O_EXCL,
550 #else
551                 0,
552 #endif
553                 0700);
554   if (ret == -1)
555     {
556 #ifdef EEXISTS
557       /* EEXIST: pathname already exists and O_CREAT and O_EXCL were used. */
558       if (errno == EEXISTS)
559         {
560           num_create_tries++;
561           if (num_create_tries < 5)
562             goto again;
563         }
564 #endif
565       num_create_tries = num_create_tries; /* To avoid -Wunused-but-set-variable */
566       g_set_error (error,
567                    G_IO_ERROR,
568                    g_io_error_from_errno (errno),
569                    _("Error creating lock file `%s': %s"),
570                    lock,
571                    strerror (errno));
572       goto out;
573     }
574
575  out:
576   g_free (lock);
577   return ret;
578 }
579
580 static gboolean
581 keyring_release_lock (const gchar  *path,
582                       gint          lock_fd,
583                       GError      **error)
584 {
585   gchar *lock;
586   gboolean ret;
587
588   g_return_val_if_fail (path != NULL, FALSE);
589   g_return_val_if_fail (lock_fd != -1, FALSE);
590   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
591
592   ret = FALSE;
593   lock = g_strdup_printf ("%s.lock", path);
594   if (close (lock_fd) != 0)
595     {
596       g_set_error (error,
597                    G_IO_ERROR,
598                    g_io_error_from_errno (errno),
599                    _("Error closing (unlinked) lock file `%s': %s"),
600                    lock,
601                    strerror (errno));
602       goto out;
603     }
604   if (g_unlink (lock) != 0)
605     {
606       g_set_error (error,
607                    G_IO_ERROR,
608                    g_io_error_from_errno (errno),
609                    _("Error unlinking lock file `%s': %s"),
610                    lock,
611                    strerror (errno));
612       goto out;
613     }
614
615   ret = TRUE;
616
617  out:
618   g_free (lock);
619   return ret;
620 }
621
622
623 /* adds an entry to the keyring, taking care of locking and deleting stale/future entries */
624 static gboolean
625 keyring_generate_entry (const gchar  *cookie_context,
626                         gint         *out_id,
627                         gchar       **out_cookie,
628                         GError      **error)
629 {
630   gboolean ret;
631   gchar *keyring_dir;
632   gchar *path;
633   gchar *contents;
634   GError *local_error;
635   gchar **lines;
636   gint max_line_id;
637   GString *new_contents;
638   guint64 now;
639   gboolean have_id;
640   gint use_id;
641   gchar *use_cookie;
642   gboolean changed_file;
643   gint lock_fd;
644
645   g_return_val_if_fail (cookie_context != NULL, FALSE);
646   g_return_val_if_fail (out_id != NULL, FALSE);
647   g_return_val_if_fail (out_cookie != NULL, FALSE);
648   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
649
650   ret = FALSE;
651   path = NULL;
652   contents = NULL;
653   lines = NULL;
654   new_contents = NULL;
655   have_id = FALSE;
656   use_id = 0;
657   use_cookie = NULL;
658   lock_fd = -1;
659
660   keyring_dir = ensure_keyring_directory (error);
661   if (keyring_dir == NULL)
662     goto out;
663
664   path = g_build_filename (keyring_dir, cookie_context, NULL);
665
666   lock_fd = keyring_acquire_lock (path, error);
667   if (lock_fd == -1)
668     goto out;
669
670   local_error = NULL;
671   contents = NULL;
672   if (!g_file_get_contents (path,
673                             &contents,
674                             NULL,
675                             &local_error))
676     {
677       if (local_error->domain == G_FILE_ERROR && local_error->code == G_FILE_ERROR_NOENT)
678         {
679           /* file doesn't have to exist */
680           g_error_free (local_error);
681         }
682       else
683         {
684           g_propagate_prefixed_error (error,
685                                       local_error,
686                                       _("Error opening keyring `%s' for writing: "),
687                                       path);
688           goto out;
689         }
690     }
691
692   new_contents = g_string_new (NULL);
693   now = time (NULL);
694   changed_file = FALSE;
695
696   max_line_id = 0;
697   if (contents != NULL)
698     {
699       guint n;
700       lines = g_strsplit (contents, "\n", 0);
701       for (n = 0; lines[n] != NULL; n++)
702         {
703           const gchar *line = lines[n];
704           gchar **tokens;
705           gchar *endp;
706           gint line_id;
707           guint64 line_when;
708           gboolean keep_entry;
709
710           if (line[0] == '\0')
711             continue;
712
713           tokens = g_strsplit (line, " ", 0);
714           if (g_strv_length (tokens) != 3)
715             {
716               g_set_error (error,
717                            G_IO_ERROR,
718                            G_IO_ERROR_FAILED,
719                            _("Line %d of the keyring at `%s' with content `%s' is malformed"),
720                            n + 1,
721                            path,
722                            line);
723               g_strfreev (tokens);
724               goto out;
725             }
726
727           line_id = g_ascii_strtoll (tokens[0], &endp, 10);
728           if (*endp != '\0')
729             {
730               g_set_error (error,
731                            G_IO_ERROR,
732                            G_IO_ERROR_FAILED,
733                            _("First token of line %d of the keyring at `%s' with content `%s' is malformed"),
734                            n + 1,
735                            path,
736                            line);
737               g_strfreev (tokens);
738               goto out;
739             }
740
741           line_when = g_ascii_strtoll (tokens[1], &endp, 10);
742           if (*endp != '\0')
743             {
744               g_set_error (error,
745                            G_IO_ERROR,
746                            G_IO_ERROR_FAILED,
747                            _("Second token of line %d of the keyring at `%s' with content `%s' is malformed"),
748                            n + 1,
749                            path,
750                            line);
751               g_strfreev (tokens);
752               goto out;
753             }
754           line_when = line_when; /* To avoid -Wunused-but-set-variable */
755
756
757           /* D-Bus spec says:
758            *
759            *  Once the lockfile has been created, the server loads the
760            *  cookie file. It should then delete any cookies that are
761            *  old (the timeout can be fairly short), or more than a
762            *  reasonable time in the future (so that cookies never
763            *  accidentally become permanent, if the clock was set far
764            *  into the future at some point). If no recent keys remain,
765            *  the server may generate a new key.
766            *
767            */
768           keep_entry = TRUE;
769           if (line_when > now)
770             {
771               /* Oddball case: entry is more recent than our current wall-clock time..
772                * This is OK, it means that another server on another machine but with
773                * same $HOME wrote the entry.
774                *
775                * So discard the entry if it's more than 1 day in the future ("reasonable
776                * time in the future").
777                */
778               if (line_when - now > 24*60*60)
779                 {
780                   keep_entry = FALSE;
781                   _log ("Deleted SHA1 cookie from %" G_GUINT64_FORMAT " seconds in the future", line_when - now);
782                 }
783             }
784           else
785             {
786               /* Discard entry if it's older than 15 minutes ("can be fairly short") */
787               if (now - line_when > 15*60)
788                 {
789                   keep_entry = FALSE;
790                 }
791             }
792
793           if (!keep_entry)
794             {
795               changed_file = FALSE;
796             }
797           else
798             {
799               g_string_append_printf (new_contents,
800                                       "%d %" G_GUINT64_FORMAT " %s\n",
801                                       line_id,
802                                       line_when,
803                                       tokens[2]);
804               max_line_id = MAX (line_id, max_line_id);
805               /* Only reuse entry if not older than 10 minutes.
806                *
807                * (We need a bit of grace time compared to 15 minutes above.. otherwise
808                * there's a race where we reuse the 14min59.9 secs old entry and a
809                * split-second later another server purges the now 15 minute old entry.)
810                */
811               if (now - line_when < 10 * 60)
812                 {
813                   if (!have_id)
814                     {
815                       use_id = line_id;
816                       use_cookie = tokens[2]; /* steal memory */
817                       tokens[2] = NULL;
818                       have_id = TRUE;
819                     }
820                 }
821             }
822           g_strfreev (tokens);
823         }
824     } /* for each line */
825
826   ret = TRUE;
827
828   if (have_id)
829     {
830       *out_id = use_id;
831       *out_cookie = use_cookie;
832       use_cookie = NULL;
833     }
834   else
835     {
836       gchar *raw_cookie;
837       *out_id = max_line_id + 1;
838       raw_cookie = random_blob (32);
839       *out_cookie = hexencode (raw_cookie, 32);
840       g_free (raw_cookie);
841
842       g_string_append_printf (new_contents,
843                               "%d %" G_GUINT64_FORMAT " %s\n",
844                               *out_id,
845                               (guint64) time (NULL),
846                               *out_cookie);
847       changed_file = TRUE;
848     }
849
850   /* and now actually write the cookie file if there are changes (this is atomic) */
851   if (changed_file)
852     {
853       if (!g_file_set_contents (path,
854                                 new_contents->str,
855                                 -1,
856                                 error))
857         {
858           *out_id = 0;
859           *out_cookie = 0;
860           g_free (*out_cookie);
861           ret = FALSE;
862           goto out;
863         }
864     }
865
866  out:
867
868   if (lock_fd != -1)
869     {
870       GError *local_error;
871       local_error = NULL;
872       if (!keyring_release_lock (path, lock_fd, &local_error))
873         {
874           if (error != NULL)
875             {
876               if (*error == NULL)
877                 {
878                   *error = local_error;
879                 }
880               else
881                 {
882                   g_prefix_error (error,
883                                   _("(Additionally, releasing the lock for `%s' also failed: %s) "),
884                                   path,
885                                   local_error->message);
886                 }
887             }
888           else
889             {
890               g_error_free (local_error);
891             }
892         }
893     }
894
895   g_free (keyring_dir);
896   g_free (path);
897   g_strfreev (lines);
898   g_free (contents);
899   if (new_contents != NULL)
900     g_string_free (new_contents, TRUE);
901   g_free (use_cookie);
902   return ret;
903 }
904
905 /* ---------------------------------------------------------------------------------------------------- */
906
907 static gchar *
908 generate_sha1 (const gchar *server_challenge,
909                const gchar *client_challenge,
910                const gchar *cookie)
911 {
912   GString *str;
913   gchar *sha1;
914
915   str = g_string_new (server_challenge);
916   g_string_append_c (str, ':');
917   g_string_append (str, client_challenge);
918   g_string_append_c (str, ':');
919   g_string_append (str, cookie);
920   sha1 = g_compute_checksum_for_string (G_CHECKSUM_SHA1, str->str, -1);
921   g_string_free (str, TRUE);
922
923   return sha1;
924 }
925
926 /* ---------------------------------------------------------------------------------------------------- */
927
928 static GDBusAuthMechanismState
929 mechanism_server_get_state (GDBusAuthMechanism   *mechanism)
930 {
931   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
932
933   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), G_DBUS_AUTH_MECHANISM_STATE_INVALID);
934   g_return_val_if_fail (m->priv->is_server && !m->priv->is_client, G_DBUS_AUTH_MECHANISM_STATE_INVALID);
935
936   return m->priv->state;
937 }
938
939 static void
940 mechanism_server_initiate (GDBusAuthMechanism   *mechanism,
941                            const gchar          *initial_response,
942                            gsize                 initial_response_len)
943 {
944   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
945
946   g_return_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism));
947   g_return_if_fail (!m->priv->is_server && !m->priv->is_client);
948
949   m->priv->is_server = TRUE;
950   m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
951
952   if (initial_response != NULL && strlen (initial_response) > 0)
953     {
954 #ifdef G_OS_UNIX
955       gint64 uid;
956       gchar *endp;
957
958       uid = g_ascii_strtoll (initial_response, &endp, 10);
959       if (*endp == '\0')
960         {
961           if (uid == getuid ())
962             {
963               m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND;
964             }
965         }
966 #elif defined(G_OS_WIN32)
967       gchar *sid;
968       sid = _g_dbus_win32_get_user_sid ();
969       if (g_strcmp0 (initial_response, sid) == 0)
970         m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND;
971       g_free (sid);
972 #else
973 #error Please implement for your OS
974 #endif
975     }
976 }
977
978 static void
979 mechanism_server_data_receive (GDBusAuthMechanism   *mechanism,
980                                const gchar          *data,
981                                gsize                 data_len)
982 {
983   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
984   gchar **tokens;
985   const gchar *client_challenge;
986   const gchar *alleged_sha1;
987   gchar *sha1;
988
989   g_return_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism));
990   g_return_if_fail (m->priv->is_server && !m->priv->is_client);
991   g_return_if_fail (m->priv->state == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA);
992
993   tokens = NULL;
994   sha1 = NULL;
995
996   tokens = g_strsplit (data, " ", 0);
997   if (g_strv_length (tokens) != 2)
998     {
999       g_warning ("Malformed data `%s'", data);
1000       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
1001       goto out;
1002     }
1003
1004   client_challenge = tokens[0];
1005   alleged_sha1 = tokens[1];
1006
1007   sha1 = generate_sha1 (m->priv->server_challenge, client_challenge, m->priv->cookie);
1008
1009   if (g_strcmp0 (sha1, alleged_sha1) == 0)
1010     {
1011       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED;
1012     }
1013   else
1014     {
1015       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
1016     }
1017
1018  out:
1019   g_strfreev (tokens);
1020   g_free (sha1);
1021 }
1022
1023 static gchar *
1024 mechanism_server_data_send (GDBusAuthMechanism   *mechanism,
1025                             gsize                *out_data_len)
1026 {
1027   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1028   gchar *s;
1029   gint cookie_id;
1030   const gchar *cookie_context;
1031   GError *error;
1032
1033   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), NULL);
1034   g_return_val_if_fail (m->priv->is_server && !m->priv->is_client, NULL);
1035   g_return_val_if_fail (m->priv->state == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND, NULL);
1036
1037   s = NULL;
1038
1039   /* TODO: use GDBusAuthObserver here to get the cookie context to use? */
1040   cookie_context = "org_gtk_gdbus_general";
1041
1042   cookie_id = -1;
1043   error = NULL;
1044   if (!keyring_generate_entry (cookie_context,
1045                                &cookie_id,
1046                                &m->priv->cookie,
1047                                &error))
1048     {
1049       g_warning ("Error adding entry to keyring: %s", error->message);
1050       g_error_free (error);
1051       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
1052       goto out;
1053     }
1054
1055   m->priv->server_challenge = random_ascii_string (16);
1056   s = g_strdup_printf ("%s %d %s",
1057                        cookie_context,
1058                        cookie_id,
1059                        m->priv->server_challenge);
1060
1061   m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA;
1062
1063  out:
1064   return s;
1065 }
1066
1067 static gchar *
1068 mechanism_server_get_reject_reason (GDBusAuthMechanism   *mechanism)
1069 {
1070   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1071
1072   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), NULL);
1073   g_return_val_if_fail (m->priv->is_server && !m->priv->is_client, NULL);
1074   g_return_val_if_fail (m->priv->state == G_DBUS_AUTH_MECHANISM_STATE_REJECTED, NULL);
1075
1076   /* can never end up here because we are never in the REJECTED state */
1077   g_assert_not_reached ();
1078
1079   return NULL;
1080 }
1081
1082 static void
1083 mechanism_server_shutdown (GDBusAuthMechanism   *mechanism)
1084 {
1085   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1086
1087   g_return_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism));
1088   g_return_if_fail (m->priv->is_server && !m->priv->is_client);
1089
1090   m->priv->is_server = FALSE;
1091 }
1092
1093 /* ---------------------------------------------------------------------------------------------------- */
1094
1095 static GDBusAuthMechanismState
1096 mechanism_client_get_state (GDBusAuthMechanism   *mechanism)
1097 {
1098   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1099
1100   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), G_DBUS_AUTH_MECHANISM_STATE_INVALID);
1101   g_return_val_if_fail (m->priv->is_client && !m->priv->is_server, G_DBUS_AUTH_MECHANISM_STATE_INVALID);
1102
1103   return m->priv->state;
1104 }
1105
1106 static gchar *
1107 mechanism_client_initiate (GDBusAuthMechanism   *mechanism,
1108                            gsize                *out_initial_response_len)
1109 {
1110   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1111   gchar *initial_response;
1112
1113   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), NULL);
1114   g_return_val_if_fail (!m->priv->is_server && !m->priv->is_client, NULL);
1115
1116   m->priv->is_client = TRUE;
1117   m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA;
1118
1119   *out_initial_response_len = -1;
1120
1121 #ifdef G_OS_UNIX
1122   initial_response = g_strdup_printf ("%" G_GINT64_FORMAT, (gint64) getuid ());
1123 #elif defined (G_OS_WIN32)
1124 initial_response = _g_dbus_win32_get_user_sid ();
1125 #else
1126 #error Please implement for your OS
1127 #endif
1128   g_assert (initial_response != NULL);
1129
1130   return initial_response;
1131 }
1132
1133 static void
1134 mechanism_client_data_receive (GDBusAuthMechanism   *mechanism,
1135                                const gchar          *data,
1136                                gsize                 data_len)
1137 {
1138   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1139   gchar **tokens;
1140   const gchar *cookie_context;
1141   guint cookie_id;
1142   const gchar *server_challenge;
1143   gchar *client_challenge;
1144   gchar *endp;
1145   gchar *cookie;
1146   GError *error;
1147   gchar *sha1;
1148
1149   g_return_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism));
1150   g_return_if_fail (m->priv->is_client && !m->priv->is_server);
1151   g_return_if_fail (m->priv->state == G_DBUS_AUTH_MECHANISM_STATE_WAITING_FOR_DATA);
1152
1153   tokens = NULL;
1154   cookie = NULL;
1155   client_challenge = NULL;
1156
1157   tokens = g_strsplit (data, " ", 0);
1158   if (g_strv_length (tokens) != 3)
1159     {
1160       g_warning ("Malformed data `%s'", data);
1161       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
1162       goto out;
1163     }
1164
1165   cookie_context = tokens[0];
1166   cookie_id = g_ascii_strtoll (tokens[1], &endp, 10);
1167   if (*endp != '\0')
1168     {
1169       g_warning ("Malformed cookie_id `%s'", tokens[1]);
1170       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
1171       goto out;
1172     }
1173   server_challenge = tokens[2];
1174
1175   error = NULL;
1176   cookie = keyring_lookup_entry (cookie_context, cookie_id, &error);
1177   if (cookie == NULL)
1178     {
1179       g_warning ("Problems looking up entry in keyring: %s", error->message);
1180       g_error_free (error);
1181       m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_REJECTED;
1182       goto out;
1183     }
1184
1185   client_challenge = random_ascii_string (16);
1186   sha1 = generate_sha1 (server_challenge, client_challenge, cookie);
1187   m->priv->to_send = g_strdup_printf ("%s %s", client_challenge, sha1);
1188   g_free (sha1);
1189   m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND;
1190
1191  out:
1192   g_strfreev (tokens);
1193   g_free (cookie);
1194   g_free (client_challenge);
1195 }
1196
1197 static gchar *
1198 mechanism_client_data_send (GDBusAuthMechanism   *mechanism,
1199                             gsize                *out_data_len)
1200 {
1201   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1202
1203   g_return_val_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism), NULL);
1204   g_return_val_if_fail (m->priv->is_client && !m->priv->is_server, NULL);
1205   g_return_val_if_fail (m->priv->state == G_DBUS_AUTH_MECHANISM_STATE_HAVE_DATA_TO_SEND, NULL);
1206
1207   g_assert (m->priv->to_send != NULL);
1208
1209   m->priv->state = G_DBUS_AUTH_MECHANISM_STATE_ACCEPTED;
1210
1211   return g_strdup (m->priv->to_send);
1212 }
1213
1214 static void
1215 mechanism_client_shutdown (GDBusAuthMechanism   *mechanism)
1216 {
1217   GDBusAuthMechanismSha1 *m = G_DBUS_AUTH_MECHANISM_SHA1 (mechanism);
1218
1219   g_return_if_fail (G_IS_DBUS_AUTH_MECHANISM_SHA1 (mechanism));
1220   g_return_if_fail (m->priv->is_client && !m->priv->is_server);
1221
1222   m->priv->is_client = FALSE;
1223 }
1224
1225 /* ---------------------------------------------------------------------------------------------------- */