1331722Seadler/*
214125Speter * Copyright (c) 1995
314125Speter *	A.R. Gordon (andrew.gordon@net-tel.co.uk).  All rights reserved.
414125Speter *
514125Speter * Redistribution and use in source and binary forms, with or without
614125Speter * modification, are permitted provided that the following conditions
714125Speter * are met:
814125Speter * 1. Redistributions of source code must retain the above copyright
914125Speter *    notice, this list of conditions and the following disclaimer.
1014125Speter * 2. Redistributions in binary form must reproduce the above copyright
1114125Speter *    notice, this list of conditions and the following disclaimer in the
1214125Speter *    documentation and/or other materials provided with the distribution.
1314125Speter * 3. All advertising materials mentioning features or use of this software
1414125Speter *    must display the following acknowledgement:
1514125Speter *	This product includes software developed for the FreeBSD project
1614125Speter * 4. Neither the name of the author nor the names of any co-contributors
1714125Speter *    may be used to endorse or promote products derived from this software
1814125Speter *    without specific prior written permission.
1914125Speter *
2014125Speter * THIS SOFTWARE IS PROVIDED BY ANDREW GORDON AND CONTRIBUTORS ``AS IS'' AND
2114125Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2214125Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2314125Speter * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2414125Speter * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2514125Speter * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2614125Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2714125Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2814125Speter * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2914125Speter * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3014125Speter * SUCH DAMAGE.
3114125Speter *
3274499Salfred * $FreeBSD$
3374499Salfred *
3414125Speter */
3514125Speter
3630376Scharnier#include <err.h>
3730376Scharnier#include <errno.h>
3830376Scharnier#include <fcntl.h>
39180025Sdfr#include <netdb.h>
4014125Speter#include <stdio.h>
4130376Scharnier#include <string.h>
4214125Speter#include <unistd.h>
4314125Speter#include <sys/types.h>
4414125Speter#include <sys/mman.h>		/* For mmap()				*/
4514125Speter#include <rpc/rpc.h>
4614125Speter#include <syslog.h>
4799786Salfred#include <stdlib.h>
4814125Speter
4914125Speter#include "statd.h"
5014125Speter
5114125SpeterFileLayout *status_info;	/* Pointer to the mmap()ed status file	*/
5214125Speterstatic int status_fd;		/* File descriptor for the open file	*/
5314125Speterstatic off_t status_file_len;	/* Current on-disc length of file	*/
5414125Speter
5514125Speter/* sync_file --------------------------------------------------------------- */
5614125Speter/*
5714125Speter   Purpose:	Packaged call of msync() to flush changes to mmap()ed file
5814125Speter   Returns:	Nothing.  Errors to syslog.
5914125Speter*/
6014125Speter
6114125Spetervoid sync_file(void)
6214125Speter{
6314125Speter  if (msync((void *)status_info, 0, 0) < 0)
6414125Speter  {
6514125Speter    syslog(LOG_ERR, "msync() failed: %s", strerror(errno));
6614125Speter  }
6714125Speter}
6814125Speter
6914125Speter/* find_host -------------------------------------------------------------- */
7014125Speter/*
7114125Speter   Purpose:	Find the entry in the status file for a given host
7214125Speter   Returns:	Pointer to that entry in the mmap() region, or NULL.
7314125Speter   Notes:	Also creates entries if requested.
7414125Speter		Failure to create also returns NULL.
7514125Speter*/
7614125Speter
7714125SpeterHostInfo *find_host(char *hostname, int create)
7814125Speter{
7914125Speter  HostInfo *hp;
8014125Speter  HostInfo *spare_slot = NULL;
8114125Speter  HostInfo *result = NULL;
82180025Sdfr  struct addrinfo *ai1, *ai2;
8314125Speter  int i;
8414125Speter
85299988Struckman  ai2 = NULL;
86180025Sdfr  if (getaddrinfo(hostname, NULL, NULL, &ai1) != 0)
87180025Sdfr    ai1 = NULL;
8814125Speter  for (i = 0, hp = status_info->hosts; i < status_info->noOfHosts; i++, hp++)
8914125Speter  {
9014125Speter    if (!strncasecmp(hostname, hp->hostname, SM_MAXSTRLEN))
9114125Speter    {
9214125Speter      result = hp;
9314125Speter      break;
9414125Speter    }
95299988Struckman    if (hp->hostname[0] != '\0' &&
96180025Sdfr	getaddrinfo(hp->hostname, NULL, NULL, &ai2) != 0)
97180025Sdfr      ai2 = NULL;
98180025Sdfr    if (ai1 && ai2)
99180025Sdfr    {
100180025Sdfr       struct addrinfo *p1, *p2;
101180025Sdfr       for (p1 = ai1; !result && p1; p1 = p1->ai_next)
102180025Sdfr       {
103180025Sdfr	 for (p2 = ai2; !result && p2; p2 = p2->ai_next)
104180025Sdfr	 {
105180025Sdfr	   if (p1->ai_family == p2->ai_family
106180025Sdfr	       && p1->ai_addrlen == p2->ai_addrlen
107180025Sdfr	       && !memcmp(p1->ai_addr, p2->ai_addr, p1->ai_addrlen))
108180025Sdfr	   {
109180025Sdfr	     result = hp;
110180025Sdfr	     break;
111180025Sdfr	   }
112180025Sdfr	 }
113180025Sdfr       }
114180025Sdfr       if (result)
115180025Sdfr	 break;
116180025Sdfr    }
117299988Struckman    if (ai2) {
118180025Sdfr      freeaddrinfo(ai2);
119299988Struckman      ai2 = NULL;
120299988Struckman    }
12114125Speter    if (!spare_slot && !hp->monList && !hp->notifyReqd)
12214125Speter      spare_slot = hp;
12314125Speter  }
124180025Sdfr  if (ai1)
125180025Sdfr    freeaddrinfo(ai1);
12614125Speter
12714125Speter  /* Return if entry found, or if not asked to create one.		*/
12814125Speter  if (result || !create) return (result);
12914125Speter
13014125Speter  /* Now create an entry, using the spare slot if one was found or	*/
13114125Speter  /* adding to the end of the list otherwise, extending file if reqd	*/
13214125Speter  if (!spare_slot)
13314125Speter  {
13414125Speter    off_t desired_size;
13514125Speter    spare_slot = &status_info->hosts[status_info->noOfHosts];
13614125Speter    desired_size = ((char*)spare_slot - (char*)status_info) + sizeof(HostInfo);
13714125Speter    if (desired_size > status_file_len)
13814125Speter    {
13914125Speter      /* Extend file by writing 1 byte of junk at the desired end pos	*/
140299988Struckman      if (lseek(status_fd, desired_size - 1, SEEK_SET) == -1 ||
141299988Struckman          write(status_fd, "\0", 1) < 0)
14214125Speter      {
14314125Speter	syslog(LOG_ERR, "Unable to extend status file");
14414125Speter	return (NULL);
14514125Speter      }
14614125Speter      status_file_len = desired_size;
14714125Speter    }
14814125Speter    status_info->noOfHosts++;
14914125Speter  }
15014125Speter
15114125Speter  /* Initialise the spare slot that has been found/created		*/
15214125Speter  /* Note that we do not msync(), since the caller is presumed to be	*/
15314125Speter  /* about to modify the entry further					*/
15414125Speter  memset(spare_slot, 0, sizeof(HostInfo));
15514125Speter  strncpy(spare_slot->hostname, hostname, SM_MAXSTRLEN);
15614125Speter  return (spare_slot);
15714125Speter}
15814125Speter
15914125Speter/* init_file -------------------------------------------------------------- */
16014125Speter/*
16114125Speter   Purpose:	Open file, create if necessary, initialise it.
16214125Speter   Returns:	Nothing - exits on error
16314125Speter   Notes:	Called before process becomes daemon, hence logs to
16414125Speter		stderr rather than syslog.
16514125Speter		Opens the file, then mmap()s it for ease of access.
16614125Speter		Also performs initial clean-up of the file, zeroing
16714125Speter		monitor list pointers, setting the notifyReqd flag in
16814125Speter		all hosts that had a monitor list, and incrementing
16914125Speter		the state number to the next even value.
17014125Speter*/
17114125Speter
17299798Salfredvoid init_file(const char *filename)
17314125Speter{
17414125Speter  int new_file = FALSE;
17514125Speter  char buf[HEADER_LEN];
17614125Speter  int i;
17714125Speter
17814125Speter  /* try to open existing file - if not present, create one		*/
17914125Speter  status_fd = open(filename, O_RDWR);
18014125Speter  if ((status_fd < 0) && (errno == ENOENT))
18114125Speter  {
18214125Speter    status_fd = open(filename, O_RDWR | O_CREAT, 0644);
18314125Speter    new_file = TRUE;
18414125Speter  }
18514125Speter  if (status_fd < 0)
18630376Scharnier    errx(1, "unable to open status file %s", filename);
18714125Speter
18814125Speter  /* File now open.  mmap() it, with a generous size to allow for	*/
18914125Speter  /* later growth, where we will extend the file but not re-map it.	*/
19014125Speter  status_info = (FileLayout *)
19114125Speter    mmap(NULL, 0x10000000, PROT_READ | PROT_WRITE, MAP_SHARED, status_fd, 0);
19214125Speter
19321786Salex  if (status_info == (FileLayout *) MAP_FAILED)
194171816Struckman    err(1, "unable to mmap() status file");
19514125Speter
19614125Speter  status_file_len = lseek(status_fd, 0L, SEEK_END);
19714125Speter
19814125Speter  /* If the file was not newly created, validate the contents, and if	*/
19914125Speter  /* defective, re-create from scratch.					*/
20014125Speter  if (!new_file)
20114125Speter  {
20214125Speter    if ((status_file_len < HEADER_LEN) || (status_file_len
20314125Speter      < (HEADER_LEN + sizeof(HostInfo) * status_info->noOfHosts)) )
20414125Speter    {
20530376Scharnier      warnx("status file is corrupt");
20614125Speter      new_file = TRUE;
20714125Speter    }
20814125Speter  }
20914125Speter
21014125Speter  /* Initialisation of a new, empty file.				*/
21114125Speter  if (new_file)
21214125Speter  {
21314125Speter    memset(buf, 0, sizeof(buf));
21414125Speter    lseek(status_fd, 0L, SEEK_SET);
21514125Speter    write(status_fd, buf, HEADER_LEN);
21614125Speter    status_file_len = HEADER_LEN;
21714125Speter  }
21814125Speter  else
21914125Speter  {
22014125Speter    /* Clean-up of existing file - monitored hosts will have a pointer	*/
22114125Speter    /* to a list of clients, which refers to memory in the previous	*/
22214125Speter    /* incarnation of the program and so are meaningless now.  These	*/
22314125Speter    /* pointers are zeroed and the fact that the host was previously	*/
22414125Speter    /* monitored is recorded by setting the notifyReqd flag, which will	*/
22514125Speter    /* in due course cause a SM_NOTIFY to be sent.			*/
22614125Speter    /* Note that if we crash twice in quick succession, some hosts may	*/
22714125Speter    /* already have notifyReqd set, where we didn't manage to notify	*/
22814125Speter    /* them before the second crash occurred.				*/
22914125Speter    for (i = 0; i < status_info->noOfHosts; i++)
23014125Speter    {
23114125Speter      HostInfo *this_host = &status_info->hosts[i];
23214125Speter
23314125Speter      if (this_host->monList)
23414125Speter      {
23514125Speter	this_host->notifyReqd = TRUE;
23614125Speter	this_host->monList = NULL;
23714125Speter      }
23814125Speter    }
23914125Speter    /* Select the next higher even number for the state counter		*/
24014125Speter    status_info->ourState = (status_info->ourState + 2) & 0xfffffffe;
24114125Speter/*???????******/ status_info->ourState++;
24214125Speter  }
24314125Speter}
24414125Speter
24514125Speter/* notify_one_host --------------------------------------------------------- */
24614125Speter/*
24714125Speter   Purpose:	Perform SM_NOTIFY procedure at specified host
24814125Speter   Returns:	TRUE if success, FALSE if failed.
24914125Speter*/
25014125Speter
25114125Speterstatic int notify_one_host(char *hostname)
25214125Speter{
25314125Speter  struct timeval timeout = { 20, 0 };	/* 20 secs timeout		*/
25414125Speter  CLIENT *cli;
25514125Speter  char dummy;
25614125Speter  stat_chge arg;
25714125Speter  char our_hostname[SM_MAXSTRLEN+1];
25814125Speter
25914125Speter  gethostname(our_hostname, sizeof(our_hostname));
26014125Speter  our_hostname[SM_MAXSTRLEN] = '\0';
26114125Speter  arg.mon_name = our_hostname;
26214125Speter  arg.state = status_info->ourState;
26314125Speter
26414125Speter  if (debug) syslog (LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s", hostname, our_hostname);
26514125Speter
26614125Speter  cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
26714125Speter  if (!cli)
26814125Speter  {
26914125Speter    syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
27014125Speter      clnt_spcreateerror(""));
27114125Speter    return (FALSE);
27214125Speter  }
27314125Speter
274121560Speter  if (clnt_call(cli, SM_NOTIFY, (xdrproc_t)xdr_stat_chge, &arg,
275121560Speter      (xdrproc_t)xdr_void, &dummy, timeout)
27614125Speter    != RPC_SUCCESS)
27714125Speter  {
27814125Speter    syslog(LOG_ERR, "Failed to contact rpc.statd at host %s", hostname);
27914125Speter    clnt_destroy(cli);
28014125Speter    return (FALSE);
28114125Speter  }
28214125Speter
28314125Speter  clnt_destroy(cli);
28414125Speter  return (TRUE);
28514125Speter}
28614125Speter
28714125Speter/* notify_hosts ------------------------------------------------------------ */
28814125Speter/*
28914125Speter   Purpose:	Send SM_NOTIFY to all hosts marked as requiring it
29014125Speter   Returns:	Nothing, immediately - forks a process to do the work.
29114125Speter   Notes:	Does nothing if there are no monitored hosts.
29214125Speter		Called after all the initialisation has been done -
29314125Speter		logs to syslog.
29414125Speter*/
29514125Speter
29614125Spetervoid notify_hosts(void)
29714125Speter{
29814125Speter  int i;
29914125Speter  int attempts;
30014125Speter  int work_to_do = FALSE;
30114125Speter  HostInfo *hp;
30214125Speter  pid_t pid;
30314125Speter
30414125Speter  /* First check if there is in fact any work to do.			*/
30514125Speter  for (i = status_info->noOfHosts, hp = status_info->hosts; i ; i--, hp++)
30614125Speter  {
30714125Speter    if (hp->notifyReqd)
30814125Speter    {
30914125Speter      work_to_do = TRUE;
31014125Speter      break;
31114125Speter    }
31214125Speter  }
31314125Speter
31414125Speter  if (!work_to_do) return;	/* No work found			*/
31514125Speter
31614125Speter  pid = fork();
31714125Speter  if (pid == -1)
31814125Speter  {
31914125Speter    syslog(LOG_ERR, "Unable to fork notify process - %s", strerror(errno));
32014125Speter    return;
32114125Speter  }
32214125Speter  if (pid) return;
32314125Speter
32414125Speter  /* Here in the child process.  We continue until all the hosts marked	*/
32514125Speter  /* as requiring notification have been duly notified.			*/
32614125Speter  /* If one of the initial attempts fails, we sleep for a while and	*/
32714125Speter  /* have another go.  This is necessary because when we have crashed,	*/
32814125Speter  /* (eg. a power outage) it is quite possible that we won't be able to	*/
32914125Speter  /* contact all monitored hosts immediately on restart, either because	*/
33014125Speter  /* they crashed too and take longer to come up (in which case the	*/
33114125Speter  /* notification isn't really required), or more importantly if some	*/
33214125Speter  /* router etc. needed to reach the monitored host has not come back	*/
33314125Speter  /* up yet.  In this case, we will be a bit late in re-establishing	*/
33414125Speter  /* locks (after the grace period) but that is the best we can do.	*/
33514125Speter  /* We try 10 times at 5 sec intervals, 10 more times at 1 minute	*/
33614125Speter  /* intervals, then 24 more times at hourly intervals, finally		*/
33714125Speter  /* giving up altogether if the host hasn't come back to life after	*/
33814125Speter  /* 24 hours.								*/
33914125Speter
34014125Speter  for (attempts = 0; attempts < 44; attempts++)
34114125Speter  {
34214125Speter    work_to_do = FALSE;		/* Unless anything fails		*/
34314125Speter    for (i = status_info->noOfHosts, hp = status_info->hosts; i ; i--, hp++)
34414125Speter    {
34514125Speter      if (hp->notifyReqd)
34614125Speter      {
34714125Speter        if (notify_one_host(hp->hostname))
34814125Speter	{
34914125Speter	  hp->notifyReqd = FALSE;
35014125Speter          sync_file();
35114125Speter	}
35214125Speter	else work_to_do = TRUE;
35314125Speter      }
35414125Speter    }
35514125Speter    if (!work_to_do) break;
35614125Speter    if (attempts < 10) sleep(5);
35714125Speter    else if (attempts < 20) sleep(60);
35814125Speter    else sleep(60*60);
35914125Speter  }
36014125Speter  exit(0);
36114125Speter}
36214125Speter
36314125Speter
364