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