]> git.ipfire.org Git - thirdparty/util-linux.git/blobdiff - term-utils/write.c
setterm: update comments about -ulcolor/-hbcolor syntax
[thirdparty/util-linux.git] / term-utils / write.c
index 11a65804112daa9a632f0f40e40cc1a0158b8ccd..bd64fc281a0872650f3141908bb864f959d8e879 100644 (file)
  *
  */
 
-#include <stdio.h>
-#include <unistd.h>
-#include <utmp.h>
 #include <errno.h>
-#include <time.h>
+#include <getopt.h>
+#include <paths.h>
 #include <pwd.h>
-#include <string.h>
-#include <stdlib.h>
 #include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <sys/param.h>
 #include <sys/stat.h>
-#include <paths.h>
-#include <getopt.h>
+#include <time.h>
+#include <unistd.h>
+#include <utmpx.h>
 
 #include "c.h"
 #include "carefulputc.h"
 #include "closestream.h"
 #include "nls.h"
 #include "strutils.h"
+#include "ttyutils.h"
 #include "xalloc.h"
 
-static void __attribute__ ((__noreturn__)) usage(FILE * out)
+static sig_atomic_t signal_received = 0;
+
+struct write_control {
+       uid_t src_uid;
+       const char *src_login;
+       const char *src_tty_path;
+       const char *src_tty_name;
+       const char *dst_login;
+       char *dst_tty_path;
+       const char *dst_tty_name;
+};
+
+static void __attribute__((__noreturn__)) usage(void)
 {
+       FILE *out = stdout;
        fputs(USAGE_HEADER, out);
        fprintf(out,
              _(" %s [options] <user> [<ttyname>]\n"),
@@ -77,62 +91,59 @@ static void __attribute__ ((__noreturn__)) usage(FILE * out)
        fputs(_("Send a message to another user.\n"), out);
 
        fputs(USAGE_OPTIONS, out);
-       fputs(USAGE_HELP, out);
-       fputs(USAGE_VERSION, out);
-
-       fprintf(out, USAGE_MAN_TAIL("write(1)"));
-       exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
+       printf(USAGE_HELP_OPTIONS(16));
+       printf(USAGE_MAN_TAIL("write(1)"));
+       exit(EXIT_SUCCESS);
 }
 
 /*
- * term_chk - check that a terminal exists, and get the message bit
+ * check_tty - check that a terminal exists, and get the message bit
  *     and the access time
  */
-static int term_chk(char *tty, int *msgsokP, time_t * atimeP, int showerror)
+static int check_tty(const char *tty, int *tty_writeable, time_t *tty_atime, int showerror)
 {
        struct stat s;
-       char path[PATH_MAX];
 
-       if (strlen(tty) + 6 > sizeof(path))
-               return 1;
-       sprintf(path, "/dev/%s", tty);
-       if (stat(path, &s) < 0) {
+       if (stat(tty, &s) < 0) {
                if (showerror)
-                       warn("%s", path);
+                       warn("%s", tty);
                return 1;
        }
        if (getuid() == 0)      /* root can always write */
-               *msgsokP = 1;
-       else
-               *msgsokP = (s.st_mode & S_IWGRP) && (getegid() == s.st_gid);
-       if (atimeP)
-               *atimeP = s.st_atime;
+               *tty_writeable = 1;
+       else {
+               if (getegid() != s.st_gid) {
+                       warnx(_("effective gid does not match group of %s"), tty);
+                       return 1;
+               }
+               *tty_writeable = s.st_mode & S_IWGRP;
+       }
+       if (tty_atime)
+               *tty_atime = s.st_atime;
        return 0;
 }
 
 /*
- * utmp_chk - checks that the given user is actually logged in on
+ * check_utmp - checks that the given user is actually logged in on
  *     the given tty
  */
-static int utmp_chk(char *user, char *tty)
+static int check_utmp(const struct write_control *ctl)
 {
-       struct utmp u;
-       struct utmp *uptr;
+       struct utmpx *u;
        int res = 1;
 
-       utmpname(_PATH_UTMP);
-       setutent();
+       utmpxname(_PATH_UTMP);
+       setutxent();
 
-       while ((uptr = getutent())) {
-               memcpy(&u, uptr, sizeof(u));
-               if (strncmp(user, u.ut_user, sizeof(u.ut_user)) == 0 &&
-                   strncmp(tty, u.ut_line, sizeof(u.ut_line)) == 0) {
+       while ((u = getutxent())) {
+               if (strncmp(ctl->dst_login, u->ut_user, sizeof(u->ut_user)) == 0 &&
+                   strncmp(ctl->dst_tty_name, u->ut_line, sizeof(u->ut_line)) == 0) {
                        res = 0;
                        break;
                }
        }
 
-       endutent();
+       endutxent();
        return res;
 }
 
@@ -147,147 +158,146 @@ static int utmp_chk(char *user, char *tty)
  * Special case for writing to yourself - ignore the terminal you're
  * writing from, unless that's the only terminal with messages enabled.
  */
-static void search_utmp(char *user, char *tty, char *mytty, uid_t myuid)
+static void search_utmp(struct write_control *ctl)
 {
-       struct utmp u;
-       struct utmp *uptr;
-       time_t bestatime, atime;
-       int nloggedttys, nttys, msgsok = 0, user_is_me;
-       char atty[sizeof(u.ut_line) + 1];
-
-       utmpname(_PATH_UTMP);
-       setutent();
-
-       nloggedttys = nttys = 0;
-       bestatime = 0;
-       user_is_me = 0;
-       while ((uptr = getutent())) {
-               memcpy(&u, uptr, sizeof(u));
-               if (strncmp(user, u.ut_user, sizeof(u.ut_user)) == 0) {
-                       ++nloggedttys;
-                       xstrncpy(atty, u.ut_line, sizeof(atty));
-                       if (term_chk(atty, &msgsok, &atime, 0))
-                               /* bad term? skip */
-                               continue;
-                       if (myuid && !msgsok)
-                               /* skip ttys with msgs off */
-                               continue;
-                       if (strcmp(atty, mytty) == 0) {
-                               user_is_me = 1;
-                               /* don't write to yourself */
-                               continue;
-                       }
-                       if (u.ut_type != USER_PROCESS)
-                               /* it's not a valid entry */
-                               continue;
-                       ++nttys;
-                       if (atime > bestatime) {
-                               bestatime = atime;
-                               strcpy(tty, atty);
-                       }
+       struct utmpx *u;
+       time_t best_atime = 0, tty_atime;
+       int num_ttys = 0, valid_ttys = 0, tty_writeable = 0, user_is_me = 0;
+       char path[sizeof(u->ut_line) + 6];
+
+       utmpxname(_PATH_UTMP);
+       setutxent();
+
+       while ((u = getutxent())) {
+               if (strncmp(ctl->dst_login, u->ut_user, sizeof(u->ut_user)) != 0)
+                       continue;
+               num_ttys++;
+               sprintf(path, "/dev/%s", u->ut_line);
+               if (check_tty(path, &tty_writeable, &tty_atime, 0))
+                       /* bad term? skip */
+                       continue;
+               if (ctl->src_uid && !tty_writeable)
+                       /* skip ttys with msgs off */
+                       continue;
+               if (strcmp(u->ut_line, ctl->src_tty_name) == 0) {
+                       user_is_me = 1;
+                       /* don't write to yourself */
+                       continue;
+               }
+               if (u->ut_type != USER_PROCESS)
+                       /* it's not a valid entry */
+                       continue;
+               valid_ttys++;
+               if (best_atime < tty_atime) {
+                       best_atime = tty_atime;
+                       free(ctl->dst_tty_path);
+                       ctl->dst_tty_path = xstrdup(path);
+                       ctl->dst_tty_name = ctl->dst_tty_path + 5;
                }
        }
 
-       endutent();
-       if (nloggedttys == 0)
-               errx(EXIT_FAILURE, _("%s is not logged in"), user);
-       if (nttys == 0) {
+       endutxent();
+       if (num_ttys == 0)
+               errx(EXIT_FAILURE, _("%s is not logged in"), ctl->dst_login);
+       if (valid_ttys == 0) {
                if (user_is_me) {
                        /* ok, so write to yourself! */
-                       strcpy(tty, mytty);
+                       if (!ctl->src_tty_path)
+                               errx(EXIT_FAILURE, _("can't find your tty's name"));
+                       ctl->dst_tty_path = xstrdup(ctl->src_tty_path);
+                       ctl->dst_tty_name = ctl->dst_tty_path + 5;
                        return;
                }
-               errx(EXIT_FAILURE, _("%s has messages disabled"), user);
-       } else if (nttys > 1) {
-               warnx(_("%s is logged in more than once; writing to %s"),
-                     user, tty);
+               errx(EXIT_FAILURE, _("%s has messages disabled"), ctl->dst_login);
        }
+       if (1 < valid_ttys)
+               warnx(_("%s is logged in more than once; writing to %s"),
+                     ctl->dst_login, ctl->dst_tty_name);
 }
 
 /*
- * done - cleanup and exit
+ * signal_handler - cause write loop to exit
  */
-static void __attribute__ ((__noreturn__))
-    done(int dummy __attribute__ ((__unused__)))
+static void signal_handler(int signo)
 {
-       printf("EOF\r\n");
-       _exit(EXIT_SUCCESS);
+       signal_received = signo;
 }
 
 /*
- * wr_fputs - like fputs(), but makes control characters visible and
+ * write_line - like fputs(), but makes control characters visible and
  *     turns \n into \r\n.
  */
-static void wr_fputs(char *s)
+static void write_line(char *s)
 {
-       char c;
-
-#define        PUTC(c) if (fputc_careful(c, stdout, '^') == EOF) \
-    err(EXIT_FAILURE, _("carefulputc failed"));
        while (*s) {
-               c = *s++;
-               if (c == '\n')
-                       PUTC('\r');
-               PUTC(c);
+               const int c = *s++;
+
+               if ((c == '\n' && fputc_careful('\r', stdout, '^') == EOF)
+                   || fputc_careful(c, stdout, '^') == EOF)
+                       err(EXIT_FAILURE, _("carefulputc failed"));
        }
-       return;
-#undef PUTC
 }
 
 /*
  * do_write - actually make the connection
  */
-static void do_write(char *tty, char *mytty, uid_t myuid)
+static void do_write(const struct write_control *ctl)
 {
-       char *login, *pwuid, *nows;
+       char *login, *pwuid;
        struct passwd *pwd;
        time_t now;
-       char path[PATH_MAX], *host, line[512];
+       struct tm *tm;
+       char *host, line[512];
+       struct sigaction sigact;
 
        /* Determine our login name(s) before the we reopen() stdout */
-       if ((pwd = getpwuid(myuid)) != NULL)
+       if ((pwd = getpwuid(ctl->src_uid)) != NULL)
                pwuid = pwd->pw_name;
        else
                pwuid = "???";
        if ((login = getlogin()) == NULL)
                login = pwuid;
 
-       if (strlen(tty) + 6 > sizeof(path))
-               errx(EXIT_FAILURE, _("tty path %s too long"), tty);
-       snprintf(path, sizeof(path), "/dev/%s", tty);
-       if ((freopen(path, "w", stdout)) == NULL)
-               err(EXIT_FAILURE, "%s", path);
+       if ((freopen(ctl->dst_tty_path, "w", stdout)) == NULL)
+               err(EXIT_FAILURE, "%s", ctl->dst_tty_path);
 
-       signal(SIGINT, done);
-       signal(SIGHUP, done);
+       sigact.sa_handler = signal_handler;
+       sigemptyset(&sigact.sa_mask);
+       sigact.sa_flags = 0;
+       sigaction(SIGINT, &sigact, NULL);
+       sigaction(SIGHUP, &sigact, NULL);
 
-       /* print greeting */
        host = xgethostname();
        if (!host)
                host = xstrdup("???");
 
-       now = time((time_t *) NULL);
-       nows = ctime(&now);
-       nows[16] = '\0';
-       printf("\r\n\007\007\007");
+       now = time((time_t *)NULL);
+       tm = localtime(&now);
+       /* print greeting */
+       printf("\r\n\a\a\a");
        if (strcmp(login, pwuid))
-               printf(_("Message from %s@%s (as %s) on %s at %s ..."),
-                      login, host, pwuid, mytty, nows + 11);
+               printf(_("Message from %s@%s (as %s) on %s at %02d:%02d ..."),
+                      login, host, pwuid, ctl->src_tty_name,
+                      tm->tm_hour, tm->tm_min);
        else
-               printf(_("Message from %s@%s on %s at %s ..."),
-                      login, host, mytty, nows + 11);
+               printf(_("Message from %s@%s on %s at %02d:%02d ..."),
+                      login, host, ctl->src_tty_name,
+                      tm->tm_hour, tm->tm_min);
        free(host);
        printf("\r\n");
 
-       while (fgets(line, sizeof(line), stdin) != NULL)
-               wr_fputs(line);
+       while (fgets(line, sizeof(line), stdin) != NULL) {
+               if (signal_received)
+                       break;
+               write_line(line);
+       }
+       printf("EOF\r\n");
 }
 
 int main(int argc, char **argv)
 {
-       uid_t myuid;
-       int msgsok = 0, myttyfd, c;
-       char tty[PATH_MAX], *mytty;
+       int tty_writeable = 0, c;
+       struct write_control ctl = { 0 };
 
        static const struct option longopts[] = {
                {"version", no_argument, NULL, 'V'},
@@ -306,70 +316,53 @@ int main(int argc, char **argv)
                        printf(UTIL_LINUX_VERSION);
                        return EXIT_SUCCESS;
                case 'h':
-                       usage(stdout);
+                       usage();
                default:
-                       usage(stderr);
+                       errtryhelp(EXIT_FAILURE);
                }
 
-       /* check that sender has write enabled */
-       if (isatty(STDIN_FILENO))
-               myttyfd = STDIN_FILENO;
-       else if (isatty(STDOUT_FILENO))
-               myttyfd = STDOUT_FILENO;
-       else if (isatty(STDERR_FILENO))
-               myttyfd = STDERR_FILENO;
-       else
-               myttyfd = -1;
-
-       if (myttyfd != -1) {
-               if (!(mytty = ttyname(myttyfd)))
-                       errx(EXIT_FAILURE,
-                            _("can't find your tty's name"));
-
-               /*
-                * We may have /dev/ttyN but also /dev/pts/xx. Below,
-                * term_chk() will put "/dev/" in front, so remove that
-                * part.
-                */
-               if (!strncmp(mytty, "/dev/", 5))
-                       mytty += 5;
-               if (term_chk(mytty, &msgsok, NULL, 1))
+       if (get_terminal_name(&ctl.src_tty_path, &ctl.src_tty_name, NULL) == 0) {
+               /* check that sender has write enabled */
+               if (check_tty(ctl.src_tty_path, &tty_writeable, NULL, 1))
                        exit(EXIT_FAILURE);
-               if (!msgsok)
+               if (!tty_writeable)
                        errx(EXIT_FAILURE,
                             _("you have write permission turned off"));
-               msgsok = 0;
+               tty_writeable = 0;
        } else
-               mytty = "<no tty>";
+               ctl.src_tty_name = "<no tty>";
 
-       myuid = getuid();
+       ctl.src_uid = getuid();
 
        /* check args */
        switch (argc) {
        case 2:
-               search_utmp(argv[1], tty, mytty, myuid);
-               do_write(tty, mytty, myuid);
+               ctl.dst_login = argv[1];
+               search_utmp(&ctl);
+               do_write(&ctl);
                break;
        case 3:
+               ctl.dst_login = argv[1];
                if (!strncmp(argv[2], "/dev/", 5))
-                       argv[2] += 5;
-               if (utmp_chk(argv[1], argv[2]))
+                       ctl.dst_tty_path = xstrdup(argv[2]);
+               else
+                       xasprintf(&ctl.dst_tty_path, "/dev/%s", argv[2]);
+               ctl.dst_tty_name = ctl.dst_tty_path + 5;
+               if (check_utmp(&ctl))
                        errx(EXIT_FAILURE,
                             _("%s is not logged in on %s"),
-                            argv[1], argv[2]);
-               if (term_chk(argv[2], &msgsok, NULL, 1))
+                            ctl.dst_login, ctl.dst_tty_name);
+               if (check_tty(ctl.dst_tty_path, &tty_writeable, NULL, 1))
                        exit(EXIT_FAILURE);
-               if (myuid && !msgsok)
+               if (ctl.src_uid && !tty_writeable)
                        errx(EXIT_FAILURE,
                             _("%s has messages disabled on %s"),
-                            argv[1], argv[2]);
-               do_write(argv[2], mytty, myuid);
+                            ctl.dst_login, ctl.dst_tty_name);
+               do_write(&ctl);
                break;
        default:
-               usage(stderr);
+               errtryhelp(EXIT_FAILURE);
        }
-
-       done(0);
-       /* NOTREACHED */
-       return EXIT_FAILURE;
+       free(ctl.dst_tty_path);
+       return EXIT_SUCCESS;
 }