Merge from vendor branch LIBARCHIVE:
[dragonfly.git] / usr.bin / write / 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  * @(#) Copyright (c) 1989, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)write.c  8.1 (Berkeley) 6/6/93
38  * $FreeBSD: src/usr.bin/write/write.c,v 1.12 1999/08/28 01:07:48 peter Exp $
39  * $DragonFly: src/usr.bin/write/write.c,v 1.4 2004/08/30 18:06:50 eirikn Exp $
40  */
41
42 #include <sys/param.h>
43 #include <sys/signal.h>
44 #include <sys/stat.h>
45 #include <sys/file.h>
46 #include <sys/time.h>
47 #include <ctype.h>
48 #include <err.h>
49 #include <locale.h>
50 #include <paths.h>
51 #include <pwd.h>
52 #include <stdio.h>
53 #include <string.h>
54 #include <unistd.h>
55 #include <utmp.h>
56
57 void done(int);
58 void do_write(char *, char *, uid_t);
59 static void usage(void);
60 int term_chk(char *, int *, time_t *, int);
61 void wr_fputs(unsigned char *s);
62 void search_utmp(char *, char *, char *, uid_t);
63 int utmp_chk(char *, char *);
64
65 int
66 main(int argc, char **argv)
67 {
68         register char *cp;
69         time_t atime;
70         uid_t myuid;
71         int msgsok, myttyfd;
72         char tty[MAXPATHLEN], *mytty;
73
74         (void)setlocale(LC_CTYPE, "");
75
76         /* check that sender has write enabled */
77         if (isatty(fileno(stdin)))
78                 myttyfd = fileno(stdin);
79         else if (isatty(fileno(stdout)))
80                 myttyfd = fileno(stdout);
81         else if (isatty(fileno(stderr)))
82                 myttyfd = fileno(stderr);
83         else
84                 errx(1, "can't find your tty");
85         if (!(mytty = ttyname(myttyfd)))
86                 errx(1, "can't find your tty's name");
87         if ((cp = strrchr(mytty, '/')))
88                 mytty = cp + 1;
89         if (term_chk(mytty, &msgsok, &atime, 1))
90                 exit(1);
91         if (!msgsok)
92                 errx(1, "you have write permission turned off");
93
94         myuid = getuid();
95
96         /* check args */
97         switch (argc) {
98         case 2:
99                 search_utmp(argv[1], tty, mytty, myuid);
100                 do_write(tty, mytty, myuid);
101                 break;
102         case 3:
103                 if (!strncmp(argv[2], _PATH_DEV, strlen(_PATH_DEV)))
104                         argv[2] += strlen(_PATH_DEV);
105                 if (utmp_chk(argv[1], argv[2]))
106                         errx(1, "%s is not logged in on %s", argv[1], argv[2]);
107                 if (term_chk(argv[2], &msgsok, &atime, 1))
108                         exit(1);
109                 if (myuid && !msgsok)
110                         errx(1, "%s has messages disabled on %s", argv[1], argv[2]);
111                 do_write(argv[2], mytty, myuid);
112                 break;
113         default:
114                 usage();
115         }
116         done(0);
117         return (0);
118 }
119
120 static void
121 usage(void)
122 {
123         (void)fprintf(stderr, "usage: write user [tty]\n");
124         exit(1);
125 }
126
127 /*
128  * utmp_chk - checks that the given user is actually logged in on
129  *     the given tty
130  */
131 int
132 utmp_chk(char *user, char *tty)
133 {
134         struct utmp u;
135         int ufd;
136
137         if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
138                 return(0);      /* ignore error, shouldn't happen anyway */
139
140         while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
141                 if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0 &&
142                     strncmp(tty, u.ut_line, sizeof(u.ut_line)) == 0) {
143                         (void)close(ufd);
144                         return(0);
145                 }
146
147         (void)close(ufd);
148         return(1);
149 }
150
151 /*
152  * search_utmp - search utmp for the "best" terminal to write to
153  *
154  * Ignores terminals with messages disabled, and of the rest, returns
155  * the one with the most recent access time.  Returns as value the number
156  * of the user's terminals with messages enabled, or -1 if the user is
157  * not logged in at all.
158  *
159  * Special case for writing to yourself - ignore the terminal you're
160  * writing from, unless that's the only terminal with messages enabled.
161  */
162 void
163 search_utmp(char *user, char *tty, char *mytty, uid_t myuid)
164 {
165         struct utmp u;
166         time_t bestatime, atime;
167         int ufd, nloggedttys, nttys, msgsok, user_is_me;
168         char atty[UT_LINESIZE + 1];
169
170         if ((ufd = open(_PATH_UTMP, O_RDONLY)) < 0)
171                 err(1, "utmp");
172
173         nloggedttys = nttys = 0;
174         bestatime = 0;
175         user_is_me = 0;
176         while (read(ufd, (char *) &u, sizeof(u)) == sizeof(u))
177                 if (strncmp(user, u.ut_name, sizeof(u.ut_name)) == 0) {
178                         ++nloggedttys;
179                         (void)strncpy(atty, u.ut_line, UT_LINESIZE);
180                         atty[UT_LINESIZE] = '\0';
181                         if (term_chk(atty, &msgsok, &atime, 0))
182                                 continue;       /* bad term? skip */
183                         if (myuid && !msgsok)
184                                 continue;       /* skip ttys with msgs off */
185                         if (strcmp(atty, mytty) == 0) {
186                                 user_is_me = 1;
187                                 continue;       /* don't write to yourself */
188                         }
189                         ++nttys;
190                         if (atime > bestatime) {
191                                 bestatime = atime;
192                                 (void)strcpy(tty, atty);
193                         }
194                 }
195
196         (void)close(ufd);
197         if (nloggedttys == 0)
198                 errx(1, "%s is not logged in", user);
199         if (nttys == 0) {
200                 if (user_is_me) {               /* ok, so write to yourself! */
201                         (void)strcpy(tty, mytty);
202                         return;
203                 }
204                 errx(1, "%s has messages disabled", user);
205         } else if (nttys > 1) {
206                 warnx("%s is logged in more than once; writing to %s", user, tty);
207         }
208 }
209
210 /*
211  * term_chk - check that a terminal exists, and get the message bit
212  *     and the access time
213  */
214 int
215 term_chk(char *tty, int *msgsokP, time_t *atimeP, int showerror)
216 {
217         struct stat s;
218         char path[MAXPATHLEN];
219
220         (void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
221         if (stat(path, &s) < 0) {
222                 if (showerror)
223                         warn("%s", path);
224                 return(1);
225         }
226         *msgsokP = (s.st_mode & (S_IWRITE >> 3)) != 0;  /* group write bit */
227         *atimeP = s.st_atime;
228         return(0);
229 }
230
231 /*
232  * do_write - actually make the connection
233  */
234 void
235 do_write(char *tty, char *mytty, uid_t myuid)
236 {
237         register char *login, *nows;
238         register struct passwd *pwd;
239         time_t now;
240         char path[MAXPATHLEN], host[MAXHOSTNAMELEN], line[512];
241
242         /* Determine our login name before the we reopen() stdout */
243         if ((login = getlogin()) == NULL) {
244                 if ((pwd = getpwuid(myuid)))
245                         login = pwd->pw_name;
246                 else
247                         login = "???";
248         }
249
250         (void)snprintf(path, sizeof(path), "%s%s", _PATH_DEV, tty);
251         if ((freopen(path, "w", stdout)) == NULL)
252                 err(1, "%s", path);
253
254         (void)signal(SIGINT, done);
255         (void)signal(SIGHUP, done);
256
257         /* print greeting */
258         if (gethostname(host, sizeof(host)) < 0)
259                 (void)strcpy(host, "???");
260         now = time((time_t *)NULL);
261         nows = ctime(&now);
262         nows[16] = '\0';
263         (void)printf("\r\n\007\007\007Message from %s@%s on %s at %s ...\r\n",
264             login, host, mytty, nows + 11);
265
266         while (fgets(line, sizeof(line), stdin) != NULL)
267                 wr_fputs(line);
268 }
269
270 /*
271  * done - cleanup and exit
272  */
273 void
274 done(int n)
275 {
276         (void)printf("EOF\r\n");
277         exit(0);
278 }
279
280 /*
281  * wr_fputs - like fputs(), but makes control characters visible and
282  *     turns \n into \r\n
283  */
284 void
285 wr_fputs(register unsigned char *s)
286 {
287
288 #define PUTC(c) if (putchar(c) == EOF) err(1, NULL);
289
290         for (; *s != '\0'; ++s) {
291                 if (*s == '\n') {
292                         PUTC('\r');
293                 } else if (((*s & 0x80) && *s < 0xA0) ||
294                            /* disable upper controls */
295                            (!isprint(*s) && !isspace(*s) &&
296                             *s != '\a' && *s != '\b')
297                           ) {
298                         if (*s & 0x80) {
299                                 *s &= ~0x80;
300                                 PUTC('M');
301                                 PUTC('-');
302                         }
303                         if (iscntrl(*s)) {
304                                 *s ^= 0x40;
305                                 PUTC('^');
306                         }
307                 }
308                 PUTC(*s);
309         }
310         return;
311 #undef PUTC
312 }