/*
 * socktest.c  --  Socket testing program.  Useful for first-cut tests on
 *                 AF_{INET,INET6}.
 *
 *
 * Copyright 1995 by Dan McDonald, Bao Phan, and Randall Atkinson,
 *	All Rights Reserved.  
 *      All Rights under this copyright have been assigned to NRL.
 */

/*----------------------------------------------------------------------
#       @(#)COPYRIGHT   1.1a (NRL) 17 August 1995

COPYRIGHT NOTICE

All of the documentation and software included in this software
distribution from the US Naval Research Laboratory (NRL) are
copyrighted by their respective developers.

This software and documentation were developed at NRL by various
people.  Those developers have each copyrighted the portions that they
developed at NRL and have assigned All Rights for those portions to
NRL.  Outside the USA, NRL also has copyright on the software
developed at NRL. The affected files all contain specific copyright
notices and those notices must be retained in any derived work.

NRL LICENSE

NRL grants permission for redistribution and use in source and binary
forms, with or without modification, of the software and documentation
created at NRL provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software
   must display the following acknowledgement:

        This product includes software developed at the Information
        Technology Division, US Naval Research Laboratory.

4. Neither the name of the NRL nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation
are those of the authors and should not be interpreted as representing
official policies, either expressed or implied, of the US Naval
Research Laboratory (NRL).

----------------------------------------------------------------------*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <sys/uio.h>

#if INET6
#include <netinet6/in6.h>
#endif /* INET6 */

#include <sys/un.h>

#if FASTCTO
#include <signal.h>
#include <setjmp.h>
#endif /* FASTCTO */

#include "support.h"

extern char *optarg;
extern int errno, optind;

struct nrl_nametonum socktypes[] = {
  { SOCK_STREAM, "stream", 0 },
  { SOCK_DGRAM, "dgram", 0 },
  { 0, NULL, 0 }
};

char *portname = NULL;
char *hostname = NULL;

int server = 0, type = SOCK_DGRAM;
int s = 0, s2 = 0, datasize = 0;
int af = 0;
int patternlen = 0;

int nflag = 0;

typedef union {
  struct sockaddr sa;
  struct sockaddr_in sin;
  struct sockaddr_un sun;
#if INET6
  struct sockaddr_in6 sin6;
#endif /* INET6 */
} su;
char addrbuf[sizeof(su)], addrbuf2[sizeof(su)];
int addrlen;

#if INET6 && defined(IPV6_RXINFO)
struct in6_pktinfo in6_pktinfo;
#endif /* INET6 && defined(IPV6_RXINFO) */

char controlbuf[1024];

char *datablock;
int datablocklen = 65535;
char mynamestr[256];
char messagebuf[1024];

char *myname;

char *requeststr = NULL;

#if INET6 && defined(IPV6_ADDRFORM)
int aform = 0;
#endif /* INET6 && defined(IPV6_ADDRFORM) */

#ifdef FASTCTO
static jmp_buf timeout_env;

static void timeout_handler(int i)
{
  longjmp(timeout_env, i);
}
#endif /* FASTCTO */

void say(char *message, ...)
{
  char a2abuf[64];
  va_list ap;

  fputs(mynamestr, stdout);
  va_start(ap, message);
  vprintf(message, ap);
  va_end(ap);
  putchar('\n');
}

#ifdef IPV6_ADDRFORM
void addrform(int form)
{
  int len, old, new;

  len = sizeof(int);
  if (getsockopt(s, IPPROTO_IPV6, IPV6_ADDRFORM, &old, &len) < 0) {
    perror("socktest: getsockopt(IPV6_ADDRFORM...)");
    exit(1);
  }

  len = sizeof(int);
  if (setsockopt(s, IPPROTO_IPV6, IPV6_ADDRFORM, &form, len) < 0) {
    perror("socktest: setsockopt(IPV6_ADDRFORM...)");
    exit(1);
  }

  len = sizeof(int);
  if (getsockopt(s, IPPROTO_IPV6, IPV6_ADDRFORM, &new, &len) < 0) {
    perror("socktest: getsockopt(IPV6_ADDRFORM...)");
    exit(1);
  }

  addrlen = sizeof(addrbuf);
  if (getsockname(s, (struct sockaddr *)addrbuf, &addrlen) < 0) {
    perror("socktest: getsockname");
    exit(1);
  }

  if (new != form) {
    fprintf(stderr, "socktest: address form error: started with %s, requested %s\n", nrl_afnumtoname(old), nrl_afnumtoname(form));
    fprintf(stderr, "socktest: address form error: but ended up with %s!\n", nrl_afnumtoname(new));
  }

  af = form;
}
#endif /* ADDRFORM */

usage(char *myname)
{
  fprintf(stderr, "usage: %s [-t socket_type] [-a address_fam]", myname);
#ifdef ADDRFORM
  fprintf(stderr, " [-f address_form]");
#endif /* ADDRFORM */
#if IPSEC
  fprintf(stderr, " [-S security_request]");
#endif /* IPSEC */
  fprintf(stderr," [-s] [host] [port]\n");
  exit(1);
}

main(argc, argv)
     int argc;
     char *argv[];
{
  int i;
  char *p;
  struct addrinfo req, *ai, *ai2;
  char ch;
  int ahlev = 0, esplev = 0, esptlev = 0;
  char hbuf[32], sbuf[8], dbuf[32], ibuf[16];
  struct msghdr msghdr, msghdr2;
  struct iovec iovec;
 
  if (myname = strrchr(argv[0], '/'))
    *(myname++) = 0;
  else
    myname = argv[0];

  while ((ch = getopt(argc, argv, "S:A:N:T:a:f:t:snp:b:")) != EOF)
    switch(ch) {
    case 'a':
      if ((af = nrl_afnametonum(optarg)) == -1) {
	fprintf(stderr,"socktest: invalid address family: %s\n", optarg);
	exit(1);
      }
      break;
#ifdef ADDRFORM
    case 'f':
      if ((aform = nrl_afnametonum(optarg)) == -1) {
	fprintf(stderr,"socktest: invalid address family: %s\n", optarg);
	exit(1);
      }
      break;
#endif /* ADDRFORM */
#if IPSEC
    case 'S':
      requeststr = optarg;
      break;
#endif /* IPSEC */
    case 's':
      server = 1;
      break;
    case 't':
      if ((type = nrl_nametonum(socktypes, optarg)) == -1) {
	fprintf(stderr, "%s: invalid socket type: %s\n", myname, optarg);
	exit(1);
      }
      break;
    case 'n':
      nflag = 1;
      break;
    case 'b':
      if (!(datablocklen = atoi(optarg))) {
        fprintf(stderr, "%s: %s: invalid buffer size\n", myname, optarg);
        exit(1);
      }
      break;
    case 'p':
      if (!(patternlen = atoi(optarg))) {
        fprintf(stderr, "%s: %s: invalid test pattern start\n", myname, optarg);
        exit(1);
      }
      break;
    default:
      usage(myname);
    }

  if (optind < argc)
    hostname = argv[optind++];

  if (!hostname && !server)
    hostname = "localhost";

  if (optind < argc)
    portname = argv[optind++];

  if (!portname)
    portname = "7777";

#if INET6 && defined(IPV6_TXINFO)
  if (optind < argc)
    if (!(in6_pktinfo.ipi6_ifindex = if_nametoindex(argv[optind]))) {
      fprintf(stderr, "%s: %s: unknown/invalid interface name\n", myname, argv[optind]);
      exit(1);
    };

  optind++;

  if (optind < argc) {
    memset(&req, 0, sizeof(struct addrinfo));
    req.ai_family = AF_INET6;
    if (i = getaddrinfo(argv[optind], NULL, &req, &ai)) {
      fprintf(stderr, "%s: getaddrinfo: %s.%s: %s\n", myname, argv[optind], NULL, nrl_gai_strerror(i));
      exit(1);
    };
    in6_pktinfo.ipi6_addr = ((struct sockaddr_in6 *)(ai->ai_addr))->sin6_addr;
  };
#endif /* INET6 && defined(IPV6_TXINFO) */

  memset(&req, 0, sizeof(struct addrinfo));

  req.ai_family = af;
  req.ai_socktype = type;
  if (server)
    req.ai_flags |= AI_PASSIVE;

  if (i = getaddrinfo(hostname, portname, &req, &ai)) {
    fprintf(stderr, "%s: getaddrinfo: %s.%s: %s\n", myname, hostname, portname, nrl_gai_strerror(i));
    exit(1);
  }

#ifdef FASTCTO
  signal(SIGALRM, &timeout_handler);
#endif /* FASTCTO */

  for (ai2 = ai, s = -1; ai; ai = ai->ai_next) {
    if (nrl_getnameinfo(ai->ai_addr, ai->ai_addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), 0)) {
      printf("%s: getnameinfo() failed!\n", myname);
      continue;
    }

    printf("Trying %s.%s...\n", hbuf, sbuf);
    
    if ((s = socket(af = ai->ai_family, ai->ai_socktype, ai->ai_protocol)) < 0) {
      perror("socket");
      continue;
    }

#if IPSEC
    if (requeststr) {
      void *request, *request2;
      int requestlen, requestlen2;

      if (nrl_strtoreq(requeststr, &request, &requestlen)) {
	fprintf(stderr, "nrl_strtoreq() failed!\n");
	exit(1);
      };
      
      if (setsockopt(s, SOL_SOCKET, SO_SECURITY_REQUEST, request, requestlen) < 0) {
	fprintf(stderr, "%s: setsockopt(..., SO_SECURITY_REQUEST, ...): %s(%d)", myname, strerror(errno), errno);
	exit(1);
      };

      if (!(request2 = malloc(requestlen2 = requestlen))) {
	fprintf(stderr, "%s: malloc(%d): %s(%d)", myname, requestlen, strerror(errno), errno);
	exit(1);
      };

      if (getsockopt(s, SOL_SOCKET, SO_SECURITY_REQUEST, request2, &requestlen2) < 0) {
	fprintf(stderr, "%s: getsockopt(..., SO_SECURITY_REQUEST, ...): %s(%d)", myname, strerror(errno), errno);
	exit(1);
      };

      if ((requestlen != requestlen2) || memcmp(request, request2, requestlen)) {
        fprintf(stderr, "%s: kernel changed request!\n", myname);
        exit(1);
      };

      {
        char buffer[8];

        if (nrl_reqtostr(request, requestlen, buffer, sizeof(buffer))) {
          fprintf(stderr, "%s: nrl_reqtostr failed\n", myname);
          exit(1);
        };

        printf("%s: made security request of '%s'\n", myname, buffer);
      };

      free(request2);
      free(request);
    };
#endif /* IPSEC */

    if (ai->ai_flags & AI_PASSIVE) {
      if (bind(s, ai->ai_addr, ai->ai_addrlen) < 0) {
	perror("bind");
	close(s);
	s = -1;
	continue;
      }

      if ((listen(s, 1) < 0) && (errno != EOPNOTSUPP)) {
	perror("listen");
	close(s);
	s = -1;
	continue;
      }
    } else {
#if FASTCTO
      if (setjmp(timeout_env)) {
	fprintf(stderr, "%s: Connection timed out\n", myname);
	continue;
      }
      
      alarm(FASTCTO);
#endif /* FASTCTO */
      
      if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0) {
#ifdef FASTCTO
	alarm(0);
#endif /* FASTCTO */
	perror("connect");
	close(s);
	s = -1;
	continue;
      }
#ifdef FASTCTO
      alarm(0);
#endif /* FASTCTO */
    }
    break;
  }
  if (s < 0)
    exit(1);

  if (ai->ai_protocol == IPPROTO_TCP) {
    int val = 1;
    if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) < 0) {
      perror("setsockopt (TCP_NODELAY)");
      exit(1);
    }
  }

  af = ai->ai_family;

#if INET6 && defined(IPV6_ADDRFORM)
  if (aform && (aform != af))
    addrform(aform);
#endif /* INET6 && defined(IPV6_ADDRFORM) */

#if INET6 && defined(IPV6_RXINFO)
  if (af == AF_INET6) {
    int val = 1;
    if (setsockopt(s, IPPROTO_IPV6, IPV6_RXINFO, &val, sizeof(val)) < 0) {
      perror("setsockopt (IPV6_RXINFO)");
      exit(1);
    }
  };
#endif /* INET6 && defined(IPV6_RXINFO) */

  if (nrl_getnameinfo(ai->ai_addr, ai->ai_addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), nflag)) {
    fprintf(stderr, "getnameinfo() failed!\n");
    exit(1);
  }

  freeaddrinfo(ai2);
  
  sprintf(mynamestr, "%s [%s.%s]:\n\t", server ? "Server" : "Client", hbuf, sbuf);

  if (patternlen > datablocklen) {
    fprintf(stderr, "%s: invalid pattern length\n", myname);
    exit(1);
  };

  if (!(datablock = malloc(datablocklen + 1))) {
    fprintf(stderr, "%s: can't allocate %d bytes buffer space\n", myname, datablocklen);
    exit(1);
  };

  memset(&msghdr, 0, sizeof(struct msghdr));
  msghdr.msg_iov = &iovec;
  msghdr.msg_iovlen = 1;
  msghdr.msg_flags = 0;

  iovec.iov_base = datablock;
  iovec.iov_len = datablocklen - 1;

  say("Ready");

  if (server)
    goto servercode;

  if (ai->ai_family == AF_INET6) {
    msghdr.msg_control = controlbuf;
    msghdr.msg_controllen = sizeof(struct cmsghdr) + sizeof(struct in6_pktinfo);

    ((struct cmsghdr *)controlbuf)->cmsg_len = sizeof(struct cmsghdr) + sizeof(struct in6_pktinfo);
    ((struct cmsghdr *)controlbuf)->cmsg_level = IPPROTO_IPV6;
    ((struct cmsghdr *)controlbuf)->cmsg_type = IPV6_RXINFO;

    memcpy(controlbuf + sizeof(struct cmsghdr), &in6_pktinfo, sizeof(struct in6_pktinfo));
  } else {
    msghdr.msg_control = NULL;
    msghdr.msg_controllen = 0;
  };

  if (patternlen)
    goto patterncode;

  while(!feof(stdin)) {
    printf("send: ");
    fgets(datablock, datablocklen, stdin);
    if (p = strchr(datablock, '\n'))
      *p = 0;

    iovec.iov_len = strlen(datablock);
    if (sendmsg(s, &msghdr, 0) < 0) {
      perror("sendmsg"); 
      exit(1);
    };

    say("Sent '%s'", datablock);

    fflush(stdout);

    memcpy(&msghdr2, &msghdr, sizeof(struct msghdr));
    msghdr2.msg_controllen = sizeof(controlbuf);

    if ((datasize = recvmsg(s, &msghdr2, 0)) < 0) {
      perror("recvmsg");
      exit(1);
    };

    datablock[datasize] = 0;
    say("Got  '%s'", datablock);

    fflush(stdout);
  }
  exit(0);

patterncode:
  while(patternlen <= datablocklen) {
    for (i = 0; i < patternlen; i++)
      datablock[i] = '0' + (i % 10);

    if ((write(s, datablock, patternlen)) < 0) { 
      perror("write");
      exit(1);
    };

    say("Sent %5d bytes", patternlen);

    if ((datasize = read(s, datablock, datablocklen)) < 0) {
      perror("read");
      exit(1);
    };

    say("Got  %5d bytes", datasize);

    i = 0;

    if (datasize != patternlen) {
      fprintf(stderr, "%s: Length mismatch (%d != %d)\n", myname, patternlen, datasize);
      i = patternlen;
    }

    while(i < patternlen) {
      if (datablock[i] != '0' + (i % 10)) {
        fprintf(stderr, "%s: Data mismatch at byte %d\n", myname, i);
        i = patternlen;
      }
      i++;
    }

    patternlen++;
  }
  exit(0);

servercode:
  s2 = -1;
  dbuf[0] = ibuf[0] = 0;
  msghdr.msg_name = addrbuf;
  msghdr.msg_namelen = sizeof(addrbuf);
  msghdr.msg_control = controlbuf;
  msghdr.msg_controllen = sizeof(controlbuf);

  while(1) {
    if (!datasize) {
      if (s2 >= 0) {
	say("Closing connection to %s.%s", hbuf, sbuf);
	close(s2);
      }

      addrlen = sizeof(addrbuf);
      if ((s2 = accept(s, (struct sockaddr *)addrbuf, &addrlen)) >= 0) {
	if (nrl_getnameinfo((struct sockaddr *)addrbuf, addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), nflag)) {
	  fprintf(stderr, "getnameinfo() failed!\n");
	  exit(1);
	}

	say("Accepted connection from %s.%s", hbuf, sbuf);

	memcpy(addrbuf2, addrbuf, sizeof(addrbuf));
      } else {
	if ((errno == EOPNOTSUPP) || (errno == EINVAL)) {
	  s2 = s;
        } else {
	  perror("accept");
	  exit(1);
	}
      }
    }

    msghdr2 = msghdr;
    iovec.iov_len = datablocklen - 1;

    if ((datasize = recvmsg(s2, &msghdr2, 0)) < 0) {
      perror("recvmsg");
      exit(1);
    }

    if (datasize && memcmp(addrbuf, addrbuf2, sizeof(addrbuf))) {
      memcpy(addrbuf2, addrbuf, sizeof(addrbuf));

      if (nrl_getnameinfo((struct sockaddr *)addrbuf, msghdr2.msg_namelen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), nflag)) {
	fprintf(stderr, "getnameinfo() failed!\n");
	exit(1);
      };
    };

#if INET6 && defined(IPV6_RXINFO)
    {
      struct cmsghdr *cmsghdr;
      for (cmsghdr = CMSG_FIRSTHDR(&msghdr2); cmsghdr; cmsghdr = CMSG_NXTHDR(&msghdr2, cmsghdr))
	if ((cmsghdr->cmsg_level == IPPROTO_IPV6) && (cmsghdr->cmsg_type == IPV6_RXINFO))
	  if (memcmp(CMSG_DATA(cmsghdr), &in6_pktinfo, sizeof(struct in6_pktinfo))) {
	    struct sockaddr_in6 sin6;
	    memcpy(&in6_pktinfo, CMSG_DATA(cmsghdr), sizeof(struct in6_pktinfo));
	    if (!if_indextoname(in6_pktinfo.ipi6_ifindex = ((struct in6_pktinfo *)CMSG_DATA(cmsghdr))->ipi6_ifindex, ibuf)) {
	      fprintf(stderr, "%s: can't convert interface index %d to name\n", in6_pktinfo.ipi6_ifindex);
	      exit(1);
	    };
	    memset(&sin6, 0, sizeof(struct sockaddr_in6));
#if SALEN
            sin6.sin6_len = sizeof(struct sockaddr_in6);
#endif /* SALEN */
            sin6.sin6_family = AF_INET6;
	    sin6.sin6_addr = in6_pktinfo.ipi6_addr;
	    if (nrl_getnameinfo((struct sockaddr *)&sin6, sizeof(struct sockaddr_in6), dbuf, sizeof(dbuf), NULL, 0, nflag)) {
	      fprintf(stderr, "getnameinfo() failed!\n");
	      exit(1);
	    };
	  };
    };
#endif /* INET6 && defined(IPV6_RXINFO) */

    if (datasize) {
      datablock[datasize] = 0;

      strcpy(messagebuf, "Got  ");
      if (patternlen)
	sprintf(messagebuf + strlen(messagebuf), "%5d bytes", datasize);
      else
	sprintf(messagebuf + strlen(messagebuf), "'%s'", datablock);

      sprintf(messagebuf + strlen(messagebuf), " from %s.%s", hbuf, sbuf);

      if (dbuf[0])
	sprintf(messagebuf + strlen(messagebuf), " to %s", dbuf);

      if (ibuf[0])
	sprintf(messagebuf + strlen(messagebuf), " via %s", ibuf);

      say(messagebuf);
      fflush(stdout);
      iovec.iov_len = datasize;
      if (!msghdr2.msg_controllen)
	msghdr2.msg_control = NULL;
      if (sendmsg(s2, &msghdr2, 0) < 0) {
	perror("sendmsg"); 
	exit(1);
      }
    }
  }
}
