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