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