/* tnprintf.c */

/* Copyright 1997 by Eberhard Mattes <mattes@azu.informatik.uni-stuttgart.de>
   Donated to the public domain.  No warranty.

   1997-01-04 Initial version
   1997-04-05 Reorganize library
   1997-07-19 Add HAVE_VSNPRINTF, use tn_write() instead of tn_puts()
   1997-07-27 Use DONT_HAVE_VSNPRINTF instead, fix return value check
   1997-08-22 Fix typo */

#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#include "firewall.h"		/* DONT_HAVE_VSNPRINTF */
#include "libemtn.h"


void tn_printf (tnconn *t, const char *fmt, ...)
{
  int n;
  va_list arg_ptr;
  static char buf[8192];

  va_start (arg_ptr, fmt);

#ifndef DONT_HAVE_VSNPRINTF
  n = vsnprintf (buf, sizeof (buf), fmt, arg_ptr);
  if (n < 0)
    return;
  if (n >= sizeof (buf))
    {
      /* vsnprintf() returns the untruncated length. */

      n = sizeof (buf) - 1;

      /* Check for broken implementation of vsnprintf(). (Consider
	 libdb of Linux!)  We assume that our caller didn't print a
	 null character using "%c".  Do not use exit() as it may use
	 memory we have overwritten (function pointers!). */

      if (buf[n] != 0)
	_exit (127);
    }
#else
  n = vsprintf (buf, fmt, arg_ptr);
  if (n < 0)
    return;

  /* Do not use exit() as it may use memory we have overwritten
     (function pointers!). */

  if (n >= sizeof (buf))
    _exit (127);
#endif

  va_end (arg_ptr);
  if (n > 0)
    tn_write (t, buf, n);
}
