2007-07-13 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-keyring.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-keyring.c Store secret cookies in your homedir
3  *
4  * Copyright (C) 2003, 2004  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-keyring.h"
25 #include "dbus-protocol.h"
26 #include <dbus/dbus-string.h>
27 #include <dbus/dbus-list.h>
28 #include <dbus/dbus-sysdeps.h>
29
30 /**
31  * @defgroup DBusKeyring keyring class
32  * @ingroup  DBusInternals
33  * @brief DBusKeyring data structure
34  *
35  * Types and functions related to DBusKeyring. DBusKeyring is intended
36  * to manage cookies used to authenticate clients to servers.  This is
37  * essentially the "verify that client can read the user's homedir"
38  * authentication mechanism.  Both client and server must have access
39  * to the homedir.
40  *
41  * The secret keys are not kept in locked memory, and are written to a
42  * file in the user's homedir. However they are transient (only used
43  * by a single server instance for a fixed period of time, then
44  * discarded). Also, the keys are not sent over the wire.
45  *
46  * @todo there's a memory leak on some codepath in here, I saw it once
47  * when running make check - probably some specific initial cookies
48  * present in the cookie file, then depending on what we do with them.
49  */
50
51 /**
52  * @defgroup DBusKeyringInternals DBusKeyring implementation details
53  * @ingroup  DBusInternals
54  * @brief DBusKeyring implementation details
55  *
56  * The guts of DBusKeyring.
57  *
58  * @{
59  */
60
61 /** The maximum age of a key before we create a new key to use in
62  * challenges.  This isn't super-reliably enforced, since system
63  * clocks can change or be wrong, but we make a best effort to only
64  * use keys for a short time.
65  */
66 #define NEW_KEY_TIMEOUT_SECONDS     (60*5)
67 /**
68  * The time after which we drop a key from the secrets file.
69  * The EXPIRE_KEYS_TIMEOUT_SECONDS - NEW_KEY_TIMEOUT_SECONDS is the minimum
70  * time window a client has to complete authentication.
71  */
72 #define EXPIRE_KEYS_TIMEOUT_SECONDS (NEW_KEY_TIMEOUT_SECONDS + (60*2))
73 /**
74  * The maximum amount of time a key can be in the future.
75  */
76 #define MAX_TIME_TRAVEL_SECONDS (60*5)
77
78 /**
79  * Maximum number of keys in the keyring before
80  * we just ignore the rest
81  */
82 #ifdef DBUS_BUILD_TESTS
83 #define MAX_KEYS_IN_FILE 10
84 #else
85 #define MAX_KEYS_IN_FILE 256
86 #endif
87
88 /**
89  * A single key from the cookie file
90  */
91 typedef struct
92 {
93   dbus_int32_t id; /**< identifier used to refer to the key */
94
95   long creation_time; /**< when the key was generated,
96                        *   as unix timestamp. signed long
97                        *   matches struct timeval.
98                        */
99   
100   DBusString secret; /**< the actual key */
101
102 } DBusKey;
103
104 /**
105  * @brief Internals of DBusKeyring.
106  * 
107  * DBusKeyring internals. DBusKeyring is an opaque object, it must be
108  * used via accessor functions.
109  */
110 struct DBusKeyring
111 {
112   int refcount;             /**< Reference count */
113   DBusString directory;     /**< Directory the below two items are inside */
114   DBusString filename;      /**< Keyring filename */
115   DBusString filename_lock; /**< Name of lockfile */
116   DBusKey *keys; /**< Keys loaded from the file */
117   int n_keys;    /**< Number of keys */
118   DBusCredentials *credentials; /**< Credentials containing user the keyring is for */
119 };
120
121 static DBusKeyring*
122 _dbus_keyring_new (void)
123 {
124   DBusKeyring *keyring;
125
126   keyring = dbus_new0 (DBusKeyring, 1);
127   if (keyring == NULL)
128     goto out_0;
129   
130   if (!_dbus_string_init (&keyring->directory))
131     goto out_1;
132
133   if (!_dbus_string_init (&keyring->filename))
134     goto out_2;
135
136   if (!_dbus_string_init (&keyring->filename_lock))
137     goto out_3;
138   
139   keyring->refcount = 1;
140   keyring->keys = NULL;
141   keyring->n_keys = 0;
142
143   return keyring;
144
145   /*  out_4: */
146   _dbus_string_free (&keyring->filename_lock);
147  out_3:
148   _dbus_string_free (&keyring->filename);
149  out_2:
150   _dbus_string_free (&keyring->directory);
151  out_1:
152   dbus_free (keyring);
153  out_0:
154   return NULL;
155 }
156
157 static void
158 free_keys (DBusKey *keys,
159            int      n_keys)
160 {
161   int i;
162
163   /* should be safe for args NULL, 0 */
164   
165   i = 0;
166   while (i < n_keys)
167     {
168       _dbus_string_free (&keys[i].secret);
169       ++i;
170     }
171
172   dbus_free (keys);
173 }
174
175 /* Our locking scheme is highly unreliable.  However, there is
176  * unfortunately no reliable locking scheme in user home directories;
177  * between bugs in Linux NFS, people using Tru64 or other total crap
178  * NFS, AFS, random-file-system-of-the-week, and so forth, fcntl() in
179  * homedirs simply generates tons of bug reports. This has been
180  * learned through hard experience with GConf, unfortunately.
181  *
182  * This bad hack might work better for the kind of lock we have here,
183  * which we don't expect to hold for any length of time.  Crashing
184  * while we hold it should be unlikely, and timing out such that we
185  * delete a stale lock should also be unlikely except when the
186  * filesystem is running really slowly.  Stuff might break in corner
187  * cases but as long as it's not a security-level breakage it should
188  * be OK.
189  */
190
191 /** Maximum number of timeouts waiting for lock before we decide it's stale */
192 #define MAX_LOCK_TIMEOUTS 32
193 /** Length of each timeout while waiting for a lock */
194 #define LOCK_TIMEOUT_MILLISECONDS 250
195
196 static dbus_bool_t
197 _dbus_keyring_lock (DBusKeyring *keyring)
198 {
199   int n_timeouts;
200   
201   n_timeouts = 0;
202   while (n_timeouts < MAX_LOCK_TIMEOUTS)
203     {
204       DBusError error;
205
206       dbus_error_init (&error);
207       if (_dbus_create_file_exclusively (&keyring->filename_lock,
208                                          &error))
209         break;
210
211       _dbus_verbose ("Did not get lock file, sleeping %d milliseconds (%s)\n",
212                      LOCK_TIMEOUT_MILLISECONDS, error.message);
213       dbus_error_free (&error);
214
215       _dbus_sleep_milliseconds (LOCK_TIMEOUT_MILLISECONDS);
216       
217       ++n_timeouts;
218     }
219
220   if (n_timeouts == MAX_LOCK_TIMEOUTS)
221     {
222       DBusError error;
223       
224       _dbus_verbose ("Lock file timed out %d times, assuming stale\n",
225                      n_timeouts);
226
227       dbus_error_init (&error);
228
229       if (!_dbus_delete_file (&keyring->filename_lock, &error))
230         {
231           _dbus_verbose ("Couldn't delete old lock file: %s\n",
232                          error.message);
233           dbus_error_free (&error);
234           return FALSE;
235         }
236
237       if (!_dbus_create_file_exclusively (&keyring->filename_lock,
238                                           &error))
239         {
240           _dbus_verbose ("Couldn't create lock file after deleting stale one: %s\n",
241                          error.message);
242           dbus_error_free (&error);
243           return FALSE;
244         }
245     }
246   
247   return TRUE;
248 }
249
250 static void
251 _dbus_keyring_unlock (DBusKeyring *keyring)
252 {
253   DBusError error;
254   dbus_error_init (&error);
255   if (!_dbus_delete_file (&keyring->filename_lock, &error))
256     {
257       _dbus_warn ("Failed to delete lock file: %s\n",
258                   error.message);
259       dbus_error_free (&error);
260     }
261 }
262
263 static DBusKey*
264 find_key_by_id (DBusKey *keys,
265                 int      n_keys,
266                 int      id)
267 {
268   int i;
269
270   i = 0;
271   while (i < n_keys)
272     {
273       if (keys[i].id == id)
274         return &keys[i];
275       
276       ++i;
277     }
278
279   return NULL;
280 }
281
282 static dbus_bool_t
283 add_new_key (DBusKey  **keys_p,
284              int       *n_keys_p,
285              DBusError *error)
286 {
287   DBusKey *new;
288   DBusString bytes;
289   int id;
290   long timestamp;
291   const unsigned char *s;
292   dbus_bool_t retval;
293   DBusKey *keys;
294   int n_keys;
295
296   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
297   
298   if (!_dbus_string_init (&bytes))
299     {
300       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
301       return FALSE;
302     }
303
304   keys = *keys_p;
305   n_keys = *n_keys_p;
306   retval = FALSE;
307       
308   /* Generate an integer ID and then the actual key. */
309  retry:
310       
311   if (!_dbus_generate_random_bytes (&bytes, 4))
312     {
313       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
314       goto out;
315     }
316
317   s = (const unsigned char*) _dbus_string_get_const_data (&bytes);
318       
319   id = s[0] | (s[1] << 8) | (s[2] << 16) | (s[3] << 24);
320   if (id < 0)
321     id = - id;
322   _dbus_assert (id >= 0);
323
324   if (find_key_by_id (keys, n_keys, id) != NULL)
325     {
326       _dbus_string_set_length (&bytes, 0);
327       _dbus_verbose ("Key ID %d already existed, trying another one\n",
328                      id);
329       goto retry;
330     }
331
332   _dbus_verbose ("Creating key with ID %d\n", id);
333       
334 #define KEY_LENGTH_BYTES 24
335   _dbus_string_set_length (&bytes, 0);
336   if (!_dbus_generate_random_bytes (&bytes, KEY_LENGTH_BYTES))
337     {
338       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
339       goto out;
340     }
341
342   new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
343   if (new == NULL)
344     {
345       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
346       goto out;
347     }
348
349   keys = new;
350   *keys_p = keys; /* otherwise *keys_p ends up invalid */
351   n_keys += 1;
352
353   if (!_dbus_string_init (&keys[n_keys-1].secret))
354     {
355       n_keys -= 1; /* we don't want to free the one we didn't init */
356       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
357       goto out;
358     }
359
360   _dbus_get_current_time (&timestamp, NULL);
361       
362   keys[n_keys-1].id = id;
363   keys[n_keys-1].creation_time = timestamp;
364   if (!_dbus_string_move (&bytes, 0,
365                           &keys[n_keys-1].secret,
366                           0))
367     {
368       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
369       _dbus_string_free (&keys[n_keys-1].secret);
370       n_keys -= 1;
371       goto out;
372     }
373   
374   retval = TRUE;
375   
376  out:
377   *n_keys_p = n_keys;
378   
379   _dbus_string_free (&bytes);
380   return retval;
381 }
382
383 /**
384  * Reloads the keyring file, optionally adds one new key to the file,
385  * removes all expired keys from the file iff a key was added, then
386  * resaves the file.  Stores the keys from the file in keyring->keys.
387  * Note that the file is only resaved (written to) if a key is added,
388  * this means that only servers ever write to the file and need to
389  * lock it, which avoids a lot of lock contention at login time and
390  * such.
391  *
392  * @param keyring the keyring
393  * @param add_new #TRUE to add a new key to the file, expire keys, and resave
394  * @param error return location for errors
395  * @returns #FALSE on failure
396  */
397 static dbus_bool_t
398 _dbus_keyring_reload (DBusKeyring *keyring,
399                       dbus_bool_t  add_new,
400                       DBusError   *error)
401 {
402   DBusString contents;
403   DBusString line;
404   dbus_bool_t retval;
405   dbus_bool_t have_lock;
406   DBusKey *keys;
407   int n_keys;
408   int i;
409   long now;
410   DBusError tmp_error;
411
412   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
413   
414   if (!_dbus_check_dir_is_private_to_user (&keyring->directory, error))
415     return FALSE;
416     
417   if (!_dbus_string_init (&contents))
418     {
419       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
420       return FALSE;
421     }
422
423   if (!_dbus_string_init (&line))
424     {
425       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
426       _dbus_string_free (&contents);
427       return FALSE;
428     }
429    
430   keys = NULL;
431   n_keys = 0;
432   retval = FALSE;
433   have_lock = FALSE;
434
435   _dbus_get_current_time (&now, NULL);
436   
437   if (add_new)
438     {
439       if (!_dbus_keyring_lock (keyring))
440         {
441           dbus_set_error (error, DBUS_ERROR_FAILED,
442                           "Could not lock keyring file to add to it");
443           goto out;
444         }
445
446       have_lock = TRUE;
447     }
448
449   dbus_error_init (&tmp_error);
450   if (!_dbus_file_get_contents (&contents, 
451                                 &keyring->filename,
452                                 &tmp_error))
453     {
454       _dbus_verbose ("Failed to load keyring file: %s\n",
455                      tmp_error.message);
456       /* continue with empty keyring file, so we recreate it */
457       dbus_error_free (&tmp_error);
458     }
459
460   if (!_dbus_string_validate_ascii (&contents, 0,
461                                     _dbus_string_get_length (&contents)))
462     {
463       _dbus_warn ("Secret keyring file contains non-ASCII! Ignoring existing contents\n");
464       _dbus_string_set_length (&contents, 0);
465     }
466
467   /* FIXME this is badly inefficient for large keyring files
468    * (not that large keyring files exist outside of test suites)
469    */
470   while (_dbus_string_pop_line (&contents, &line))
471     {
472       int next;
473       long val;
474       int id;
475       long timestamp;
476       int len;
477       int end;
478       DBusKey *new;
479
480       /* Don't load more than the max. */
481       if (n_keys >= (add_new ? MAX_KEYS_IN_FILE - 1 : MAX_KEYS_IN_FILE))
482         break;
483       
484       next = 0;
485       if (!_dbus_string_parse_int (&line, 0, &val, &next))
486         {
487           _dbus_verbose ("could not parse secret key ID at start of line\n");
488           continue;
489         }
490
491       if (val > _DBUS_INT32_MAX || val < 0)
492         {
493           _dbus_verbose ("invalid secret key ID at start of line\n");
494           continue;
495         }
496       
497       id = val;
498
499       _dbus_string_skip_blank (&line, next, &next);
500       
501       if (!_dbus_string_parse_int (&line, next, &timestamp, &next))
502         {
503           _dbus_verbose ("could not parse secret key timestamp\n");
504           continue;
505         }
506
507       if (timestamp < 0 ||
508           (now + MAX_TIME_TRAVEL_SECONDS) < timestamp ||
509           (now - EXPIRE_KEYS_TIMEOUT_SECONDS) > timestamp)
510         {
511           _dbus_verbose ("dropping/ignoring %ld-seconds old key with timestamp %ld as current time is %ld\n",
512                          now - timestamp, timestamp, now);
513           continue;
514         }
515       
516       _dbus_string_skip_blank (&line, next, &next);
517
518       len = _dbus_string_get_length (&line);
519
520       if ((len - next) == 0)
521         {
522           _dbus_verbose ("no secret key after ID and timestamp\n");
523           continue;
524         }
525       
526       /* We have all three parts */
527       new = dbus_realloc (keys, sizeof (DBusKey) * (n_keys + 1));
528       if (new == NULL)
529         {
530           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
531           goto out;
532         }
533
534       keys = new;
535       n_keys += 1;
536
537       if (!_dbus_string_init (&keys[n_keys-1].secret))
538         {
539           n_keys -= 1; /* we don't want to free the one we didn't init */
540           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
541           goto out;
542         }
543       
544       keys[n_keys-1].id = id;
545       keys[n_keys-1].creation_time = timestamp;
546       if (!_dbus_string_hex_decode (&line, next, &end,
547                                     &keys[n_keys-1].secret, 0))
548         {
549           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
550           goto out;
551         }
552
553       if (_dbus_string_get_length (&line) != end)
554         {
555           _dbus_verbose ("invalid hex encoding in keyring file\n");
556           _dbus_string_free (&keys[n_keys - 1].secret);
557           n_keys -= 1;
558           continue;
559         }
560     }
561
562   _dbus_verbose ("Successfully loaded %d existing keys\n",
563                  n_keys);
564
565   if (add_new)
566     {
567       if (!add_new_key (&keys, &n_keys, error))
568         {
569           _dbus_verbose ("Failed to generate new key: %s\n",
570                          error ? error->message : "(unknown)");
571           goto out;
572         }
573
574       _dbus_string_set_length (&contents, 0);
575
576       i = 0;
577       while (i < n_keys)
578         {
579           if (!_dbus_string_append_int (&contents,
580                                         keys[i].id))
581             goto nomem;
582
583           if (!_dbus_string_append_byte (&contents, ' '))
584             goto nomem;
585
586           if (!_dbus_string_append_int (&contents,
587                                         keys[i].creation_time))
588             goto nomem;
589
590           if (!_dbus_string_append_byte (&contents, ' '))
591             goto nomem;
592
593           if (!_dbus_string_hex_encode (&keys[i].secret, 0,
594                                         &contents,
595                                         _dbus_string_get_length (&contents)))
596             goto nomem;
597
598           if (!_dbus_string_append_byte (&contents, '\n'))
599             goto nomem;          
600           
601           ++i;
602           continue;
603
604         nomem:
605           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
606           goto out;
607         }
608       
609       if (!_dbus_string_save_to_file (&contents, &keyring->filename,
610                                       error))
611         goto out;
612     }
613
614   if (keyring->keys)
615     free_keys (keyring->keys, keyring->n_keys);
616   keyring->keys = keys;
617   keyring->n_keys = n_keys;
618   keys = NULL;
619   n_keys = 0;
620   
621   retval = TRUE;  
622   
623  out:
624   if (have_lock)
625     _dbus_keyring_unlock (keyring);
626   
627   if (! ((retval == TRUE && (error == NULL || error->name == NULL)) ||
628          (retval == FALSE && (error == NULL || error->name != NULL))))
629     {
630       if (error && error->name)
631         _dbus_verbose ("error is %s: %s\n", error->name, error->message);
632       _dbus_warn ("returning %d but error pointer %p name %s\n",
633                   retval, error, error->name ? error->name : "(none)");
634       _dbus_assert_not_reached ("didn't handle errors properly");
635     }
636   
637   if (keys != NULL)
638     {
639       i = 0;
640       while (i < n_keys)
641         {
642           _dbus_string_zero (&keys[i].secret);
643           _dbus_string_free (&keys[i].secret);
644           ++i;
645         }
646
647       dbus_free (keys);
648     }
649   
650   _dbus_string_free (&contents);
651   _dbus_string_free (&line);
652
653   return retval;
654 }
655
656 /** @} */ /* end of internals */
657
658 /**
659  * @addtogroup DBusKeyring
660  *
661  * @{
662  */
663
664 /**
665  * Increments reference count of the keyring
666  *
667  * @param keyring the keyring
668  * @returns the keyring
669  */
670 DBusKeyring *
671 _dbus_keyring_ref (DBusKeyring *keyring)
672 {
673   keyring->refcount += 1;
674
675   return keyring;
676 }
677
678 /**
679  * Decrements refcount and finalizes if it reaches
680  * zero.
681  *
682  * @param keyring the keyring
683  */
684 void
685 _dbus_keyring_unref (DBusKeyring *keyring)
686 {
687   keyring->refcount -= 1;
688
689   if (keyring->refcount == 0)
690     {
691       if (keyring->credentials)
692         _dbus_credentials_unref (keyring->credentials);
693
694       _dbus_string_free (&keyring->filename);
695       _dbus_string_free (&keyring->filename_lock);
696       _dbus_string_free (&keyring->directory);
697       free_keys (keyring->keys, keyring->n_keys);
698       dbus_free (keyring);      
699     }
700 }
701
702 /**
703  * Creates a new keyring that lives in the ~/.dbus-keyrings directory
704  * of the given user credentials. If the credentials are #NULL or
705  * empty, uses those of the current process.
706  *
707  * @param username username to get keyring for, or #NULL
708  * @param context which keyring to get
709  * @param error return location for errors
710  * @returns the keyring or #NULL on error
711  */
712 DBusKeyring*
713 _dbus_keyring_new_for_credentials (DBusCredentials  *credentials,
714                                    const DBusString *context,
715                                    DBusError        *error)
716 {
717   DBusString ringdir;
718   DBusKeyring *keyring;
719   dbus_bool_t error_set;
720   DBusError tmp_error;
721   DBusCredentials *our_credentials;
722   
723   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
724   
725   keyring = NULL;
726   error_set = FALSE;
727   our_credentials = NULL;
728   
729   if (!_dbus_string_init (&ringdir))
730     {
731       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
732       return NULL;
733     }
734
735   if (credentials != NULL)
736     {
737       our_credentials = _dbus_credentials_copy (credentials);
738     }
739   else
740     {
741       our_credentials = _dbus_credentials_new_from_current_process ();
742     }
743   
744   if (our_credentials == NULL)
745     goto failed;
746
747   if (_dbus_credentials_are_anonymous (our_credentials))
748     {
749       if (!_dbus_credentials_add_from_current_process (our_credentials))
750         goto failed;
751     }
752   
753   if (!_dbus_append_keyring_directory_for_credentials (&ringdir,
754                                                        our_credentials))
755     goto failed;
756   
757   keyring = _dbus_keyring_new ();
758   if (keyring == NULL)
759     goto failed;
760
761   _dbus_assert (keyring->credentials == NULL);
762   keyring->credentials = our_credentials;
763   our_credentials = NULL; /* so we don't unref it again later */
764   
765   /* should have been validated already, but paranoia check here */
766   if (!_dbus_keyring_validate_context (context))
767     {
768       error_set = TRUE;
769       dbus_set_error_const (error,
770                             DBUS_ERROR_FAILED,
771                             "Invalid context in keyring creation");
772       goto failed;
773     }
774
775   /* Save keyring dir in the keyring object */
776   if (!_dbus_string_copy (&ringdir, 0,
777                           &keyring->directory, 0))
778     goto failed;  
779
780   /* Create keyring->filename based on keyring dir and context */
781   if (!_dbus_string_copy (&keyring->directory, 0,
782                           &keyring->filename, 0))
783     goto failed;
784
785   if (!_dbus_concat_dir_and_file (&keyring->filename,
786                                   context))
787     goto failed;
788
789   /* Create lockfile name */
790   if (!_dbus_string_copy (&keyring->filename, 0,
791                           &keyring->filename_lock, 0))
792     goto failed;
793
794   if (!_dbus_string_append (&keyring->filename_lock, ".lock"))
795     goto failed;
796
797   /* Reload keyring */
798   dbus_error_init (&tmp_error);
799   if (!_dbus_keyring_reload (keyring, FALSE, &tmp_error))
800     {
801       _dbus_verbose ("didn't load an existing keyring: %s\n",
802                      tmp_error.message);
803       dbus_error_free (&tmp_error);
804     }
805   
806   /* We don't fail fatally if we can't create the directory,
807    * but the keyring will probably always be empty
808    * unless someone else manages to create it
809    */
810   dbus_error_init (&tmp_error);
811   if (!_dbus_create_directory (&keyring->directory,
812                                &tmp_error))
813     {
814       _dbus_verbose ("Creating keyring directory: %s\n",
815                      tmp_error.message);
816       dbus_error_free (&tmp_error);
817     }
818
819   _dbus_string_free (&ringdir);
820   
821   return keyring;
822   
823  failed:
824   if (!error_set)
825     dbus_set_error_const (error,
826                           DBUS_ERROR_NO_MEMORY,
827                           NULL);
828   if (our_credentials)
829     _dbus_credentials_unref (our_credentials);
830   if (keyring)
831     _dbus_keyring_unref (keyring);
832   _dbus_string_free (&ringdir);
833   return NULL;
834
835 }
836
837 /**
838  * Checks whether the context is a valid context.
839  * Contexts that might cause confusion when used
840  * in filenames are not allowed (contexts can't
841  * start with a dot or contain dir separators).
842  *
843  * @todo this is the most inefficient implementation
844  * imaginable.
845  *
846  * @param context the context
847  * @returns #TRUE if valid
848  */
849 dbus_bool_t
850 _dbus_keyring_validate_context (const DBusString *context)
851 {
852   if (_dbus_string_get_length (context) == 0)
853     {
854       _dbus_verbose ("context is zero-length\n");
855       return FALSE;
856     }
857
858   if (!_dbus_string_validate_ascii (context, 0,
859                                     _dbus_string_get_length (context)))
860     {
861       _dbus_verbose ("context not valid ascii\n");
862       return FALSE;
863     }
864   
865   /* no directory separators */  
866   if (_dbus_string_find (context, 0, "/", NULL))
867     {
868       _dbus_verbose ("context contains a slash\n");
869       return FALSE;
870     }
871
872   if (_dbus_string_find (context, 0, "\\", NULL))
873     {
874       _dbus_verbose ("context contains a backslash\n");
875       return FALSE;
876     }
877
878   /* prevent attempts to use dotfiles or ".." or ".lock"
879    * all of which might allow some kind of attack
880    */
881   if (_dbus_string_find (context, 0, ".", NULL))
882     {
883       _dbus_verbose ("context contains a dot\n");
884       return FALSE;
885     }
886
887   /* no spaces/tabs, those are used for separators in the protocol */
888   if (_dbus_string_find_blank (context, 0, NULL))
889     {
890       _dbus_verbose ("context contains a blank\n");
891       return FALSE;
892     }
893
894   if (_dbus_string_find (context, 0, "\n", NULL))
895     {
896       _dbus_verbose ("context contains a newline\n");
897       return FALSE;
898     }
899
900   if (_dbus_string_find (context, 0, "\r", NULL))
901     {
902       _dbus_verbose ("context contains a carriage return\n");
903       return FALSE;
904     }
905   
906   return TRUE;
907 }
908
909 static DBusKey*
910 find_recent_key (DBusKeyring *keyring)
911 {
912   int i;
913   long tv_sec, tv_usec;
914
915   _dbus_get_current_time (&tv_sec, &tv_usec);
916   
917   i = 0;
918   while (i < keyring->n_keys)
919     {
920       DBusKey *key = &keyring->keys[i];
921
922       _dbus_verbose ("Key %d is %ld seconds old\n",
923                      i, tv_sec - key->creation_time);
924       
925       if ((tv_sec - NEW_KEY_TIMEOUT_SECONDS) < key->creation_time)
926         return key;
927       
928       ++i;
929     }
930
931   return NULL;
932 }
933
934 /**
935  * Gets a recent key to use for authentication.
936  * If no recent key exists, creates one. Returns
937  * the key ID. If a key can't be written to the keyring
938  * file so no recent key can be created, returns -1.
939  * All valid keys are > 0.
940  *
941  * @param keyring the keyring
942  * @param error error on failure
943  * @returns key ID to use for auth, or -1 on failure
944  */
945 int
946 _dbus_keyring_get_best_key (DBusKeyring  *keyring,
947                             DBusError    *error)
948 {
949   DBusKey *key;
950
951   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
952   
953   key = find_recent_key (keyring);
954   if (key)
955     return key->id;
956
957   /* All our keys are too old, or we've never loaded the
958    * keyring. Create a new one.
959    */
960   if (!_dbus_keyring_reload (keyring, TRUE,
961                              error))
962     return -1;
963
964   key = find_recent_key (keyring);
965   if (key)
966     return key->id;
967   else
968     {
969       dbus_set_error_const (error,
970                             DBUS_ERROR_FAILED,
971                             "No recent-enough key found in keyring, and unable to create a new key");
972       return -1;
973     }
974 }
975
976 /**
977  * Checks whether the keyring is for the same user as the given credentials.
978  *
979  * @param keyring the keyring
980  * @param credentials the credentials to check
981  *
982  * @returns #TRUE if the keyring belongs to the given user
983  */
984 dbus_bool_t
985 _dbus_keyring_is_for_credentials (DBusKeyring           *keyring,
986                                   DBusCredentials       *credentials)
987 {
988   return _dbus_credentials_same_user (keyring->credentials,
989                                       credentials);
990 }
991
992 /**
993  * Gets the hex-encoded secret key for the given ID.
994  * Returns #FALSE if not enough memory. Returns #TRUE
995  * but empty key on any other error such as unknown
996  * key ID.
997  *
998  * @param keyring the keyring
999  * @param key_id the key ID
1000  * @param hex_key string to append hex-encoded key to
1001  * @returns #TRUE if we had enough memory
1002  */
1003 dbus_bool_t
1004 _dbus_keyring_get_hex_key (DBusKeyring       *keyring,
1005                            int                key_id,
1006                            DBusString        *hex_key)
1007 {
1008   DBusKey *key;
1009
1010   key = find_key_by_id (keyring->keys,
1011                         keyring->n_keys,
1012                         key_id);
1013   if (key == NULL)
1014     return TRUE; /* had enough memory, so TRUE */
1015
1016   return _dbus_string_hex_encode (&key->secret, 0,
1017                                   hex_key,
1018                                   _dbus_string_get_length (hex_key));
1019 }
1020
1021 /** @} */ /* end of exposed API */
1022
1023 #ifdef DBUS_BUILD_TESTS
1024 #include "dbus-test.h"
1025 #include <stdio.h>
1026
1027 dbus_bool_t
1028 _dbus_keyring_test (void)
1029 {
1030   DBusString context;
1031   DBusKeyring *ring1;
1032   DBusKeyring *ring2;
1033   int id;
1034   DBusError error;
1035   int i;
1036
1037   ring1 = NULL;
1038   ring2 = NULL;
1039   
1040   /* Context validation */
1041   
1042   _dbus_string_init_const (&context, "foo");
1043   _dbus_assert (_dbus_keyring_validate_context (&context));
1044   _dbus_string_init_const (&context, "org_freedesktop_blah");
1045   _dbus_assert (_dbus_keyring_validate_context (&context));
1046   
1047   _dbus_string_init_const (&context, "");
1048   _dbus_assert (!_dbus_keyring_validate_context (&context));
1049   _dbus_string_init_const (&context, ".foo");
1050   _dbus_assert (!_dbus_keyring_validate_context (&context));
1051   _dbus_string_init_const (&context, "bar.foo");
1052   _dbus_assert (!_dbus_keyring_validate_context (&context));
1053   _dbus_string_init_const (&context, "bar/foo");
1054   _dbus_assert (!_dbus_keyring_validate_context (&context));
1055   _dbus_string_init_const (&context, "bar\\foo");
1056   _dbus_assert (!_dbus_keyring_validate_context (&context));
1057   _dbus_string_init_const (&context, "foo\xfa\xf0");
1058   _dbus_assert (!_dbus_keyring_validate_context (&context));
1059   _dbus_string_init_const (&context, "foo\x80");
1060   _dbus_assert (!_dbus_keyring_validate_context (&context));
1061   _dbus_string_init_const (&context, "foo\x7f");
1062   _dbus_assert (_dbus_keyring_validate_context (&context));
1063   _dbus_string_init_const (&context, "foo bar");
1064   _dbus_assert (!_dbus_keyring_validate_context (&context));
1065   
1066   if (!_dbus_string_init (&context))
1067     _dbus_assert_not_reached ("no memory");
1068   if (!_dbus_string_append_byte (&context, '\0'))
1069     _dbus_assert_not_reached ("no memory");
1070   _dbus_assert (!_dbus_keyring_validate_context (&context));
1071   _dbus_string_free (&context);
1072
1073   /* Now verify that if we create a key in keyring 1,
1074    * it is properly loaded in keyring 2
1075    */
1076
1077   _dbus_string_init_const (&context, "org_freedesktop_dbus_testsuite");
1078   dbus_error_init (&error);
1079   ring1 = _dbus_keyring_new_for_credentials (NULL, &context,
1080                                              &error);
1081   _dbus_assert (ring1);
1082   _dbus_assert (error.name == NULL);
1083
1084   id = _dbus_keyring_get_best_key (ring1, &error);
1085   if (id < 0)
1086     {
1087       fprintf (stderr, "Could not load keyring: %s\n", error.message);
1088       dbus_error_free (&error);
1089       goto failure;
1090     }
1091
1092   ring2 = _dbus_keyring_new_for_credentials (NULL, &context, &error);
1093   _dbus_assert (ring2);
1094   _dbus_assert (error.name == NULL);
1095   
1096   if (ring1->n_keys != ring2->n_keys)
1097     {
1098       fprintf (stderr, "Different number of keys in keyrings\n");
1099       goto failure;
1100     }
1101
1102   /* We guarantee we load and save keeping keys in a fixed
1103    * order
1104    */
1105   i = 0;
1106   while (i < ring1->n_keys)
1107     {
1108       if (ring1->keys[i].id != ring2->keys[i].id)
1109         {
1110           fprintf (stderr, "Keyring 1 has first key ID %d and keyring 2 has %d\n",
1111                    ring1->keys[i].id, ring2->keys[i].id);
1112           goto failure;
1113         }      
1114
1115       if (ring1->keys[i].creation_time != ring2->keys[i].creation_time)
1116         {
1117           fprintf (stderr, "Keyring 1 has first key time %ld and keyring 2 has %ld\n",
1118                    ring1->keys[i].creation_time, ring2->keys[i].creation_time);
1119           goto failure;
1120         }
1121
1122       if (!_dbus_string_equal (&ring1->keys[i].secret,
1123                                &ring2->keys[i].secret))
1124         {
1125           fprintf (stderr, "Keyrings 1 and 2 have different secrets for same ID/timestamp\n");
1126           goto failure;
1127         }
1128       
1129       ++i;
1130     }
1131
1132   printf (" %d keys in test\n", ring1->n_keys);
1133
1134   /* Test ref/unref */
1135   _dbus_keyring_ref (ring1);
1136   _dbus_keyring_ref (ring2);
1137   _dbus_keyring_unref (ring1);
1138   _dbus_keyring_unref (ring2);
1139
1140
1141   /* really unref */
1142   _dbus_keyring_unref (ring1);
1143   _dbus_keyring_unref (ring2);
1144   
1145   return TRUE;
1146
1147  failure:
1148   if (ring1)
1149     _dbus_keyring_unref (ring1);
1150   if (ring2)
1151     _dbus_keyring_unref (ring2);
1152
1153   return FALSE;
1154 }
1155
1156 #endif /* DBUS_BUILD_TESTS */
1157