shell_misc.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * shell_misc.c
  3. */
  4. #include <stdlib.h>
  5. #include <assert.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. #include <pwd.h>
  9. #include <string.h>
  10. #include "private.h"
  11. CLISH_GET_STR(shell, overview);
  12. bool_t clish_shell_is_machine_interface(const clish_shell_t *shell)
  13. {
  14. assert(shell);
  15. if (!shell)
  16. return BOOL_FALSE;
  17. return shell->machine_interface;
  18. }
  19. void clish_shell_set_machine_interface(clish_shell_t *shell)
  20. {
  21. assert(shell);
  22. if (!shell)
  23. return;
  24. shell->machine_interface = BOOL_TRUE;
  25. if (shell->tinyrl)
  26. tinyrl_set_machine_interface(shell->tinyrl);
  27. }
  28. void clish_shell_set_human_interface(clish_shell_t *shell)
  29. {
  30. assert(shell);
  31. if (!shell)
  32. return;
  33. shell->machine_interface = BOOL_FALSE;
  34. if (shell->tinyrl)
  35. tinyrl_set_human_interface(shell->tinyrl);
  36. }
  37. /* Get user name.
  38. * Return value must be freed after using.
  39. */
  40. char *clish_shell_format_username(const clish_shell_t *shell)
  41. {
  42. char *uname = NULL;
  43. /* Try to get username from environment variables
  44. * USER and LOGNAME and then from /etc/passwd. Else use UID.
  45. */
  46. if (!(uname = getenv("USER"))) {
  47. if (!(uname = getenv("LOGNAME"))) {
  48. struct passwd *user = NULL;
  49. user = clish_shell__get_user(shell);
  50. if (user) {
  51. uname = user->pw_name;
  52. } else {
  53. char tmp[10] = {};
  54. snprintf(tmp, sizeof(tmp), "%u", getuid());
  55. tmp[sizeof(tmp) - 1] = '\0';
  56. uname = tmp;
  57. }
  58. }
  59. }
  60. return strdup(uname);
  61. }