who.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* vi: set sw=4 ts=4: */
  2. /*----------------------------------------------------------------------
  3. * Mini who is used to display user name, login time,
  4. * idle time and host name.
  5. *
  6. * Author: Da Chen <dchen@ayrnetworks.com>
  7. *
  8. * This is a free document; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation:
  11. * http://www.gnu.org/copyleft/gpl.html
  12. *
  13. * Copyright (c) 2002 AYR Networks, Inc.
  14. *
  15. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  16. *
  17. *----------------------------------------------------------------------
  18. */
  19. /* BB_AUDIT SUSv3 _NOT_ compliant -- missing options -b, -d, -l, -m, -p, -q, -r, -s, -t, -T, -u; Missing argument 'file'. */
  20. #include "libbb.h"
  21. #include <utmp.h>
  22. static void idle_string(char *str6, time_t t)
  23. {
  24. t = time(NULL) - t;
  25. /*if (t < 60) {
  26. str6[0] = '.';
  27. str6[1] = '\0';
  28. return;
  29. }*/
  30. if (t >= 0 && t < (24 * 60 * 60)) {
  31. sprintf(str6, "%02d:%02d",
  32. (int) (t / (60 * 60)),
  33. (int) ((t % (60 * 60)) / 60));
  34. return;
  35. }
  36. strcpy(str6, "old");
  37. }
  38. int who_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  39. int who_main(int argc UNUSED_PARAM, char **argv)
  40. {
  41. struct utmp *ut;
  42. unsigned opt;
  43. opt_complementary = "=0";
  44. opt = getopt32(argv, "aH");
  45. if (opt & 2) // -H
  46. printf("USER\t\tTTY\t\tIDLE\tTIME\t\t HOST\n");
  47. setutent();
  48. while ((ut = getutent()) != NULL) {
  49. if (ut->ut_user[0]
  50. && ((opt & 1) || ut->ut_type == USER_PROCESS)
  51. ) {
  52. char str6[6];
  53. char name[sizeof("/dev/") + sizeof(ut->ut_line) + 1];
  54. struct stat st;
  55. time_t seconds;
  56. str6[0] = '?';
  57. str6[1] = '\0';
  58. strcpy(name, "/dev/");
  59. safe_strncpy(ut->ut_line[0] == '/' ? name : name + sizeof("/dev/")-1,
  60. ut->ut_line,
  61. sizeof(ut->ut_line)+1
  62. );
  63. if (stat(name, &st) == 0)
  64. idle_string(str6, st.st_atime);
  65. /* manpages say ut_tv.tv_sec *is* time_t,
  66. * but some systems have it wrong */
  67. seconds = ut->ut_tv.tv_sec;
  68. /* How wide time field can be?
  69. * "Nov 10 19:33:20": 15 chars
  70. * "2010-11-10 19:33": 16 chars
  71. */
  72. printf("%-15.*s %-15.*s %-7s %-16.16s %.*s\n",
  73. (int)sizeof(ut->ut_user), ut->ut_user,
  74. (int)sizeof(ut->ut_line), ut->ut_line,
  75. str6,
  76. ctime(&seconds) + 4,
  77. (int)sizeof(ut->ut_host), ut->ut_host
  78. );
  79. }
  80. }
  81. if (ENABLE_FEATURE_CLEAN_UP)
  82. endutent();
  83. return EXIT_SUCCESS;
  84. }