more code cleanup
[oweals/gnunet.git] / src / transport / gnunet-nat-server-windows.c
index a23d9954db56a9d7b0456480caab07784111b8c0..ceff3fb8d9b5c2b0ffd894406a506eaa0342ebe6 100644 (file)
  */
 #define _GNU_SOURCE
 
-#ifdef WIN32
+
 #include <winsock2.h>
-#else
-#include <sys/types.h> 
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <sys/select.h>
-#include <netinet/ip.h>
-#include <netinet/ip_icmp.h>
-#include <netinet/in.h>
-#endif
+#include <ws2tcpip.h>
 #include <sys/time.h>
 #include <sys/types.h>
 #include <unistd.h>
 #include <stdint.h>
 #include <time.h>
 
-
-#ifdef WIN32
-typedef unsigned int uid_t;
-typedef SOCKET Socket;
-typedef unsigned short ushort;
-#define ICMP_ECHO 8
-#define IPDEFTTL        64              /* default ttl, from RFC 1340 */
-#define ICMP_TIME_EXCEEDED      11      /* Time Exceeded                */
-#define IP_HDRINCL      3       /* int; Header is included with data.  */
-#else
-typedef int Socket;
-#endif
+/**
+ * Should we print some debug output?
+ */
+#define VERBOSE 0
 
 /**
  * Must match IP given in the client.
  */
 #define DUMMY_IP "192.0.2.86"
 
-#define VERBOSE 0
+/**
+ * TTL to use for our outgoing messages.
+ */
+#define IPDEFTTL 64
+
+#define ICMP_ECHO 8
+
+#define ICMP_TIME_EXCEEDED      11      /* Time Exceeded */
 
 /**
  * How often do we send our ICMP messages to receive replies?
  */
 #define ICMP_SEND_FREQUENCY_MS 500
 
+/**
+ * IPv4 header.
+ */
 struct ip_packet 
 {
-  uint8_t vers_ihl;
-  uint8_t tos;
-  uint16_t pkt_len;
-  uint16_t id;
-  uint16_t flags_frag_offset;
-  uint8_t ttl;
-  uint8_t proto;
-  uint16_t checksum;
-  uint32_t src_ip;
-  uint32_t dst_ip;
+
+  /**
+   * Version (4 bits) + Internet header length (4 bits) 
+   */
+  uint8_t vers_ihl; 
+
+  /**
+   * Type of service
+   */
+  uint8_t tos;  
+
+  /**
+   * Total length
+   */
+  uint16_t pkt_len;  
+
+  /**
+   * Identification
+   */
+  uint16_t id;    
+
+  /**
+   * Flags (3 bits) + Fragment offset (13 bits)
+   */
+  uint16_t flags_frag_offset; 
+
+  /**
+   * Time to live
+   */
+  uint8_t  ttl;   
+
+  /**
+   * Protocol       
+   */
+  uint8_t  proto; 
+
+  /**
+   * Header checksum
+   */
+  uint16_t checksum; 
+
+  /**
+   * Source address
+   */
+  uint32_t  src_ip;  
+
+  /**
+   * Destination address 
+   */
+  uint32_t  dst_ip;  
 };
 
+/**
+ * Format of ICMP packet.
+ */
 struct icmp_packet 
 {
   uint8_t type;
+
   uint8_t code;
+
   uint16_t checksum;
+
   uint32_t reserved;
 };
 
+/**
+ * Beginning of UDP packet.
+ */
 struct udp_packet
 {
   uint16_t src_port;
@@ -118,12 +161,29 @@ struct udp_packet
   uint32_t length;
 };
 
-static Socket icmpsock;
+/**
+ * Socket we use to receive "fake" ICMP replies.
+ */
+static SOCKET icmpsock;
 
-static Socket rawsock;
+/**
+ * Socket we use to send our ICMP requests.
+ */
+static SOCKET rawsock;
 
+/**
+ * Target "dummy" address.
+ */
 static struct in_addr dummy;
 
+
+/**
+ * CRC-16 for IP/ICMP headers.
+ *
+ * @param data what to calculate the CRC over
+ * @param bytes number of bytes in data (must be multiple of 2)
+ * @return the CRC 16.
+ */
 static uint16_t 
 calc_checksum(const uint16_t *data, 
              unsigned int bytes)
@@ -139,36 +199,30 @@ calc_checksum(const uint16_t *data,
   return sum;
 }
 
-#if WIN32
+
 /**
+ * Convert IPv4 address from text to binary form.
+ *
  * @param af address family
  * @param cp the address to print
  * @param buf where to write the address result
+ * @return 1 on success
  */
-static int inet_pton (int af, char *cp, struct in_addr *buf)
+static int 
+inet_pton (int af, 
+          const char *cp, 
+          struct in_addr *buf)
 {
-  //ret = WSAStringToAddress (cp, af, NULL, (LPSOCKADDR)buf, &ssize);
   buf->s_addr = inet_addr(cp);
-  if (buf->s_addr != INADDR_NONE)
+  if (buf->s_addr == INADDR_NONE)
     {
-      fprintf(stderr, "Error %d handling address %s", WSAGetLastError(), cp);
+      fprintf(stderr, 
+             "Error %d handling address %s", 
+             WSAGetLastError(), 
+             cp);
       return 0;
     }
-  else
-    return 1;
-}
-#endif
-
-static void
-make_echo (const struct in_addr *src_ip,
-          struct icmp_packet *echo)
-{
-  memset(echo, 0, sizeof(struct icmp_packet));
-  echo->type = ICMP_ECHO;
-  echo->code = 0;
-  echo->reserved = 0;
-  echo->checksum = 0;
-  echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
+  return 1;
 }
 
 
@@ -193,17 +247,23 @@ send_icmp_echo (const struct in_addr *my_ip)
   ip_pkt.vers_ihl = 0x45;
   ip_pkt.tos = 0;
   ip_pkt.pkt_len = sizeof (packet);
-  ip_pkt.id = 1;
+  ip_pkt.id = htons (256);
   ip_pkt.flags_frag_offset = 0;
   ip_pkt.ttl = IPDEFTTL;
   ip_pkt.proto = IPPROTO_ICMP;
-  ip_pkt.checksum = 0; 
+  ip_pkt.checksum = 0;
   ip_pkt.src_ip = my_ip->s_addr;
   ip_pkt.dst_ip = dummy.s_addr;
   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
   off += sizeof (ip_pkt);
-  make_echo (my_ip, &icmp_echo);
+
+  icmp_echo.type = ICMP_ECHO;
+  icmp_echo.code = 0;
+  icmp_echo.reserved = 0;
+  icmp_echo.checksum = 0;
+  icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
+                                          sizeof (struct icmp_packet)));
   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
   off += sizeof (icmp_echo);
  
@@ -211,9 +271,9 @@ send_icmp_echo (const struct in_addr *my_ip)
   dst.sin_family = AF_INET;
   dst.sin_addr = dummy;
   err = sendto(rawsock, 
-              packet, off, 0, 
-              (struct sockaddr*)&dst, 
-              sizeof(dst));
+               packet, off, 0,
+               (struct sockaddr*)&dst,
+               sizeof(dst));
   if (err < 0) 
     {
 #if VERBOSE
@@ -229,6 +289,9 @@ send_icmp_echo (const struct in_addr *my_ip)
 }
 
 
+/**
+ * We've received an ICMP response.  Process it.
+ */
 static void
 process_icmp_response ()
 {
@@ -240,8 +303,8 @@ process_icmp_response ()
   struct udp_packet udp_pkt;
   size_t off;
   int have_port;
-  int have_udp;
   uint32_t port;
+
   have = read (icmpsock, buf, sizeof (buf));
   if (have == -1)
     {
@@ -251,7 +314,11 @@ process_icmp_response ()
       return; 
     }
   have_port = 0;
-
+#if VERBOSE
+  fprintf (stderr,
+           "Received message of %u bytes\n",
+           (unsigned int) have);
+#endif
   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
     {
       have_port = 1;
@@ -280,173 +347,141 @@ process_icmp_response ()
   memcpy(&sip, 
         &ip_pkt.src_ip, 
         sizeof (sip));
-
   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
   off += sizeof (ip_pkt);
 
-  have_udp = 0;
-  if (ip_pkt.proto == IPPROTO_UDP)
-    {
-      have_udp = 1;
-    }
-
   if (have_port)
     {
-      memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
+      memcpy(&port, 
+            &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], 
+            sizeof(uint32_t));
       port = ntohs(port);
-#ifdef WIN32
       DWORD ssize = sizeof(buf);
-      WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
-      fprintf (stdout, "%s:%d\n", buf, port);
-#else
-      fprintf (stdout,
-              "%s:%d\n",
-              inet_ntop (AF_INET,
-                         &sip,
-                         buf,
-                         sizeof (buf)), port);
-#endif
+      WSAAddressToString((LPSOCKADDR)&sip, 
+                        sizeof(sip),
+                        NULL, 
+                        buf, 
+                        &ssize);
+      fprintf (stdout, 
+              "%s:%d\n",
+              buf, 
+              port);
     }
-  else if (have_udp)
+  else if (ip_pkt.proto == IPPROTO_UDP)
     {
-      memcpy(&udp_pkt, &buf[off], sizeof(udp_pkt));
-#ifdef WIN32
+      memcpy(&udp_pkt,
+            &buf[off],
+            sizeof(udp_pkt));
       DWORD ssize = sizeof(buf);
-      WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
-      fprintf (stdout, "%s:%d\n", buf, ntohs((int)udp_pkt.length));
-#else
-      fprintf (stdout,
-               "%s:%d\n",
-               inet_ntop (AF_INET,
-                          &sip,
-                          buf,
-                          sizeof (buf)), ntohl(udp_pkt.length));
-#endif
+      WSAAddressToString((LPSOCKADDR)&sip, 
+                        sizeof(sip),
+                        NULL,
+                        buf, 
+                        &ssize);
+      fprintf (stdout, 
+              "%s:%d\n", 
+              buf, 
+              ntohs((uint16_t)udp_pkt.length));
     }
   else
     {
-#ifdef WIN32
       DWORD ssize = sizeof(buf);
-      WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
-      fprintf (stdout, "%s\n", buf);
-#else
-      fprintf (stdout,
-              "%s\n",
-              inet_ntop (AF_INET,
-                         &sip,
-                         buf,
-                         sizeof (buf)));
-#endif
+      WSAAddressToString((LPSOCKADDR)&sip,
+                        sizeof(sip),
+                        NULL,
+                        buf,
+                        &ssize);
+      fprintf (stdout, 
+              "%s\n",
+              buf);
     }
   fflush (stdout);
 }
 
 
-static Socket
+/**
+ * Create an ICMP raw socket for reading.
+ *
+ * @return INVALID_SOCKET on error
+ */
+static SOCKET
 make_icmp_socket ()
 {
-  Socket ret;
+  SOCKET ret;
 
   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
-  if (-1 == ret)
+  if (INVALID_SOCKET == ret)
     {
       fprintf (stderr,
               "Error opening RAW socket: %s\n",
               strerror (errno));
-      return -1;
+      return INVALID_SOCKET;
     }  
-#if WIN32
-  if (ret == INVALID_SOCKET)
-    {
-      fprintf (stderr, "Invalid socket %d!\n", ret);
-      closesocket (ret);
-    }
-#else
-  if (ret >= FD_SETSIZE) 
-    {
-      fprintf (stderr,
-              "Socket number too large (%d > %u)\n",
-              ret,
-              (unsigned int) FD_SETSIZE);
-      close (ret);
-      return -1;
-    }
-#endif
   return ret;
 }
 
 
-static Socket
+/**
+ * Create an ICMP raw socket for writing.
+ *
+ * @return INVALID_SOCKET on error
+ */
+static SOCKET
 make_raw_socket ()
 {
-  const int one = 1;
-  Socket ret;
+  DWORD bOptVal = TRUE;
+  int bOptLen = sizeof(bOptVal);
 
-  ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
-  if (-1 == ret)
+  rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
+  if (INVALID_SOCKET == rawsock)
     {
       fprintf (stderr,
               "Error opening RAW socket: %s\n",
               strerror (errno));
-      return -1;
-    }  
-  if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
-                (char *)&one, sizeof(one)) == -1)
-    fprintf(stderr,
-           "setsockopt failed: %s\n",
-           strerror (errno));
-  if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
-                (char *)&one, sizeof(one)) == -1)
-    fprintf(stderr,
-           "setsockopt failed: %s\n",
-           strerror (errno));
-  return ret;
+      return INVALID_SOCKET;
+    }
+
+  if (setsockopt(rawsock, 
+                SOL_SOCKET, 
+                SO_BROADCAST, 
+                (char*)&bOptVal, bOptLen) != 0)
+    {
+      fprintf(stderr, 
+             "Error setting SO_BROADCAST to ON: %s\n",
+             strerror (errno));
+      closesocket(rawsock);
+      return INVALID_SOCKET;
+    }
+  if (setsockopt(rawsock, 
+                IPPROTO_IP, 
+                IP_HDRINCL, 
+                (char*)&bOptVal, bOptLen) != 0)
+    {
+      fprintf(stderr, 
+             "Error setting IP_HDRINCL to ON: %s\n",
+             strerror (errno));
+      closesocket(rawsock);
+      return INVALID_SOCKET;
+    }
+  return rawsock;
 }
 
 
 int
-main (int argc, char *const *argv)
+main (int argc, 
+      char *const *argv)
 {
   struct in_addr external;
   fd_set rs;
   struct timeval tv;
-#ifndef WIN32
-  uid_t uid;
-#else
-  struct sockaddr_storage saddr;
-#endif
-
-#ifdef WIN32
-  // WSA startup
   WSADATA wsaData;
-  if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
-  {
-      fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
-      return 4;                       // ERROR
-  }
-#endif
 
-  if (-1 == (icmpsock = make_icmp_socket()))
-    return 1; 
-  if (-1 == (rawsock = make_raw_socket()))
-    {
-      close (icmpsock);
-      return 1; 
-    }
-#ifndef WIN32
-  uid = getuid ();
-  if (0 != setresuid (uid, uid, uid))
-    fprintf (stderr,
-            "Failed to setresuid: %s\n",
-            strerror (errno));
-#endif
   if (argc != 2)
     {
       fprintf (stderr,
               "This program must be started with our (internal NAT) IP as the only argument.\n");
       return 1;
     }
-
   if (1 != inet_pton (AF_INET, argv[1], &external))
     {
       fprintf (stderr,
@@ -454,26 +489,50 @@ main (int argc, char *const *argv)
               argv[1], strerror (errno));
       return 1;
     }
-
-  if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
+  if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
+    {
+      fprintf (stderr,
+              "Internal error converting dummy IP to binary.\n");
+      return 2;
+    }
+  if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
+    {
+      fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
+      return 2;
+    }
+  if (INVALID_SOCKET == (icmpsock = make_icmp_socket()))
+    {
+      return 3; 
+    }
+  if (INVALID_SOCKET == (make_raw_socket()))
+    {
+      closesocket (icmpsock);
+      return 3; 
+    }
   while (1)
     {
       FD_ZERO (&rs);
       FD_SET (icmpsock, &rs);
       tv.tv_sec = 0;
       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
-      select (icmpsock + 1, &rs, NULL, NULL, &tv);
+      if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
+       {
+         if (errno == EINTR)
+           continue;
+         fprintf (stderr,
+                  "select failed: %s\n",
+                  strerror (errno));
+         break;
+       }
       if (FD_ISSET (icmpsock, &rs))
-       process_icmp_response ();
+        process_icmp_response ();
       send_icmp_echo (&external);
-    }  
-
-#ifdef WIN32
+    }
+  /* select failed (internal error or OS out of resources) */
   closesocket(icmpsock);
   closesocket(rawsock);
   WSACleanup ();
-#endif
-  return 0;
+  return 4; 
 }