dos2unix
authorDavid Barksdale <amatus.amongus@gmail.com>
Sun, 21 Jun 2015 18:14:58 +0000 (18:14 +0000)
committerDavid Barksdale <amatus.amongus@gmail.com>
Sun, 21 Jun 2015 18:14:58 +0000 (18:14 +0000)
contrib/gnunet_pyexpect.py.in
contrib/terminate.py.in
m4/ac_define_dir.m4
src/consensus/consensus-simulation.py
src/dns/Makefile.am
src/integration-tests/gnunet_pyexpect.py.in
src/nat/test_stun.c
src/nat/test_stun.h

index f8b7cc88f38132b727288a1b8b64e14bbb49b28f..b03bcc55701790c4c7d582006d63883f01ee6f23 100644 (file)
@@ -1,83 +1,83 @@
-#!@PYTHON@\r
-#    This file is part of GNUnet.\r
-#    (C) 2010 Christian Grothoff (and other contributing authors)\r
-#\r
-#    GNUnet is free software; you can redistribute it and/or modify\r
-#    it under the terms of the GNU General Public License as published\r
-#    by the Free Software Foundation; either version 2, or (at your\r
-#    option) any later version.\r
-#\r
-#    GNUnet is distributed in the hope that it will be useful, but\r
-#    WITHOUT ANY WARRANTY; without even the implied warranty of\r
-#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-#    General Public License for more details.\r
-#\r
-#    You should have received a copy of the GNU General Public License\r
-#    along with GNUnet; see the file COPYING.  If not, write to the\r
-#    Free Software Foundation, Inc., 59 Temple Place - Suite 330,\r
-#    Boston, MA 02111-1307, USA.\r
-#\r
-# Testcase for gnunet-peerinfo\r
-from __future__ import print_function\r
-import os\r
-import re\r
-import subprocess\r
-import sys\r
-import shutil\r
-import time\r
-\r
-class pexpect (object):\r
-  def __init__ (self):\r
-    super (pexpect, self).__init__ ()\r
-\r
-  def spawn (self, stdin, arglist, *pargs, **kwargs):\r
-    env = kwargs.pop ('env', None)\r
-    if env is None:\r
-      env = os.environ.copy ()\r
-    # This messes up some testcases, disable log redirection\r
-    env.pop ('GNUNET_FORCE_LOGFILE', None)\r
-    self.proc = subprocess.Popen (arglist, *pargs, env=env, **kwargs)\r
-    if self.proc is None:\r
-      print ("Failed to spawn a process {0}".format (arglist))\r
-      sys.exit (1)\r
-    if stdin is not None:\r
-      self.stdo, self.stde = self.proc.communicate (stdin)\r
-    else:\r
-      self.stdo, self.stde = self.proc.communicate ()\r
-    return self.proc\r
-\r
-  def expect (self, s, r, flags=0):\r
-    stream = self.stdo if s == 'stdout' else self.stde\r
-    if isinstance (r, str):\r
-      if r == "EOF":\r
-        if len (stream) == 0:\r
-          return True\r
-        else:\r
-          print ("Failed to find `{1}' in {0}, which is `{2}' ({3})".format (s, r, stream, len (stream)))\r
-          sys.exit (2)\r
-      raise ValueError ("Argument `r' should be an instance of re.RegexObject or a special string, but is `{0}'".format (r))\r
-    m = r.search (stream.decode(), flags)\r
-    if not m:\r
-      print ("Failed to find `{1}' in {0}, which is is `{2}'".format (s, r.pattern, stream))\r
-      sys.exit (2)\r
-    stream = stream[m.end ():]\r
-    if s == 'stdout':\r
-      self.stdo = stream\r
-    else:\r
-      self.stde = stream\r
-    return m\r
-\r
-  def read (self, s, size=-1):\r
-    stream = self.stdo if s == 'stdout' else self.stde\r
-    result = ""\r
-    if size < 0:\r
-      result = stream\r
-      new_stream = ""\r
-    else:\r
-      result = stream[0:size]\r
-      new_stream = stream[size:]\r
-    if s == 'stdout':\r
-      self.stdo = new_stream\r
-    else:\r
-      self.stde = new_stream\r
-    return result\r
+#!@PYTHON@
+#    This file is part of GNUnet.
+#    (C) 2010 Christian Grothoff (and other contributing authors)
+#
+#    GNUnet 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 2, or (at your
+#    option) any later version.
+#
+#    GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
+#    Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+#    Boston, MA 02111-1307, USA.
+#
+# Testcase for gnunet-peerinfo
+from __future__ import print_function
+import os
+import re
+import subprocess
+import sys
+import shutil
+import time
+
+class pexpect (object):
+  def __init__ (self):
+    super (pexpect, self).__init__ ()
+
+  def spawn (self, stdin, arglist, *pargs, **kwargs):
+    env = kwargs.pop ('env', None)
+    if env is None:
+      env = os.environ.copy ()
+    # This messes up some testcases, disable log redirection
+    env.pop ('GNUNET_FORCE_LOGFILE', None)
+    self.proc = subprocess.Popen (arglist, *pargs, env=env, **kwargs)
+    if self.proc is None:
+      print ("Failed to spawn a process {0}".format (arglist))
+      sys.exit (1)
+    if stdin is not None:
+      self.stdo, self.stde = self.proc.communicate (stdin)
+    else:
+      self.stdo, self.stde = self.proc.communicate ()
+    return self.proc
+
+  def expect (self, s, r, flags=0):
+    stream = self.stdo if s == 'stdout' else self.stde
+    if isinstance (r, str):
+      if r == "EOF":
+        if len (stream) == 0:
+          return True
+        else:
+          print ("Failed to find `{1}' in {0}, which is `{2}' ({3})".format (s, r, stream, len (stream)))
+          sys.exit (2)
+      raise ValueError ("Argument `r' should be an instance of re.RegexObject or a special string, but is `{0}'".format (r))
+    m = r.search (stream.decode(), flags)
+    if not m:
+      print ("Failed to find `{1}' in {0}, which is is `{2}'".format (s, r.pattern, stream))
+      sys.exit (2)
+    stream = stream[m.end ():]
+    if s == 'stdout':
+      self.stdo = stream
+    else:
+      self.stde = stream
+    return m
+
+  def read (self, s, size=-1):
+    stream = self.stdo if s == 'stdout' else self.stde
+    result = ""
+    if size < 0:
+      result = stream
+      new_stream = ""
+    else:
+      result = stream[0:size]
+      new_stream = stream[size:]
+    if s == 'stdout':
+      self.stdo = new_stream
+    else:
+      self.stde = new_stream
+    return result
index 14c79c10d0959e565ac264f4c0c9fe6aa8498398..aeaaa1501467936add94f51dd4042bcf953ccf54 100644 (file)
 # Utility module that implements safe process termination for W32.
 # For other platforms it's equivalent to Popen.kill ()
 # Requires pywin32 on W32.
-\r
-import sys\r
-import os\r
-import subprocess\r
-if os.name == 'nt':\r
-  import win32api\r
-  import win32process\r
-\r
-class dummyobj (object):\r
-  pass\r
-\r
-def safe_terminate_process_by_pid (pid, code):\r
-  if os.name == 'nt':\r
-    p = dummyobj ()\r
-    p._handle = win32api.OpenProcess (2 | 1024 | 8 | 32 | 16, 0, pid)\r
-    result = safe_terminate_process (p, code)\r
-    win32api.CloseHandle (p._handle)\r
-    return result\r
-  else:\r
-    return os.kill (int (pid), SIGKILL)\r
-\r
-def safe_terminate_process (proc, code):\r
-  if os.name == 'nt':\r
-    cp = win32api.GetCurrentProcess ()\r
-    result = False\r
-    dupproc = win32api.DuplicateHandle (cp, proc._handle, cp, 2 | 1024 | 8 | 32 | 16, 0, 0)\r
-    try:\r
-      exitcode = win32process.GetExitCodeProcess (dupproc)\r
-      if exitcode == 0x103:\r
-        kernel32 = win32api.GetModuleHandle ("kernel32")\r
-        exitprocess = win32api.GetProcAddress (kernel32, "ExitProcess")\r
-        th, tid = win32process.CreateRemoteThread (dupproc, None, 0, exitprocess, code, 0)\r
-        win32api.CloseHandle (th)\r
-        result = True\r
-      else:\r
-        result = True\r
-    # except failed to get exit code? failed to get module handle?\r
-    finally:\r
-      win32api.CloseHandle (dupproc)\r
-    return result\r
-  else:\r
-    return proc.kill ()\r
+
+import sys
+import os
+import subprocess
+if os.name == 'nt':
+  import win32api
+  import win32process
+
+class dummyobj (object):
+  pass
+
+def safe_terminate_process_by_pid (pid, code):
+  if os.name == 'nt':
+    p = dummyobj ()
+    p._handle = win32api.OpenProcess (2 | 1024 | 8 | 32 | 16, 0, pid)
+    result = safe_terminate_process (p, code)
+    win32api.CloseHandle (p._handle)
+    return result
+  else:
+    return os.kill (int (pid), SIGKILL)
+
+def safe_terminate_process (proc, code):
+  if os.name == 'nt':
+    cp = win32api.GetCurrentProcess ()
+    result = False
+    dupproc = win32api.DuplicateHandle (cp, proc._handle, cp, 2 | 1024 | 8 | 32 | 16, 0, 0)
+    try:
+      exitcode = win32process.GetExitCodeProcess (dupproc)
+      if exitcode == 0x103:
+        kernel32 = win32api.GetModuleHandle ("kernel32")
+        exitprocess = win32api.GetProcAddress (kernel32, "ExitProcess")
+        th, tid = win32process.CreateRemoteThread (dupproc, None, 0, exitprocess, code, 0)
+        win32api.CloseHandle (th)
+        result = True
+      else:
+        result = True
+    # except failed to get exit code? failed to get module handle?
+    finally:
+      win32api.CloseHandle (dupproc)
+    return result
+  else:
+    return proc.kill ()
index f7e028fca2e22dc2e34deba062a008586f2e61a7..c4f07c50b3e2b30bdb9b96a55dbaabf085768576 100644 (file)
@@ -1,35 +1,35 @@
-dnl @synopsis AC_DEFINE_DIR(VARNAME, DIR [, DESCRIPTION])\r
-dnl\r
-dnl This macro _AC_DEFINEs VARNAME to the expansion of the DIR\r
-dnl variable, taking care of fixing up ${prefix} and such.\r
-dnl\r
-dnl VARNAME is offered as both a C preprocessor symbol, and an output\r
-dnl variable.\r
-dnl\r
-dnl Note that the 3 argument form is only supported with autoconf 2.13\r
-dnl and later (i.e. only where _AC_DEFINE supports 3 arguments).\r
-dnl\r
-dnl Examples:\r
-dnl\r
-dnl    AC_DEFINE_DIR(DATADIR, datadir)\r
-dnl    AC_DEFINE_DIR(PROG_PATH, bindir, [Location of installed binaries])\r
-dnl\r
-dnl @category Misc\r
-dnl @author Stepan Kasal <kasal@ucw.cz>\r
-dnl @author Andreas Schwab <schwab@suse.de>\r
-dnl @author Guido Draheim <guidod@gmx.de>\r
-dnl @author Alexandre Oliva\r
-dnl @version 2005-01-17\r
-dnl @license AllPermissive\r
-\r
-AC_DEFUN([AC_DEFINE_DIR], [\r
-  prefix_NONE=\r
-  exec_prefix_NONE=\r
-  test "x$prefix" = xNONE && prefix_NONE=yes && prefix=$ac_default_prefix\r
-  test "x$exec_prefix" = xNONE && exec_prefix_NONE=yes && exec_prefix=$prefix\r
-  eval ac_define_dir="\"[$]$2\""\r
-  AC_SUBST($1, "$ac_define_dir")\r
-  AC_DEFINE_UNQUOTED($1, "$ac_define_dir", [$3])\r
-  test "$prefix_NONE" && prefix=NONE\r
-  test "$exec_prefix_NONE" && exec_prefix=NONE\r
-])\r
+dnl @synopsis AC_DEFINE_DIR(VARNAME, DIR [, DESCRIPTION])
+dnl
+dnl This macro _AC_DEFINEs VARNAME to the expansion of the DIR
+dnl variable, taking care of fixing up ${prefix} and such.
+dnl
+dnl VARNAME is offered as both a C preprocessor symbol, and an output
+dnl variable.
+dnl
+dnl Note that the 3 argument form is only supported with autoconf 2.13
+dnl and later (i.e. only where _AC_DEFINE supports 3 arguments).
+dnl
+dnl Examples:
+dnl
+dnl    AC_DEFINE_DIR(DATADIR, datadir)
+dnl    AC_DEFINE_DIR(PROG_PATH, bindir, [Location of installed binaries])
+dnl
+dnl @category Misc
+dnl @author Stepan Kasal <kasal@ucw.cz>
+dnl @author Andreas Schwab <schwab@suse.de>
+dnl @author Guido Draheim <guidod@gmx.de>
+dnl @author Alexandre Oliva
+dnl @version 2005-01-17
+dnl @license AllPermissive
+
+AC_DEFUN([AC_DEFINE_DIR], [
+  prefix_NONE=
+  exec_prefix_NONE=
+  test "x$prefix" = xNONE && prefix_NONE=yes && prefix=$ac_default_prefix
+  test "x$exec_prefix" = xNONE && exec_prefix_NONE=yes && exec_prefix=$prefix
+  eval ac_define_dir="\"[$]$2\""
+  AC_SUBST($1, "$ac_define_dir")
+  AC_DEFINE_UNQUOTED($1, "$ac_define_dir", [$3])
+  test "$prefix_NONE" && prefix=NONE
+  test "$exec_prefix_NONE" && exec_prefix=NONE
+])
index 930dfee62b8e4941e43e14a15c19647953cedc84..3bc4ab652a258f76e65189786063957a1757c343 100644 (file)
-#!/usr/bin/python\r
-# This file is part of GNUnet\r
-# (C) 2013 Christian Grothoff (and other contributing authors)\r
-#\r
-# GNUnet is free software; you can redistribute it and/or modify\r
-# it under the terms of the GNU General Public License as published\r
-# by the Free Software Foundation; either version 2, or (at your\r
-# option) any later version.\r
-#\r
-# GNUnet is distributed in the hope that it will be useful, but\r
-# WITHOUT ANY WARRANTY; without even the implied warranty of\r
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-# General Public License for more details.\r
-#\r
-# You should have received a copy of the GNU General Public License\r
-# along with GNUnet; see the file COPYING.  If not, write to the\r
-# Free Software Foundation, Inc., 59 Temple Place - Suite 330,\r
-# Boston, MA 02111-1307, USA.\r
-\r
-import argparse\r
-import random\r
-from math import ceil,log,floor\r
-\r
-def bsc(n):\r
-  """ count the bits set in n"""\r
-  l = n.bit_length()\r
-  c = 0\r
-  x = 1\r
-  for _ in range(0, l):\r
-    if n & x:\r
-      c = c + 1\r
-    x = x << 1\r
-  return c\r
-\r
-def simulate(k, n, verbose):\r
-  assert k < n\r
-  largest_arc = int(2**ceil(log(n, 2))) / 2\r
-  num_ghosts = (2 * largest_arc) - n\r
-  if verbose:\r
-    print "we have", num_ghosts, "ghost peers"\r
-  # n.b. all peers with idx<k are evil\r
-  peers = range(n)\r
-  info = [1 << x for x in xrange(n)]\r
-  def done_p():\r
-    for x in xrange(k, n):\r
-      if bsc(info[x]) < n-k:\r
-        return False\r
-    return True\r
-  rounds = 0\r
-  while not done_p():\r
-    if verbose:\r
-      print "-- round --"\r
-    arc = 1\r
-    while arc <= largest_arc:\r
-      if verbose:\r
-        print "-- subround --"\r
-      new_info = [x for x in info]\r
-      for peer_physical in xrange(n):\r
-        peer_logical = peers[peer_physical]\r
-        peer_type = None\r
-        partner_logical = (peer_logical + arc) % n\r
-        partner_physical = peers.index(partner_logical)\r
-        if peer_physical < k or partner_physical < k:\r
-          if verbose:\r
-            print "bad peer in connection", peer_physical, "--", partner_physical\r
-          continue\r
-        if peer_logical & arc == 0:\r
-          # we are outgoing\r
-          if verbose:\r
-            print peer_physical, "connects to", partner_physical\r
-          peer_type = "outgoing"\r
-          if peer_logical < num_ghosts:\r
-            # we have a ghost, check if the peer who connects\r
-            # to our ghost is actually outgoing\r
-            ghost_partner_logical = (peer_logical - arc) % n\r
-            if ghost_partner_logical & arc == 0:\r
-              peer_type = peer_type + ", ghost incoming"\r
-          new_info[peer_physical] = new_info[peer_physical] | info[peer_physical] | info[partner_physical]\r
-          new_info[partner_physical] = new_info[partner_physical] | info[peer_physical] | info[partner_physical]\r
-        else:\r
-          peer_type = "incoming"\r
-        if verbose > 1:\r
-          print "type of", str(peer_physical) + ":", peer_type\r
-      info = new_info\r
-      arc = arc << 1;\r
-    rounds = rounds + 1\r
-    random.shuffle(peers)\r
-  return rounds\r
-\r
-if __name__ == "__main__":\r
-  parser = argparse.ArgumentParser()\r
-  parser.add_argument("k", metavar="k", type=int, help="#(bad peers)")\r
-  parser.add_argument("n", metavar="n", type=int, help="#(all peers)")\r
-  parser.add_argument("r", metavar="r", type=int, help="#(rounds)")\r
-  parser.add_argument('--verbose', '-v', action='count')\r
-\r
-  args = parser.parse_args()\r
-  sum = 0.0;\r
-  for n in xrange (0, args.r):\r
-    sum += simulate(args.k, args.n, args.verbose)\r
-  print sum / args.r;\r
-\r
-\r
+#!/usr/bin/python
+# This file is part of GNUnet
+# (C) 2013 Christian Grothoff (and other contributing authors)
+#
+# GNUnet 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 2, or (at your
+# option) any later version.
+#
+# GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
+# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
+import argparse
+import random
+from math import ceil,log,floor
+
+def bsc(n):
+  """ count the bits set in n"""
+  l = n.bit_length()
+  c = 0
+  x = 1
+  for _ in range(0, l):
+    if n & x:
+      c = c + 1
+    x = x << 1
+  return c
+
+def simulate(k, n, verbose):
+  assert k < n
+  largest_arc = int(2**ceil(log(n, 2))) / 2
+  num_ghosts = (2 * largest_arc) - n
+  if verbose:
+    print "we have", num_ghosts, "ghost peers"
+  # n.b. all peers with idx<k are evil
+  peers = range(n)
+  info = [1 << x for x in xrange(n)]
+  def done_p():
+    for x in xrange(k, n):
+      if bsc(info[x]) < n-k:
+        return False
+    return True
+  rounds = 0
+  while not done_p():
+    if verbose:
+      print "-- round --"
+    arc = 1
+    while arc <= largest_arc:
+      if verbose:
+        print "-- subround --"
+      new_info = [x for x in info]
+      for peer_physical in xrange(n):
+        peer_logical = peers[peer_physical]
+        peer_type = None
+        partner_logical = (peer_logical + arc) % n
+        partner_physical = peers.index(partner_logical)
+        if peer_physical < k or partner_physical < k:
+          if verbose:
+            print "bad peer in connection", peer_physical, "--", partner_physical
+          continue
+        if peer_logical & arc == 0:
+          # we are outgoing
+          if verbose:
+            print peer_physical, "connects to", partner_physical
+          peer_type = "outgoing"
+          if peer_logical < num_ghosts:
+            # we have a ghost, check if the peer who connects
+            # to our ghost is actually outgoing
+            ghost_partner_logical = (peer_logical - arc) % n
+            if ghost_partner_logical & arc == 0:
+              peer_type = peer_type + ", ghost incoming"
+          new_info[peer_physical] = new_info[peer_physical] | info[peer_physical] | info[partner_physical]
+          new_info[partner_physical] = new_info[partner_physical] | info[peer_physical] | info[partner_physical]
+        else:
+          peer_type = "incoming"
+        if verbose > 1:
+          print "type of", str(peer_physical) + ":", peer_type
+      info = new_info
+      arc = arc << 1;
+    rounds = rounds + 1
+    random.shuffle(peers)
+  return rounds
+
+if __name__ == "__main__":
+  parser = argparse.ArgumentParser()
+  parser.add_argument("k", metavar="k", type=int, help="#(bad peers)")
+  parser.add_argument("n", metavar="n", type=int, help="#(all peers)")
+  parser.add_argument("r", metavar="r", type=int, help="#(rounds)")
+  parser.add_argument('--verbose', '-v', action='count')
+
+  args = parser.parse_args()
+  sum = 0.0;
+  for n in xrange (0, args.r):
+    sum += simulate(args.k, args.n, args.verbose)
+  print sum / args.r;
+
+
index e2f9a07833a181051dafdbff9159313e66601557..a8ff4265dbd0413614ba500565f7706ac674120f 100644 (file)
-# This Makefile.am is in the public domain\r
-AM_CPPFLAGS = -I$(top_srcdir)/src/include\r
-\r
-if MINGW\r
-  WINFLAGS = -Wl,--no-undefined -Wl,--export-all-symbols\r
-endif\r
-\r
-if USE_COVERAGE\r
-  AM_CFLAGS = --coverage -O0\r
-endif\r
-\r
-pkgcfgdir= $(pkgdatadir)/config.d/\r
-\r
-libexecdir= $(pkglibdir)/libexec/\r
-\r
-plugindir = $(libdir)/gnunet\r
-\r
-pkgcfg_DATA = \\r
-  dns.conf\r
-\r
-if LINUX\r
-HIJACKBIN = gnunet-helper-dns\r
-install-exec-hook:\r
-       $(top_srcdir)/src/dns/install-dns-helper.sh $(libexecdir) $(GNUNETDNS_GROUP) $(SUDO_BINARY) || true\r
-else\r
-install-exec-hook:\r
-endif\r
-\r
-lib_LTLIBRARIES = \\r
-  libgnunetdnsparser.la \\r
-  libgnunetdnsstub.la \\r
-  libgnunetdns.la\r
-\r
-libexec_PROGRAMS = \\r
-  gnunet-service-dns $(HIJACKBIN)\r
-\r
-noinst_PROGRAMS = \\r
-  gnunet-dns-monitor gnunet-dns-redirector\r
-\r
-plugin_LTLIBRARIES = \\r
-  libgnunet_plugin_block_dns.la\r
-\r
-if LINUX\r
-check_SCRIPTS = \\r
- test_gnunet_dns.sh\r
-endif\r
-\r
-check_PROGRAMS = \\r
- test_hexcoder\r
-\r
-gnunet_helper_dns_SOURCES = \\r
- gnunet-helper-dns.c\r
-\r
-\r
-gnunet_dns_monitor_SOURCES = \\r
- gnunet-dns-monitor.c\r
-gnunet_dns_monitor_LDADD = \\r
-  libgnunetdnsparser.la \\r
-  libgnunetdns.la \\r
-  $(top_builddir)/src/util/libgnunetutil.la \\r
-  $(GN_LIBINTL)\r
-\r
-gnunet_dns_redirector_SOURCES = \\r
- gnunet-dns-redirector.c\r
-gnunet_dns_redirector_LDADD = \\r
-  libgnunetdnsparser.la \\r
-  libgnunetdns.la \\r
-  $(top_builddir)/src/util/libgnunetutil.la \\r
-  $(GN_LIBINTL)\r
-\r
-gnunet_service_dns_SOURCES = \\r
- gnunet-service-dns.c\r
-gnunet_service_dns_LDADD = \\r
-  libgnunetdnsstub.la \\r
-  $(top_builddir)/src/tun/libgnunettun.la \\r
-  $(top_builddir)/src/statistics/libgnunetstatistics.la \\r
-  $(top_builddir)/src/util/libgnunetutil.la \\r
-  $(GN_LIBINTL)\r
-\r
-libgnunetdnsparser_la_SOURCES = \\r
- dnsparser.c\r
-libgnunetdnsparser_la_LIBADD = \\r
- $(top_builddir)/src/util/libgnunetutil.la $(XLIB) \\r
-  -lidn\r
-libgnunetdnsparser_la_LDFLAGS = \\r
-  $(GN_LIB_LDFLAGS) \\r
-  -version-info 1:0:1\r
-\r
-libgnunetdnsstub_la_SOURCES = \\r
- dnsstub.c\r
-libgnunetdnsstub_la_LIBADD = \\r
- $(top_builddir)/src/util/libgnunetutil.la $(XLIB)\r
-libgnunetdnsstub_la_LDFLAGS = \\r
-  $(GN_LIB_LDFLAGS) \\r
-  -version-info 0:0:0\r
-\r
-libgnunetdns_la_SOURCES = \\r
- dns_api.c dns.h\r
-libgnunetdns_la_LIBADD = \\r
- $(top_builddir)/src/util/libgnunetutil.la $(XLIB)\r
-libgnunetdns_la_LDFLAGS = \\r
-  $(GN_LIB_LDFLAGS) \\r
-  -version-info 0:0:0\r
-\r
-libgnunet_plugin_block_dns_la_SOURCES = \\r
-  plugin_block_dns.c\r
-libgnunet_plugin_block_dns_la_LIBADD = \\r
-  $(top_builddir)/src/util/libgnunetutil.la\r
-libgnunet_plugin_block_dns_la_LDFLAGS = \\r
-  $(top_builddir)/src/block/$(GN_PLUGIN_LDFLAGS)\r
-\r
-\r
-if ENABLE_TEST_RUN\r
-AM_TESTS_ENVIRONMENT=export GNUNET_PREFIX=$${GNUNET_PREFIX:-@libdir@};export PATH=$${GNUNET_PREFIX:-@prefix@}/bin:$$PATH;\r
-TESTS = $(check_PROGRAMS)  $(check_SCRIPTS)\r
-endif\r
-\r
-EXTRA_DIST = \\r
-  $(check_SCRIPTS)\r
-\r
-\r
-test_hexcoder_SOURCES = \\r
- test_hexcoder.c\r
-test_hexcoder_LDADD = \\r
- libgnunetdnsparser.la \\r
- $(top_builddir)/src/util/libgnunetutil.la\r
+# This Makefile.am is in the public domain
+AM_CPPFLAGS = -I$(top_srcdir)/src/include
+
+if MINGW
+  WINFLAGS = -Wl,--no-undefined -Wl,--export-all-symbols
+endif
+
+if USE_COVERAGE
+  AM_CFLAGS = --coverage -O0
+endif
+
+pkgcfgdir= $(pkgdatadir)/config.d/
+
+libexecdir= $(pkglibdir)/libexec/
+
+plugindir = $(libdir)/gnunet
+
+pkgcfg_DATA = \
+  dns.conf
+
+if LINUX
+HIJACKBIN = gnunet-helper-dns
+install-exec-hook:
+       $(top_srcdir)/src/dns/install-dns-helper.sh $(libexecdir) $(GNUNETDNS_GROUP) $(SUDO_BINARY) || true
+else
+install-exec-hook:
+endif
+
+lib_LTLIBRARIES = \
+  libgnunetdnsparser.la \
+  libgnunetdnsstub.la \
+  libgnunetdns.la
+
+libexec_PROGRAMS = \
+  gnunet-service-dns $(HIJACKBIN)
+
+noinst_PROGRAMS = \
+  gnunet-dns-monitor gnunet-dns-redirector
+
+plugin_LTLIBRARIES = \
+  libgnunet_plugin_block_dns.la
+
+if LINUX
+check_SCRIPTS = \
+ test_gnunet_dns.sh
+endif
+
+check_PROGRAMS = \
+ test_hexcoder
+
+gnunet_helper_dns_SOURCES = \
+ gnunet-helper-dns.c
+
+
+gnunet_dns_monitor_SOURCES = \
+ gnunet-dns-monitor.c
+gnunet_dns_monitor_LDADD = \
+  libgnunetdnsparser.la \
+  libgnunetdns.la \
+  $(top_builddir)/src/util/libgnunetutil.la \
+  $(GN_LIBINTL)
+
+gnunet_dns_redirector_SOURCES = \
+ gnunet-dns-redirector.c
+gnunet_dns_redirector_LDADD = \
+  libgnunetdnsparser.la \
+  libgnunetdns.la \
+  $(top_builddir)/src/util/libgnunetutil.la \
+  $(GN_LIBINTL)
+
+gnunet_service_dns_SOURCES = \
+ gnunet-service-dns.c
+gnunet_service_dns_LDADD = \
+  libgnunetdnsstub.la \
+  $(top_builddir)/src/tun/libgnunettun.la \
+  $(top_builddir)/src/statistics/libgnunetstatistics.la \
+  $(top_builddir)/src/util/libgnunetutil.la \
+  $(GN_LIBINTL)
+
+libgnunetdnsparser_la_SOURCES = \
+ dnsparser.c
+libgnunetdnsparser_la_LIBADD = \
+ $(top_builddir)/src/util/libgnunetutil.la $(XLIB) \
+  -lidn
+libgnunetdnsparser_la_LDFLAGS = \
+  $(GN_LIB_LDFLAGS) \
+  -version-info 1:0:1
+
+libgnunetdnsstub_la_SOURCES = \
+ dnsstub.c
+libgnunetdnsstub_la_LIBADD = \
+ $(top_builddir)/src/util/libgnunetutil.la $(XLIB)
+libgnunetdnsstub_la_LDFLAGS = \
+  $(GN_LIB_LDFLAGS) \
+  -version-info 0:0:0
+
+libgnunetdns_la_SOURCES = \
+ dns_api.c dns.h
+libgnunetdns_la_LIBADD = \
+ $(top_builddir)/src/util/libgnunetutil.la $(XLIB)
+libgnunetdns_la_LDFLAGS = \
+  $(GN_LIB_LDFLAGS) \
+  -version-info 0:0:0
+
+libgnunet_plugin_block_dns_la_SOURCES = \
+  plugin_block_dns.c
+libgnunet_plugin_block_dns_la_LIBADD = \
+  $(top_builddir)/src/util/libgnunetutil.la
+libgnunet_plugin_block_dns_la_LDFLAGS = \
+  $(top_builddir)/src/block/$(GN_PLUGIN_LDFLAGS)
+
+
+if ENABLE_TEST_RUN
+AM_TESTS_ENVIRONMENT=export GNUNET_PREFIX=$${GNUNET_PREFIX:-@libdir@};export PATH=$${GNUNET_PREFIX:-@prefix@}/bin:$$PATH;
+TESTS = $(check_PROGRAMS)  $(check_SCRIPTS)
+endif
+
+EXTRA_DIST = \
+  $(check_SCRIPTS)
+
+
+test_hexcoder_SOURCES = \
+ test_hexcoder.c
+test_hexcoder_LDADD = \
+ libgnunetdnsparser.la \
+ $(top_builddir)/src/util/libgnunetutil.la
index 9e5c83fa37e66aca3eda47f5abce6da1b4f868b4..3ca3c0a69c6f72704945efaa329ef55f536c689e 100644 (file)
@@ -1,83 +1,83 @@
-#!@PYTHON@\r
-#    This file is part of GNUnet.\r
-#    (C) 2010 Christian Grothoff (and other contributing authors)\r
-#\r
-#    GNUnet is free software; you can redistribute it and/or modify\r
-#    it under the terms of the GNU General Public License as published\r
-#    by the Free Software Foundation; either version 2, or (at your\r
-#    option) any later version.\r
-#\r
-#    GNUnet is distributed in the hope that it will be useful, but\r
-#    WITHOUT ANY WARRANTY; without even the implied warranty of\r
-#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-#    General Public License for more details.\r
-#\r
-#    You should have received a copy of the GNU General Public License\r
-#    along with GNUnet; see the file COPYING.  If not, write to the\r
-#    Free Software Foundation, Inc., 59 Temple Place - Suite 330,\r
-#    Boston, MA 02111-1307, USA.\r
-#\r
-# Testcase for gnunet-peerinfo\r
-from __future__ import print_function\r
-import os\r
-import re\r
-import subprocess\r
-import sys\r
-import shutil\r
-import time\r
-\r
-class pexpect (object):\r
-  def __init__ (self):\r
-    super (pexpect, self).__init__ ()\r
-\r
-  def spawn (self, stdin, arglist, *pargs, **kwargs):\r
-    env = kwargs.pop ('env', None)\r
-    if env is None:\r
-      env = os.environ.copy ()\r
-    # This messes up some testcases, disable log redirection\r
-    env.pop ('GNUNET_FORCE_LOGFILE', None)\r
-    self.proc = subprocess.Popen (arglist, *pargs, env=env, **kwargs)\r
-    if self.proc is None:\r
-      print ("Failed to spawn a process {0}".format (arglist))\r
-      sys.exit (1)\r
-    if stdin is not None:\r
-      self.stdo, self.stde = self.proc.communicate (stdin)\r
-    else:\r
-      self.stdo, self.stde = self.proc.communicate ()\r
-    return self.proc\r
-\r
-  def expect (self, s, r, flags=0):\r
-    stream = self.stdo if s == 'stdout' else self.stde\r
-    if isinstance (r, str):\r
-      if r == "EOF":\r
-        if len (stream) == 0:\r
-          return True\r
-        else:\r
-          print ("Failed to find `{1}' in {0}, which is `{2}' ({3})".format (s, r, stream, len (stream)))\r
-          sys.exit (2)\r
-      raise ValueError ("Argument `r' should be an instance of re.RegexObject or a special string, but is `{0}'".format (r))\r
-    m = r.search (stream, flags)\r
-    if not m:\r
-      print ("Failed to find `{1}' in {0}, which is is `{2}'".format (s, r.pattern, stream))\r
-      sys.exit (2)\r
-    stream = stream[m.end ():]\r
-    if s == 'stdout':\r
-      self.stdo = stream\r
-    else:\r
-      self.stde = stream\r
-    return m\r
-\r
-  def read (self, s, size=-1):\r
-    stream = self.stdo if s == 'stdout' else self.stde\r
-    result = ""\r
-    if size < 0:\r
-      result = stream\r
-      new_stream = ""\r
-    else:\r
-      result = stream[0:size]\r
-      new_stream = stream[size:]\r
-    if s == 'stdout':\r
-      self.stdo = new_stream\r
-    else:\r
-      self.stde = new_stream\r
-    return result\r
+#!@PYTHON@
+#    This file is part of GNUnet.
+#    (C) 2010 Christian Grothoff (and other contributing authors)
+#
+#    GNUnet 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 2, or (at your
+#    option) any later version.
+#
+#    GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
+#    Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+#    Boston, MA 02111-1307, USA.
+#
+# Testcase for gnunet-peerinfo
+from __future__ import print_function
+import os
+import re
+import subprocess
+import sys
+import shutil
+import time
+
+class pexpect (object):
+  def __init__ (self):
+    super (pexpect, self).__init__ ()
+
+  def spawn (self, stdin, arglist, *pargs, **kwargs):
+    env = kwargs.pop ('env', None)
+    if env is None:
+      env = os.environ.copy ()
+    # This messes up some testcases, disable log redirection
+    env.pop ('GNUNET_FORCE_LOGFILE', None)
+    self.proc = subprocess.Popen (arglist, *pargs, env=env, **kwargs)
+    if self.proc is None:
+      print ("Failed to spawn a process {0}".format (arglist))
+      sys.exit (1)
+    if stdin is not None:
+      self.stdo, self.stde = self.proc.communicate (stdin)
+    else:
+      self.stdo, self.stde = self.proc.communicate ()
+    return self.proc
+
+  def expect (self, s, r, flags=0):
+    stream = self.stdo if s == 'stdout' else self.stde
+    if isinstance (r, str):
+      if r == "EOF":
+        if len (stream) == 0:
+          return True
+        else:
+          print ("Failed to find `{1}' in {0}, which is `{2}' ({3})".format (s, r, stream, len (stream)))
+          sys.exit (2)
+      raise ValueError ("Argument `r' should be an instance of re.RegexObject or a special string, but is `{0}'".format (r))
+    m = r.search (stream, flags)
+    if not m:
+      print ("Failed to find `{1}' in {0}, which is is `{2}'".format (s, r.pattern, stream))
+      sys.exit (2)
+    stream = stream[m.end ():]
+    if s == 'stdout':
+      self.stdo = stream
+    else:
+      self.stde = stream
+    return m
+
+  def read (self, s, size=-1):
+    stream = self.stdo if s == 'stdout' else self.stde
+    result = ""
+    if size < 0:
+      result = stream
+      new_stream = ""
+    else:
+      result = stream[0:size]
+      new_stream = stream[size:]
+    if s == 'stdout':
+      self.stdo = new_stream
+    else:
+      self.stde = new_stream
+    return result
index adb485e99cce5c43435f4673eef2633b27da151b..8448f7f853d5ed6973249abb5cf238ffd825acf4 100644 (file)
-/*\r
-     This file is part of GNUnet.\r
-     Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)\r
-\r
-     GNUnet is free software; you can redistribute it and/or modify\r
-     it under the terms of the GNU General Public License as published\r
-     by the Free Software Foundation; either version 3, or (at your\r
-     option) any later version.\r
-\r
-     GNUnet is distributed in the hope that it will be useful, but\r
-     WITHOUT ANY WARRANTY; without even the implied warranty of\r
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-     General Public License for more details.\r
-\r
-     You should have received a copy of the GNU General Public License\r
-     along with GNUnet; see the file COPYING.  If not, write to the\r
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,\r
-     Boston, MA 02111-1307, USA.\r
-*/\r
-\r
-/**\r
- * Testcase for STUN server resolution\r
- *\r
- * @file nat/test_stun.c\r
- * @brief Testcase for STUN library\r
- * @author Bruno Souza Cabral\r
- * @autor Mark Spencer (Original code borrowed from Asterisk)\r
- *\r
- */\r
-\r
-\r
-#include "platform.h"\r
-#include "gnunet_util_lib.h"\r
-#include "gnunet_program_lib.h"\r
-#include "gnunet_scheduler_lib.h"\r
-#include "gnunet_nat_lib.h"\r
-\r
-\r
-#include "test_stun.h"\r
-\r
-\r
-/**\r
- * The port the test service is running on (default 7895)\r
- */\r
-static unsigned long port = 7895;\r
-\r
-static int ret = 1;\r
-\r
-/**\r
- * The listen socket of the service for IPv4\r
- */\r
-static struct GNUNET_NETWORK_Handle *lsock4;\r
-\r
-\r
-/**\r
- * The listen task ID for IPv4\r
- */\r
-static struct GNUNET_SCHEDULER_Task * ltask4;\r
-\r
-\r
-static char *stun_server = STUN_SERVER;\r
-static int stun_port = STUN_PORT;\r
-\r
-static int stun_debug = 1;\r
-\r
-\r
-struct stun_strings {\r
-    const int value;\r
-    const char *name;\r
-};\r
-\r
-\r
-static inline int stun_msg2class(int msg)\r
-{\r
-    return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);\r
-}\r
-\r
-static inline int stun_msg2method(int msg)\r
-{\r
-    return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);\r
-}\r
-\r
-static inline int stun_msg2type(int class, int method)\r
-{\r
-    return ((class & 1) << 4) | ((class & 2) << 7) |\r
-            (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);\r
-}\r
-\r
-/* helper function to print message names */\r
-static const char *stun_msg2str(int msg)\r
-{\r
-    static const struct stun_strings classes[] = {\r
-    { STUN_REQUEST, "Request" },\r
-    { STUN_INDICATION, "Indication" },\r
-    { STUN_RESPONSE, "Response" },\r
-    { STUN_ERROR_RESPONSE, "Error Response" },\r
-    { 0, NULL }\r
-};\r
-    static const struct stun_strings methods[] = {\r
-    { STUN_BINDING, "Binding" },\r
-    { 0, NULL }\r
-};\r
-    static char result[32];\r
-    const char *class = NULL, *method = NULL;\r
-    int i, value;\r
-\r
-    value = stun_msg2class(msg);\r
-    for (i = 0; classes[i].name; i++) {\r
-        class = classes[i].name;\r
-        if (classes[i].value == value)\r
-            break;\r
-    }\r
-    value = stun_msg2method(msg);\r
-    for (i = 0; methods[i].name; i++) {\r
-        method = methods[i].name;\r
-        if (methods[i].value == value)\r
-            break;\r
-    }\r
-    snprintf(result, sizeof(result), "%s %s",\r
-             method ? : "Unknown Method",\r
-             class ? : "Unknown Class Message");\r
-    return result;\r
-}\r
-\r
-/* helper function to print attribute names */\r
-static const char *stun_attr2str(int msg)\r
-{\r
-    static const struct stun_strings attrs[] = {\r
-    { STUN_MAPPED_ADDRESS, "Mapped Address" },\r
-    { STUN_RESPONSE_ADDRESS, "Response Address" },\r
-    { STUN_CHANGE_ADDRESS, "Change Address" },\r
-    { STUN_SOURCE_ADDRESS, "Source Address" },\r
-    { STUN_CHANGED_ADDRESS, "Changed Address" },\r
-    { STUN_USERNAME, "Username" },\r
-    { STUN_PASSWORD, "Password" },\r
-    { STUN_MESSAGE_INTEGRITY, "Message Integrity" },\r
-    { STUN_ERROR_CODE, "Error Code" },\r
-    { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },\r
-    { STUN_REFLECTED_FROM, "Reflected From" },\r
-    { STUN_REALM, "Realm" },\r
-    { STUN_NONCE, "Nonce" },\r
-    { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },\r
-    { STUN_MS_VERSION, "MS Version" },\r
-    { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },\r
-    { STUN_SOFTWARE, "Software" },\r
-    { STUN_ALTERNATE_SERVER, "Alternate Server" },\r
-    { STUN_FINGERPRINT, "Fingerprint" },\r
-    { 0, NULL }\r
-};\r
-    int i;\r
-\r
-    for (i = 0; attrs[i].name; i++) {\r
-        if (attrs[i].value == msg)\r
-            return attrs[i].name;\r
-    }\r
-    return "Unknown Attribute";\r
-}\r
-\r
-/* here we store credentials extracted from a message */\r
-struct stun_state {\r
-    unsigned short attr;\r
-};\r
-\r
-static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)\r
-{\r
-    if (stun_debug)\r
-        fprintf(stderr, "Found STUN Attribute %s (%04x), length %d\n",\r
-                stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));\r
-    switch (ntohs(attr->attr)) {\r
-    case STUN_MAPPED_ADDRESS:\r
-    case STUN_XOR_MAPPED_ADDRESS:\r
-    case STUN_MS_XOR_MAPPED_ADDRESS:\r
-        break;\r
-    default:\r
-        if (stun_debug)\r
-            fprintf(stderr, "Ignoring STUN Attribute %s (%04x), length %d\n",\r
-                    stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));\r
-    }\r
-    return 0;\r
-}\r
-\r
-/* append a string to an STUN message */\r
-static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)\r
-{\r
-    int str_length = strlen(s);\r
-    int attr_length = str_length + ((~(str_length - 1)) & 0x3);\r
-    int size = sizeof(**attr) + attr_length;\r
-    if (*left > size) {\r
-        (*attr)->attr = htons(attrval);\r
-        (*attr)->len = htons(attr_length);\r
-        memcpy((*attr)->value, s, str_length);\r
-        memset((*attr)->value + str_length, 0, attr_length - str_length);\r
-        (*attr) = (struct stun_attr *)((*attr)->value + attr_length);\r
-        *len += size;\r
-        *left -= size;\r
-    }\r
-}\r
-\r
-\r
-/* helper function to generate a random request id */\r
-static void stun_req_id(struct stun_header *req)\r
-{\r
-    int x;\r
-    srand(time(0));\r
-    req->magic = htonl(STUN_MAGIC_COOKIE);\r
-    for (x = 0; x < 3; x++)\r
-        req->id.id[x] = rand();\r
-}\r
-\r
-/* callback type to be invoked on stun responses. */\r
-typedef int (stun_cb_f)(struct stun_state *st, struct stun_attr *attr, void *arg, unsigned int magic);\r
-\r
-/* handle an incoming STUN message.\r
- *\r
- * Do some basic sanity checks on packet size and content,\r
- * try to extract a bit of information, and possibly reply.\r
- * At the moment this only processes BIND requests, and returns\r
- * the externally visible address of the request.\r
- * If a callback is specified, invoke it with the attribute.\r
- */\r
-static int stun_handle_packet(unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)\r
-{\r
-    struct stun_header *hdr = (struct stun_header *)data;\r
-    struct stun_attr *attr;\r
-    struct stun_state st;\r
-    int ret = STUN_IGNORE;\r
-    int x;\r
-\r
-    /* On entry, 'len' is the length of the udp payload. After the\r
-         * initial checks it becomes the size of unprocessed options,\r
-         * while 'data' is advanced accordingly.\r
-         */\r
-    if (len < sizeof(struct stun_header)) {\r
-        fprintf(stderr, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));\r
-        return -1;\r
-    }\r
-    len -= sizeof(struct stun_header);\r
-    data += sizeof(struct stun_header);\r
-    x = ntohs(hdr->msglen);    /* len as advertised in the message */\r
-    if (stun_debug)\r
-        fprintf(stderr, "STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);\r
-    if (x > len) {\r
-        fprintf(stderr, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);\r
-    } else\r
-        len = x;\r
-    memset(&st,0, sizeof(st));\r
-\r
-    while (len) {\r
-        if (len < sizeof(struct stun_attr)) {\r
-            fprintf(stderr, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));\r
-            break;\r
-        }\r
-        attr = (struct stun_attr *)data;\r
-\r
-        /* compute total attribute length */\r
-        x = ntohs(attr->len) + sizeof(struct stun_attr);\r
-        if (x > len) {\r
-            fprintf(stderr, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);\r
-            break;\r
-        }\r
-        if (stun_cb)\r
-            stun_cb(&st, attr, arg, hdr->magic);\r
-        if (stun_process_attr(&st, attr)) {\r
-            fprintf(stderr, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));\r
-            break;\r
-        }\r
-        /* Clear attribute id: in case previous entry was a string,\r
-                 * this will act as the terminator for the string.\r
-                 */\r
-        attr->attr = 0;\r
-        data += x;\r
-        len -= x;\r
-    }\r
-    /* Null terminate any string.\r
-         * XXX NOTE, we write past the size of the buffer passed by the\r
-         * caller, so this is potentially dangerous. The only thing that\r
-         * saves us is that usually we read the incoming message in a\r
-         * much larger buffer\r
-         */\r
-    *data = '\0';\r
-\r
-    return ret;\r
-}\r
-\r
-/* Extract the STUN_MAPPED_ADDRESS from the stun response.\r
- * This is used as a callback for stun_handle_response\r
- * when called from stun_request.\r
- */\r
-static int stun_get_mapped(struct stun_state *st, struct stun_attr *attr, void *arg, unsigned int magic)\r
-{\r
-    struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);\r
-    struct sockaddr_in *sa = (struct sockaddr_in *)arg;\r
-    unsigned short type = ntohs(attr->attr);\r
-\r
-    switch (type) {\r
-    case STUN_MAPPED_ADDRESS:\r
-        if (st->attr == STUN_XOR_MAPPED_ADDRESS ||\r
-                st->attr == STUN_MS_XOR_MAPPED_ADDRESS)\r
-            return 1;\r
-        magic = 0;\r
-        break;\r
-    case STUN_MS_XOR_MAPPED_ADDRESS:\r
-        if (st->attr == STUN_XOR_MAPPED_ADDRESS)\r
-            return 1;\r
-        break;\r
-    case STUN_XOR_MAPPED_ADDRESS:\r
-        break;\r
-    default:\r
-        return 1;\r
-    }\r
-    if (ntohs(attr->len) < 8 && returned_addr->family != 1)\r
-        return 1;\r
-\r
-    st->attr = type;\r
-    sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);\r
-    sa->sin_addr.s_addr = returned_addr->addr ^ magic;\r
-    return 0;\r
-}\r
-\r
-/* Generic STUN request\r
- * Send a generic stun request to the server specified,\r
- * possibly waiting for a reply and filling the 'reply' field with\r
- * the externally visible address. \r
\r
- * \param s the socket used to send the request\r
- * \return 0 on success, other values on error.\r
- */\r
-int stun_request(struct GNUNET_NETWORK_Handle * sock)\r
-{\r
-    struct stun_header *req;\r
-    unsigned char reqdata[1024];\r
-    int reqlen, reqleft;\r
-    struct stun_attr *attr;\r
-\r
-\r
-       \r
-       \r
-       struct sockaddr_in server;\r
-       struct hostent *hostinfo = gethostbyname(stun_server);\r
-       if (!hostinfo) {\r
-               fprintf(stderr, "Error resolving host %s\n", stun_server);\r
-               return -1;\r
-       }\r
-       memset(&server,0, sizeof(server));\r
-       server.sin_family = AF_INET;\r
-       server.sin_addr = *(struct in_addr*) hostinfo->h_addr;\r
-       server.sin_port = htons(stun_port);\r
-       \r
-       \r
-\r
-    req = (struct stun_header *)reqdata;\r
-    stun_req_id(req);\r
-    reqlen = 0;\r
-    reqleft = sizeof(reqdata) - sizeof(struct stun_header);\r
-    req->msgtype = 0;\r
-    req->msglen = 0;\r
-    attr = (struct stun_attr *)req->ies;\r
-\r
-    append_attr_string(&attr, STUN_SOFTWARE, PACKAGE " v" VERSION_PACKAGE, &reqlen, &reqleft);\r
-    req->msglen = htons(reqlen);\r
-    req->msgtype = htons(stun_msg2type(STUN_REQUEST, STUN_BINDING));\r
-\r
-\r
-       if (-1 == GNUNET_NETWORK_socket_sendto (sock, req, ntohs(req->msglen) + sizeof(*req),\r
-                                    (const struct sockaddr *) &server, sizeof (server)))\r
-       {\r
-               GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");\r
-       }\r
-\r
-    return -1;\r
-}\r
-\r
-static void print_answer(struct sockaddr_in* answer)\r
-{\r
-       printf("External IP is: %s , with port %d\n", inet_ntoa(answer->sin_addr), ntohs(answer->sin_port));\r
-}\r
-\r
-\r
-/**\r
- * Activity on our incoming socket.  Read data from the\r
- * incoming connection.\r
- *\r
- * @param cls \r
- * @param tc scheduler context\r
- */\r
-static void\r
-do_udp_read (void *cls,\r
-             const struct GNUNET_SCHEDULER_TaskContext *tc)\r
-{\r
-    //struct GNUNET_NAT_Test *tst = cls;\r
-       unsigned char reply_buf[1024];\r
-       ssize_t rlen;\r
-       struct sockaddr_in answer;\r
-\r
-\r
-    if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&\r
-      (GNUNET_NETWORK_fdset_isset (tc->read_ready,\r
-                                   lsock4)))\r
-       {\r
-               rlen = GNUNET_NETWORK_socket_recv (lsock4, reply_buf, sizeof (reply_buf));\r
-               printf("Recivied something of size %d", rlen);\r
-               \r
-               //Lets handle the packet\r
-               memset(&answer, 0, sizeof(struct sockaddr_in));\r
-        stun_handle_packet(reply_buf, rlen, stun_get_mapped, &answer);\r
-               //Print the anser\r
-               //TODO: Delete the object\r
-               ret = 0;\r
-               print_answer(&answer);\r
-               \r
-               \r
-       }\r
-}\r
-\r
-\r
-/**\r
- * Create an IPv4 listen socket bound to our port.\r
- *\r
- * @return NULL on error\r
- */\r
-static struct GNUNET_NETWORK_Handle *\r
-        bind_v4 ()\r
-{\r
-    struct GNUNET_NETWORK_Handle *ls;\r
-    struct sockaddr_in sa4;\r
-    int eno;\r
-\r
-    memset (&sa4, 0, sizeof (sa4));\r
-    sa4.sin_family = AF_INET;\r
-    sa4.sin_port = htons (port);\r
-#if HAVE_SOCKADDR_IN_SIN_LEN\r
-    sa4.sin_len = sizeof (sa4);\r
-#endif \r
-    ls = GNUNET_NETWORK_socket_create (AF_INET,\r
-                                       SOCK_DGRAM,\r
-                                       0);\r
-    if (NULL == ls)\r
-        return NULL;\r
-    if (GNUNET_OK !=\r
-            GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,\r
-                                        sizeof (sa4)))\r
-    {\r
-        eno = errno;\r
-        GNUNET_NETWORK_socket_close (ls);\r
-        errno = eno;\r
-        return NULL;\r
-    }\r
-    return ls;\r
-}\r
-\r
-\r
-\r
-/**\r
- * Main function run with scheduler.\r
- */\r
-\r
-\r
-static void\r
-run (void *cls, char *const *args, const char *cfgfile,\r
-     const struct GNUNET_CONFIGURATION_Handle *cfg)\r
-{\r
-\r
-\r
-    //Lets create the socket\r
-    lsock4 = bind_v4 ();\r
-    if (NULL == lsock4)\r
-    {\r
-        GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");\r
-    }\r
-    else\r
-    {\r
-               printf("Binded, now will call add_read\n");\r
-        //Lets call our function now when it accepts\r
-        ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,\r
-                                                lsock4, &do_udp_read, NULL);\r
-\r
-    }\r
-    if(NULL == lsock4 )\r
-    {\r
-        GNUNET_SCHEDULER_shutdown ();\r
-        return;\r
-    }\r
-    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,\r
-                "Service listens on port %u\n",\r
-                port);\r
-       printf("Start main event\n");\r
-       stun_request(lsock4);\r
-    //Main event\r
-    //main_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);\r
-\r
-}\r
-\r
-\r
-int\r
-main (int argc, char *const argv[])\r
-{\r
-    struct GNUNET_GETOPT_CommandLineOption options[] = {\r
-        GNUNET_GETOPT_OPTION_END\r
-    };\r
-\r
-    char *const argv_prog[] = {\r
-        "test-stun",\r
-        NULL\r
-    };\r
-    GNUNET_log_setup ("test-stun",\r
-                      "WARNING",\r
-                      NULL);\r
-\r
-    GNUNET_PROGRAM_run (1, argv_prog, "test-stun", "nohelp", options, &run, NULL);\r
-    \r
-       return ret;\r
-}\r
-\r
-/* end of test_nat.c */\r
+/*
+     This file is part of GNUnet.
+     Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)
+
+     GNUnet 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, or (at your
+     option) any later version.
+
+     GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+     Boston, MA 02111-1307, USA.
+*/
+
+/**
+ * Testcase for STUN server resolution
+ *
+ * @file nat/test_stun.c
+ * @brief Testcase for STUN library
+ * @author Bruno Souza Cabral
+ * @autor Mark Spencer (Original code borrowed from Asterisk)
+ *
+ */
+
+
+#include "platform.h"
+#include "gnunet_util_lib.h"
+#include "gnunet_program_lib.h"
+#include "gnunet_scheduler_lib.h"
+#include "gnunet_nat_lib.h"
+
+
+#include "test_stun.h"
+
+
+/**
+ * The port the test service is running on (default 7895)
+ */
+static unsigned long port = 7895;
+
+static int ret = 1;
+
+/**
+ * The listen socket of the service for IPv4
+ */
+static struct GNUNET_NETWORK_Handle *lsock4;
+
+
+/**
+ * The listen task ID for IPv4
+ */
+static struct GNUNET_SCHEDULER_Task * ltask4;
+
+
+static char *stun_server = STUN_SERVER;
+static int stun_port = STUN_PORT;
+
+static int stun_debug = 1;
+
+
+struct stun_strings {
+    const int value;
+    const char *name;
+};
+
+
+static inline int stun_msg2class(int msg)
+{
+    return ((msg & 0x0010) >> 4) | ((msg & 0x0100) >> 7);
+}
+
+static inline int stun_msg2method(int msg)
+{
+    return (msg & 0x000f) | ((msg & 0x00e0) >> 1) | ((msg & 0x3e00) >> 2);
+}
+
+static inline int stun_msg2type(int class, int method)
+{
+    return ((class & 1) << 4) | ((class & 2) << 7) |
+            (method & 0x000f) | ((method & 0x0070) << 1) | ((method & 0x0f800) << 2);
+}
+
+/* helper function to print message names */
+static const char *stun_msg2str(int msg)
+{
+    static const struct stun_strings classes[] = {
+    { STUN_REQUEST, "Request" },
+    { STUN_INDICATION, "Indication" },
+    { STUN_RESPONSE, "Response" },
+    { STUN_ERROR_RESPONSE, "Error Response" },
+    { 0, NULL }
+};
+    static const struct stun_strings methods[] = {
+    { STUN_BINDING, "Binding" },
+    { 0, NULL }
+};
+    static char result[32];
+    const char *class = NULL, *method = NULL;
+    int i, value;
+
+    value = stun_msg2class(msg);
+    for (i = 0; classes[i].name; i++) {
+        class = classes[i].name;
+        if (classes[i].value == value)
+            break;
+    }
+    value = stun_msg2method(msg);
+    for (i = 0; methods[i].name; i++) {
+        method = methods[i].name;
+        if (methods[i].value == value)
+            break;
+    }
+    snprintf(result, sizeof(result), "%s %s",
+             method ? : "Unknown Method",
+             class ? : "Unknown Class Message");
+    return result;
+}
+
+/* helper function to print attribute names */
+static const char *stun_attr2str(int msg)
+{
+    static const struct stun_strings attrs[] = {
+    { STUN_MAPPED_ADDRESS, "Mapped Address" },
+    { STUN_RESPONSE_ADDRESS, "Response Address" },
+    { STUN_CHANGE_ADDRESS, "Change Address" },
+    { STUN_SOURCE_ADDRESS, "Source Address" },
+    { STUN_CHANGED_ADDRESS, "Changed Address" },
+    { STUN_USERNAME, "Username" },
+    { STUN_PASSWORD, "Password" },
+    { STUN_MESSAGE_INTEGRITY, "Message Integrity" },
+    { STUN_ERROR_CODE, "Error Code" },
+    { STUN_UNKNOWN_ATTRIBUTES, "Unknown Attributes" },
+    { STUN_REFLECTED_FROM, "Reflected From" },
+    { STUN_REALM, "Realm" },
+    { STUN_NONCE, "Nonce" },
+    { STUN_XOR_MAPPED_ADDRESS, "XOR Mapped Address" },
+    { STUN_MS_VERSION, "MS Version" },
+    { STUN_MS_XOR_MAPPED_ADDRESS, "MS XOR Mapped Address" },
+    { STUN_SOFTWARE, "Software" },
+    { STUN_ALTERNATE_SERVER, "Alternate Server" },
+    { STUN_FINGERPRINT, "Fingerprint" },
+    { 0, NULL }
+};
+    int i;
+
+    for (i = 0; attrs[i].name; i++) {
+        if (attrs[i].value == msg)
+            return attrs[i].name;
+    }
+    return "Unknown Attribute";
+}
+
+/* here we store credentials extracted from a message */
+struct stun_state {
+    unsigned short attr;
+};
+
+static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
+{
+    if (stun_debug)
+        fprintf(stderr, "Found STUN Attribute %s (%04x), length %d\n",
+                stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
+    switch (ntohs(attr->attr)) {
+    case STUN_MAPPED_ADDRESS:
+    case STUN_XOR_MAPPED_ADDRESS:
+    case STUN_MS_XOR_MAPPED_ADDRESS:
+        break;
+    default:
+        if (stun_debug)
+            fprintf(stderr, "Ignoring STUN Attribute %s (%04x), length %d\n",
+                    stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
+    }
+    return 0;
+}
+
+/* append a string to an STUN message */
+static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
+{
+    int str_length = strlen(s);
+    int attr_length = str_length + ((~(str_length - 1)) & 0x3);
+    int size = sizeof(**attr) + attr_length;
+    if (*left > size) {
+        (*attr)->attr = htons(attrval);
+        (*attr)->len = htons(attr_length);
+        memcpy((*attr)->value, s, str_length);
+        memset((*attr)->value + str_length, 0, attr_length - str_length);
+        (*attr) = (struct stun_attr *)((*attr)->value + attr_length);
+        *len += size;
+        *left -= size;
+    }
+}
+
+
+/* helper function to generate a random request id */
+static void stun_req_id(struct stun_header *req)
+{
+    int x;
+    srand(time(0));
+    req->magic = htonl(STUN_MAGIC_COOKIE);
+    for (x = 0; x < 3; x++)
+        req->id.id[x] = rand();
+}
+
+/* callback type to be invoked on stun responses. */
+typedef int (stun_cb_f)(struct stun_state *st, struct stun_attr *attr, void *arg, unsigned int magic);
+
+/* handle an incoming STUN message.
+ *
+ * Do some basic sanity checks on packet size and content,
+ * try to extract a bit of information, and possibly reply.
+ * At the moment this only processes BIND requests, and returns
+ * the externally visible address of the request.
+ * If a callback is specified, invoke it with the attribute.
+ */
+static int stun_handle_packet(unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
+{
+    struct stun_header *hdr = (struct stun_header *)data;
+    struct stun_attr *attr;
+    struct stun_state st;
+    int ret = STUN_IGNORE;
+    int x;
+
+    /* On entry, 'len' is the length of the udp payload. After the
+         * initial checks it becomes the size of unprocessed options,
+         * while 'data' is advanced accordingly.
+         */
+    if (len < sizeof(struct stun_header)) {
+        fprintf(stderr, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
+        return -1;
+    }
+    len -= sizeof(struct stun_header);
+    data += sizeof(struct stun_header);
+    x = ntohs(hdr->msglen);    /* len as advertised in the message */
+    if (stun_debug)
+        fprintf(stderr, "STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
+    if (x > len) {
+        fprintf(stderr, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
+    } else
+        len = x;
+    memset(&st,0, sizeof(st));
+
+    while (len) {
+        if (len < sizeof(struct stun_attr)) {
+            fprintf(stderr, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
+            break;
+        }
+        attr = (struct stun_attr *)data;
+
+        /* compute total attribute length */
+        x = ntohs(attr->len) + sizeof(struct stun_attr);
+        if (x > len) {
+            fprintf(stderr, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
+            break;
+        }
+        if (stun_cb)
+            stun_cb(&st, attr, arg, hdr->magic);
+        if (stun_process_attr(&st, attr)) {
+            fprintf(stderr, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
+            break;
+        }
+        /* Clear attribute id: in case previous entry was a string,
+                 * this will act as the terminator for the string.
+                 */
+        attr->attr = 0;
+        data += x;
+        len -= x;
+    }
+    /* Null terminate any string.
+         * XXX NOTE, we write past the size of the buffer passed by the
+         * caller, so this is potentially dangerous. The only thing that
+         * saves us is that usually we read the incoming message in a
+         * much larger buffer
+         */
+    *data = '\0';
+
+    return ret;
+}
+
+/* Extract the STUN_MAPPED_ADDRESS from the stun response.
+ * This is used as a callback for stun_handle_response
+ * when called from stun_request.
+ */
+static int stun_get_mapped(struct stun_state *st, struct stun_attr *attr, void *arg, unsigned int magic)
+{
+    struct stun_addr *returned_addr = (struct stun_addr *)(attr + 1);
+    struct sockaddr_in *sa = (struct sockaddr_in *)arg;
+    unsigned short type = ntohs(attr->attr);
+
+    switch (type) {
+    case STUN_MAPPED_ADDRESS:
+        if (st->attr == STUN_XOR_MAPPED_ADDRESS ||
+                st->attr == STUN_MS_XOR_MAPPED_ADDRESS)
+            return 1;
+        magic = 0;
+        break;
+    case STUN_MS_XOR_MAPPED_ADDRESS:
+        if (st->attr == STUN_XOR_MAPPED_ADDRESS)
+            return 1;
+        break;
+    case STUN_XOR_MAPPED_ADDRESS:
+        break;
+    default:
+        return 1;
+    }
+    if (ntohs(attr->len) < 8 && returned_addr->family != 1)
+        return 1;
+
+    st->attr = type;
+    sa->sin_port = returned_addr->port ^ htons(ntohl(magic) >> 16);
+    sa->sin_addr.s_addr = returned_addr->addr ^ magic;
+    return 0;
+}
+
+/* Generic STUN request
+ * Send a generic stun request to the server specified,
+ * possibly waiting for a reply and filling the 'reply' field with
+ * the externally visible address. 
+ * \param s the socket used to send the request
+ * \return 0 on success, other values on error.
+ */
+int stun_request(struct GNUNET_NETWORK_Handle * sock)
+{
+    struct stun_header *req;
+    unsigned char reqdata[1024];
+    int reqlen, reqleft;
+    struct stun_attr *attr;
+
+
+       
+       
+       struct sockaddr_in server;
+       struct hostent *hostinfo = gethostbyname(stun_server);
+       if (!hostinfo) {
+               fprintf(stderr, "Error resolving host %s\n", stun_server);
+               return -1;
+       }
+       memset(&server,0, sizeof(server));
+       server.sin_family = AF_INET;
+       server.sin_addr = *(struct in_addr*) hostinfo->h_addr;
+       server.sin_port = htons(stun_port);
+       
+       
+
+    req = (struct stun_header *)reqdata;
+    stun_req_id(req);
+    reqlen = 0;
+    reqleft = sizeof(reqdata) - sizeof(struct stun_header);
+    req->msgtype = 0;
+    req->msglen = 0;
+    attr = (struct stun_attr *)req->ies;
+
+    append_attr_string(&attr, STUN_SOFTWARE, PACKAGE " v" VERSION_PACKAGE, &reqlen, &reqleft);
+    req->msglen = htons(reqlen);
+    req->msgtype = htons(stun_msg2type(STUN_REQUEST, STUN_BINDING));
+
+
+       if (-1 == GNUNET_NETWORK_socket_sendto (sock, req, ntohs(req->msglen) + sizeof(*req),
+                                    (const struct sockaddr *) &server, sizeof (server)))
+       {
+               GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "sendto");
+       }
+
+    return -1;
+}
+
+static void print_answer(struct sockaddr_in* answer)
+{
+       printf("External IP is: %s , with port %d\n", inet_ntoa(answer->sin_addr), ntohs(answer->sin_port));
+}
+
+
+/**
+ * Activity on our incoming socket.  Read data from the
+ * incoming connection.
+ *
+ * @param cls 
+ * @param tc scheduler context
+ */
+static void
+do_udp_read (void *cls,
+             const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+    //struct GNUNET_NAT_Test *tst = cls;
+       unsigned char reply_buf[1024];
+       ssize_t rlen;
+       struct sockaddr_in answer;
+
+
+    if ((0 != (tc->reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
+      (GNUNET_NETWORK_fdset_isset (tc->read_ready,
+                                   lsock4)))
+       {
+               rlen = GNUNET_NETWORK_socket_recv (lsock4, reply_buf, sizeof (reply_buf));
+               printf("Recivied something of size %d", rlen);
+               
+               //Lets handle the packet
+               memset(&answer, 0, sizeof(struct sockaddr_in));
+        stun_handle_packet(reply_buf, rlen, stun_get_mapped, &answer);
+               //Print the anser
+               //TODO: Delete the object
+               ret = 0;
+               print_answer(&answer);
+               
+               
+       }
+}
+
+
+/**
+ * Create an IPv4 listen socket bound to our port.
+ *
+ * @return NULL on error
+ */
+static struct GNUNET_NETWORK_Handle *
+        bind_v4 ()
+{
+    struct GNUNET_NETWORK_Handle *ls;
+    struct sockaddr_in sa4;
+    int eno;
+
+    memset (&sa4, 0, sizeof (sa4));
+    sa4.sin_family = AF_INET;
+    sa4.sin_port = htons (port);
+#if HAVE_SOCKADDR_IN_SIN_LEN
+    sa4.sin_len = sizeof (sa4);
+#endif 
+    ls = GNUNET_NETWORK_socket_create (AF_INET,
+                                       SOCK_DGRAM,
+                                       0);
+    if (NULL == ls)
+        return NULL;
+    if (GNUNET_OK !=
+            GNUNET_NETWORK_socket_bind (ls, (const struct sockaddr *) &sa4,
+                                        sizeof (sa4)))
+    {
+        eno = errno;
+        GNUNET_NETWORK_socket_close (ls);
+        errno = eno;
+        return NULL;
+    }
+    return ls;
+}
+
+
+
+/**
+ * Main function run with scheduler.
+ */
+
+
+static void
+run (void *cls, char *const *args, const char *cfgfile,
+     const struct GNUNET_CONFIGURATION_Handle *cfg)
+{
+
+
+    //Lets create the socket
+    lsock4 = bind_v4 ();
+    if (NULL == lsock4)
+    {
+        GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
+    }
+    else
+    {
+               printf("Binded, now will call add_read\n");
+        //Lets call our function now when it accepts
+        ltask4 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL,
+                                                lsock4, &do_udp_read, NULL);
+
+    }
+    if(NULL == lsock4 )
+    {
+        GNUNET_SCHEDULER_shutdown ();
+        return;
+    }
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+                "Service listens on port %u\n",
+                port);
+       printf("Start main event\n");
+       stun_request(lsock4);
+    //Main event
+    //main_task = GNUNET_SCHEDULER_add_delayed (timeout, &do_timeout, nh);
+
+}
+
+
+int
+main (int argc, char *const argv[])
+{
+    struct GNUNET_GETOPT_CommandLineOption options[] = {
+        GNUNET_GETOPT_OPTION_END
+    };
+
+    char *const argv_prog[] = {
+        "test-stun",
+        NULL
+    };
+    GNUNET_log_setup ("test-stun",
+                      "WARNING",
+                      NULL);
+
+    GNUNET_PROGRAM_run (1, argv_prog, "test-stun", "nohelp", options, &run, NULL);
+    
+       return ret;
+}
+
+/* end of test_nat.c */
index 0e049d3a2eb24365105b497a6309c8190f429ac9..9beae6f795ff1539552c1ef5c14506d441bc5697 100644 (file)
-/*\r
-     This file is part of GNUnet.\r
-     Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)\r
-\r
-     GNUnet is free software; you can redistribute it and/or modify\r
-     it under the terms of the GNU General Public License as published\r
-     by the Free Software Foundation; either version 3, or (at your\r
-     option) any later version.\r
-\r
-     GNUnet is distributed in the hope that it will be useful, but\r
-     WITHOUT ANY WARRANTY; without even the implied warranty of\r
-     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
-     General Public License for more details.\r
-\r
-     You should have received a copy of the GNU General Public License\r
-     along with GNUnet; see the file COPYING.  If not, write to the\r
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,\r
-     Boston, MA 02111-1307, USA.\r
-*/\r
-\r
-/**\r
- * Testcase for STUN server resolution\r
- *\r
- * @file nat/test_stun.h\r
- * @brief Testcase for STUN library\r
- * @author Bruno Souza Cabral\r
- * @autor Mark Spencer (Original code borrowed from Asterisk)\r
- *\r
- */\r
-\r
-#define PACKAGE                "gnunet"\r
-#define VERSION_PACKAGE                "0.4"\r
-\r
-#define STUN_SERVER    "stun.services.mozilla.com"\r
-#define STUN_PORT      3478\r
-#define STUN_COUNT     3\r
-#define STUN_RTO       500 /* ms */\r
-#define STUN_MRC       3\r
-\r
-typedef struct { unsigned int id[3]; } __attribute__((packed)) stun_trans_id;\r
-\r
-struct stun_header {\r
-       unsigned short msgtype;\r
-       unsigned short msglen;\r
-       unsigned int magic;\r
-       stun_trans_id  id;\r
-       unsigned char  ies[0];\r
-} __attribute__((packed));\r
-\r
-struct stun_attr {\r
-       unsigned short attr;\r
-       unsigned short len;\r
-       unsigned char  value[0];\r
-} __attribute__((packed));\r
-\r
-/*\r
- * The format normally used for addresses carried by STUN messages.\r
- */\r
-struct stun_addr {\r
-       unsigned char  unused;\r
-       unsigned char  family;\r
-       unsigned short port;\r
-       unsigned int   addr;\r
-} __attribute__((packed));\r
-\r
-#define STUN_IGNORE            (0)\r
-#define STUN_ACCEPT            (1)\r
-\r
-#define STUN_MAGIC_COOKIE      0x2112A442\r
-\r
-/* STUN message classes */\r
-#define STUN_REQUEST           0x0000\r
-#define STUN_INDICATION                0x0001\r
-#define STUN_RESPONSE          0x0002\r
-#define STUN_ERROR_RESPONSE    0x0003\r
-\r
-/* STUN message methods */\r
-#define STUN_BINDING           0x0001\r
-#define STUN_SHARED_SECRET     0x0002\r
-#define STUN_ALLOCATE          0x0003\r
-#define STUN_REFRESH           0x0004\r
-#define STUN_SEND              0x0006\r
-#define STUN_DATA              0x0007\r
-#define STUN_CREATE_PERMISSION 0x0008\r
-#define STUN_CHANNEL_BIND      0x0009\r
-\r
-/* Basic attribute types in stun messages.\r
- * Messages can also contain custom attributes (codes above 0x7fff)\r
- */\r
-#define STUN_MAPPED_ADDRESS    0x0001\r
-#define STUN_RESPONSE_ADDRESS  0x0002\r
-#define STUN_CHANGE_ADDRESS    0x0003\r
-#define STUN_SOURCE_ADDRESS    0x0004\r
-#define STUN_CHANGED_ADDRESS   0x0005\r
-#define STUN_USERNAME          0x0006\r
-#define STUN_PASSWORD          0x0007\r
-#define STUN_MESSAGE_INTEGRITY 0x0008\r
-#define STUN_ERROR_CODE                0x0009\r
-#define STUN_UNKNOWN_ATTRIBUTES        0x000a\r
-#define STUN_REFLECTED_FROM    0x000b\r
-#define STUN_REALM             0x0014\r
-#define STUN_NONCE             0x0015\r
-#define STUN_XOR_MAPPED_ADDRESS        0x0020\r
-#define STUN_MS_VERSION                0x8008\r
-#define STUN_MS_XOR_MAPPED_ADDRESS 0x8020\r
-#define STUN_SOFTWARE          0x8022\r
-#define STUN_ALTERNATE_SERVER  0x8023\r
-#define STUN_FINGERPRINT       0x8028\r
+/*
+     This file is part of GNUnet.
+     Copyright (C) 2009, 2015 Christian Grothoff (and other contributing authors)
+
+     GNUnet 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, or (at your
+     option) any later version.
+
+     GNUnet 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 GNUnet; see the file COPYING.  If not, write to the
+     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+     Boston, MA 02111-1307, USA.
+*/
+
+/**
+ * Testcase for STUN server resolution
+ *
+ * @file nat/test_stun.h
+ * @brief Testcase for STUN library
+ * @author Bruno Souza Cabral
+ * @autor Mark Spencer (Original code borrowed from Asterisk)
+ *
+ */
+
+#define PACKAGE                "gnunet"
+#define VERSION_PACKAGE                "0.4"
+
+#define STUN_SERVER    "stun.services.mozilla.com"
+#define STUN_PORT      3478
+#define STUN_COUNT     3
+#define STUN_RTO       500 /* ms */
+#define STUN_MRC       3
+
+typedef struct { unsigned int id[3]; } __attribute__((packed)) stun_trans_id;
+
+struct stun_header {
+       unsigned short msgtype;
+       unsigned short msglen;
+       unsigned int magic;
+       stun_trans_id  id;
+       unsigned char  ies[0];
+} __attribute__((packed));
+
+struct stun_attr {
+       unsigned short attr;
+       unsigned short len;
+       unsigned char  value[0];
+} __attribute__((packed));
+
+/*
+ * The format normally used for addresses carried by STUN messages.
+ */
+struct stun_addr {
+       unsigned char  unused;
+       unsigned char  family;
+       unsigned short port;
+       unsigned int   addr;
+} __attribute__((packed));
+
+#define STUN_IGNORE            (0)
+#define STUN_ACCEPT            (1)
+
+#define STUN_MAGIC_COOKIE      0x2112A442
+
+/* STUN message classes */
+#define STUN_REQUEST           0x0000
+#define STUN_INDICATION                0x0001
+#define STUN_RESPONSE          0x0002
+#define STUN_ERROR_RESPONSE    0x0003
+
+/* STUN message methods */
+#define STUN_BINDING           0x0001
+#define STUN_SHARED_SECRET     0x0002
+#define STUN_ALLOCATE          0x0003
+#define STUN_REFRESH           0x0004
+#define STUN_SEND              0x0006
+#define STUN_DATA              0x0007
+#define STUN_CREATE_PERMISSION 0x0008
+#define STUN_CHANNEL_BIND      0x0009
+
+/* Basic attribute types in stun messages.
+ * Messages can also contain custom attributes (codes above 0x7fff)
+ */
+#define STUN_MAPPED_ADDRESS    0x0001
+#define STUN_RESPONSE_ADDRESS  0x0002
+#define STUN_CHANGE_ADDRESS    0x0003
+#define STUN_SOURCE_ADDRESS    0x0004
+#define STUN_CHANGED_ADDRESS   0x0005
+#define STUN_USERNAME          0x0006
+#define STUN_PASSWORD          0x0007
+#define STUN_MESSAGE_INTEGRITY 0x0008
+#define STUN_ERROR_CODE                0x0009
+#define STUN_UNKNOWN_ATTRIBUTES        0x000a
+#define STUN_REFLECTED_FROM    0x000b
+#define STUN_REALM             0x0014
+#define STUN_NONCE             0x0015
+#define STUN_XOR_MAPPED_ADDRESS        0x0020
+#define STUN_MS_VERSION                0x8008
+#define STUN_MS_XOR_MAPPED_ADDRESS 0x8020
+#define STUN_SOFTWARE          0x8022
+#define STUN_ALTERNATE_SERVER  0x8023
+#define STUN_FINGERPRINT       0x8028