/**************************************************************************** 
** File: udp.c
**
** Author: Mike Borella
**
** Comments: Dump UDP header information
**
*****************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "config.h"
#include "udp.h"

extern u_char *packet_end;
extern struct arg_t *my_args;

/*----------------------------------------------------------------------------
**
** dump_udp()
**
** Parse UDP header and dump fields
**
**----------------------------------------------------------------------------
*/

void dump_udp(u_char *bp, int length)
{
  UDPHdr *up;
  u_char *ep = bp + length;
  u_short sport, dport, len;
  struct servent *se;
  char *udpport_string(u_short);
  void syserr(char *, ...);
  void dump_payload(u_char *, int);
  void dump_dns(u_char *, int);
  void dump_l2tp(u_char *, int);
  void dump_dhcp(u_char *, int);
  
  /*
   * Make sure we don't run off the end of the packet
   */

  if (ep > packet_end) ep = packet_end;

  /*
   * Check for truncated packet
   */

  if (length < sizeof(UDPHdr))
    {
      printf("Truncated header, length = %d bytes\n", length);
      return;
    }

  up = (UDPHdr *) bp;
  sport = ntohs(up->uh_src);
  dport = ntohs(up->uh_dst);
  len = ntohs(up->uh_len);

  /*
   * Dump UDP header info
   */
  
  printf("-----------------------------------------------------------------\n");
  printf("                        UDP Header\n");
  printf("-----------------------------------------------------------------\n");

  if (!my_args->t)
    {  
      printf("Source port:            %d", sport);
      if (sport < 1024) 
	printf(" (%s)\n", udpport_string(sport));
      else 
	printf("\n");
      
      printf("Destination port:       %d", dport);
      if (dport < 1024) 
	printf(" (%s)\n", udpport_string(dport));
      else 
	printf("\n");
      
      printf("Length:                 %d\n", len);
      printf("Checksum:               %d\n", ntohs(up->uh_chk));
    }


  /*
   * Take care of DNS packets
   */

  se = getservbyname("domain", "udp");
  if (se == NULL) 
    syserr("can't get services entries");
  if (sport == ntohs(se->s_port) || dport == ntohs(se->s_port))
    dump_dns((u_char *) bp + sizeof(UDPHdr), len);

  /*
   * Take care of L2TP packets
   */

  if (sport == L2TP_PORT || dport == L2TP_PORT)
    dump_l2tp((u_char *) bp + sizeof(UDPHdr), len);

  /*
   * Take care of DHCP packets
   */

  if (sport == DHCP_CLIENT_PORT || dport == DHCP_CLIENT_PORT)
    dump_dhcp((u_char *) bp + sizeof(UDPHdr), len);


  /*
   * print payload if there is one
   */

  if (my_args->p && len > 0) 
    dump_payload((u_char *) bp + sizeof(UDPHdr), len);

  return;
}
