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