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