1 #include "all.h"
2
3 #define SIZE 1024
4
5 int chatty;
6 int conftime;
7
8 #define NSIZE 128
9
10 static char nbuf[NSIZE];
11 static int chatpid;
12
13 static void
killchat(void)14 killchat(void)
15 {
16 char buf[NSIZE];
17 int fd;
18
19 remove(nbuf);
20 snprint(buf, sizeof buf, "/proc/%d/note", chatpid);
21 fd = open(buf, OWRITE);
22 write(fd, "kill\n", 5);
23 close(fd);
24 }
25
26 void
chatsrv(char * name)27 chatsrv(char *name)
28 {
29 int n, sfd, pfd[2];
30 char *p, buf[256];
31
32 if(name && *name)
33 snprint(nbuf, sizeof nbuf, "/srv/%s", name);
34 else{
35 if(p = strrchr(argv0, '/')) /* assign = */
36 name = p+1;
37 else
38 name = argv0;
39 snprint(nbuf, sizeof nbuf, "/srv/%s.chat", name);
40 }
41 remove(nbuf);
42 if(pipe(pfd) < 0)
43 panic("chatsrv pipe");
44 sfd = create(nbuf, OWRITE, 0600);
45 if(sfd < 0)
46 panic("chatsrv create %s", nbuf);
47 chatpid = rfork(RFPROC|RFMEM);
48 switch(chatpid){
49 case -1:
50 panic("chatsrv fork");
51 case 0:
52 break;
53 default:
54 atexit(killchat);
55 return;
56 }
57 fprint(sfd, "%d", pfd[1]);
58 close(sfd);
59 close(pfd[1]);
60 for(;;){
61 n = read(pfd[0], buf, sizeof(buf)-1);
62 if(n < 0)
63 break;
64 if(n == 0)
65 continue;
66 buf[n] = 0;
67 if(buf[0] == 'c')
68 conftime = 999;
69 chatty = strtol(buf, 0, 0);
70 if(abs(chatty) < 2)
71 rpcdebug = 0;
72 else
73 rpcdebug = abs(chatty) - 1;
74 fprint(2, "%s: chatty=%d, rpcdebug=%d, conftime=%d\n",
75 nbuf, chatty, rpcdebug, conftime);
76 }
77 _exits(0);
78 }
79
80 void
chat(char * fmt,...)81 chat(char *fmt, ...)
82 {
83 char buf[SIZE];
84 va_list arg;
85 Fmt f;
86
87 if(!chatty)
88 return;
89
90 fmtfdinit(&f, 2, buf, sizeof buf);
91 va_start(arg, fmt);
92 fmtvprint(&f, fmt, arg);
93 va_end(arg);
94 fmtfdflush(&f);
95 }
96
97 void
clog(char * fmt,...)98 clog(char *fmt, ...)
99 {
100 char buf[SIZE];
101 va_list arg;
102 int n;
103
104 va_start(arg, fmt);
105 vseprint(buf, buf+SIZE, fmt, arg);
106 va_end(arg);
107 n = strlen(buf);
108 if(chatty || rpcdebug)
109 write(2, buf, n);
110 if(chatty <= 0){
111 if(n>0 && buf[n-1] == '\n')
112 buf[n-1] = 0;
113 syslog(0, "nfs", buf);
114 }
115 }
116
117 void
panic(char * fmt,...)118 panic(char *fmt, ...)
119 {
120 char buf[SIZE];
121 va_list arg;
122
123 va_start(arg, fmt);
124 vseprint(buf, buf+SIZE, fmt, arg);
125 va_end(arg);
126 if(chatty || rpcdebug)
127 fprint(2, "%s %d: %s: %r\n", argv0, getpid(), buf);
128 if(chatty <= 0)
129 syslog(0, "nfs", buf);
130 exits("panic");
131 }
132