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