#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#include "sigformat.h"
#include "gensig.h"

char format_fn[BUFSIZ] = "";
char sigformat[BUFSIZ] = "";
char sigbuffer[BUFSIZ] = "";
time_t format_last_read = 0;

void read_sigformat()
{
   int rv = 0;
   struct stat statbuf;
   int fd;

   rv = stat(format_fn, &statbuf);

   if ( (rv == 0) && S_ISREG(statbuf.st_mode) )
   {
      if (statbuf.st_size > (BUFSIZ-1))
      {
         fprintf(stderr, "Signature format too large!  (%ld>%d)\n",
		(long)statbuf.st_size, BUFSIZ);
      }
      else
      {

         fd = open(format_fn, O_RDONLY);

         if (rv >= 0)
         {
            rv = read(fd, sigformat, statbuf.st_size);
            close(fd);
            if (rv == statbuf.st_size)
            {
               sigformat[statbuf.st_size] = 0;
               format_last_read = statbuf.st_mtime;
            }
            else
            {
               perror("sigformat read");
            }
         }
         else
         {
            perror("sigformat open");
         }
      }
   }

   if (sigformat[0] == 0)
   {
      strncpy(sigformat, "%s\n", BUFSIZ);
   }

}

void init_sigformat(const char*fn)
{
   if (fn == NULL)
   {
      sprintf(format_fn, "%s/.signature.tmpl", getpwuid(getuid())->pw_dir);
   }
   else
   {
      strncpy(format_fn, fn, BUFSIZ);
   }

   read_sigformat();
}

char *get_sigformat()
{
   struct stat statbuf;
   int rv;

   /* no format file: init */
   if (format_fn[0] == 0) init_sigformat(NULL);

   /* check up to date... */
   rv = stat(format_fn, &statbuf);
   if (rv == 0)
   {
      if (statbuf.st_mtime >= format_last_read)
      {
         read_sigformat();
      }
   }
   else
   {
      read_sigformat();
   }

   return sigformat;
}




syntax highlighted by Code2HTML, v. 0.9.1