Add support for RT2501USB/RT2601USB devices.
[dragonfly.git] / usr.sbin / rpc.statd / file.c
1 /*
2  * Copyright (c) 1995
3  *      A.R. Gordon (andrew.gordon@net-tel.co.uk).  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed for the FreeBSD project
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY ANDREW GORDON AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $DragonFly: src/usr.sbin/rpc.statd/file.c,v 1.2 2005/11/25 00:32:49 swildner Exp $
33  */
34
35 #include <err.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <sys/mman.h>           /* For mmap()                           */
43 #include <rpc/rpc.h>
44 #include <syslog.h>
45
46 #include "statd.h"
47
48 FileLayout *status_info;        /* Pointer to the mmap()ed status file  */
49 static int status_fd;           /* File descriptor for the open file    */
50 static off_t status_file_len;   /* Current on-disc length of file       */
51
52 /* sync_file --------------------------------------------------------------- */
53 /*
54    Purpose:     Packaged call of msync() to flush changes to mmap()ed file
55    Returns:     Nothing.  Errors to syslog.
56 */
57
58 void
59 sync_file(void)
60 {
61   if (msync((void *)status_info, 0, 0) < 0)
62   {
63     syslog(LOG_ERR, "msync() failed: %s", strerror(errno));
64   }
65 }
66
67 /* find_host -------------------------------------------------------------- */
68 /*
69    Purpose:     Find the entry in the status file for a given host
70    Returns:     Pointer to that entry in the mmap() region, or NULL.
71    Notes:       Also creates entries if requested.
72                 Failure to create also returns NULL.
73 */
74
75 HostInfo *
76 find_host(char *hostname, int create)
77 {
78   HostInfo *hp;
79   HostInfo *spare_slot = NULL;
80   HostInfo *result = NULL;
81   int i;
82
83   for (i = 0, hp = status_info->hosts; i < status_info->noOfHosts; i++, hp++)
84   {
85     if (!strncasecmp(hostname, hp->hostname, SM_MAXSTRLEN))
86     {
87       result = hp;
88       break;
89     }
90     if (!spare_slot && !hp->monList && !hp->notifyReqd)
91       spare_slot = hp;
92   }
93
94   /* Return if entry found, or if not asked to create one.              */
95   if (result || !create) return (result);
96
97   /* Now create an entry, using the spare slot if one was found or      */
98   /* adding to the end of the list otherwise, extending file if reqd    */
99   if (!spare_slot)
100   {
101     off_t desired_size;
102     spare_slot = &status_info->hosts[status_info->noOfHosts];
103     desired_size = ((char*)spare_slot - (char*)status_info) + sizeof(HostInfo);
104     if (desired_size > status_file_len)
105     {
106       /* Extend file by writing 1 byte of junk at the desired end pos   */
107       lseek(status_fd, desired_size - 1, SEEK_SET);
108       i = write(status_fd, &i, 1);
109       if (i < 1)
110       {
111         syslog(LOG_ERR, "Unable to extend status file");
112         return (NULL);
113       }
114       status_file_len = desired_size;
115     }
116     status_info->noOfHosts++;
117   }
118
119   /* Initialise the spare slot that has been found/created              */
120   /* Note that we do not msync(), since the caller is presumed to be    */
121   /* about to modify the entry further                                  */
122   memset(spare_slot, 0, sizeof(HostInfo));
123   strncpy(spare_slot->hostname, hostname, SM_MAXSTRLEN);
124   return (spare_slot);
125 }
126
127 /* init_file -------------------------------------------------------------- */
128 /*
129    Purpose:     Open file, create if necessary, initialise it.
130    Returns:     Nothing - exits on error
131    Notes:       Called before process becomes daemon, hence logs to
132                 stderr rather than syslog.
133                 Opens the file, then mmap()s it for ease of access.
134                 Also performs initial clean-up of the file, zeroing
135                 monitor list pointers, setting the notifyReqd flag in
136                 all hosts that had a monitor list, and incrementing
137                 the state number to the next even value.
138 */
139
140 void
141 init_file(char *filename)
142 {
143   int new_file = FALSE;
144   char buf[HEADER_LEN];
145   int i;
146
147   /* try to open existing file - if not present, create one             */
148   status_fd = open(filename, O_RDWR);
149   if ((status_fd < 0) && (errno == ENOENT))
150   {
151     status_fd = open(filename, O_RDWR | O_CREAT, 0644);
152     new_file = TRUE;
153   }
154   if (status_fd < 0)
155     errx(1, "unable to open status file %s", filename);
156
157   /* File now open.  mmap() it, with a generous size to allow for       */
158   /* later growth, where we will extend the file but not re-map it.     */
159   status_info = (FileLayout *)
160     mmap(NULL, 0x10000000, PROT_READ | PROT_WRITE, MAP_SHARED, status_fd, 0);
161
162   if (status_info == (FileLayout *) MAP_FAILED)
163     warn("unable to mmap() status file");
164
165   status_file_len = lseek(status_fd, 0L, SEEK_END);
166
167   /* If the file was not newly created, validate the contents, and if   */
168   /* defective, re-create from scratch.                                 */
169   if (!new_file)
170   {
171     if ((status_file_len < HEADER_LEN) || (status_file_len
172       < (HEADER_LEN + sizeof(HostInfo) * status_info->noOfHosts)) )
173     {
174       warnx("status file is corrupt");
175       new_file = TRUE;
176     }
177   }
178
179   /* Initialisation of a new, empty file.                               */
180   if (new_file)
181   {
182     memset(buf, 0, sizeof(buf));
183     lseek(status_fd, 0L, SEEK_SET);
184     write(status_fd, buf, HEADER_LEN);
185     status_file_len = HEADER_LEN;
186   }
187   else
188   {
189     /* Clean-up of existing file - monitored hosts will have a pointer  */
190     /* to a list of clients, which refers to memory in the previous     */
191     /* incarnation of the program and so are meaningless now.  These    */
192     /* pointers are zeroed and the fact that the host was previously    */
193     /* monitored is recorded by setting the notifyReqd flag, which will */
194     /* in due course cause a SM_NOTIFY to be sent.                      */
195     /* Note that if we crash twice in quick succession, some hosts may  */
196     /* already have notifyReqd set, where we didn't manage to notify    */
197     /* them before the second crash occurred.                           */
198     for (i = 0; i < status_info->noOfHosts; i++)
199     {
200       HostInfo *this_host = &status_info->hosts[i];
201
202       if (this_host->monList)
203       {
204         this_host->notifyReqd = TRUE;
205         this_host->monList = NULL;
206       }
207     }
208     /* Select the next higher even number for the state counter         */
209     status_info->ourState = (status_info->ourState + 2) & 0xfffffffe;
210 /*???????******/ status_info->ourState++;
211   }
212 }
213
214 /* xdr_stat_chge ----------------------------------------------------------- */
215 /*
216    Purpose:     XDR-encode structure of type stat_chge
217    Returns:     TRUE if successful
218    Notes:       This function is missing from librpcsvc, because the
219                 sm_inter.x distributed by Sun omits the SM_NOTIFY
220                 procedure used between co-operating statd's
221 */
222
223 bool_t
224 xdr_stat_chge(XDR *xdrs, stat_chge *objp)
225 {
226   if (!xdr_string(xdrs, &objp->mon_name, SM_MAXSTRLEN))
227   {
228     return (FALSE);
229   }
230   if (!xdr_int(xdrs, &objp->state))
231   {
232     return (FALSE);
233   }
234   return (TRUE);
235 }
236
237
238 /* notify_one_host --------------------------------------------------------- */
239 /*
240    Purpose:     Perform SM_NOTIFY procedure at specified host
241    Returns:     TRUE if success, FALSE if failed.
242 */
243
244 static int
245 notify_one_host(char *hostname)
246 {
247   struct timeval timeout = { 20, 0 };   /* 20 secs timeout              */
248   CLIENT *cli;
249   char dummy; 
250   stat_chge arg;
251   char our_hostname[SM_MAXSTRLEN+1];
252
253   gethostname(our_hostname, sizeof(our_hostname));
254   our_hostname[SM_MAXSTRLEN] = '\0';
255   arg.mon_name = our_hostname;
256   arg.state = status_info->ourState;
257
258   if (debug) syslog (LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s", hostname, our_hostname);
259
260   cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
261   if (!cli)
262   {
263     syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
264       clnt_spcreateerror(""));
265     return (FALSE);
266   }
267
268   if (clnt_call(cli, SM_NOTIFY, xdr_stat_chge, &arg, xdr_void, &dummy, timeout)
269     != RPC_SUCCESS)
270   {
271     syslog(LOG_ERR, "Failed to contact rpc.statd at host %s", hostname);
272     clnt_destroy(cli);
273     return (FALSE);
274   }
275
276   clnt_destroy(cli);
277   return (TRUE);
278 }
279
280 /* notify_hosts ------------------------------------------------------------ */
281 /*
282    Purpose:     Send SM_NOTIFY to all hosts marked as requiring it
283    Returns:     Nothing, immediately - forks a process to do the work.
284    Notes:       Does nothing if there are no monitored hosts.
285                 Called after all the initialisation has been done - 
286                 logs to syslog.
287 */
288
289 void
290 notify_hosts(void)
291 {
292   int i;
293   int attempts;
294   int work_to_do = FALSE;
295   HostInfo *hp;
296   pid_t pid;
297
298   /* First check if there is in fact any work to do.                    */
299   for (i = status_info->noOfHosts, hp = status_info->hosts; i ; i--, hp++)
300   {
301     if (hp->notifyReqd)
302     {
303       work_to_do = TRUE;
304       break;
305     }
306   }
307
308   if (!work_to_do) return;      /* No work found                        */
309
310   pid = fork();
311   if (pid == -1)
312   {
313     syslog(LOG_ERR, "Unable to fork notify process - %s", strerror(errno));
314     return;
315   }
316   if (pid) return;
317
318   /* Here in the child process.  We continue until all the hosts marked */
319   /* as requiring notification have been duly notified.                 */
320   /* If one of the initial attempts fails, we sleep for a while and     */
321   /* have another go.  This is necessary because when we have crashed,  */
322   /* (eg. a power outage) it is quite possible that we won't be able to */
323   /* contact all monitored hosts immediately on restart, either because */
324   /* they crashed too and take longer to come up (in which case the     */
325   /* notification isn't really required), or more importantly if some   */
326   /* router etc. needed to reach the monitored host has not come back   */
327   /* up yet.  In this case, we will be a bit late in re-establishing    */
328   /* locks (after the grace period) but that is the best we can do.     */
329   /* We try 10 times at 5 sec intervals, 10 more times at 1 minute      */
330   /* intervals, then 24 more times at hourly intervals, finally         */
331   /* giving up altogether if the host hasn't come back to life after    */
332   /* 24 hours.                                                          */
333
334   for (attempts = 0; attempts < 44; attempts++)
335   {
336     work_to_do = FALSE;         /* Unless anything fails                */
337     for (i = status_info->noOfHosts, hp = status_info->hosts; i ; i--, hp++)
338     {
339       if (hp->notifyReqd)
340       {
341         if (notify_one_host(hp->hostname))
342         {
343           hp->notifyReqd = FALSE;
344           sync_file();
345         }
346         else work_to_do = TRUE;
347       }
348     }
349     if (!work_to_do) break;
350     if (attempts < 10) sleep(5);
351     else if (attempts < 20) sleep(60);
352     else sleep(60*60);
353   }
354   exit(0);
355 }
356
357