2007-07-13 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-userdb.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-userdb.c User database abstraction
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 #define DBUS_USERDB_INCLUDES_PRIVATE 1
24 #include "dbus-userdb.h"
25 #include "dbus-hash.h"
26 #include "dbus-test.h"
27 #include "dbus-internals.h"
28 #include "dbus-protocol.h"
29 #include "dbus-credentials.h"
30 #include <string.h>
31
32 /**
33  * @addtogroup DBusInternalsUtils
34  * @{
35  */
36
37 /**
38  * Frees the given #DBusUserInfo's members with _dbus_user_info_free()
39  * and also calls dbus_free() on the block itself
40  *
41  * @param info the info
42  */
43 void
44 _dbus_user_info_free_allocated (DBusUserInfo *info)
45 {
46   if (info == NULL) /* hash table will pass NULL */
47     return;
48
49   _dbus_user_info_free (info);
50   dbus_free (info);
51 }
52
53 /**
54  * Frees the given #DBusGroupInfo's members with _dbus_group_info_free()
55  * and also calls dbus_free() on the block itself
56  *
57  * @param info the info
58  */
59 void
60 _dbus_group_info_free_allocated (DBusGroupInfo *info)
61 {
62   if (info == NULL) /* hash table will pass NULL */
63     return;
64
65   _dbus_group_info_free (info);
66   dbus_free (info);
67 }
68
69 /**
70  * Frees the members of info
71  * (but not info itself)
72  * @param info the user info struct
73  */
74 void
75 _dbus_user_info_free (DBusUserInfo *info)
76 {
77   dbus_free (info->group_ids);
78   dbus_free (info->username);
79   dbus_free (info->homedir);
80 }
81
82 /**
83  * Frees the members of info (but not info itself).
84  *
85  * @param info the group info
86  */
87 void
88 _dbus_group_info_free (DBusGroupInfo    *info)
89 {
90   dbus_free (info->groupname);
91 }
92
93 /**
94  * Checks if a given string is actually a number 
95  * and converts it if it is 
96  *
97  * @param str the string to check
98  * @param num the memory location of the unsigned long to fill in
99  * @returns TRUE if str is a number and num is filled in 
100  */
101 dbus_bool_t
102 _dbus_is_a_number (const DBusString *str,
103                    unsigned long    *num)
104 {
105   int end;
106
107   if (_dbus_string_parse_uint (str, 0, num, &end) &&
108       end == _dbus_string_get_length (str))
109     return TRUE;
110   else
111     return FALSE;
112 }
113
114 /**
115  * Looks up a uid or username in the user database.  Only one of name
116  * or UID can be provided. There are wrapper functions for this that
117  * are better to use, this one does no locking or anything on the
118  * database and otherwise sort of sucks.
119  *
120  * @param db the database
121  * @param uid the user ID or #DBUS_UID_UNSET
122  * @param username username or #NULL 
123  * @param error error to fill in
124  * @returns the entry in the database
125  */
126 DBusUserInfo*
127 _dbus_user_database_lookup (DBusUserDatabase *db,
128                             dbus_uid_t        uid,
129                             const DBusString *username,
130                             DBusError        *error)
131 {
132   DBusUserInfo *info;
133
134   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
135   _dbus_assert (uid != DBUS_UID_UNSET || username != NULL);
136
137   /* See if the username is really a number */
138   if (uid == DBUS_UID_UNSET)
139     {
140       unsigned long n;
141
142       if (_dbus_is_a_number (username, &n))
143         uid = n;
144     }
145
146 #ifdef DBUS_ENABLE_USER_CACHE  
147   if (uid != DBUS_UID_UNSET)
148     info = _dbus_hash_table_lookup_ulong (db->users, uid);
149   else
150     info = _dbus_hash_table_lookup_string (db->users_by_name, _dbus_string_get_const_data (username));
151
152   if (info)
153     {
154       _dbus_verbose ("Using cache for UID "DBUS_UID_FORMAT" information\n",
155                      info->uid);
156       return info;
157     }
158   else
159 #else 
160   if (1)
161 #endif
162     {
163       if (uid != DBUS_UID_UNSET)
164         _dbus_verbose ("No cache for UID "DBUS_UID_FORMAT"\n",
165                        uid);
166       else
167         _dbus_verbose ("No cache for user \"%s\"\n",
168                        _dbus_string_get_const_data (username));
169       
170       info = dbus_new0 (DBusUserInfo, 1);
171       if (info == NULL)
172         {
173           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
174           return NULL;
175         }
176
177       if (uid != DBUS_UID_UNSET)
178         {
179           if (!_dbus_user_info_fill_uid (info, uid, error))
180             {
181               _DBUS_ASSERT_ERROR_IS_SET (error);
182               _dbus_user_info_free_allocated (info);
183               return NULL;
184             }
185         }
186       else
187         {
188           if (!_dbus_user_info_fill (info, username, error))
189             {
190               _DBUS_ASSERT_ERROR_IS_SET (error);
191               _dbus_user_info_free_allocated (info);
192               return NULL;
193             }
194         }
195
196       /* be sure we don't use these after here */
197       uid = DBUS_UID_UNSET;
198       username = NULL;
199
200       /* insert into hash */
201       if (!_dbus_hash_table_insert_ulong (db->users, info->uid, info))
202         {
203           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
204           _dbus_user_info_free_allocated (info);
205           return NULL;
206         }
207
208       if (!_dbus_hash_table_insert_string (db->users_by_name,
209                                            info->username,
210                                            info))
211         {
212           _dbus_hash_table_remove_ulong (db->users, info->uid);
213           dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
214           return NULL;
215         }
216       
217       return info;
218     }
219 }
220
221 static dbus_bool_t database_locked = FALSE;
222 static DBusUserDatabase *system_db = NULL;
223 static DBusString process_username;
224 static DBusString process_homedir;
225       
226 static void
227 shutdown_system_db (void *data)
228 {
229   _dbus_user_database_unref (system_db);
230   system_db = NULL;
231   _dbus_string_free (&process_username);
232   _dbus_string_free (&process_homedir);
233 }
234
235 static dbus_bool_t
236 init_system_db (void)
237 {
238   _dbus_assert (database_locked);
239     
240   if (system_db == NULL)
241     {
242       DBusError error;
243       const DBusUserInfo *info;
244       
245       system_db = _dbus_user_database_new ();
246       if (system_db == NULL)
247         return FALSE;
248
249       dbus_error_init (&error);
250
251       if (!_dbus_user_database_get_uid (system_db,
252                                         _dbus_getuid (),
253                                         &info,
254                                         &error))
255         {
256           _dbus_user_database_unref (system_db);
257           system_db = NULL;
258           
259           if (dbus_error_has_name (&error, DBUS_ERROR_NO_MEMORY))
260             {
261               dbus_error_free (&error);
262               return FALSE;
263             }
264           else
265             {
266               /* This really should not happen. */
267               _dbus_warn ("Could not get password database information for UID of current process: %s\n",
268                           error.message);
269               dbus_error_free (&error);
270               return FALSE;
271             }
272         }
273
274       if (!_dbus_string_init (&process_username))
275         {
276           _dbus_user_database_unref (system_db);
277           system_db = NULL;
278           return FALSE;
279         }
280
281       if (!_dbus_string_init (&process_homedir))
282         {
283           _dbus_string_free (&process_username);
284           _dbus_user_database_unref (system_db);
285           system_db = NULL;
286           return FALSE;
287         }
288
289       if (!_dbus_string_append (&process_username,
290                                 info->username) ||
291           !_dbus_string_append (&process_homedir,
292                                 info->homedir) ||
293           !_dbus_register_shutdown_func (shutdown_system_db, NULL))
294         {
295           _dbus_string_free (&process_username);
296           _dbus_string_free (&process_homedir);
297           _dbus_user_database_unref (system_db);
298           system_db = NULL;
299           return FALSE;
300         }
301     }
302
303   return TRUE;
304 }
305
306 /**
307  * Locks global system user database.
308  */
309 void
310 _dbus_user_database_lock_system (void)
311 {
312   _DBUS_LOCK (system_users);
313   database_locked = TRUE;
314 }
315
316 /**
317  * Unlocks global system user database.
318  */
319 void
320 _dbus_user_database_unlock_system (void)
321 {
322   database_locked = FALSE;
323   _DBUS_UNLOCK (system_users);
324 }
325
326 /**
327  * Gets the system global user database;
328  * must be called with lock held (_dbus_user_database_lock_system()).
329  *
330  * @returns the database or #NULL if no memory
331  */
332 DBusUserDatabase*
333 _dbus_user_database_get_system (void)
334 {
335   _dbus_assert (database_locked);
336
337   init_system_db ();
338   
339   return system_db;
340 }
341
342 /**
343  * Flushes the system global user database;
344  */
345 void
346 _dbus_user_database_flush_system (void)
347 {
348   _dbus_user_database_lock_system ();
349    
350   _dbus_user_database_flush (system_db);
351
352   _dbus_user_database_unlock_system ();
353 }
354
355 /**
356  * Gets username of user owning current process.  The returned string
357  * is valid until dbus_shutdown() is called.
358  *
359  * @param username place to store pointer to username
360  * @returns #FALSE if no memory
361  */
362 dbus_bool_t
363 _dbus_username_from_current_process (const DBusString **username)
364 {
365   _dbus_user_database_lock_system ();
366   if (!init_system_db ())
367     {
368       _dbus_user_database_unlock_system ();
369       return FALSE;
370     }
371   *username = &process_username;
372   _dbus_user_database_unlock_system ();  
373
374   return TRUE;
375 }
376
377 /**
378  * Gets homedir of user owning current process.  The returned string
379  * is valid until dbus_shutdown() is called.
380  *
381  * @param homedir place to store pointer to homedir
382  * @returns #FALSE if no memory
383  */
384 dbus_bool_t
385 _dbus_homedir_from_current_process (const DBusString  **homedir)
386 {
387   _dbus_user_database_lock_system ();
388   if (!init_system_db ())
389     {
390       _dbus_user_database_unlock_system ();
391       return FALSE;
392     }
393   *homedir = &process_homedir;
394   _dbus_user_database_unlock_system ();
395
396   return TRUE;
397 }
398
399 /**
400  * Gets the home directory for the given user.
401  *
402  * @param username the username
403  * @param homedir string to append home directory to
404  * @returns #TRUE if user existed and we appended their homedir
405  */
406 dbus_bool_t
407 _dbus_homedir_from_username (const DBusString *username,
408                              DBusString       *homedir)
409 {
410   DBusUserDatabase *db;
411   const DBusUserInfo *info;
412   _dbus_user_database_lock_system ();
413
414   db = _dbus_user_database_get_system ();
415   if (db == NULL)
416     {
417       _dbus_user_database_unlock_system ();
418       return FALSE;
419     }
420
421   if (!_dbus_user_database_get_username (db, username,
422                                          &info, NULL))
423     {
424       _dbus_user_database_unlock_system ();
425       return FALSE;
426     }
427
428   if (!_dbus_string_append (homedir, info->homedir))
429     {
430       _dbus_user_database_unlock_system ();
431       return FALSE;
432     }
433   
434   _dbus_user_database_unlock_system ();
435   return TRUE;
436 }
437
438 /**
439  * Gets the home directory for the given user.
440  *
441  * @param uid the uid
442  * @param homedir string to append home directory to
443  * @returns #TRUE if user existed and we appended their homedir
444  */
445 dbus_bool_t
446 _dbus_homedir_from_uid (dbus_uid_t         uid,
447                         DBusString        *homedir)
448 {
449   DBusUserDatabase *db;
450   const DBusUserInfo *info;
451   _dbus_user_database_lock_system ();
452
453   db = _dbus_user_database_get_system ();
454   if (db == NULL)
455     {
456       _dbus_user_database_unlock_system ();
457       return FALSE;
458     }
459
460   if (!_dbus_user_database_get_uid (db, uid,
461                                     &info, NULL))
462     {
463       _dbus_user_database_unlock_system ();
464       return FALSE;
465     }
466
467   if (!_dbus_string_append (homedir, info->homedir))
468     {
469       _dbus_user_database_unlock_system ();
470       return FALSE;
471     }
472   
473   _dbus_user_database_unlock_system ();
474   return TRUE;
475 }
476
477 /**
478  * Adds the credentials corresponding to the given username.
479  *
480  * Used among other purposes to parses a desired identity provided
481  * from a client in the auth protocol. On UNIX this means parsing a
482  * UID, on Windows probably parsing an SID string.
483  * 
484  * @todo this is broken because it treats OOM and parse error
485  * the same way. Needs a #DBusError.
486  * 
487  * @param credentials credentials to fill in 
488  * @param username the username
489  * @returns #TRUE if the username existed and we got some credentials
490  */
491 dbus_bool_t
492 _dbus_credentials_add_from_user (DBusCredentials  *credentials,
493                                  const DBusString *username)
494 {
495   DBusUserDatabase *db;
496   const DBusUserInfo *info;
497
498   _dbus_user_database_lock_system ();
499
500   db = _dbus_user_database_get_system ();
501   if (db == NULL)
502     {
503       _dbus_user_database_unlock_system ();
504       return FALSE;
505     }
506
507   if (!_dbus_user_database_get_username (db, username,
508                                          &info, NULL))
509     {
510       _dbus_user_database_unlock_system ();
511       return FALSE;
512     }
513
514   if (!_dbus_credentials_add_unix_uid(credentials, info->uid))
515     {
516       _dbus_user_database_unlock_system ();
517       return FALSE;
518     }
519   
520   _dbus_user_database_unlock_system ();
521   return TRUE;
522 }
523
524 /**
525  * Creates a new user database object used to look up and
526  * cache user information.
527  * @returns new database, or #NULL on out of memory
528  */
529 DBusUserDatabase*
530 _dbus_user_database_new (void)
531 {
532   DBusUserDatabase *db;
533   
534   db = dbus_new0 (DBusUserDatabase, 1);
535   if (db == NULL)
536     return NULL;
537
538   db->refcount = 1;
539
540   db->users = _dbus_hash_table_new (DBUS_HASH_ULONG,
541                                     NULL, (DBusFreeFunction) _dbus_user_info_free_allocated);
542   
543   if (db->users == NULL)
544     goto failed;
545
546   db->groups = _dbus_hash_table_new (DBUS_HASH_ULONG,
547                                      NULL, (DBusFreeFunction) _dbus_group_info_free_allocated);
548   
549   if (db->groups == NULL)
550     goto failed;
551
552   db->users_by_name = _dbus_hash_table_new (DBUS_HASH_STRING,
553                                             NULL, NULL);
554   if (db->users_by_name == NULL)
555     goto failed;
556   
557   db->groups_by_name = _dbus_hash_table_new (DBUS_HASH_STRING,
558                                              NULL, NULL);
559   if (db->groups_by_name == NULL)
560     goto failed;
561   
562   return db;
563   
564  failed:
565   _dbus_user_database_unref (db);
566   return NULL;
567 }
568
569 /**
570  * Flush all information out of the user database. 
571  */
572 void
573 _dbus_user_database_flush (DBusUserDatabase *db) 
574 {
575   _dbus_hash_table_remove_all(db->users_by_name);
576   _dbus_hash_table_remove_all(db->groups_by_name);
577   _dbus_hash_table_remove_all(db->users);
578   _dbus_hash_table_remove_all(db->groups);
579 }
580
581 #ifdef DBUS_BUILD_TESTS
582 /**
583  * Increments refcount of user database.
584  * @param db the database
585  * @returns the database
586  */
587 DBusUserDatabase *
588 _dbus_user_database_ref (DBusUserDatabase  *db)
589 {
590   _dbus_assert (db->refcount > 0);
591
592   db->refcount += 1;
593
594   return db;
595 }
596 #endif /* DBUS_BUILD_TESTS */
597
598 /**
599  * Decrements refcount of user database.
600  * @param db the database
601  */
602 void
603 _dbus_user_database_unref (DBusUserDatabase  *db)
604 {
605   _dbus_assert (db->refcount > 0);
606
607   db->refcount -= 1;
608   if (db->refcount == 0)
609     {
610       if (db->users)
611         _dbus_hash_table_unref (db->users);
612
613       if (db->groups)
614         _dbus_hash_table_unref (db->groups);
615
616       if (db->users_by_name)
617         _dbus_hash_table_unref (db->users_by_name);
618
619       if (db->groups_by_name)
620         _dbus_hash_table_unref (db->groups_by_name);
621       
622       dbus_free (db);
623     }
624 }
625
626 /**
627  * Gets the user information for the given UID,
628  * returned user info should not be freed. 
629  *
630  * @param db user database
631  * @param uid the user ID
632  * @param info return location for const ref to user info
633  * @param error error location
634  * @returns #FALSE if error is set
635  */
636 dbus_bool_t
637 _dbus_user_database_get_uid (DBusUserDatabase    *db,
638                              dbus_uid_t           uid,
639                              const DBusUserInfo **info,
640                              DBusError           *error)
641 {
642   *info = _dbus_user_database_lookup (db, uid, NULL, error);
643   return *info != NULL;
644 }
645
646 /**
647  * Gets the user information for the given username.
648  *
649  * @param db user database
650  * @param username the user name
651  * @param info return location for const ref to user info
652  * @param error error location
653  * @returns #FALSE if error is set
654  */
655 dbus_bool_t
656 _dbus_user_database_get_username  (DBusUserDatabase     *db,
657                                    const DBusString     *username,
658                                    const DBusUserInfo  **info,
659                                    DBusError            *error)
660 {
661   *info = _dbus_user_database_lookup (db, DBUS_UID_UNSET, username, error);
662   return *info != NULL;
663 }
664
665 /** @} */
666
667 /* Tests in dbus-userdb-util.c */