(root)/
util-linux-2.39/
term-utils/
write.c
       1  /*
       2   * Copyright (c) 1989, 1993
       3   *	The Regents of the University of California.  All rights reserved.
       4   *
       5   * This code is derived from software contributed to Berkeley by
       6   * Jef Poskanzer and Craig Leres of the Lawrence Berkeley Laboratory.
       7   *
       8   * Redistribution and use in source and binary forms, with or without
       9   * modification, are permitted provided that the following conditions
      10   * are met:
      11   * 1. Redistributions of source code must retain the above copyright
      12   *    notice, this list of conditions and the following disclaimer.
      13   * 2. Redistributions in binary form must reproduce the above copyright
      14   *    notice, this list of conditions and the following disclaimer in the
      15   *    documentation and/or other materials provided with the distribution.
      16   * 3. All advertising materials mentioning features or use of this software
      17   *    must display the following acknowledgement:
      18   *	This product includes software developed by the University of
      19   *	California, Berkeley and its contributors.
      20   * 4. Neither the name of the University nor the names of its contributors
      21   *    may be used to endorse or promote products derived from this software
      22   *    without specific prior written permission.
      23   *
      24   * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
      25   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      26   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      27   * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
      28   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
      29   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
      30   * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
      31   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
      32   * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
      33   * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
      34   * SUCH DAMAGE.
      35   *
      36   * Modified for Linux, Mon Mar  8 18:16:24 1993, faith@cs.unc.edu
      37   * Wed Jun 22 21:41:56 1994, faith@cs.unc.edu:
      38   *      Added fix from Mike Grupenhoff (kashmir@umiacs.umd.edu)
      39   * Mon Jul  1 17:01:39 MET DST 1996, janl@math.uio.no:
      40   *      - Added fix from David.Chapell@mail.trincoll.edu enabling daemons
      41   *	  to use write.
      42   *      - ANSIed it since I was working on it anyway.
      43   * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
      44   * - added Native Language Support
      45   *
      46   */
      47  
      48  #include <errno.h>
      49  #include <getopt.h>
      50  #include <paths.h>
      51  #include <pwd.h>
      52  #include <signal.h>
      53  #include <stdio.h>
      54  #include <stdlib.h>
      55  #include <string.h>
      56  #include <sys/param.h>
      57  #include <sys/stat.h>
      58  #include <time.h>
      59  #include <unistd.h>
      60  #include <utmpx.h>
      61  
      62  #include "c.h"
      63  #include "carefulputc.h"
      64  #include "closestream.h"
      65  #include "nls.h"
      66  #include "strutils.h"
      67  #include "ttyutils.h"
      68  #include "xalloc.h"
      69  
      70  static volatile sig_atomic_t signal_received = 0;
      71  
      72  struct write_control {
      73  	uid_t src_uid;
      74  	const char *src_login;
      75  	const char *src_tty_path;
      76  	const char *src_tty_name;
      77  	const char *dst_login;
      78  	char *dst_tty_path;
      79  	const char *dst_tty_name;
      80  };
      81  
      82  static void __attribute__((__noreturn__)) usage(void)
      83  {
      84  	FILE *out = stdout;
      85  	fputs(USAGE_HEADER, out);
      86  	fprintf(out,
      87  	      _(" %s [options] <user> [<ttyname>]\n"),
      88  	      program_invocation_short_name);
      89  
      90  	fputs(USAGE_SEPARATOR, out);
      91  	fputs(_("Send a message to another user.\n"), out);
      92  
      93  	fputs(USAGE_OPTIONS, out);
      94  	printf(USAGE_HELP_OPTIONS(16));
      95  	printf(USAGE_MAN_TAIL("write(1)"));
      96  	exit(EXIT_SUCCESS);
      97  }
      98  
      99  /*
     100   * check_tty - check that a terminal exists, and get the message bit
     101   *     and the access time
     102   */
     103  static int check_tty(const char *tty, int *tty_writeable, time_t *tty_atime, int showerror)
     104  {
     105  	struct stat s;
     106  
     107  	if (stat(tty, &s) < 0) {
     108  		if (showerror)
     109  			warn("%s", tty);
     110  		return 1;
     111  	}
     112  	if (getuid() == 0)	/* root can always write */
     113  		*tty_writeable = 1;
     114  	else {
     115  		if (getegid() != s.st_gid) {
     116  			warnx(_("effective gid does not match group of %s"), tty);
     117  			return 1;
     118  		}
     119  		*tty_writeable = s.st_mode & S_IWGRP;
     120  	}
     121  	if (tty_atime)
     122  		*tty_atime = s.st_atime;
     123  	return 0;
     124  }
     125  
     126  /*
     127   * check_utmp - checks that the given user is actually logged in on
     128   *     the given tty
     129   */
     130  static int check_utmp(const struct write_control *ctl)
     131  {
     132  	struct utmpx *u;
     133  	int res = 1;
     134  
     135  	utmpxname(_PATH_UTMP);
     136  	setutxent();
     137  
     138  	while ((u = getutxent())) {
     139  		if (strncmp(ctl->dst_login, u->ut_user, sizeof(u->ut_user)) == 0 &&
     140  		    strncmp(ctl->dst_tty_name, u->ut_line, sizeof(u->ut_line)) == 0) {
     141  			res = 0;
     142  			break;
     143  		}
     144  	}
     145  
     146  	endutxent();
     147  	return res;
     148  }
     149  
     150  /*
     151   * search_utmp - search utmp for the "best" terminal to write to
     152   *
     153   * Ignores terminals with messages disabled, and of the rest, returns
     154   * the one with the most recent access time.  Returns as value the number
     155   * of the user's terminals with messages enabled, or -1 if the user is
     156   * not logged in at all.
     157   *
     158   * Special case for writing to yourself - ignore the terminal you're
     159   * writing from, unless that's the only terminal with messages enabled.
     160   */
     161  static void search_utmp(struct write_control *ctl)
     162  {
     163  	struct utmpx *u;
     164  	time_t best_atime = 0, tty_atime;
     165  	int num_ttys = 0, valid_ttys = 0, tty_writeable = 0, user_is_me = 0;
     166  	char path[sizeof(u->ut_line) + 6];
     167  
     168  	utmpxname(_PATH_UTMP);
     169  	setutxent();
     170  
     171  	while ((u = getutxent())) {
     172  		if (strncmp(ctl->dst_login, u->ut_user, sizeof(u->ut_user)) != 0)
     173  			continue;
     174  		num_ttys++;
     175  		snprintf(path, sizeof(path), "/dev/%s", u->ut_line);
     176  		if (check_tty(path, &tty_writeable, &tty_atime, 0))
     177  			/* bad term? skip */
     178  			continue;
     179  		if (ctl->src_uid && !tty_writeable)
     180  			/* skip ttys with msgs off */
     181  			continue;
     182  		if (memcmp(u->ut_line, ctl->src_tty_name, strlen(ctl->src_tty_name) + 1) == 0) {
     183  			user_is_me = 1;
     184  			/* don't write to yourself */
     185  			continue;
     186  		}
     187  		if (u->ut_type != USER_PROCESS)
     188  			/* it's not a valid entry */
     189  			continue;
     190  		valid_ttys++;
     191  		if (best_atime < tty_atime) {
     192  			best_atime = tty_atime;
     193  			free(ctl->dst_tty_path);
     194  			ctl->dst_tty_path = xstrdup(path);
     195  			ctl->dst_tty_name = ctl->dst_tty_path + 5;
     196  		}
     197  	}
     198  
     199  	endutxent();
     200  	if (num_ttys == 0)
     201  		errx(EXIT_FAILURE, _("%s is not logged in"), ctl->dst_login);
     202  	if (valid_ttys == 0) {
     203  		if (user_is_me) {
     204  			/* ok, so write to yourself! */
     205  			if (!ctl->src_tty_path)
     206  				errx(EXIT_FAILURE, _("can't find your tty's name"));
     207  			ctl->dst_tty_path = xstrdup(ctl->src_tty_path);
     208  			ctl->dst_tty_name = ctl->dst_tty_path + 5;
     209  			return;
     210  		}
     211  		errx(EXIT_FAILURE, _("%s has messages disabled"), ctl->dst_login);
     212  	}
     213  	if (1 < valid_ttys)
     214  		warnx(_("%s is logged in more than once; writing to %s"),
     215  		      ctl->dst_login, ctl->dst_tty_name);
     216  }
     217  
     218  /*
     219   * signal_handler - cause write loop to exit
     220   */
     221  static void signal_handler(int signo)
     222  {
     223  	signal_received = signo;
     224  }
     225  
     226  /*
     227   * do_write - actually make the connection
     228   */
     229  static void do_write(const struct write_control *ctl)
     230  {
     231  	char *login, *pwuid;
     232  	struct passwd *pwd;
     233  	time_t now;
     234  	struct tm *tm;
     235  	char *host, *line = NULL;
     236  	size_t linelen = 0;
     237  	struct sigaction sigact;
     238  
     239  	/* Determine our login name(s) before the we reopen() stdout */
     240  	if ((pwd = getpwuid(ctl->src_uid)) != NULL)
     241  		pwuid = pwd->pw_name;
     242  	else
     243  		pwuid = "???";
     244  	if ((login = getlogin()) == NULL)
     245  		login = pwuid;
     246  
     247  	if ((freopen(ctl->dst_tty_path, "w", stdout)) == NULL)
     248  		err(EXIT_FAILURE, "%s", ctl->dst_tty_path);
     249  
     250  	sigact.sa_handler = signal_handler;
     251  	sigemptyset(&sigact.sa_mask);
     252  	sigact.sa_flags = 0;
     253  	sigaction(SIGINT, &sigact, NULL);
     254  	sigaction(SIGHUP, &sigact, NULL);
     255  
     256  	host = xgethostname();
     257  	if (!host)
     258  		host = xstrdup("???");
     259  
     260  	now = time((time_t *)NULL);
     261  	tm = localtime(&now);
     262  	/* print greeting */
     263  	printf("\r\n\a\a\a");
     264  	if (strcmp(login, pwuid) != 0)
     265  		printf(_("Message from %s@%s (as %s) on %s at %02d:%02d ..."),
     266  		       login, host, pwuid, ctl->src_tty_name,
     267  		       tm->tm_hour, tm->tm_min);
     268  	else
     269  		printf(_("Message from %s@%s on %s at %02d:%02d ..."),
     270  		       login, host, ctl->src_tty_name,
     271  		       tm->tm_hour, tm->tm_min);
     272  	free(host);
     273  	printf("\r\n");
     274  
     275  	while (getline(&line, &linelen, stdin) >= 0) {
     276  		if (signal_received)
     277  			break;
     278  
     279  		if (fputs_careful(line, stdout, '^', true, 0) == EOF)
     280  			err(EXIT_FAILURE, _("carefulputc failed"));
     281  	}
     282  	free(line);
     283  	printf("EOF\r\n");
     284  }
     285  
     286  int main(int argc, char **argv)
     287  {
     288  	int tty_writeable = 0, c;
     289  	struct write_control ctl = { 0 };
     290  
     291  	static const struct option longopts[] = {
     292  		{"version", no_argument, NULL, 'V'},
     293  		{"help", no_argument, NULL, 'h'},
     294  		{NULL, 0, NULL, 0}
     295  	};
     296  
     297  	setlocale(LC_ALL, "");
     298  	bindtextdomain(PACKAGE, LOCALEDIR);
     299  	textdomain(PACKAGE);
     300  	close_stdout_atexit();
     301  
     302  	while ((c = getopt_long(argc, argv, "Vh", longopts, NULL)) != -1)
     303  		switch (c) {
     304  		case 'V':
     305  			print_version(EXIT_SUCCESS);
     306  		case 'h':
     307  			usage();
     308  		default:
     309  			errtryhelp(EXIT_FAILURE);
     310  		}
     311  
     312  	if (get_terminal_name(&ctl.src_tty_path, &ctl.src_tty_name, NULL) == 0) {
     313  		/* check that sender has write enabled */
     314  		if (check_tty(ctl.src_tty_path, &tty_writeable, NULL, 1))
     315  			exit(EXIT_FAILURE);
     316  		if (!tty_writeable)
     317  			errx(EXIT_FAILURE,
     318  			     _("you have write permission turned off"));
     319  		tty_writeable = 0;
     320  	} else
     321  		ctl.src_tty_name = "<no tty>";
     322  
     323  	ctl.src_uid = getuid();
     324  
     325  	/* check args */
     326  	switch (argc) {
     327  	case 2:
     328  		ctl.dst_login = argv[1];
     329  		search_utmp(&ctl);
     330  		do_write(&ctl);
     331  		break;
     332  	case 3:
     333  		ctl.dst_login = argv[1];
     334  		if (!strncmp(argv[2], "/dev/", 5))
     335  			ctl.dst_tty_path = xstrdup(argv[2]);
     336  		else
     337  			xasprintf(&ctl.dst_tty_path, "/dev/%s", argv[2]);
     338  		ctl.dst_tty_name = ctl.dst_tty_path + 5;
     339  		if (check_utmp(&ctl))
     340  			errx(EXIT_FAILURE,
     341  			     _("%s is not logged in on %s"),
     342  			     ctl.dst_login, ctl.dst_tty_name);
     343  		if (check_tty(ctl.dst_tty_path, &tty_writeable, NULL, 1))
     344  			exit(EXIT_FAILURE);
     345  		if (ctl.src_uid && !tty_writeable)
     346  			errx(EXIT_FAILURE,
     347  			     _("%s has messages disabled on %s"),
     348  			     ctl.dst_login, ctl.dst_tty_name);
     349  		do_write(&ctl);
     350  		break;
     351  	default:
     352  		errtryhelp(EXIT_FAILURE);
     353  	}
     354  	free(ctl.dst_tty_path);
     355  	return EXIT_SUCCESS;
     356  }