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