/*  Copyright (C) 2013-2026  P.D. Buchan (pdbuchan@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

// Send an IPv6 TCP packet via raw socket at the link layer (Ethernet frame).
// with a large payload requiring fragmentation. Include a hop-by-hop options
// extension header with a router alert option. Include an encapsulating security
// payload (ESP) extension header (with some random bogus integrity check value (ICV)).
// See Section 3.2 of RFC 2406 for information on properly calculating ICV.
// The ESP header is used here in tunnel mode.
// Need to have destination MAC address.

#define _GNU_SOURCE           // Sometimes required for GNU/Linux-specific interfaces. e.g., SO_BINDTODEVICE
#define __FAVOR_BSD           // Use BSD-style networking structures. e.g., struct tcphdr
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>           // close()
#include <string.h>           // memset(), memcpy()
#include <stdint.h>           // uint8_t, uint16_t, uint32_t

#include <netdb.h>            // struct addrinfo
#include <sys/socket.h>       // socket()
#include <netinet/in.h>       // IPPROTO_RAW, IPPROTO_HOPOPTS, IPPROTO_ESP, IPPROTO_TCP, IPPROTO_FRAGMENT, INET6_ADDRSTRLEN
#include <netinet/ip.h>       // IP_MAXPACKET (which is 65535)
#include <netinet/ip6.h>      // struct ip6_hdr
#include <netinet/tcp.h>      // struct tcphdr
#include <arpa/inet.h>        // inet_pton(), inet_ntop()
#include <sys/ioctl.h>        // macro ioctl is defined
#include <net/if.h>           // struct ifreq
#include <linux/if_ether.h>   // ETH_HLEN, ETH_P_IPV6
#include <linux/if_packet.h>  // struct sockaddr_ll (see man 7 packet)
#include <time.h>             // time()

#include <errno.h>            // errno

// Define a struct for hop-by-hop header, excluding options.
typedef struct {
  uint8_t nxt_hdr;
  uint8_t hdr_len;
} HOP_HDR;

// Define a struct for head of ESP header, excluding payload and authentication data.
typedef struct {
  uint32_t spi;
  uint32_t seq;
} ESP_HDR;

// Define a struct for tail of ESP header, excluding payload and authentication data.
typedef struct {
  uint8_t pad_len;
  uint8_t nxt_hdr;
} ESP_TAIL;

// Define some constants.
#define ETH_HDRLEN ETH_HLEN   // Ethernet header length
#define MAC_LEN 6             // Length of a hardware (MAC) address
#define IP6_HDRLEN 40         // IPv6 header length
#define HOP_HDRLEN 2          // Hop-by-hop header length, excluding options
#define TCP_HDRLEN 20         // TCP header length, excludes options data
#define FRG_HDRLEN 8          // IPv6 fragment header
#define MAX_FRAGS 3119        // Maximum number of packet fragments
#define MAX_HBHOPTIONS 10     // Maximum number of extension header options
#define MAX_HBHOPTLEN 256     // Maximum length of a hop-by-hop option (some large value)
#define ESP_HDRLEN 8          // Encapsulating security payload (ESP) header, excluding payload data, padding, ESP trailer, and authentication data
#define ESP_TAILLEN 2         // Encapsulating security payload (ESP) tail, excluding ESP header (above), payload data, padding, and auth. data
#define HOSTNAME_LEN 255      // Maximum FQDN length including terminating null byte

// Function prototypes
uint16_t checksum (uint8_t *, int);
uint16_t tcp6_checksum (struct ip6_hdr, struct tcphdr, uint8_t *, int, uint8_t *, int);
int option_pad (int *, uint8_t *, int *, int, int);
char *allocate_strmem (int);
uint8_t *allocate_ustrmem (int);
uint8_t **allocate_ustrmemp (int);
int *allocate_intmem (int);

int
main (void) {

  int i, j, n, indx, status, frame_length, sd;
  int hoplen, mtu, frag_flags[2] = {0}, tcp_flags[8] = {0}, c, nframes, offset[MAX_FRAGS] = {0}, len[MAX_FRAGS] = {0}, esp_padlen;
  ssize_t bytes;
  HOP_HDR hophdr;
  ESP_HDR esphdr;
  ESP_TAIL esptail;
  int hbh_optpadlen;
  char *interface, *target, *src_ip, *dst_ip;
  struct ip6_hdr iphdr, newiphdr;
  struct tcphdr tcphdr;
  struct ip6_frag fraghdr;
  int tcp_datalen, fragbufferlen;
  uint8_t *tcp_data, *fragbuffer, src_mac[MAC_LEN] = {0}, *ether_frame;
  uint32_t seq;
  struct addrinfo hints, *res;
  struct sockaddr_in6 dst;
  struct sockaddr_ll device;
  struct ifreq ifr;
  FILE *fi;

  memset (&iphdr, 0, sizeof (iphdr));
  memset (&newiphdr, 0, sizeof (newiphdr));
  memset (&tcphdr, 0, sizeof (tcphdr));
  memset (&fraghdr, 0, sizeof (fraghdr));
  memset (&hophdr, 0, sizeof (hophdr));
  memset (&esphdr, 0, sizeof (esphdr));
  memset (&esptail, 0, sizeof (esptail));

  int hbh_nopt;  // Number of hop-by-hop options
  int hbh_opt_totlen;  // Total length of hop-by-hop options
  int *hbh_optlen;  // Hop-by-hop option length: hbh_optlen[option #] = int
  uint8_t **hbh_options;  // Hop-by-hop options data: hbh_options[option #] = uint8_t *
  int *hbh_x, *hbh_y;  // Alignment requirements for hop-by-hop options: hbh_x[option #] = int, hbh_y[option #] = int

  uint8_t *auth_data;  // Authentication data (integrity check value (ICV)): auth_data = uint8_t *
  int auth_len;  // Authentication header data length
  uint8_t *esp_payload;  // Encapsulating security payload (ESP) data: esp_payload = uint8_t *
  int esp_paylen;  // Encapsulating security payload (ESP) data length

  // Allocate memory for various arrays.
  hbh_optlen = allocate_intmem (MAX_HBHOPTIONS);  // hbh_optlen[option #] = int
  hbh_options = allocate_ustrmemp (MAX_HBHOPTIONS);  // hbh_options[option #] = uint8_t *
  for (i = 0; i < MAX_HBHOPTIONS; i++) {
    hbh_options[i] = allocate_ustrmem (MAX_HBHOPTLEN);
  }
  hbh_x = allocate_intmem (MAX_HBHOPTIONS);  // Hop-by-hop option alignment requirement x (of xN + y): hbh_x[option #] = int
  hbh_y = allocate_intmem (MAX_HBHOPTIONS);  // Hop-by-hop option alignment requirement y (of xN + y): hbh_y[option #] = int
  auth_data = allocate_ustrmem (0xff * 0xffff);  // auth_data = uint8_t *
  ether_frame = allocate_ustrmem (ETH_HDRLEN + IP_MAXPACKET);
  interface = allocate_strmem (sizeof (ifr.ifr_name));
  target = allocate_strmem (HOSTNAME_LEN);
  src_ip = allocate_strmem (INET6_ADDRSTRLEN);
  dst_ip = allocate_strmem (INET6_ADDRSTRLEN);
  tcp_data = allocate_ustrmem (IP_MAXPACKET);

  // Random number seed
  srand ((unsigned) time (NULL));

  // Interface to send packet through.
  snprintf (interface, sizeof (ifr.ifr_name), "enp7s0");

  // Submit request for a socket descriptor to look up interface.
  if ((sd = socket (AF_INET6, SOCK_DGRAM, 0)) < 0) {
    status = errno;
    fprintf (stderr, "socket() failed to get socket descriptor for using ioctl().\nError message: %s\n", strerror (status));
    exit (EXIT_FAILURE);
  }

  // Use ioctl() to get interface maximum transmission unit (MTU).
  memset (&ifr, 0, sizeof (ifr));
  n = snprintf (ifr.ifr_name, sizeof (ifr.ifr_name), "%s", interface);
  if ((n < 0) || (n >= (int) sizeof (ifr.ifr_name))) {
    fprintf (stderr, "Invalid interface name: %s\n", interface);
    exit (EXIT_FAILURE);
  }
  if (ioctl (sd, SIOCGIFMTU, &ifr) < 0) {
    fprintf (stderr, "ioctl(SIOCGIFMTU) failed to get interface MTU.\nError message: %s\n", strerror (errno));
    close (sd);
    exit (EXIT_FAILURE);
  }
  mtu = ifr.ifr_mtu;
  fprintf (stdout, "Current MTU of interface %s is: %d\n", interface, mtu);

  // Use ioctl() to look up interface name and get its MAC address.
  if (ioctl (sd, SIOCGIFHWADDR, &ifr) < 0) {
    fprintf (stderr, "ioctl(SIOCGIFHWADDR) failed to get source MAC address.\nError message: %s\n", strerror (errno));
    close (sd);
    exit (EXIT_FAILURE);
  }
  close (sd);

  // Copy source MAC address.
  memcpy (src_mac, ifr.ifr_hwaddr.sa_data, sizeof (src_mac));

  // Report source MAC address to stdout.
  fprintf (stdout, "MAC address for interface %s is ", interface);
  for (i = 0; i < (int) sizeof (src_mac); i++) {
    fprintf (stdout, "%02x%s", src_mac[i], (i < (int) sizeof (src_mac) - 1) ? ":" : "\n");
  }

  // Destination Ethernet MAC address: You need to fill these out.
  // For off-link destinations, this is normally the next-hop router's MAC address.
  uint8_t dst_mac[MAC_LEN] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01};

  // Source IPv6 address: You need to fill this out.
  snprintf (src_ip, INET6_ADDRSTRLEN, "2001:db8::214:51ff:fe2f:1556");

  // Destination hostname or IPv6 address: You need to fill this out.
  snprintf (target, HOSTNAME_LEN, "ipv6.google.com");

  // Number of hop-by-hop extension header options.
  hbh_nopt = 1;

  // Hop-by-hop option: router alert (with bogus value)
  // Alignment requirement is 2n+0 for router alert. See Section 2.1 of RFC 2711.
  hbh_x[0] = 2;
  hbh_y[0] = 0;
  // hbh_options[option #] = uint8_t *
  hbh_options[0][0] = 5;  // Option Type: router alert
  hbh_options[0][1] = 2;  // Length of Option Data field
  hbh_options[0][2] = 0;  // Option Data: some unassigned IANA value, you
  hbh_options[0][3] = 5;  // should select what you want.
  // Hop-by-hop option length.
  hbh_optlen[0] = 4;  // Hop-by-hop header option length (excludes hop-by-hop header itself (2 bytes))

  // Calculate total length of hop-by-hop options.
  hbh_opt_totlen = 0;
  for (i = 0; i < hbh_nopt; i++) {
    hbh_opt_totlen += hbh_optlen[i];
  }

  // Determine total padding needed to align and pad hop-by-hop options (Section 4.2 of RFC 2460).
  indx = 0;
  if (hbh_nopt > 0) {
    indx += HOP_HDRLEN; // Account for hop-by-hop header (Next Header and Header Length)
    for (i = 0; i < hbh_nopt; i++) {
      // Add any necessary alignment for option i
      while ((indx % hbh_x[i]) != hbh_y[i]) {
        indx++;
      }
      // Add length of option i
      indx += hbh_optlen[i];
    }
    // Now pad last option to next 8-byte boundary (Section 4.2 of RFC 2460).
    while ((indx % 8) != 0) {
      indx++;
    }

    // Total of alignments and final padding = indx - HOP_HDRLEN - total length of hop-by-hop (non-pad) options
    hbh_optpadlen = indx - HOP_HDRLEN - hbh_opt_totlen;

    // Determine length of hop-by-hop header in units of 8 bytes, excluding first 8 bytes.
    // Section 4.3 of RFC 2460.
    i = (indx - 8) / 8;
    if (i < 0) {
      i = 0;
    }
    hophdr.hdr_len = i;
  } else {
    hbh_opt_totlen = 0;
    hbh_optpadlen = 0;
  }

  // Print some information about hop-by-hop options.
  fprintf (stdout, "Number of hop-by-hop options: %d\n", hbh_nopt);
  fprintf (stdout, "Total length of hop-by-hop options, excluding 2-byte hop-by-hop header and padding: %d\n", hbh_opt_totlen);
  fprintf (stdout, "Total length of hop-by-hop alignment padding and end-padding: %d\n", hbh_optpadlen);

  // Encapsulating security payload (ESP) header
  esphdr.spi = htonl (31415);  // Security parameters index (SPI)
  esphdr.seq = htonl (51413);  // Sequence number

  // Authentication data (integrity check value (ICV))
  auth_data[0] = 34;  // Made-up numbers used here. You need to compute as per Section 3 of RFC 2406.
  auth_data[1] = 2;
  auth_data[2] = 0;
  auth_data[3] = 16;
  auth_data[4] = 66;
  auth_data[5] = 99;
  auth_data[6] = 11;
  auth_data[7] = 2;
  auth_data[8] = 31;
  auth_data[9] = 0;
  auth_data[10] = 8;
  auth_data[11] = 23;

  // Length of authentication data (ICV) above.
  auth_len = 12;

  // Print some information about authentication data.
  fprintf (stdout, "Length of authentication data (integrity check value (ICV)): %d\n", auth_len);

  // Fill out hints for getaddrinfo().
  memset (&hints, 0, sizeof (hints));
  hints.ai_family = AF_INET6;
  hints.ai_socktype = 0;  // Address resolution only; any socket type.
  hints.ai_flags = hints.ai_flags | AI_CANONNAME;

  // Resolve target using getaddrinfo().
  if ((status = getaddrinfo (target, NULL, &hints, &res)) != 0) {
    fprintf (stderr, "getaddrinfo() failed for target.\nError message: %s\n", gai_strerror (status));
    exit (EXIT_FAILURE);
  }
  memset (&dst, 0, sizeof (dst));
  memcpy (&dst, res->ai_addr, res->ai_addrlen);
  if (inet_ntop (AF_INET6, &dst.sin6_addr, dst_ip, INET6_ADDRSTRLEN) == NULL) {
    status = errno;
    fprintf (stderr, "inet_ntop() failed for target.\nError message: %s\n", strerror (status));
    exit (EXIT_FAILURE);
  }
  freeaddrinfo (res);

  // Fill out device's sockaddr_ll struct.
  memset (&device, 0, sizeof (device));
  device.sll_family = AF_PACKET;
  device.sll_protocol = htons (ETH_P_IPV6);
  if ((device.sll_ifindex = if_nametoindex (interface)) == 0) {
    status = errno;
    fprintf (stderr, "if_nametoindex(\"%s\") failed to obtain interface index.\nError message: %s\n", interface, strerror (status));
    exit (EXIT_FAILURE);
  }
  fprintf (stdout, "Index for interface %s is %d\n", interface, device.sll_ifindex);
  memcpy (device.sll_addr, dst_mac, sizeof (dst_mac));
  device.sll_halen = sizeof (dst_mac);

  // Get TCP data.
  i = 0;
  fi = fopen ("data", "r");
  if (fi == NULL) {
    fprintf (stderr, "Can't open file 'data'.\n");
    exit (EXIT_FAILURE);
  }
  while ((n = fgetc (fi)) != EOF) {
    if (i >= (IP_MAXPACKET - IP6_HDRLEN - TCP_HDRLEN)) {
      fprintf (stderr, "Payload too large.\n");
      exit (EXIT_FAILURE);
    }
    tcp_data[i] = n;
    i++;
  }
  fclose (fi);
  tcp_datalen = i;
  fprintf (stdout, "Upper layer protocol header length (bytes): %d\n", TCP_HDRLEN);
  fprintf (stdout, "Payload length (bytes): %d\n", tcp_datalen);

  // Length of hop-by-hop header, options, and padding.
  if (hbh_nopt > 0) {
    hoplen = HOP_HDRLEN + hbh_opt_totlen + hbh_optpadlen;
  } else {
    hoplen = 0;
  }

  // The ESP header Pad Length and Next Header must be right-aligned to nearest 4-byte block.
  // See Section 2.4 of RFC 2406. Padding values added to esp_payload later.
  esp_paylen = IP6_HDRLEN + hoplen + TCP_HDRLEN + tcp_datalen;
  esp_padlen = 0;
  while (((esp_paylen + ESP_TAILLEN) % 4) != 0) {
    esp_paylen++;
    esp_padlen++;
  }

  // Allocate memory for encapsulating security payload (ESP) payload data.
  // esp_payload = uint8_t *
  esp_payload = allocate_ustrmem (esp_paylen);

  // Length of fragmentable portion of packet.
  fragbufferlen = ESP_HDRLEN + esp_paylen + ESP_TAILLEN + auth_len;
  fprintf (stdout, "Total fragmentable data (bytes): %d\n", fragbufferlen);

  // Allocate memory for the fragmentable portion.
  fragbuffer = allocate_ustrmem (fragbufferlen);

  // Determine how many Ethernet frames we'll need.
  memset (len, 0, MAX_FRAGS * sizeof (int));
  memset (offset, 0, MAX_FRAGS * sizeof (int));
  i = 0;
  c = 0;  // Variable c is index to buffer, which contains upper layer protocol header and data.
  while (c < fragbufferlen) {

    // Do we still need to fragment remainder of fragmentable portion?
    if ((fragbufferlen - c) > (mtu - IP6_HDRLEN - FRG_HDRLEN)) {  // Yes
      len[i] = mtu - IP6_HDRLEN - FRG_HDRLEN;  // len[i] is amount of fragmentable part we can include in this frame.

    } else {  // No
      len[i] = fragbufferlen - c;  // len[i] is amount of fragmentable part we can include in this frame.
    }
    c += len[i];

    // If not last fragment, make sure we have an even number of 8-byte blocks.
    // Reduce length as necessary.
    if (c < fragbufferlen) {
      while ((len[i] % 8) > 0) {
        len[i]--;
        c--;
      }
    }
    fprintf (stdout, "Frag: %d,  Data (bytes): %d,  Data Offset (8-byte blocks): %d\n", i, len[i], offset[i]);
    i++;
    if (i >= MAX_FRAGS) {
     fprintf (stderr, "Too many fragments.\n");
       exit (EXIT_FAILURE);
    }
    offset[i] = (len[i - 1] / 8) + offset[i - 1];
  }
  nframes = i;
  fprintf (stdout, "Total number of frames to send: %d\n", nframes);

  // IPv6 header

  // IPv6 version (4 bits), Traffic class (8 bits), Flow label (20 bits)
  iphdr.ip6_flow = htonl ((6 << 28) | (0 << 20) | 0);

  // Payload length (16 bits)
  // iphdr.ip6_plen is set for each fragment in loop below.

  // Next header (8 bits): 6 for TCP
  // We'll change this later, otherwise TCP checksum will be wrong.
  iphdr.ip6_nxt = IPPROTO_TCP;

  // Hop limit (8 bits): Default to maximum value.
  iphdr.ip6_hops = 255;

  // Source IPv6 address (128 bits)
  if ((status = inet_pton (AF_INET6, src_ip, &(iphdr.ip6_src))) != 1) {
    if (status == 0) {
      fprintf (stderr, "inet_pton() failed for source address.\nError message: Invalid address\n");
    } else if (status < 0) {
      fprintf (stderr, "inet_pton() failed for source address.\nError message: %s\n", strerror (errno));
    }
    exit (EXIT_FAILURE);
  }

  // Destination IPv6 address (128 bits)
  if ((status = inet_pton (AF_INET6, dst_ip, &(iphdr.ip6_dst))) != 1) {
    if (status == 0) {
      fprintf (stderr, "inet_pton() failed for destination address.\nError message: Invalid address\n");
    } else if (status < 0) {
      fprintf (stderr, "inet_pton() failed for destination address.\nError message: %s\n", strerror (errno));
    }
    exit (EXIT_FAILURE);
  }

  // TCP header

  // Source port number (16 bits)
  // Some random, high ephemeral port number; Some firewalls dislike packets claiming to originate from Port 80.
  tcphdr.th_sport = htons (49152 + (rand () % 16384));

  // Destination port number (16 bits)
  tcphdr.th_dport = htons (80);

  // Sequence number (32 bits): Random initial sequence number (ISN).
  seq = ((uint32_t) rand () << 16) | ((uint32_t) rand () & 0xffff);
  tcphdr.th_seq = htonl (seq);

  // Acknowledgement number (32 bits): Not used in an initial SYN.
  tcphdr.th_ack = htonl (0);

  // Reserved (4 bits): Should be 0.
  tcphdr.th_x2 = 0;

  // Data offset (4 bits): Size of TCP header in 32-bit words.
  tcphdr.th_off = TCP_HDRLEN / 4;

  // Flags (8 bits)

  // FIN flag (1 bit)
  tcp_flags[0] = 0;

  // SYN flag (1 bit): Set to 1.
  tcp_flags[1] = 1;

  // RST flag (1 bit)
  tcp_flags[2] = 0;

  // PSH flag (1 bit)
  tcp_flags[3] = 0;

  // ACK flag (1 bit)
  tcp_flags[4] = 0;

  // URG flag (1 bit)
  tcp_flags[5] = 0;

  // ECE flag (1 bit)
  tcp_flags[6] = 0;

  // CWR flag (1 bit)
  tcp_flags[7] = 0;

  tcphdr.th_flags = 0;
  for (i = 0; i < 8; i++) {
    tcphdr.th_flags += (tcp_flags[i] << i);
  }

  // Window size (16 bits)
  tcphdr.th_win = htons (65535);

  // Urgent pointer (16 bits): 0 (only valid if URG flag is set)
  tcphdr.th_urp = htons (0);

  // TCP checksum (16 bits): Set to 0 for checksum calculation.
  tcphdr.th_sum = 0;
  tcphdr.th_sum = tcp6_checksum (iphdr, tcphdr, NULL, 0, tcp_data, tcp_datalen);

  // Next header (8 bits): 0 for hop-by-hop extension header
  iphdr.ip6_nxt = IPPROTO_HOPOPTS;

  // New IPv6 header

  // IPv6 version (4 bits), Traffic class (8 bits), Flow label (20 bits)
  newiphdr.ip6_flow = htonl ((6 << 28) | (0 << 20) | 0);

  // Payload length (16 bits)
  // newiphdr.ip6_plen is set for each fragment in loop below.

  // Next header (8 bits)
  if (nframes == 1)  {
    newiphdr.ip6_nxt = IPPROTO_ESP;  // 50 for encapsulating security payload (ESP) extension header
  } else {
    newiphdr.ip6_nxt = IPPROTO_FRAGMENT;  // 44 for Fragmentation extension header
  }

  // Hop limit (8 bits): Default to maximum value.
  newiphdr.ip6_hops = 255;

  // Source IPv6 address (128 bits)
  if ((status = inet_pton (AF_INET6, src_ip, &(newiphdr.ip6_src))) != 1) {
    if (status == 0) {
      fprintf (stderr, "inet_pton() failed for source address for new IPv6 header.\nError message: Invalid address\n");
    } else if (status < 0) {
      fprintf (stderr, "inet_pton() failed for source address for new IPv6 header.\nError message: %s\n", strerror (errno));
    }
    exit (EXIT_FAILURE);
  }

  // Destination IPv6 address (128 bits)
  if ((status = inet_pton (AF_INET6, dst_ip, &(newiphdr.ip6_dst))) != 1) {
    if (status == 0) {
      fprintf (stderr, "inet_pton() failed for destination address for new IPv6 header.\nError message: Invalid address\n");
    } else if (status < 0) {
      fprintf (stderr, "inet_pton() failed for destination address for new IPv6 header.\nError message: %s\n", strerror (errno));
    }
    exit (EXIT_FAILURE);
  }

  // Hop-by-hop extension header
  hophdr.nxt_hdr = IPPROTO_TCP;  // 6 for TCP

  // Inner IPv6 payload length: hop-by-hop header + TCP header + TCP data.
  iphdr.ip6_plen = htons (hoplen + TCP_HDRLEN + tcp_datalen);

  // Build ESP payload (inner IPv6 header, hop-by-hop ext. header, TCP header, TCP data, padding).
  c = 0;
  memcpy (esp_payload, &iphdr, IP6_HDRLEN);
  c += IP6_HDRLEN;

  // Add hop-by-hop header and options, if specified.
  indx = 0;  // Index is zero at start of hop-by-hop header.
  if (hbh_nopt > 0) {

    // Copy hop-by-hop extension header (without options) to Ethernet frame.
    memcpy (esp_payload + c, &hophdr, HOP_HDRLEN);
    c += HOP_HDRLEN;
    indx += HOP_HDRLEN;

    // Copy hop-by_hop extension header options to Ethernet frame.
    for (j = 0; j < hbh_nopt; j++) {
      // Pad as needed to achieve alignment requirements for option j (Section 4.2 of RFC 2460).
      option_pad (&indx, esp_payload, &c, hbh_x[j], hbh_y[j]);

      // Copy hop-by-hop option to Ethernet frame.
      memcpy (esp_payload + c, hbh_options[j], hbh_optlen[j]);
      c += hbh_optlen[j];
      indx += hbh_optlen[j];
    }

    // Now pad last option to next 8-byte boundary (Section 4.2 of RFC 2460).
    option_pad (&indx, esp_payload, &c, 8, 0);
  }

  // TCP header
  memcpy (esp_payload + c, &tcphdr, TCP_HDRLEN);
  c += TCP_HDRLEN;

  // TCP data
  memcpy (esp_payload + c, tcp_data, tcp_datalen);
  c += tcp_datalen;

  // Add ESP padding so that the Pad Length and Next Header fields end on a 4-byte boundary.
  // See Section 2.4 of RFC 2406.
  for (i = 0; i < esp_padlen; i++) {
    esp_payload[esp_paylen - esp_padlen + i] = (uint8_t) (i + 1u);
  }

  // ESP trailer.
  esptail.pad_len = esp_padlen;  // Amount of padding for ESP payload
  esptail.nxt_hdr = IPPROTO_IPV6;  // 41 for IPv6 header

  // Build buffer array containing fragmentable portion.
  // Encapsulating security payload (ESP) header 
  memcpy (fragbuffer, &esphdr, ESP_HDRLEN);  // ESP header, excluding payload data, ESP tail, and auth. data
  memcpy (fragbuffer + ESP_HDRLEN, esp_payload, esp_paylen);  // ESP payload (TCP header and TCP payload data)
  memcpy (fragbuffer + ESP_HDRLEN + esp_paylen, &esptail, ESP_TAILLEN);  // ESP trailer
  memcpy (fragbuffer + ESP_HDRLEN + esp_paylen + ESP_TAILLEN, auth_data, auth_len);  // Authentication data (ICV)

  // Submit request for a raw socket descriptor.
  if ((sd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 0) {
    perror ("socket() failed ");
    exit (EXIT_FAILURE);
  }

  // Loop through fragments.
  for (i = 0; i < nframes; i++) {

    // Set Ethernet frame contents to zero initially.
    memset (ether_frame, 0, ETH_HDRLEN + IP_MAXPACKET);

    // Index of Ethernet frame.
    c = 0;

    // Fill out Ethernet frame header.

    // Copy destination and source MAC addresses to Ethernet frame.
    memcpy (ether_frame, dst_mac, sizeof (dst_mac));
    memcpy (ether_frame + sizeof (dst_mac), src_mac, sizeof (src_mac));

    // EtherType (16 bits): ETH_P_IPV6
    // http://www.iana.org/assignments/ethernet-numbers
    ether_frame[12] = ETH_P_IPV6 / 256;
    ether_frame[13] = ETH_P_IPV6 % 256;
    c += ETH_HDRLEN;

    // Next is Ethernet frame data.

    // Payload length (16 bits): See 3 of RFC 2460.
    // Set to zero if hop-by-hop extension header includes a jumbogram.
    if (nframes == 1) {
      newiphdr.ip6_plen = htons (len[i]);
    } else {
      newiphdr.ip6_plen = htons (FRG_HDRLEN + len[i]);
    }

    // Copy new IPv6 header to Ethernet frame.
    memcpy (ether_frame + c, &newiphdr, IP6_HDRLEN);
    c += IP6_HDRLEN;

    // Fill out and copy fragmentation extension header, if necessary, to Ethernet frame.
    if (nframes > 1) {
      fraghdr.ip6f_nxt = IPPROTO_ESP;  // Next header is an encapsulating security payload (ESP) header.
      fraghdr.ip6f_reserved = 0;  // Reserved
      frag_flags[1] = 0;  // Reserved
      if (i < (nframes - 1)) {
        frag_flags[0] = 1;  // More fragments to follow.
      } else {
        frag_flags[0] = 0;  // This is the last fragment.
      }
      fraghdr.ip6f_offlg = htons ((offset[i] << 3) + frag_flags[0] + (frag_flags[1] <<1));
      fraghdr.ip6f_ident = htonl (31415);
      memcpy (ether_frame + c, &fraghdr, FRG_HDRLEN);
      c += FRG_HDRLEN;
    }

    // Copy fragmentable portion of packet to Ethernet frame.
    if (nframes == 1) {
      memcpy (ether_frame + ETH_HDRLEN + IP6_HDRLEN, fragbuffer, fragbufferlen);
    } else {
      memcpy (ether_frame + ETH_HDRLEN + IP6_HDRLEN + FRG_HDRLEN, fragbuffer + (offset[i] * 8), len[i]);
    }

    // Ethernet frame length = Ethernet header (MAC + MAC + Ethernet type) + Ethernet data (IPv6 header + [fragment header] + fragmentable portion)
    if (nframes == 1) {
      frame_length = ETH_HDRLEN + IP6_HDRLEN + len[i];
    } else {
      frame_length = ETH_HDRLEN + IP6_HDRLEN + FRG_HDRLEN + len[i];
    }

    // Send Ethernet frame to socket.
    fprintf (stdout, "Sending fragment: %d\n", i);
    bytes = sendto (sd, ether_frame, frame_length, 0, (struct sockaddr *) &device, sizeof (device));
    if (bytes == -1) {
      status = errno;
      fprintf (stderr, "sendto() failed.\nError message: %s\n", strerror (status));
      exit (EXIT_FAILURE);
    }
    // Check for short send.
    if (bytes != frame_length) {
      fprintf (stderr, "sendto() sent %zd bytes but expected to send %d bytes.\n", bytes, frame_length);
      exit (EXIT_FAILURE);
    }
  }

  // Close socket descriptor.
  close (sd);

  // Free allocated memory.
  free (ether_frame);
  free (interface);
  free (target);
  free (src_ip);
  free (dst_ip);
  free (tcp_data);
  free (fragbuffer);

  free (hbh_optlen);

  for (i = 0; i < MAX_HBHOPTIONS; i++) {
    free (hbh_options[i]);
  }
  free (hbh_options);

  free (hbh_x);
  free (hbh_y);

  free (auth_data);
  free (esp_payload);

  return (EXIT_SUCCESS);
}

// Computing the internet checksum (RFC 1071).
// Note that the internet checksum is not guaranteed to preclude collisions.
uint16_t
checksum (uint8_t *addr, int len) {

  int count = len;
  uint32_t sum = 0;
  uint16_t answer = 0;

  // Sum up 2-byte values until none or only one byte left.
  while (count > 1) {
    sum += ((uint16_t) addr[0] << 8) + addr[1];
    addr += 2;
    count -= 2;
  }

  // Add left-over byte, if any. For an odd-length buffer, the
  // remaining byte is the high-order byte of the final 16-bit word.
  if (count > 0) {
    sum += ((uint16_t) addr[0] << 8);
  }

  // Fold the accumulated sum into 16 bits by repeatedly adding
  // carries back into the low 16 bits (one's-complement arithmetic).
  // sum = (lower 16 bits) + (upper 16 bits shifted right 16 bits)
  while (sum >> 16) {
    sum = (sum & 0xffff) + (sum >> 16);
  }

  // Checksum is one's-complement of sum. Return it in network byte order
  // so it can be copied directly into the packet header.
  answer = ~sum;

  return (htons (answer));
}

// Build IPv6 TCP pseudo-header and call checksum function.
// This version supports any combination of TCP options and TCP data:
//   options == NULL and opt_len == 0        : no TCP options
//   tcp_data == NULL and tcp_datalen == 0   : no TCP data
//   options + tcp_data                      : TCP options followed by TCP data
//
// The caller must set tcphdr.th_off before calling this function. th_off is
// the TCP header length in 32-bit words, so it must include any TCP options.
// For example:
//   tcphdr.th_off = (TCP_HDRLEN + opt_len) / 4;
//
// opt_len should normally be padded to a 4-byte boundary before calling this
// function, because TCP options are part of the TCP header and the TCP header
// length is measured in 32-bit words.
uint16_t
tcp6_checksum (struct ip6_hdr iphdr, struct tcphdr tcphdr, uint8_t *options, int opt_len, uint8_t *tcp_data, int tcp_datalen) {

  int tcp_hdrlen, tcp_segment_len, chksumlen = 0;
  uint8_t *buf, *ptr, cvalue;
  uint16_t answer = 0;
  uint32_t lvalue;

  cvalue = IPPROTO_TCP;

  if (opt_len < 0) {
    fprintf (stderr, "ERROR: opt_len must not be negative in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }
  if (tcp_datalen < 0) {
    fprintf (stderr, "ERROR: tcp_datalen must not be negative in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }
  if ((opt_len > 0) && (options == NULL)) {
    fprintf (stderr, "ERROR: options is NULL but opt_len > 0 in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }
  if ((tcp_datalen > 0) && (tcp_data == NULL)) {
    fprintf (stderr, "ERROR: tcp_data is NULL but tcp_datalen > 0 in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }

  tcp_hdrlen = tcphdr.th_off * 4;
  tcp_segment_len = tcp_hdrlen + tcp_datalen;

  if (tcp_hdrlen < TCP_HDRLEN) {
    fprintf (stderr, "ERROR: TCP header length is too small in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }
  if (tcp_hdrlen != (TCP_HDRLEN + opt_len)) {
    fprintf (stderr, "ERROR: TCP header length does not match TCP_HDRLEN + opt_len in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }
  if ((opt_len % 4) != 0) {
    fprintf (stderr, "ERROR: TCP option length must be padded to a 4-byte boundary in tcp6_checksum().\n");
    exit (EXIT_FAILURE);
  }

  // Allocate memory for buffer.
  buf = allocate_ustrmem (40 + tcp_segment_len + 1);  // Add 1 for possible padding.
  ptr = &buf[0];  // ptr points to beginning of buffer buf

  // Copy source IP address into buf (128 bits)
  memcpy (ptr, &iphdr.ip6_src, sizeof (iphdr.ip6_src));
  ptr += sizeof (iphdr.ip6_src);
  chksumlen += sizeof (iphdr.ip6_src);

  // Copy destination IP address into buf (128 bits)
  memcpy (ptr, &iphdr.ip6_dst, sizeof (iphdr.ip6_dst));
  ptr += sizeof (iphdr.ip6_dst);
  chksumlen += sizeof (iphdr.ip6_dst);

  // Copy TCP length to buf (32 bits)
  lvalue = htonl (tcp_segment_len);
  memcpy (ptr, &lvalue, sizeof (lvalue));
  ptr += sizeof (lvalue);
  chksumlen += sizeof (lvalue);

  // Copy zero field to buf (24 bits)
  *ptr = 0; ptr++;
  *ptr = 0; ptr++;
  *ptr = 0; ptr++;
  chksumlen += 3;

  // Copy next header field to buf (8 bits)
  memcpy (ptr, &cvalue, sizeof (cvalue));
  ptr += sizeof (iphdr.ip6_nxt);
  chksumlen += sizeof (iphdr.ip6_nxt);

  // Copy TCP source port to buf (16 bits)
  memcpy (ptr, &tcphdr.th_sport, sizeof (tcphdr.th_sport));
  ptr += sizeof (tcphdr.th_sport);
  chksumlen += sizeof (tcphdr.th_sport);

  // Copy TCP destination port to buf (16 bits)
  memcpy (ptr, &tcphdr.th_dport, sizeof (tcphdr.th_dport));
  ptr += sizeof (tcphdr.th_dport);
  chksumlen += sizeof (tcphdr.th_dport);

  // Copy sequence number to buf (32 bits)
  memcpy (ptr, &tcphdr.th_seq, sizeof (tcphdr.th_seq));
  ptr += sizeof (tcphdr.th_seq);
  chksumlen += sizeof (tcphdr.th_seq);

  // Copy acknowledgement number to buf (32 bits)
  memcpy (ptr, &tcphdr.th_ack, sizeof (tcphdr.th_ack));
  ptr += sizeof (tcphdr.th_ack);
  chksumlen += sizeof (tcphdr.th_ack);

  // Copy data offset to buf (4 bits) and
  // copy reserved bits to buf (4 bits)
  cvalue = (tcphdr.th_off << 4) + tcphdr.th_x2;
  memcpy (ptr, &cvalue, sizeof (cvalue));
  ptr += sizeof (cvalue);
  chksumlen += sizeof (cvalue);

  // Copy TCP flags to buf (8 bits)
  memcpy (ptr, &tcphdr.th_flags, sizeof (tcphdr.th_flags));
  ptr += sizeof (tcphdr.th_flags);
  chksumlen += sizeof (tcphdr.th_flags);

  // Copy TCP window size to buf (16 bits)
  memcpy (ptr, &tcphdr.th_win, sizeof (tcphdr.th_win));
  ptr += sizeof (tcphdr.th_win);
  chksumlen += sizeof (tcphdr.th_win);

  // Copy TCP checksum to buf (16 bits)
  // Zero, since we don't know it yet
  *ptr = 0; ptr++;
  *ptr = 0; ptr++;
  chksumlen += 2;

  // Copy urgent pointer to buf (16 bits)
  memcpy (ptr, &tcphdr.th_urp, sizeof (tcphdr.th_urp));
  ptr += sizeof (tcphdr.th_urp);
  chksumlen += sizeof (tcphdr.th_urp);

  // Copy TCP options to buf, if any. TCP options come immediately after
  // the fixed 20-byte TCP header and before any TCP data.
  if (opt_len > 0) {
    memcpy (ptr, options, opt_len);
    ptr += opt_len;
    chksumlen += opt_len;
  }

  // Copy TCP data to buf, if any.
  if (tcp_datalen > 0) {
    memcpy (ptr, tcp_data, tcp_datalen);
    ptr += tcp_datalen;
    chksumlen += tcp_datalen;
  }

  // Pad to the next 16-bit boundary. The padding byte is used only for
  // checksum calculation and is not part of the TCP segment length.
  if ((tcp_segment_len % 2) != 0) {
    *ptr = 0;
    chksumlen++;
  }

  answer = checksum ((uint8_t *) buf, chksumlen);

  // Free allocated memory.
  free (buf);

  return (answer);
}

// Provide padding as needed to achieve alignment requirements of hop-by-hop or destination option.
int
option_pad (int *indx, uint8_t *padding, int *c, int x, int y) {

  int needpad;

  // Find number of padding bytes needed to achieve alignment requirements for option (Section 4.2 of RFC 2460).
  // Alignment is expressed as xN + y, which means the start of the option must occur at xN + y bytes
  // from the start of the hop-by-hop or destination header, where N is integer 0, 1, 2, ...etc.
  needpad = 0;
  while (((*indx + needpad) % x) != y) {
    needpad++;
  }

  // If required padding = 1 byte, we use Pad1 option.
  if (needpad == 1) {
    padding[*c] = 0;  // Padding option type: Pad1
    (*indx)++;
    (*c)++;

  // If required padding is > 1 byte, we use PadN option.
  } else if (needpad > 1) {
    padding[*c] = 1;  // Padding option type: PadN
    (*indx)++;
    (*c)++;
    padding[*c] = needpad - 2;  // PadN length: N - 2
    (*indx)++;
    (*c)++;
    memset (padding + (*c), 0, needpad - 2);
    (*indx) += needpad - 2;
    (*c) += needpad - 2;
  }

  return (EXIT_SUCCESS);
}

// Allocate memory for an array of chars.
char *
allocate_strmem (int len) {

  void *tmp;

  if (len <= 0) {
    fprintf (stderr, "ERROR: Cannot allocate memory because len = %d in allocate_strmem().\n", len);
    exit (EXIT_FAILURE);
  }

  tmp = calloc (len, sizeof (char));
  if (tmp != NULL) {
    return (tmp);
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array allocate_strmem().\n");
    exit (EXIT_FAILURE);
  }
}

// Allocate memory for an array of unsigned chars.
uint8_t *
allocate_ustrmem (int len) {

  void *tmp;

  if (len <= 0) {
    fprintf (stderr, "ERROR: Cannot allocate memory because len = %d in allocate_ustrmem().\n", len);
    exit (EXIT_FAILURE);
  }

  tmp = calloc (len, sizeof (uint8_t));
  if (tmp != NULL) {
    return (tmp);
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array allocate_ustrmem().\n");
    exit (EXIT_FAILURE);
  }
}

// Allocate memory for an array of pointers to arrays of unsigned chars.
uint8_t **
allocate_ustrmemp (int len) {

  void *tmp;

  if (len <= 0) {
    fprintf (stderr, "ERROR: Cannot allocate memory because len = %d in allocate_ustrmemp().\n", len);
    exit (EXIT_FAILURE);
  }

  tmp = calloc (len, sizeof (uint8_t *));
  if (tmp != NULL) {
    return (tmp);
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array allocate_ustrmemp().\n");
    exit (EXIT_FAILURE);
  }
}

// Allocate memory for an array of ints.
int *
allocate_intmem (int len) {

  void *tmp;

  if (len <= 0) {
    fprintf (stderr, "ERROR: Cannot allocate memory because len = %d in allocate_intmem().\n", len);
    exit (EXIT_FAILURE);
  }

  tmp = calloc (len, sizeof (int));
  if (tmp != NULL) {
    return (tmp);
  } else {
    fprintf (stderr, "ERROR: Cannot allocate memory for array allocate_intmem().\n");
    exit (EXIT_FAILURE);
  }
}
