
#include <stdlib.h>
#include <sys/param.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/tcp.h>
#include <netinet/tcpip.h>
#include "interface.h"
#include "seq.h"

#define LINE_LEN 256

/* vt100 escapes for boldface */
char csf_bld[] = {27, 91, 49, 58, 109, 0};
char csb_def[] = {27, 91, 52, 59, 109, 0};

void 
print_content(const u_char *start, const u_char *end)
{
  int i = 0;
  u_char *cp = (u_char *)start;

  while(cp++ < end)
    {
      if (i >= LINE_LEN)
	{
	  printf("\n\t");
	  i = 0;
	}
      if (isprint(*cp))
	{
	  if (zflag > 1)
	    printf("%s%c%s", csf_bld, *cp, csb_def);
	  else
	    printf("%c", *cp);
	  i++;
	}
      else if (*cp == 0x0a)
	{
	  printf("<NL>\n\t"); /* explicitly show nl */
	  i = 0;
	}
      else if (*cp == 0x0d)
	{
	  printf("<CR>"); /* explicitly show cr */
	  i += 4;
	}
      else if (*cp == 0x09)
	{
	  printf("<tab>"); /* explicitly show tab */
	  i += 5;
	}
      else
	{
	  printf("[%02x]", *cp);
	  i += 4;
	}
    }
}

void 
http_print(struct tcphdr *tp, int length)	  /* length = TCP payload */

{
  u_char *zp = (u_char *)tp + (tp->th_off * 4) -1;
  u_char *end = snapend -1;
  int truncated = (zp + length) - end;

  char http_delim[] = {0x0d, 0x0a, 0x0d, 0x0a, '\0'};
  u_char *http_end = (u_char *)seqstr_l((char *)zp, http_delim, snapend - zp);

  printf("\n\t");

  if (http_end)
    {
      http_end += 3;		/* print delim seq as part of hdr */
      print_content(zp, http_end); /* HTTP header */
      zp = http_end;
    }
  
  print_content(zp, end); /* HTML content */

  
 
  if (truncated)
    {
      if (truncated < 0)
	{
	  if (truncated != -6) /* min len tcp packet with ether 'padding' */
	    printf("\n\ttruncation error!");
	}
      else
	{
	  printf("\n\t---truncated by %d bytes---", truncated);
	}
    }
}
