/* getservhost.c -- Return the name of the server host. */

/* Copyright (C) 1988, 1990, 1992 Free Software Foundation, Inc.

   This file is part of GNU Finger.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */


#include <stdio.h>
#include <config.h>

#include <general.h>
#include <fingerpaths.h>
#include <util.h>
extern char *progname;

/* Return a new string which is the name of the local GNU Finger server
   host.  If this cannot be determined, return a NULL pointer instead.
   Single argument ERROR_STREAM is a stream to print errors to; a NULL
   value for this argument means print no errors. */
char *
getservhost (error_stream)
  FILE *error_stream;
{
  char *serverhost = NULL;
  FILE *stream;
  char *buffer = NULL;
  int buffer_size = 0;


  stream = fopen (SERVERHOSTFILE, "r");

  if (!stream)
    {
      if (error_stream)
	fprintf (error_stream, "%s:Missing server file `%s'\n",
		 progname, SERVERHOSTFILE);

      return ((char *)NULL);
    }

  /* Read lines from this file until we find the server host's name. */
  while (getline (&buffer, &buffer_size, stream) >= 0)
    {
      register char *t, *t1;

      t = buffer;

      while (*t && whitespace (*t))
	t++;

      if (*t == '#')
	continue;

      t1 = t;

      while (*t1 && !whitespace (*t1))
	t1++;

      *t1 = '\0';

      serverhost = savestring (t);
      break;
    }

  fclose (stream);

  if (buffer)
    free (buffer);

  return (serverhost);
}


/* Return a new string which is the name of the host to forward
   unsatisfied requests to.  If this cannot be determined, return a NULL
   pointer instead. */

char *
getforwardhost ()
{
  char *forwardhost = NULL;
  FILE *stream;
  char *buffer = NULL;
  int buffer_size = 0;


  stream = fopen (FORWARDHOSTFILE, "r");

  if (!stream)
    return ((char *)NULL);

  /* Read lines from this file until we find the forward host's name. */
  while (getline (&buffer, &buffer_size, stream) >= 0)
    {
      register char *t, *t1;

      t = buffer;

      while (*t && whitespace (*t))
	t++;

      if (*t == '#')
	continue;

      t1 = t;

      while (*t1 && !whitespace (*t1))
	t1++;

      *t1 = '\0';

      forwardhost = savestring (t);
      break;
    }

  fclose (stream);

  if (buffer)
    free (buffer);

  return (forwardhost);
}
