114125Speter/*
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
85180025Sdfr  if (getaddrinfo(hostname, NULL, NULL, &ai1) != 0)
86180025Sdfr    ai1 = NULL;
8714125Speter  for (i = 0, hp = status_info->hosts; i < status_info->noOfHosts; i++, hp++)
8814125Speter  {
8914125Speter    if (!strncasecmp(hostname, hp->hostname, SM_MAXSTRLEN))
9014125Speter    {
9114125Speter      result = hp;
9214125Speter      break;
9314125Speter    }
94180025Sdfr    if (hp->hostname[0] &&
95180025Sdfr	getaddrinfo(hp->hostname, NULL, NULL, &ai2) != 0)
96180025Sdfr      ai2 = NULL;
97180025Sdfr    if (ai1 && ai2)
98180025Sdfr    {
99180025Sdfr       struct addrinfo *p1, *p2;
100180025Sdfr       for (p1 = ai1; !result && p1; p1 = p1->ai_next)
101180025Sdfr       {
102180025Sdfr	 for (p2 = ai2; !result && p2; p2 = p2->ai_next)
103180025Sdfr	 {
104180025Sdfr	   if (p1->ai_family == p2->ai_family
105180025Sdfr	       && p1->ai_addrlen == p2->ai_addrlen
106180025Sdfr	       && !memcmp(p1->ai_addr, p2->ai_addr, p1->ai_addrlen))
107180025Sdfr	   {
108180025Sdfr	     result = hp;
109180025Sdfr	     break;
110180025Sdfr	   }
111180025Sdfr	 }
112180025Sdfr       }
113180025Sdfr       if (result)
114180025Sdfr	 break;
115180025Sdfr    }
116180025Sdfr    if (ai2)
117180025Sdfr      freeaddrinfo(ai2);
11814125Speter    if (!spare_slot && !hp->monList && !hp->notifyReqd)
11914125Speter      spare_slot = hp;
12014125Speter  }
121180025Sdfr  if (ai1)
122180025Sdfr    freeaddrinfo(ai1);
12314125Speter
12414125Speter  /* Return if entry found, or if not asked to create one.		*/
12514125Speter  if (result || !create) return (result);
12614125Speter
12714125Speter  /* Now create an entry, using the spare slot if one was found or	*/
12814125Speter  /* adding to the end of the list otherwise, extending file if reqd	*/
12914125Speter  if (!spare_slot)
13014125Speter  {
13114125Speter    off_t desired_size;
13214125Speter    spare_slot = &status_info->hosts[status_info->noOfHosts];
13314125Speter    desired_size = ((char*)spare_slot - (char*)status_info) + sizeof(HostInfo);
13414125Speter    if (desired_size > status_file_len)
13514125Speter    {
13614125Speter      /* Extend file by writing 1 byte of junk at the desired end pos	*/
13714125Speter      lseek(status_fd, desired_size - 1, SEEK_SET);
13814125Speter      i = write(status_fd, &i, 1);
13914125Speter      if (i < 1)
14014125Speter      {
14114125Speter	syslog(LOG_ERR, "Unable to extend status file");
14214125Speter	return (NULL);
14314125Speter      }
14414125Speter      status_file_len = desired_size;
14514125Speter    }
14614125Speter    status_info->noOfHosts++;
14714125Speter  }
14814125Speter
14914125Speter  /* Initialise the spare slot that has been found/created		*/
15014125Speter  /* Note that we do not msync(), since the caller is presumed to be	*/
15114125Speter  /* about to modify the entry further					*/
15214125Speter  memset(spare_slot, 0, sizeof(HostInfo));
15314125Speter  strncpy(spare_slot->hostname, hostname, SM_MAXSTRLEN);
15414125Speter  return (spare_slot);
15514125Speter}
15614125Speter
15714125Speter/* init_file -------------------------------------------------------------- */
15814125Speter/*
15914125Speter   Purpose:	Open file, create if necessary, initialise it.
16014125Speter   Returns:	Nothing - exits on error
16114125Speter   Notes:	Called before process becomes daemon, hence logs to
16214125Speter		stderr rather than syslog.
16314125Speter		Opens the file, then mmap()s it for ease of access.
16414125Speter		Also performs initial clean-up of the file, zeroing
16514125Speter		monitor list pointers, setting the notifyReqd flag in
16614125Speter		all hosts that had a monitor list, and incrementing
16714125Speter		the state number to the next even value.
16814125Speter*/
16914125Speter
17099798Salfredvoid init_file(const char *filename)
17114125Speter{
17214125Speter  int new_file = FALSE;
17314125Speter  char buf[HEADER_LEN];
17414125Speter  int i;
17514125Speter
17614125Speter  /* try to open existing file - if not present, create one		*/
17714125Speter  status_fd = open(filename, O_RDWR);
17814125Speter  if ((status_fd < 0) && (errno == ENOENT))
17914125Speter  {
18014125Speter    status_fd = open(filename, O_RDWR | O_CREAT, 0644);
18114125Speter    new_file = TRUE;
18214125Speter  }
18314125Speter  if (status_fd < 0)
18430376Scharnier    errx(1, "unable to open status file %s", filename);
18514125Speter
18614125Speter  /* File now open.  mmap() it, with a generous size to allow for	*/
18714125Speter  /* later growth, where we will extend the file but not re-map it.	*/
18814125Speter  status_info = (FileLayout *)
18914125Speter    mmap(NULL, 0x10000000, PROT_READ | PROT_WRITE, MAP_SHARED, status_fd, 0);
19014125Speter
19121786Salex  if (status_info == (FileLayout *) MAP_FAILED)
192171816Struckman    err(1, "unable to mmap() status file");
19314125Speter
19414125Speter  status_file_len = lseek(status_fd, 0L, SEEK_END);
19514125Speter
19614125Speter  /* If the file was not newly created, validate the contents, and if	*/
19714125Speter  /* defective, re-create from scratch.					*/
19814125Speter  if (!new_file)
19914125Speter  {
20014125Speter    if ((status_file_len < HEADER_LEN) || (status_file_len
20114125Speter      < (HEADER_LEN + sizeof(HostInfo) * status_info->noOfHosts)) )
20214125Speter    {
20330376Scharnier      warnx("status file is corrupt");
20414125Speter      new_file = TRUE;
20514125Speter    }
20614125Speter  }
20714125Speter
20814125Speter  /* Initialisation of a new, empty file.				*/
20914125Speter  if (new_file)
21014125Speter  {
21114125Speter    memset(buf, 0, sizeof(buf));
21214125Speter    lseek(status_fd, 0L, SEEK_SET);
21314125Speter    write(status_fd, buf, HEADER_LEN);
21414125Speter    status_file_len = HEADER_LEN;
21514125Speter  }
21614125Speter  else
21714125Speter  {
21814125Speter    /* Clean-up of existing file - monitored hosts will have a pointer	*/
21914125Speter    /* to a list of clients, which refers to memory in the previous	*/
22014125Speter    /* incarnation of the program and so are meaningless now.  These	*/
22114125Speter    /* pointers are zeroed and the fact that the host was previously	*/
22214125Speter    /* monitored is recorded by setting the notifyReqd flag, which will	*/
22314125Speter    /* in due course cause a SM_NOTIFY to be sent.			*/
22414125Speter    /* Note that if we crash twice in quick succession, some hosts may	*/
22514125Speter    /* already have notifyReqd set, where we didn't manage to notify	*/
22614125Speter    /* them before the second crash occurred.				*/
22714125Speter    for (i = 0; i < status_info->noOfHosts; i++)
22814125Speter    {
22914125Speter      HostInfo *this_host = &status_info->hosts[i];
23014125Speter
23114125Speter      if (this_host->monList)
23214125Speter      {
23314125Speter	this_host->notifyReqd = TRUE;
23414125Speter	this_host->monList = NULL;
23514125Speter      }
23614125Speter    }
23714125Speter    /* Select the next higher even number for the state counter		*/
23814125Speter    status_info->ourState = (status_info->ourState + 2) & 0xfffffffe;
23914125Speter/*???????******/ status_info->ourState++;
24014125Speter  }
24114125Speter}
24214125Speter
24314125Speter/* notify_one_host --------------------------------------------------------- */
24414125Speter/*
24514125Speter   Purpose:	Perform SM_NOTIFY procedure at specified host
24614125Speter   Returns:	TRUE if success, FALSE if failed.
24714125Speter*/
24814125Speter
24914125Speterstatic int notify_one_host(char *hostname)
25014125Speter{
25114125Speter  struct timeval timeout = { 20, 0 };	/* 20 secs timeout		*/
25214125Speter  CLIENT *cli;
25314125Speter  char dummy;
25414125Speter  stat_chge arg;
25514125Speter  char our_hostname[SM_MAXSTRLEN+1];
25614125Speter
25714125Speter  gethostname(our_hostname, sizeof(our_hostname));
25814125Speter  our_hostname[SM_MAXSTRLEN] = '\0';
25914125Speter  arg.mon_name = our_hostname;
26014125Speter  arg.state = status_info->ourState;
26114125Speter
26214125Speter  if (debug) syslog (LOG_DEBUG, "Sending SM_NOTIFY to host %s from %s", hostname, our_hostname);
26314125Speter
26414125Speter  cli = clnt_create(hostname, SM_PROG, SM_VERS, "udp");
26514125Speter  if (!cli)
26614125Speter  {
26714125Speter    syslog(LOG_ERR, "Failed to contact host %s%s", hostname,
26814125Speter      clnt_spcreateerror(""));
26914125Speter    return (FALSE);
27014125Speter  }
27114125Speter
272121560Speter  if (clnt_call(cli, SM_NOTIFY, (xdrproc_t)xdr_stat_chge, &arg,
273121560Speter      (xdrproc_t)xdr_void, &dummy, timeout)
27414125Speter    != RPC_SUCCESS)
27514125Speter  {
27614125Speter    syslog(LOG_ERR, "Failed to contact rpc.statd at host %s", hostname);
27714125Speter    clnt_destroy(cli);
27814125Speter    return (FALSE);
27914125Speter  }
28014125Speter
28114125Speter  clnt_destroy(cli);
28214125Speter  return (TRUE);
28314125Speter}
28414125Speter
28514125Speter/* notify_hosts ------------------------------------------------------------ */
28614125Speter/*
28714125Speter   Purpose:	Send SM_NOTIFY to all hosts marked as requiring it
28814125Speter   Returns:	Nothing, immediately - forks a process to do the work.
28914125Speter   Notes:	Does nothing if there are no monitored hosts.
29014125Speter		Called after all the initialisation has been done -
29114125Speter		logs to syslog.
29214125Speter*/
29314125Speter
29414125Spetervoid notify_hosts(void)
29514125Speter{
29614125Speter  int i;
29714125Speter  int attempts;
29814125Speter  int work_to_do = FALSE;
29914125Speter  HostInfo *hp;
30014125Speter  pid_t pid;
30114125Speter
30214125Speter  /* First check if there is in fact any work to do.			*/
30314125Speter  for (i = status_info->noOfHosts, hp = status_info->hosts; i ; i--, hp++)
30414125Speter  {
30514125Speter    if (hp->notifyReqd)
30614125Speter    {
30714125Speter      work_to_do = TRUE;
30814125Speter      break;
30914125Speter    }
31014125Speter  }
31114125Speter
31214125Speter  if (!work_to_do) return;	/* No work found			*/
31314125Speter
31414125Speter  pid = fork();
31514125Speter  if (pid == -1)
31614125Speter  {
31714125Speter    syslog(LOG_ERR, "Unable to fork notify process - %s", strerror(errno));
31814125Speter    return;
31914125Speter  }
32014125Speter  if (pid) return;
32114125Speter
32214125Speter  /* Here in the child process.  We continue until all the hosts marked	*/
32314125Speter  /* as requiring notification have been duly notified.			*/
32414125Speter  /* If one of the initial attempts fails, we sleep for a while and	*/
32514125Speter  /* have another go.  This is necessary because when we have crashed,	*/
32614125Speter  /* (eg. a power outage) it is quite possible that we won't be able to	*/
32714125Speter  /* contact all monitored hosts immediately on restart, either because	*/
32814125Speter  /* they crashed too and take longer to come up (in which case the	*/
32914125Speter  /* notification isn't really required), or more importantly if some	*/
33014125Speter  /* router etc. needed to reach the monitored host has not come back	*/
33114125Speter  /* up yet.  In this case, we will be a bit late in re-establishing	*/
33214125Speter  /* locks (after the grace period) but that is the best we can do.	*/
33314125Speter  /* We try 10 times at 5 sec intervals, 10 more times at 1 minute	*/
33414125Speter  /* intervals, then 24 more times at hourly intervals, finally		*/
33514125Speter  /* giving up altogether if the host hasn't come back to life after	*/
33614125Speter  /* 24 hours.								*/
33714125Speter
33814125Speter  for (attempts = 0; attempts < 44; attempts++)
33914125Speter  {
34014125Speter    work_to_do = FALSE;		/* Unless anything fails		*/
34114125Speter    for (i = status_info->noOfHosts, hp = status_info->hosts; i ; i--, hp++)
34214125Speter    {
34314125Speter      if (hp->notifyReqd)
34414125Speter      {
34514125Speter        if (notify_one_host(hp->hostname))
34614125Speter	{
34714125Speter	  hp->notifyReqd = FALSE;
34814125Speter          sync_file();
34914125Speter	}
35014125Speter	else work_to_do = TRUE;
35114125Speter      }
35214125Speter    }
35314125Speter    if (!work_to_do) break;
35414125Speter    if (attempts < 10) sleep(5);
35514125Speter    else if (attempts < 20) sleep(60);
35614125Speter    else sleep(60*60);
35714125Speter  }
35814125Speter  exit(0);
35914125Speter}
36014125Speter
36114125Speter
362