logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git/

mesg.c (1837B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <sys/stat.h> // stat, chmod
  9. #include <unistd.h> // ttyname
  10. int
  11. main(int argc, char *argv[])
  12. {
  13. argc -= 1;
  14. argv += 1;
  15. if(argc > 1)
  16. {
  17. fprintf(stderr, "mesg: error: Expected either 0 or 1 argument, got %d\n", argc);
  18. return 2;
  19. }
  20. if(argc == 1)
  21. {
  22. if(argv[0][0] == '\0')
  23. {
  24. fputs("mesg: error: argument is empty, expected 'y' or 'n'\n", stderr);
  25. return 2;
  26. }
  27. if(argv[0][1] != '\0')
  28. {
  29. fputs("mesg: error: argument is too long, expected 'y' or 'n'\n", stderr);
  30. return 2;
  31. }
  32. if(argv[0][0] != 'y' && argv[0][0] != 'n')
  33. {
  34. fprintf(stderr, "mesg: error: unknown argument '%s', expected 'y' or 'n'\n", argv[0]);
  35. return 2;
  36. }
  37. }
  38. char *tty = ttyname(STDIN_FILENO);
  39. if(!tty) ttyname(STDOUT_FILENO);
  40. if(!tty) ttyname(STDERR_FILENO);
  41. if(!tty)
  42. {
  43. fputs("mesg: error: Could not determine TTY from stdin/stdout/stderr\n", stderr);
  44. return 2;
  45. }
  46. struct stat tty_st;
  47. if(stat(tty, &tty_st) < 0)
  48. {
  49. fprintf(
  50. stderr, "mesg: error: Failed getting file status from '%s': %s\n", tty, strerror(errno));
  51. return 2;
  52. }
  53. if(argc == 0)
  54. {
  55. if((tty_st.st_mode & 0022) == 0022)
  56. {
  57. fputs("messages allowed\n", stdout);
  58. return 0;
  59. }
  60. fputs("messages denied\n", stdout);
  61. return 1;
  62. }
  63. mode_t new_mode = tty_st.st_mode;
  64. if(argv[0][0] == 'y')
  65. new_mode |= 0022;
  66. else
  67. new_mode &= ~0022;
  68. if(chmod(tty, new_mode) < 0)
  69. {
  70. fprintf(stderr,
  71. "mesg: error: Failed setting new mode (0%03o) on terminal '%s': %s\n",
  72. new_mode,
  73. tty,
  74. strerror(errno));
  75. return 2;
  76. }
  77. return 0;
  78. }