/src/ug.c

http://bdremote-ng.googlecode.com/ · C · 94 lines · 38 code · 17 blank · 39 comment · 8 complexity · aec4c504b42733643cd7b7bdb920f211 MD5 · raw file

  1. /*
  2. * bdremoteng - helper daemon for Sony(R) BD Remote Control
  3. * Based on bdremoted, written by Anton Starikov <antst@mail.ru>.
  4. *
  5. * Copyright (C) 2009 Michael Wojciechowski <wojci@wojci.dk>
  6. *
  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 St, Fifth Floor, Boston, MA 02110-1301 USA
  21. *
  22. */
  23. /** \ingroup UID
  24. * @{
  25. */
  26. /*! \file ug.c
  27. \brief Change UID/GID implemention.
  28. A function used to resolve user/group into UID/GID and then to
  29. change the current UID/GID into the specified ones.
  30. */
  31. #include "ug.h"
  32. #include <sys/types.h>
  33. #include <pwd.h>
  34. #include <grp.h>
  35. #include <unistd.h>
  36. #include <globaldefs.h>
  37. /* The following function was taken from BTG (btg.berlios.de), also
  38. * written by me.
  39. */
  40. int changeUIDAndGID(const char* _user,
  41. const char* _group)
  42. {
  43. int result = BDREMOTE_OK;
  44. struct passwd* s_passwd = NULL;
  45. uid_t uid = -1;
  46. struct group* s_group = NULL;
  47. gid_t gid = -1;
  48. /* Resolve the user and group into uid/gid. */
  49. /* User. */
  50. s_passwd = getpwnam(_user);
  51. if (s_passwd == 0)
  52. {
  53. result = BDREMOTE_FAIL;
  54. return result;
  55. }
  56. uid = s_passwd->pw_uid;
  57. /* Group. */
  58. s_group = getgrnam(_group);
  59. if (s_group == 0)
  60. {
  61. result = BDREMOTE_FAIL;
  62. return result;
  63. }
  64. gid = s_group->gr_gid;
  65. /* Do the change. */
  66. if (setgid(gid) != 0)
  67. {
  68. result = BDREMOTE_FAIL;
  69. }
  70. if (setuid(uid) != 0)
  71. {
  72. result = BDREMOTE_FAIL;
  73. }
  74. return result;
  75. }