Parcourir la source

[3391] Removed DNS specific folders from the tree.

Also, updated configure.ac to not reference removed files. The
--disable-dhcp and --disable-dns configuration flags have been removed.
Marcin Siodelski il y a 11 ans
Parent
commit
10de8bbabd
100 fichiers modifiés avec 5 ajouts et 18111 suppressions
  1. 0 163
      configure.ac
  2. 1 7
      src/Makefile.am
  3. 4 36
      src/bin/Makefile.am
  4. 0 15
      src/bin/auth/.gitignore
  5. 0 110
      src/bin/auth/Makefile.am
  6. 0 145
      src/bin/auth/auth.spec.pre.in
  7. 0 218
      src/bin/auth/auth_config.cc
  8. 0 202
      src/bin/auth/auth_config.h
  9. 0 32
      src/bin/auth/auth_log.cc
  10. 0 56
      src/bin/auth/auth_log.h
  11. 0 434
      src/bin/auth/auth_messages.mes
  12. 0 978
      src/bin/auth/auth_srv.cc
  13. 0 297
      src/bin/auth/auth_srv.h
  14. 0 327
      src/bin/auth/b10-auth.xml.pre
  15. 0 1
      src/bin/auth/benchmarks/.gitignore
  16. 0 39
      src/bin/auth/benchmarks/Makefile.am
  17. 0 305
      src/bin/auth/benchmarks/query_bench.cc
  18. 0 224
      src/bin/auth/command.cc
  19. 0 61
      src/bin/auth/command.h
  20. 0 60
      src/bin/auth/common.cc
  21. 0 69
      src/bin/auth/common.h
  22. 0 922
      src/bin/auth/datasrc_clients_mgr.h
  23. 0 24
      src/bin/auth/datasrc_config.cc
  24. 0 82
      src/bin/auth/datasrc_config.h
  25. 0 385
      src/bin/auth/gen-statisticsitems.py.pre.in
  26. 0 270
      src/bin/auth/main.cc
  27. 0 604
      src/bin/auth/query.cc
  28. 0 510
      src/bin/auth/query.h
  29. 0 17
      src/bin/auth/spec_config.h.pre.in
  30. 0 286
      src/bin/auth/statistics.cc.pre
  31. 0 329
      src/bin/auth/statistics.h
  32. 0 53
      src/bin/auth/statistics_items.h.pre
  33. 0 49
      src/bin/auth/statistics_msg_items.def
  34. 0 4
      src/bin/auth/tests/.gitignore
  35. 0 128
      src/bin/auth/tests/Makefile.am
  36. 0 2186
      src/bin/auth/tests/auth_srv_unittest.cc
  37. 0 177
      src/bin/auth/tests/command_unittest.cc
  38. 0 122
      src/bin/auth/tests/common_unittest.cc
  39. 0 89
      src/bin/auth/tests/config_syntax_unittest.cc
  40. 0 158
      src/bin/auth/tests/config_unittest.cc
  41. 0 759
      src/bin/auth/tests/datasrc_clients_builder_unittest.cc
  42. 0 323
      src/bin/auth/tests/datasrc_clients_mgr_unittest.cc
  43. 0 298
      src/bin/auth/tests/datasrc_config_unittest.cc
  44. 0 77
      src/bin/auth/tests/datasrc_util.cc
  45. 0 58
      src/bin/auth/tests/datasrc_util.h
  46. 0 98
      src/bin/auth/tests/gen-query-testdata.py
  47. 0 90
      src/bin/auth/tests/gen-statisticsitems_test.py
  48. 0 2863
      src/bin/auth/tests/query_unittest.cc
  49. 0 29
      src/bin/auth/tests/run_unittests.cc
  50. 0 772
      src/bin/auth/tests/statistics_unittest.cc.pre
  51. 0 75
      src/bin/auth/tests/statistics_util.cc
  52. 0 38
      src/bin/auth/tests/statistics_util.h
  53. 0 102
      src/bin/auth/tests/test_datasrc_clients_mgr.cc
  54. 0 243
      src/bin/auth/tests/test_datasrc_clients_mgr.h
  55. 0 18
      src/bin/auth/tests/testdata/.gitignore
  56. 0 32
      src/bin/auth/tests/testdata/Makefile.am
  57. 0 10
      src/bin/auth/tests/testdata/badExampleQuery_fromWire.spec
  58. 0 241
      src/bin/auth/tests/testdata/example-base-inc.zone
  59. 0 7
      src/bin/auth/tests/testdata/example-base.zone.in
  60. 0 5
      src/bin/auth/tests/testdata/example-common-inc-template.zone
  61. 0 16
      src/bin/auth/tests/testdata/example-nsec3-inc.zone
  62. 0 8
      src/bin/auth/tests/testdata/example-nsec3.zone.in
  63. 0 8
      src/bin/auth/tests/testdata/example.com
  64. BIN
      src/bin/auth/tests/testdata/example.sqlite3
  65. 0 6
      src/bin/auth/tests/testdata/example.zone.in
  66. 0 9
      src/bin/auth/tests/testdata/examplequery_fromWire.spec
  67. 0 9
      src/bin/auth/tests/testdata/iqueryresponse_fromWire.spec
  68. 0 12
      src/bin/auth/tests/testdata/multiquestion_fromWire.spec
  69. 0 12
      src/bin/auth/tests/testdata/queryBadEDNS_fromWire.spec
  70. 0 10
      src/bin/auth/tests/testdata/shortanswer_fromWire.spec
  71. 0 9
      src/bin/auth/tests/testdata/shortmessage_fromWire
  72. 0 13
      src/bin/auth/tests/testdata/shortquestion_fromWire
  73. 0 13
      src/bin/auth/tests/testdata/shortresponse_fromWire
  74. 0 8
      src/bin/auth/tests/testdata/simplequery_fromWire.spec
  75. 0 8
      src/bin/auth/tests/testdata/simpleresponse_fromWire.spec
  76. 0 5
      src/bin/auth/tests/testdata/spec.spec
  77. 0 7
      src/bin/cfgmgr/plugins/Makefile.am
  78. 0 8
      src/bin/cfgmgr/plugins/tests/Makefile.am
  79. 0 4
      src/bin/dbutil/.gitignore
  80. 0 46
      src/bin/dbutil/Makefile.am
  81. 0 196
      src/bin/dbutil/b10-dbutil.xml
  82. 0 627
      src/bin/dbutil/dbutil.py.in
  83. 0 114
      src/bin/dbutil/dbutil_messages.mes
  84. 0 43
      src/bin/dbutil/run_dbutil.sh.in
  85. 0 2
      src/bin/dbutil/tests/.gitignore
  86. 0 15
      src/bin/dbutil/tests/Makefile.am
  87. 0 536
      src/bin/dbutil/tests/dbutil_test.sh.in
  88. 0 14
      src/bin/dbutil/tests/testdata/Makefile.am
  89. 0 41
      src/bin/dbutil/tests/testdata/README
  90. BIN
      src/bin/dbutil/tests/testdata/corrupt.sqlite3
  91. BIN
      src/bin/dbutil/tests/testdata/empty_schema.sqlite3
  92. BIN
      src/bin/dbutil/tests/testdata/empty_v1.sqlite3
  93. BIN
      src/bin/dbutil/tests/testdata/empty_version.sqlite3
  94. BIN
      src/bin/dbutil/tests/testdata/invalid_v1.sqlite3
  95. BIN
      src/bin/dbutil/tests/testdata/new_v1.sqlite3
  96. BIN
      src/bin/dbutil/tests/testdata/no_schema.sqlite3
  97. BIN
      src/bin/dbutil/tests/testdata/old_v1.sqlite3
  98. BIN
      src/bin/dbutil/tests/testdata/too_many_version.sqlite3
  99. BIN
      src/bin/dbutil/tests/testdata/v2_0.sqlite3
  100. 0 0
      src/bin/dbutil/tests/testdata/v2_1.sqlite3

+ 0 - 163
configure.ac

@@ -24,55 +24,6 @@ AC_CONFIG_MACRO_DIR([m4macros])
 # Checks for programs.
 AC_PROG_CXX
 
-want_dns=yes
-AC_ARG_ENABLE(dns,
-  [AC_HELP_STRING([--disable-dns],
-  [disable DNS components])],
-  [want_dns=$enableval])
-AM_CONDITIONAL([WANT_DNS], [test "$want_dns" = "yes"])
-if test "$want_dns" = "yes"; then
-   WANT_DNS=yes
-else
-   WANT_DNS=no
-fi
-AC_SUBST(WANT_DNS)
-
-want_dhcp=yes
-AC_ARG_ENABLE(dhcp,
-  [AC_HELP_STRING([--disable-dhcp],
-  [disable DHCP components])],
-  [want_dhcp=$enableval])
-AM_CONDITIONAL([WANT_DHCP], [test "$want_dhcp" = "yes"])
-if test "$want_dhcp" = "yes"; then
-   WANT_DHCP=yes
-else
-   WANT_DHCP=no
-fi
-AC_SUBST(WANT_DHCP)
-
-want_experimental_resolver=no
-AC_ARG_ENABLE(experimental-resolver,
-  [AC_HELP_STRING([--enable-experimental-resolver],
-  [enable the experimental resolver [default=no]])],
-  [want_experimental_resolver=$enableval])
-AM_CONDITIONAL([WANT_EXPERIMENTAL_RESOLVER], [test "$want_experimental_resolver" = "yes"])
-if test "$want_experimental_resolver" = "yes"; then
-   WANT_EXPERIMENTAL_RESOLVER=yes
-else
-   WANT_EXPERIMENTAL_RESOLVER=no
-fi
-AC_SUBST(WANT_EXPERIMENTAL_RESOLVER)
-
-# At least DNS or DHCP components must be enabled
-if test "$want_dns" != "yes" -a "$want_dhcp" != "yes"; then
-    AC_MSG_ERROR([At least one of DNS or DHCP components must be enabled to do a BIND 10 build.])
-fi
-
-# Experimental resolver requires DNS components to be enabled
-if test "$want_experimental_resolver" = "yes" -a "$want_dns" != "yes"; then
-    AC_MSG_ERROR([You must also enable DNS components if you want to enable the experimental resolver.])
-fi
-
 # Enable low-performing debugging facilities? This option optionally
 # enables some debugging aids that perform slowly and hence aren't built
 # by default.
@@ -926,10 +877,6 @@ elif test "${mysql_config}" != "no" ; then
 fi
 
 if test "$MYSQL_CONFIG" != "" ; then
-    if test "$want_dhcp" != "yes"; then
-        AC_MSG_ERROR([--with-dhcp-mysql should not be used when DHCP components are disabled])
-    fi
-
     if test -d "$MYSQL_CONFIG" -o ! -x "$MYSQL_CONFIG" ; then
         AC_MSG_ERROR([--with-dhcp-mysql should point to a mysql_config program])
     fi
@@ -1434,16 +1381,6 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  ext/Makefile
                  m4macros/Makefile
                  Makefile
-                 src/bin/auth/auth.spec.pre
-                 src/bin/auth/benchmarks/Makefile
-                 src/bin/auth/gen-statisticsitems.py.pre
-                 src/bin/auth/Makefile
-                 src/bin/auth/spec_config.h.pre
-                 src/bin/auth/tests/Makefile
-                 src/bin/auth/tests/testdata/example-base.zone
-                 src/bin/auth/tests/testdata/example-nsec3.zone
-                 src/bin/auth/tests/testdata/example.zone
-                 src/bin/auth/tests/testdata/Makefile
                  src/bin/bind10/bind10
                  src/bin/bind10/init.py
                  src/bin/bind10/Makefile
@@ -1473,15 +1410,6 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/bin/d2/spec_config.h.pre
                  src/bin/d2/tests/Makefile
                  src/bin/d2/tests/test_data_files_config.h
-                 src/bin/dbutil/dbutil.py
-                 src/bin/dbutil/Makefile
-                 src/bin/dbutil/run_dbutil.sh
-                 src/bin/dbutil/tests/dbutil_test.sh
-                 src/bin/dbutil/tests/Makefile
-                 src/bin/dbutil/tests/testdata/Makefile
-                 src/bin/ddns/ddns.py
-                 src/bin/ddns/Makefile
-                 src/bin/ddns/tests/Makefile
                  src/bin/dhcp4/Makefile
                  src/bin/dhcp4/spec_config.h.pre
                  src/bin/dhcp4/tests/Makefile
@@ -1494,26 +1422,11 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/bin/dhcp6/tests/marker_file.h
                  src/bin/dhcp6/tests/test_data_files_config.h
                  src/bin/dhcp6/tests/test_libraries.h
-                 src/bin/loadzone/loadzone.py
-                 src/bin/loadzone/Makefile
-                 src/bin/loadzone/run_loadzone.sh
-                 src/bin/loadzone/tests/correct/correct_test.sh
-                 src/bin/loadzone/tests/correct/Makefile
-                 src/bin/loadzone/tests/Makefile
                  src/bin/Makefile
-                 src/bin/memmgr/Makefile
-                 src/bin/memmgr/memmgr.py
-                 src/bin/memmgr/memmgr.spec.pre
-                 src/bin/memmgr/tests/Makefile
                  src/bin/msgq/Makefile
                  src/bin/msgq/msgq.py
                  src/bin/msgq/run_msgq.sh
                  src/bin/msgq/tests/Makefile
-                 src/bin/resolver/bench/Makefile
-                 src/bin/resolver/Makefile
-                 src/bin/resolver/resolver.spec.pre
-                 src/bin/resolver/spec_config.h.pre
-                 src/bin/resolver/tests/Makefile
                  src/bin/sockcreator/Makefile
                  src/bin/sockcreator/tests/Makefile
                  src/bin/stats/Makefile
@@ -1530,41 +1443,15 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/bin/usermgr/Makefile
                  src/bin/usermgr/run_b10-cmdctl-usermgr.sh
                  src/bin/usermgr/tests/Makefile
-                 src/bin/xfrin/Makefile
-                 src/bin/xfrin/run_b10-xfrin.sh
-                 src/bin/xfrin/tests/Makefile
-                 src/bin/xfrin/tests/testdata/Makefile
-                 src/bin/xfrin/tests/xfrin_test
-                 src/bin/xfrin/xfrin.py
-                 src/bin/xfrout/Makefile
-                 src/bin/xfrout/run_b10-xfrout.sh
-                 src/bin/xfrout/tests/Makefile
-                 src/bin/xfrout/tests/xfrout_test
-                 src/bin/xfrout/tests/xfrout_test.py
-                 src/bin/xfrout/xfrout.py
-                 src/bin/xfrout/xfrout.spec.pre
-                 src/bin/zonemgr/Makefile
-                 src/bin/zonemgr/run_b10-zonemgr.sh
-                 src/bin/zonemgr/tests/Makefile
-                 src/bin/zonemgr/tests/zonemgr_test
-                 src/bin/zonemgr/zonemgr.py
-                 src/bin/zonemgr/zonemgr.spec.pre
                  src/hooks/dhcp/Makefile
                  src/hooks/dhcp/user_chk/Makefile
                  src/hooks/dhcp/user_chk/tests/Makefile
                  src/hooks/dhcp/user_chk/tests/test_data_files_config.h
                  src/hooks/Makefile
-                 src/lib/acl/Makefile
-                 src/lib/acl/tests/Makefile
                  src/lib/asiodns/Makefile
                  src/lib/asiodns/tests/Makefile
                  src/lib/asiolink/Makefile
                  src/lib/asiolink/tests/Makefile
-                 src/lib/bench/example/Makefile
-                 src/lib/bench/Makefile
-                 src/lib/bench/tests/Makefile
-                 src/lib/cache/Makefile
-                 src/lib/cache/tests/Makefile
                  src/lib/cc/Makefile
                  src/lib/cc/session_config.h.pre
                  src/lib/cc/tests/Makefile
@@ -1575,14 +1462,6 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/config/tests/testdata/Makefile
                  src/lib/cryptolink/Makefile
                  src/lib/cryptolink/tests/Makefile
-                 src/lib/datasrc/datasrc_config.h.pre
-                 src/lib/datasrc/Makefile
-                 src/lib/datasrc/memory/benchmarks/Makefile
-                 src/lib/datasrc/memory/Makefile
-                 src/lib/datasrc/tests/Makefile
-                 src/lib/datasrc/tests/memory/Makefile
-                 src/lib/datasrc/tests/memory/testdata/Makefile
-                 src/lib/datasrc/tests/testdata/Makefile
                  src/lib/dhcp_ddns/Makefile
                  src/lib/dhcp_ddns/tests/Makefile
                  src/lib/dhcp/Makefile
@@ -1618,11 +1497,7 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/log/tests/severity_test.sh
                  src/lib/log/tests/tempdir.h
                  src/lib/Makefile
-                 src/lib/nsas/Makefile
-                 src/lib/nsas/tests/Makefile
                  src/lib/python/bind10_config.py
-                 src/lib/python/isc/acl/Makefile
-                 src/lib/python/isc/acl/tests/Makefile
                  src/lib/python/isc/bind10/Makefile
                  src/lib/python/isc/bind10/tests/Makefile
                  src/lib/python/isc/cc/cc_generated/Makefile
@@ -1632,11 +1507,6 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/python/isc/config/Makefile
                  src/lib/python/isc/config/tests/config_test
                  src/lib/python/isc/config/tests/Makefile
-                 src/lib/python/isc/datasrc/Makefile
-                 src/lib/python/isc/datasrc/tests/Makefile
-                 src/lib/python/isc/datasrc/tests/testdata/Makefile
-                 src/lib/python/isc/ddns/Makefile
-                 src/lib/python/isc/ddns/tests/Makefile
                  src/lib/python/isc/dns/Makefile
                  src/lib/python/isc/log/Makefile
                  src/lib/python/isc/log_messages/Makefile
@@ -1645,18 +1515,8 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/python/isc/log/tests/log_console.py
                  src/lib/python/isc/log/tests/Makefile
                  src/lib/python/isc/Makefile
-                 src/lib/python/isc/memmgr/Makefile
-                 src/lib/python/isc/memmgr/tests/Makefile
-                 src/lib/python/isc/memmgr/tests/testdata/Makefile
                  src/lib/python/isc/net/Makefile
                  src/lib/python/isc/net/tests/Makefile
-                 src/lib/python/isc/notify/Makefile
-                 src/lib/python/isc/notify/tests/Makefile
-                 src/lib/python/isc/notify/tests/notify_out_test
-                 src/lib/python/isc/server_common/Makefile
-                 src/lib/python/isc/server_common/tests/Makefile
-                 src/lib/python/isc/statistics/Makefile
-                 src/lib/python/isc/statistics/tests/Makefile
                  src/lib/python/isc/sysinfo/Makefile
                  src/lib/python/isc/sysinfo/tests/Makefile
                  src/lib/python/isc/testutils/Makefile
@@ -1664,16 +1524,7 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/python/isc/util/cio/tests/Makefile
                  src/lib/python/isc/util/Makefile
                  src/lib/python/isc/util/tests/Makefile
-                 src/lib/python/isc/xfrin/Makefile
-                 src/lib/python/isc/xfrin/tests/Makefile
                  src/lib/python/Makefile
-                 src/lib/resolve/Makefile
-                 src/lib/resolve/tests/Makefile
-                 src/lib/server_common/Makefile
-                 src/lib/server_common/tests/data_path.h
-                 src/lib/server_common/tests/Makefile
-                 src/lib/statistics/Makefile
-                 src/lib/statistics/tests/Makefile
                  src/lib/testutils/Makefile
                  src/lib/testutils/testdata/Makefile
                  src/lib/util/io/Makefile
@@ -1687,14 +1538,10 @@ AC_CONFIG_FILES([compatcheck/Makefile
                  src/lib/util/threads/Makefile
                  src/lib/util/threads/tests/Makefile
                  src/lib/util/unittests/Makefile
-                 src/lib/xfr/Makefile
-                 src/lib/xfr/tests/Makefile
                  src/Makefile
                  tests/lettuce/Makefile
                  tests/lettuce/setup_intree_bind10.sh
                  tests/Makefile
-                 tests/tools/badpacket/Makefile
-                 tests/tools/badpacket/tests/Makefile
                  tests/tools/Makefile
                  tests/tools/perfdhcp/Makefile
                  tests/tools/perfdhcp/tests/Makefile
@@ -1708,19 +1555,9 @@ AC_CONFIG_FILES([compatcheck/Makefile
            chmod +x src/bin/bindctl/tests/bindctl_test
            chmod +x src/bin/cmdctl/run_b10-cmdctl.sh
            chmod +x src/bin/cmdctl/tests/cmdctl_test
-           chmod +x src/bin/dbutil/run_dbutil.sh
-           chmod +x src/bin/dbutil/tests/dbutil_test.sh
-           chmod +x src/bin/loadzone/run_loadzone.sh
-           chmod +x src/bin/loadzone/tests/correct/correct_test.sh
            chmod +x src/bin/msgq/run_msgq.sh
            chmod +x src/bin/sysinfo/run_sysinfo.sh
            chmod +x src/bin/usermgr/run_b10-cmdctl-usermgr.sh
-           chmod +x src/bin/xfrin/run_b10-xfrin.sh
-           chmod +x src/bin/xfrin/tests/xfrin_test
-           chmod +x src/bin/xfrout/run_b10-xfrout.sh
-           chmod +x src/bin/xfrout/tests/xfrout_test
-           chmod +x src/bin/zonemgr/run_b10-zonemgr.sh
-           chmod +x src/bin/zonemgr/tests/zonemgr_test
            chmod +x src/lib/dns/gen-rdatacode.py
            chmod +x src/lib/log/tests/console_test.sh
            chmod +x src/lib/log/tests/destination_test.sh

+ 1 - 7
src/Makefile.am

@@ -1,10 +1,4 @@
-if WANT_DHCP
-
-want_hooks = hooks
-
-endif # WANT_DHCP
-
-SUBDIRS = lib bin $(want_hooks)
+SUBDIRS = lib bin hooks
 
 EXTRA_DIST = \
 	cppcheck-suppress.lst		\

+ 4 - 36
src/bin/Makefile.am

@@ -1,38 +1,6 @@
-if WANT_DHCP
-
-want_d2 = d2
-want_dhcp4 = dhcp4
-want_dhcp6 = dhcp6
-
-endif # WANT_DHCP
-
-if WANT_DNS
-
-want_auth = auth
-want_dbutil = dbutil
-want_ddns = ddns
-want_loadzone = loadzone
-want_xfrin = xfrin
-want_xfrout = xfrout
-want_zonemgr = zonemgr
-
-if WANT_EXPERIMENTAL_RESOLVER
-want_resolver = resolver
-endif
-
-if USE_SHARED_MEMORY
-# Build the memory manager only if we have shared memory.
-# It is useless without it.
-want_memmgr = memmgr
-endif
-
-endif # WANT_DNS
-
-# The following build order must be maintained. So we create the
-# variables above and add directories in that order to SUBDIRS.
-SUBDIRS = bind10 bindctl cfgmgr $(want_ddns) $(want_loadzone) msgq cmdctl \
-	$(want_auth) $(want_xfrin) $(want_xfrout) usermgr $(want_zonemgr) \
-	stats tests $(want_resolver) sockcreator $(want_dhcp4) $(want_dhcp6) \
-	$(want_d2) $(want_dbutil) sysinfo $(want_memmgr)
+# The following build order must be maintained.
+SUBDIRS = bind10 bindctl cfgmgr msgq cmdctl \
+	usermgr stats tests  sockcreator dhcp4 dhcp6 \
+	d2 sysinfo
 
 check-recursive: all-recursive

+ 0 - 15
src/bin/auth/.gitignore

@@ -1,15 +0,0 @@
-/auth.spec
-/auth.spec.pre
-/auth_messages.cc
-/auth_messages.h
-/b10-auth
-/spec_config.h
-/spec_config.h.pre
-/b10-auth.8
-/b10-auth.xml
-/gen-statisticsitems.py
-/gen-statisticsitems.py.pre
-/statistics.cc
-/statistics_items.h
-/s-genstats
-/s-messages

+ 0 - 110
src/bin/auth/Makefile.am

@@ -1,110 +0,0 @@
-SUBDIRS = . tests benchmarks
-
-AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
-AM_CPPFLAGS += -I$(top_srcdir)/src/bin -I$(top_builddir)/src/bin
-AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
-AM_CPPFLAGS += -I$(top_srcdir)/src/lib/cc -I$(top_builddir)/src/lib/cc
-AM_CPPFLAGS += -I$(top_srcdir)/src/lib/asiolink
-AM_CPPFLAGS += -I$(top_builddir)/src/lib/asiolink
-AM_CPPFLAGS += $(BOOST_INCLUDES)
-
-AM_CXXFLAGS = $(B10_CXXFLAGS)
-
-if USE_STATIC_LINK
-AM_LDFLAGS = -static
-endif
-
-pkglibexecdir = $(libexecdir)/@PACKAGE@
-
-CLEANFILES  = *.gcno *.gcda auth.spec spec_config.h
-CLEANFILES += auth_messages.h auth_messages.cc
-CLEANFILES += gen-statisticsitems.py
-# auto-generated by gen-statisticsitems.py
-CLEANFILES += statistics.cc statistics_items.h b10-auth.xml tests/statistics_unittest.cc s-genstats s-messages
-
-man_MANS = b10-auth.8
-DISTCLEANFILES = $(man_MANS)
-EXTRA_DIST = $(man_MANS) b10-auth.xml
-
-if GENERATE_DOCS
-
-b10-auth.8: b10-auth.xml
-	@XSLTPROC@ --novalid --xinclude --nonet -o $@ http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl $(builddir)/b10-auth.xml
-
-else
-
-$(man_MANS):
-	@echo Man generation disabled.  Creating dummy $@.  Configure with --enable-generate-docs to enable it.
-	@echo Man generation disabled.  Remove this file, configure with --enable-generate-docs, and rebuild BIND 10 > $@
-
-endif
-
-auth.spec: auth.spec.pre statistics_msg_items.def
-b10-auth.xml: b10-auth.xml.pre statistics_msg_items.def
-statistics_items.h: statistics_items.h.pre statistics_msg_items.def
-statistics.cc: statistics.cc.pre statistics_msg_items.def
-tests/statistics_unittest.cc: tests/statistics_unittest.cc.pre statistics_msg_items.def
-
-gen-statisticsitems.py: gen-statisticsitems.py.pre Makefile
-	$(SED) -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" gen-statisticsitems.py.pre >$@
-	chmod +x $@
-
-auth.spec b10-auth.xml statistics_items.h statistics.cc tests/statistics_unittest.cc: s-genstats
-
-s-genstats: gen-statisticsitems.py
-	./gen-statisticsitems.py
-	touch $@
-
-spec_config.h: spec_config.h.pre
-	$(SED) -e "s|@@LOCALSTATEDIR@@|$(localstatedir)|" spec_config.h.pre >$@
-
-auth_messages.h auth_messages.cc: s-messages
-
-s-messages: auth_messages.mes
-	$(top_builddir)/src/lib/log/compiler/message $(top_srcdir)/src/bin/auth/auth_messages.mes
-	touch $@
-
-BUILT_SOURCES = spec_config.h auth_messages.h auth_messages.cc
-# auto-generated by gen-statisticsitems.py
-BUILT_SOURCES += statistics_items.h statistics.cc
-
-pkglibexec_PROGRAMS = b10-auth
-b10_auth_SOURCES = query.cc query.h
-b10_auth_SOURCES += auth_srv.cc auth_srv.h
-b10_auth_SOURCES += auth_log.cc auth_log.h
-b10_auth_SOURCES += auth_config.cc auth_config.h
-b10_auth_SOURCES += command.cc command.h
-b10_auth_SOURCES += common.h common.cc
-b10_auth_SOURCES += statistics.h
-b10_auth_SOURCES += datasrc_clients_mgr.h
-b10_auth_SOURCES += datasrc_config.h datasrc_config.cc
-b10_auth_SOURCES += main.cc
-
-nodist_b10_auth_SOURCES = auth_messages.h auth_messages.cc
-nodist_b10_auth_SOURCES += statistics.cc statistics_items.h
-EXTRA_DIST += auth_messages.mes
-EXTRA_DIST += statistics_msg_items.def
-EXTRA_DIST += b10-auth.xml.pre
-EXTRA_DIST += statistics_items.h.pre statistics.cc.pre
-EXTRA_DIST += tests/statistics_unittest.cc.pre
-
-b10_auth_LDADD =  $(top_builddir)/src/lib/datasrc/libb10-datasrc.la
-b10_auth_LDADD += $(top_builddir)/src/lib/dns/libb10-dns++.la
-b10_auth_LDADD += $(top_builddir)/src/lib/util/libb10-util.la
-b10_auth_LDADD += $(top_builddir)/src/lib/util/io/libb10-util-io.la
-b10_auth_LDADD += $(top_builddir)/src/lib/config/libb10-cfgclient.la
-b10_auth_LDADD += $(top_builddir)/src/lib/cc/libb10-cc.la
-b10_auth_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
-b10_auth_LDADD += $(top_builddir)/src/lib/asiodns/libb10-asiodns.la
-b10_auth_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
-b10_auth_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
-b10_auth_LDADD += $(top_builddir)/src/lib/xfr/libb10-xfr.la
-b10_auth_LDADD += $(top_builddir)/src/lib/server_common/libb10-server-common.la
-b10_auth_LDADD += $(top_builddir)/src/lib/util/threads/libb10-threads.la
-b10_auth_LDADD += $(SQLITE_LIBS)
-
-# TODO: config.h.in is wrong because doesn't honor pkgdatadir
-# and can't use @datadir@ because doesn't expand default ${prefix}
-b10_authdir = $(pkgdatadir)
-b10_auth_DATA = auth.spec
-

+ 0 - 145
src/bin/auth/auth.spec.pre.in

@@ -1,145 +0,0 @@
-{
-  "module_spec": {
-    "module_name": "Auth",
-    "module_description": "Authoritative service",
-    "config_data": [
-      { "item_name": "database_file",
-        "item_type": "string",
-        "item_optional": true,
-        "item_default": "@@LOCALSTATEDIR@@/@PACKAGE@/zone.sqlite3"
-      },
-      { "item_name": "datasources",
-        "item_type": "list",
-        "item_optional": true,
-        "item_default": [],
-        "list_item_spec":
-        { "item_name": "list_element",
-          "item_type": "map",
-          "item_optional": false,
-          "item_default": {},
-          "map_item_spec": [
-          { "item_name": "type",
-            "item_type": "string",
-            "item_optional": false,
-            "item_default": ""
-          },
-          { "item_name": "class",
-            "item_type": "string",
-            "item_optional": false,
-            "item_default": "IN"
-          },
-          { "item_name": "zones",
-            "item_type": "list",
-            "item_optional": false,
-            "item_default": [],
-            "list_item_spec":
-            { "item_name": "list_element",
-              "item_type": "map",
-              "item_optional": true,
-              "item_default": { "origin": "", "file": "" },
-              "map_item_spec": [
-              { "item_name": "origin",
-                "item_type": "string",
-                "item_optional": false,
-                "item_default": ""
-              },
-              { "item_name": "file",
-                "item_type": "string",
-                "item_optional": false,
-                "item_default": ""
-              },
-              { "item_name": "filetype",
-                "item_type": "string",
-                "item_optional": true
-              }]
-            }
-          }]
-        }
-      },
-      {
-        "item_name": "listen_on",
-        "item_type": "list",
-        "item_optional": false,
-        "item_default": [
-          {
-            "address": "::",
-            "port": 53
-          },
-          {
-            "address": "0.0.0.0",
-            "port": 53
-          }
-        ],
-        "list_item_spec": {
-          "item_name": "address",
-          "item_type": "map",
-          "item_optional": false,
-          "item_default": {},
-          "map_item_spec": [
-            {
-              "item_name": "address",
-              "item_type": "string",
-              "item_optional": false,
-              "item_default": "::1"
-            },
-            {
-              "item_name": "port",
-              "item_type": "integer",
-              "item_optional": false,
-              "item_default": 53
-            }
-          ]
-        }
-      },
-      { "item_name": "tcp_recv_timeout",
-        "item_type": "integer",
-        "item_optional": false,
-        "item_default": 5000
-      }
-    ],
-    "commands": [
-      {
-        "command_name": "shutdown",
-        "command_description": "Shut down authoritative DNS server",
-        "command_args": [
-          {
-            "item_name": "pid",
-            "item_type": "integer",
-            "item_optional": true
-          }
-        ]
-      },
-      {
-        "command_name": "getstats",
-        "command_description": "Retrieve statistics data",
-        "command_args": []
-      },
-      {
-        "command_name": "loadzone",
-        "command_description": "(Re)load a specified zone",
-        "command_args": [
-          {
-            "item_name": "class", "item_type": "string",
-            "item_optional": true, "item_default": "IN"
-          },
-          {
-            "item_name": "origin", "item_type": "string",
-            "item_optional": false, "item_default": ""
-          }
-        ]
-      },
-      {
-        "command_name": "start_ddns_forwarder",
-        "command_description": "(Re)start internal forwarding of DDNS Update messages. This is automatically called if b10-ddns is started, and is not expected to be called by administrators; it will be removed as a public command in the future.",
-        "command_args": []
-      },
-      {
-        "command_name": "stop_ddns_forwarder",
-        "command_description": "Stop internal forwarding of DDNS Update messages. This is automatically called if b10-ddns is stopped, and is not expected to be called by administrators; it will be removed as a public command in the future.",
-        "command_args": []
-      }
-    ],
-    "statistics": [
-    ]
-  }
-}

+ 0 - 218
src/bin/auth/auth_config.cc

@@ -1,218 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <dns/name.h>
-#include <dns/rrclass.h>
-
-#include <cc/data.h>
-
-#include <datasrc/factory.h>
-
-#include <auth/auth_srv.h>
-#include <auth/auth_config.h>
-#include <auth/common.h>
-
-#include <server_common/portconfig.h>
-
-#include <boost/foreach.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/scoped_ptr.hpp>
-
-#include <set>
-#include <string>
-#include <utility>
-#include <vector>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::datasrc;
-using namespace isc::server_common::portconfig;
-
-namespace {
-
-/// A derived \c AuthConfigParser for the version value
-/// (which is not used at this moment)
-class VersionConfig : public AuthConfigParser {
-public:
-    VersionConfig() {}
-    virtual void build(ConstElementPtr) {};
-    virtual void commit() {};
-};
-
-/// A special parser for testing: it throws from commit() despite the
-/// suggested convention of the class interface.
-class ThrowerCommitConfig : public AuthConfigParser {
-public:
-    virtual void build(ConstElementPtr) {} // ignore param, do nothing
-    virtual void commit() {
-        throw 10;
-    }
-};
-
-/**
- * \brief Configuration parser for listen_on.
- *
- * It parses and sets the listening addresses of the server.
- *
- * It acts in unusual way. Since actually binding (changing) the sockets
- * is an operation that is expected to throw often, it shouldn't happen
- * in commit. Thefere we do it in build. But if the config is not committed
- * then, we would have it wrong. So we store the old addresses and if
- * commit is not called before destruction of the object, we return the
- * old addresses (which is the same kind of dangerous operation, but it is
- * expected that if we just managed to bind some and had the old ones binded
- * before, it should work).
- *
- * We might do something better in future (like open only the ports that are
- * extra, put them in in commit and close the old ones), but that's left out
- * for now.
- */
-class ListenAddressConfig : public AuthConfigParser {
-public:
-    ListenAddressConfig(AuthSrv& server) :
-        server_(server)
-    { }
-    ~ ListenAddressConfig() {
-        if (rollbackAddresses_.get() != NULL) {
-            server_.setListenAddresses(*rollbackAddresses_);
-        }
-    }
-private:
-    typedef auto_ptr<AddressList> AddrListPtr;
-public:
-    virtual void build(ConstElementPtr config) {
-        AddressList newAddresses = parseAddresses(config, "listen_on");
-        AddrListPtr old(new AddressList(server_.getListenAddresses()));
-        server_.setListenAddresses(newAddresses);
-        /*
-         * Set the rollback addresses only after successful setting of the
-         * new addresses, so we don't try to rollback if the setup is
-         * unsuccessful (the above can easily throw).
-         */
-        rollbackAddresses_ = old;
-    }
-    virtual void commit() {
-        rollbackAddresses_.reset();
-    }
-private:
-    AuthSrv& server_;
-    /**
-     * This is the old address list, if we expect to roll back. When we commit,
-     * this is set to NULL.
-     */
-    AddrListPtr rollbackAddresses_;
-};
-
-/// \brief Configuration for TCP receive timeouts
-class TCPRecvTimeoutConfig : public AuthConfigParser {
-public:
-    TCPRecvTimeoutConfig(AuthSrv& server) : server_(server), timeout_(0)
-    {}
-
-    virtual void build(ConstElementPtr config) {
-        if (config->intValue() >= 0) {
-            timeout_ = config->intValue();
-        } else {
-            isc_throw(AuthConfigError, "tcp_recv_timeout must be 0 or higher");
-        }
-    }
-
-    virtual void commit() {
-        server_.setTCPRecvTimeout(timeout_);
-    }
-private:
-    AuthSrv& server_;
-    size_t timeout_;
-};
-
-} // end of unnamed namespace
-
-AuthConfigParser*
-createAuthConfigParser(AuthSrv& server, const std::string& config_id) {
-    // For the initial implementation we use a naive if-else blocks for
-    // simplicity.  In future we'll probably generalize it using map-like
-    // data structure, and may even provide external register interface so
-    // that it can be dynamically customized.
-    if (config_id == "listen_on") {
-        return (new ListenAddressConfig(server));
-    } else if (config_id == "_commit_throw") {
-        // This is for testing purpose only and should not appear in the
-        // actual configuration syntax.  While this could crash the caller
-        // as a result, the server implementation is expected to perform
-        // syntax level validation and should be safe in practice.  In future,
-        // we may introduce dynamic registration of configuration parsers,
-        // and then this test can be done in a cleaner and safer way.
-        return (new ThrowerCommitConfig());
-    } else if (config_id == "version") {
-        // Currently, the version identifier is ignored, but it should
-        // later be used to mark backwards incompatible changes in the
-        // config data
-        return (new VersionConfig());
-    } else if (config_id == "datasources") {
-        // TODO: Ignored for now, since the value is probably used by
-        // other modules. Once they have been removed from there, remove
-        // it from here and the spec file.
-
-        // We need to return something. The VersionConfig is empty now,
-        // so we may abuse that one, as it is a short-term solution only.
-        return (new VersionConfig());
-    } else if (config_id == "tcp_recv_timeout") {
-        return (new TCPRecvTimeoutConfig(server));
-    } else {
-        isc_throw(AuthConfigError, "Unknown configuration identifier: " <<
-                  config_id);
-    }
-}
-
-void
-configureAuthServer(AuthSrv& server, ConstElementPtr config_set) {
-    if (!config_set) {
-        isc_throw(AuthConfigError,
-                  "Null pointer is passed to configuration parser");
-    }
-
-    typedef boost::shared_ptr<AuthConfigParser> ParserPtr;
-    vector<ParserPtr> parsers;
-    typedef pair<string, ConstElementPtr> ConfigPair;
-    try {
-        BOOST_FOREACH(ConfigPair config_pair, config_set->mapValue()) {
-            // We should eventually integrate the sqlite3 DB configuration to
-            // this framework, but to minimize diff we begin with skipping that
-            // part.
-            if (config_pair.first == "database_file") {
-                continue;
-            }
-
-            ParserPtr parser(createAuthConfigParser(server,
-                                                    config_pair.first));
-            parser->build(config_pair.second);
-            parsers.push_back(parser);
-        }
-    } catch (const AuthConfigError& ex) {
-        throw;                  // simply rethrowing it
-    } catch (const isc::Exception& ex) {
-        isc_throw(AuthConfigError, "Server configuration failed: " <<
-                  ex.what());
-    }
-
-    try {
-        BOOST_FOREACH(ParserPtr parser, parsers) {
-            parser->commit();
-        }
-    } catch (...) {
-        throw FatalError("Unrecoverable error: "
-                         "a configuration parser threw in commit");
-    }
-}

+ 0 - 202
src/bin/auth/auth_config.h

@@ -1,202 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <string>
-
-#include <exceptions/exceptions.h>
-
-#include <cc/data.h>
-
-#ifndef CONFIG_H
-#define CONFIG_H 1
-
-class AuthSrv;
-
-/// An exception that is thrown if an error occurs while configuring an
-/// \c AuthSrv object.
-class AuthConfigError : public isc::Exception {
-public:
-    AuthConfigError(const char* file, size_t line, const char* what) :
-        isc::Exception(file, line, what) {}
-};
-
-/// The abstract base class that represents a single configuration identifier
-/// for an \c AuthSrv object.
-///
-/// In general, each top level configuration identifier for \c AuthSrv is
-/// expected to have its own derived class of this base class.
-/// For example, for the following configuration:
-/// \code { "param1": 10, "param2": { "subparam1": "foo", "subparam2": [] } }
-/// \endcode
-/// "param1" and "param2" are top level identifiers, and would correspond to
-/// derived \c AuthConfigParser classes.
-/// "subparam1" and/or "subparam2" may also have dedicated derived classes.
-///
-/// These derived classes are hidden inside the implementation; applications
-/// are not expected to (and in fact cannot) instantiate them directly.
-///
-/// Each derived class is generally expected to be constructed with an
-/// \c AuthSrv object to be configured and hold a reference to the server
-/// throughout the configuration process.
-/// For each derived class, the \c build() method parses the configuration
-/// value for the corresponding identifier and prepares new configuration
-/// value(s) to be applied to the server.  This method may throw an exception
-/// when it encounters an error.
-/// The \c commit() method actually applies the new configuration value
-/// to the server.  It's basically not expected to throw an exception;
-/// any configuration operations that can fail (such as ones involving
-/// resource allocation) should be done in \c build().
-///
-/// When the destructor is called before \c commit(), the destructor is
-/// supposed to make sure the state of the \c AuthSrv object is the same
-/// as that before it starts building the configuration value.
-/// If \c build() doesn't change the server state (which is recommended)
-/// the destructor doesn't have to do anything special in this regard.
-/// This is a key to ensure the strong exception guarantee (see also
-/// the description of \c configureAuthServer()).
-class AuthConfigParser {
-    ///
-    /// \name Constructors and Destructor
-    ///
-    /// Note: The copy constructor and the assignment operator are
-    /// intentionally defined as private to make it explicit that this is a
-    /// pure base class.
-    //@{
-private:
-    AuthConfigParser(const AuthConfigParser& source);
-    AuthConfigParser& operator=(const AuthConfigParser& source);
-protected:
-    /// \brief The default constructor.
-    ///
-    /// This is intentionally defined as \c protected as this base class should
-    /// never be instantiated (except as part of a derived class).
-    AuthConfigParser() {}
-public:
-    /// The destructor.
-    virtual ~AuthConfigParser() {}
-    //@}
-
-    /// Prepare configuration value.
-    ///
-    /// This method parses the "value part" of the configuration identifier
-    /// that corresponds to this derived class and prepares a new value to
-    /// apply to the server.
-    /// In the above example, the derived class for the identifier "param1"
-    /// would be passed a data \c Element storing an integer whose value
-    /// is 10, and would record that value internally;
-    /// the derived class for the identifier "param2" would be passed a
-    /// map element and (after parsing) convert it into some internal
-    /// data structure.
-    ///
-    /// This method must validate the given value both in terms of syntax
-    /// and semantics of the configuration, so that the server will be
-    /// validly configured at the time of \c commit().  Note: the given
-    /// configuration value is normally syntactically validated, but the
-    /// \c build() implementation must also expect invalid input.  If it
-    /// detects an error it may throw an exception of a derived class
-    /// of \c isc::Exception.
-    ///
-    /// Preparing a configuration value will often require resource
-    /// allocation.  If it fails, it may throw a corresponding standard
-    /// exception.
-    ///
-    /// This method is not expected to be called more than once.  Although
-    /// multiple calls are not prohibited by the interface, the behavior
-    /// is undefined.
-    ///
-    /// \param config_value The configuration value for the identifier
-    /// corresponding to the derived class.
-    virtual void build(isc::data::ConstElementPtr config_value) = 0;
-
-    /// Apply the prepared configuration value to the server.
-    ///
-    /// This method is expected to be exception free, and, as a consequence,
-    /// it should normally not involve resource allocation.
-    /// Typically it would simply perform exception free assignment or swap
-    /// operation on the value prepared in \c build().
-    /// In some cases, however, it may be very difficult to meet this
-    /// condition in a realistic way, while the failure case should really
-    /// be very rare.  In such a case it may throw, and, if the parser is
-    /// called via \c configureAuthServer(), the caller will convert the
-    /// exception as a fatal error.
-    ///
-    /// This method is expected to be called after \c build(), and only once.
-    /// The result is undefined otherwise.
-    virtual void commit() = 0;
-};
-
-/// Configure an \c AuthSrv object with a set of configuration values.
-///
-/// This function parses configuration information stored in \c config_set
-/// and configures the \c server by applying the configuration to it.
-/// It provides the strong exception guarantee as long as the underlying
-/// derived class implementations of \c AuthConfigParser meet the assumption,
-/// that is, it ensures that either configuration is fully applied or the
-/// state of the server is intact.
-///
-/// If a syntax or semantics level error happens during the configuration
-/// (such as malformed configuration or invalid configuration parameter),
-/// this function throws an exception of class \c AuthConfigError.
-/// If the given configuration requires resource allocation and it fails,
-/// a corresponding standard exception will be thrown.
-/// Other exceptions may also be thrown, depending on the implementation of
-/// the underlying derived class of \c AuthConfigError.
-/// In any case the strong guarantee is provided as described above except
-/// in the very rare cases where the \c commit() method of a parser throws
-/// an exception.  If that happens this function converts the exception
-/// into a \c FatalError exception and rethrows it.  This exception is
-/// expected to be caught at the highest level of the application to terminate
-/// the program gracefully.
-///
-/// \param server The \c AuthSrv object to be configured.
-/// \param config_set A JSON style configuration to apply to \c server.
-void configureAuthServer(AuthSrv& server,
-                         isc::data::ConstElementPtr config_set);
-
-/// Create a new \c AuthConfigParser object for a given configuration
-/// identifier.
-///
-/// It internally identifies an appropriate derived class for the given
-/// identifier and creates a new instance of that class.  The caller can
-/// then configure the \c server regarding the identifier by calling
-/// the \c build() and \c commit() methods of the returned object.
-///
-/// In practice, this function is only expected to be used as a backend of
-/// \c configureAuthServer() and is not supposed to be called directly
-/// by applications.  It is publicly available mainly for testing purposes.
-/// When called directly, the created object must be deleted by the caller.
-/// Note: this means if this module and the caller use incompatible sets of
-/// new/delete, it may cause unexpected strange failure.  We could avoid that
-/// by providing a separate deallocation function or by using a smart pointer,
-/// but since the expected usage of this function is very limited (i.e. for
-/// our own testing purposes) it would be an overkilling.  We therefore prefer
-/// simplicity and keeping the interface intuitive.
-///
-/// If the resource allocation for the new object fails, a corresponding
-/// standard exception will be thrown.  Otherwise this function is not
-/// expected to throw an exception, unless the constructor of the underlying
-/// derived class implementation (unexpectedly) throws.
-///
-/// \param server The \c AuthSrv object to be configured.
-/// \param config_id The configuration identifier for which a parser object
-/// is to be created.
-/// \return A pointer to an \c AuthConfigParser object.
-AuthConfigParser* createAuthConfigParser(AuthSrv& server,
-                                         const std::string& config_id);
-
-#endif // CONFIG_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 32
src/bin/auth/auth_log.cc

@@ -1,32 +0,0 @@
-// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-/// Defines the logger used by the top-level component of b10-auth.
-
-#include "auth_log.h"
-
-namespace isc {
-namespace auth {
-
-isc::log::Logger auth_logger("auth");
-
-const int DBG_AUTH_START = DBGLVL_START_SHUT;
-const int DBG_AUTH_SHUT = DBGLVL_START_SHUT;
-const int DBG_AUTH_OPS = DBGLVL_COMMAND;
-const int DBG_AUTH_DETAIL = DBGLVL_TRACE_BASIC;
-const int DBG_AUTH_MESSAGES = DBGLVL_TRACE_DETAIL_DATA;
-
-} // namespace auth
-} // namespace isc
-

+ 0 - 56
src/bin/auth/auth_log.h

@@ -1,56 +0,0 @@
-// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef AUTH_LOG_H
-#define AUTH_LOG_H
-
-#include <log/macros.h>
-#include <auth/auth_messages.h>
-
-namespace isc {
-namespace auth {
-
-/// \brief Auth Logging
-///
-/// Defines the levels used to output debug messages in the "auth" part of
-/// the b10-auth program.  Higher numbers equate to more verbose (and detailed)
-/// output.
-
-// Debug messages indicating normal startup are logged at this debug level.
-extern const int DBG_AUTH_START;
-// Debug messages upon shutdown
-extern const int DBG_AUTH_SHUT;
-
-// Debug level used to log setting information (such as configuration changes).
-extern const int DBG_AUTH_OPS;
-
-// Trace detailed operations, including errors raised when processing invalid
-// packets.  (These are not logged at severities of WARN or higher for fear
-// that a set of deliberately invalid packets set to the authoritative server
-// could overwhelm the logging.)
-extern const int DBG_AUTH_DETAIL;
-
-// This level is used to log the contents of packets received and sent.
-extern const int DBG_AUTH_MESSAGES;
-
-/// Define the logger for the "auth" module part of b10-auth.  We could define
-/// a logger in each file, but we would want to define a common name to avoid
-/// spelling mistakes, so it is just one small step from there to define a
-/// module-common logger.
-extern isc::log::Logger auth_logger;
-
-} // namespace nsas
-} // namespace isc
-
-#endif // AUTH_LOG_H

+ 0 - 434
src/bin/auth/auth_messages.mes

@@ -1,434 +0,0 @@
-# Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
-#
-# Permission to use, copy, modify, and/or distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-# PERFORMANCE OF THIS SOFTWARE.
-
-$NAMESPACE isc::auth
-
-% AUTH_AXFR_PROBLEM error handling AXFR request: %1
-This is a debug message produced by the authoritative server when it
-has encountered an error processing an AXFR request. The message gives
-the reason for the error, and the server will return a SERVFAIL code to
-the sender.
-
-% AUTH_AXFR_UDP AXFR query received over UDP
-This is a debug message output when the authoritative server has received
-an AXFR query over UDP. Use of UDP for AXFRs is not permitted by the
-protocol, so the server will return a FORMERR error to the sender.
-
-% AUTH_COMMAND_FAILED execution of command channel instruction '%1' failed: %2
-Execution of the specified command by the authoritative server failed. The
-message contains the reason for the failure.
-
-% AUTH_CONFIG_CHANNEL_CREATED configuration session channel created
-This is a debug message indicating that authoritative server has created
-the channel to the configuration manager.  It is issued during server
-startup is an indication that the initialization is proceeding normally.
-
-% AUTH_CONFIG_CHANNEL_ESTABLISHED configuration session channel established
-This is a debug message indicating that authoritative server
-has established communication the configuration manager over the
-previously-created channel. It is issued during server startup is an
-indication that the initialization is proceeding normally.
-
-% AUTH_CONFIG_CHANNEL_STARTED configuration session channel started
-This is a debug message, issued when the authoritative server has
-posted a request to be notified when new configuration information is
-available. It is issued during server startup is an indication that
-the initialization is proceeding normally.
-
-% AUTH_CONFIG_LOAD_FAIL load of configuration failed: %1
-An attempt to configure the server with information from the
-configuration database during the startup sequence has failed.  The
-server will continue its initialization although it may not be
-configured in the desired way.  The reason for the failure is given in
-the message.  One common reason is that the server failed to acquire a
-socket bound to a privileged port (53 for DNS).  In that case the
-reason in the log message should show something like "permission
-denied", and the solution would be to restart BIND 10 as a super
-(root) user.
-
-% AUTH_CONFIG_UPDATE_FAIL update of configuration failed: %1
-At attempt to update the configuration the server with information
-from the configuration database has failed, the reason being given in
-the message.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_COMMAND data source builder received command: %1
-A debug message, showing when the separate thread for maintaining data
-source clients receives a command from the manager.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_COMMAND_ERROR command execution failure: %1
-The separate thread for maintaining data source clients failed to complete a
-command given by the main thread.  In most cases this is some kind of
-configuration or temporary error such as an attempt to load a non-existent
-zone or a temporary DB connection failure.  So the event is just logged and
-the thread keeps running.  In some rare cases, however, this may indicate an
-internal bug and it may be better to restart the entire program, so the log
-message should be carefully examined.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_FAILED data source builder thread stopped due to an exception: %1
-The separate thread for maintaining data source clients has been
-terminated due to some uncaught exception.  When this happens, the
-thread immediately terminates the entire process because the manager
-cannot always catch this condition in a timely fashion and it would be
-worse to keep running with such a half-broken state.  This is really
-an unexpected event and should generally indicate an internal bug.
-It's advisable to file a bug report when this message is logged (and
-b10-auth subsequently stops).
-
-% AUTH_DATASRC_CLIENTS_BUILDER_FAILED_UNEXPECTED data source builder thread stopped due to an unexpected exception
-This is similar to AUTH_DATASRC_CLIENTS_BUILDER_FAILED, but the
-exception type indicates it's not thrown either within the BIND 10
-implementation or other standard-compliant libraries.  This may rather
-indicate some run time failure than program errors.  As in the other
-failure case, the thread terminates the entire process immediately
-after logging this message.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_LOAD_ZONE loaded zone %1/%2
-This debug message is issued when the separate thread for maintaining data
-source clients successfully loaded the named zone of the named class as a
-result of the 'loadzone' command.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_LOAD_ZONE_NOCACHE skipped loading zone %1/%2 due to no in-memory cache
-This debug message is issued when the separate thread for maintaining data
-source clients received a command to reload a zone but skipped it because
-the specified zone is not loaded in-memory (but served from an underlying
-data source).  This could happen if the loadzone command is manually issued
-by a user but the zone name is misspelled, but a more likely cause is
-that the command is sent from another BIND 10 module (such as xfrin or DDNS).
-In the latter case it can be simply ignored because there is no need
-for explicit reloading.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_CONFIG_ERROR Error in data source configuration: %1
-The thread for maintaining data source clients has received a command to
-reconfigure, but the parameter data (the new configuration) contains an
-error. The most likely cause is that the datasource-specific configuration
-data is not what the data source expects. The system is still running with
-the data sources that were previously configured (i.e. as if the
-configuration has not changed), and the configuration data needs to be
-checked.
-The specific problem is printed in the log message.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_DATASRC_ERROR Error setting up data source: %1
-The thread for maintaining data source clients has received a command to
-reconfigure, but a data source failed to set up. This may be a problem with
-the data that is configured (e.g. unreadable files, inconsistent data,
-parser problems, database connection problems, etc.), but it could be a bug
-in the data source implementation as well. The system is still running with
-the data sources that were previously configured (i.e. as if the
-configuration has not changed).
-The specific problem is printed in the log message.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_ERROR Internal error setting up data source: %1
-The thread for maintaining data source clients has received a command to
-reconfigure, but raised an exception while setting up data sources. This is
-most likely an internal error in a data source, or a bug in the data source
-or the system itself, but it is probably a good idea to verify the
-configuration first. The system is still running with the data sources that
-were previously configured (i.e. as if the configuration has not changed).
-The specific problem is printed in the log message.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_STARTED data source reconfiguration started
-The thread for maintaining data source clients has received a command to
-reconfigure, and has now started this process.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_SUCCESS data source reconfiguration completed successfully
-The thread for maintaining data source clients has finished reconfiguring
-the data source clients, and is now running with the new configuration.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_BAD_CLASS invalid RRclass %1 at segment update
-A memory segment update message was sent to the authoritative
-server. But the class contained there is invalid. This means that the
-system is in an inconsistent state and the authoritative server aborts
-to minimize the problem. This is likely caused by a bug in the code.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_ERROR error updating the memory segment: %1
-The authoritative server tried to update the memory segment, but the update
-failed. The authoritative server aborts to avoid system inconsistency. This is
-likely caused by a bug in the code.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_NO_DATASRC there's no data source named %2 in class %1
-The authoritative server was asked to update the memory segment of the
-given data source, but no data source by that name was found. The
-authoritative server aborts because this indicates that the system is in
-an inconsistent state. This is likely caused by a bug in the code.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_UNKNOWN_CLASS unknown class %1 at segment update
-A memory segment update message was sent to the authoritative
-server. The class name for which the update should happen is valid, but
-no client lists are configured for that class. The system is in an
-inconsistent state and the authoritative server aborts. This may be
-caused by a bug in the code.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_STARTED data source builder thread started
-A separate thread for maintaining data source clients has been started.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_STOPPED data source builder thread stopped
-The separate thread for maintaining data source clients has been stopped.
-
-% AUTH_DATASRC_CLIENTS_BUILDER_WAKE_ERR failed to wake up main thread: %1
-A low-level error happened when trying to send data to the main thread to wake
-it up. Terminating to prevent inconsistent state and possible hang ups.
-
-% AUTH_DATASRC_CLIENTS_SHUTDOWN_ERROR error on waiting for data source builder thread: %1
-This indicates that the separate thread for maintaining data source
-clients had been terminated due to an uncaught exception, and the
-manager notices that at its own termination.  This is not an expected
-event, because the thread is implemented so it catches all exceptions
-internally.  So, if this message is logged it's most likely some internal
-bug, and it would be nice to file a bug report.
-
-% AUTH_DATASRC_CLIENTS_SHUTDOWN_UNEXPECTED_ERROR Unexpected error on waiting for data source builder thread
-Some exception happens while waiting for the termination of the
-separate thread for maintaining data source clients.  This shouldn't
-happen in normal conditions; it should be either fatal system level
-errors such as severe memory shortage or some internal bug.  If that
-happens, and if it's not in the middle of terminating b10-auth, it's
-probably better to stop and restart it.
-
-% AUTH_DATA_SOURCE data source database file: %1
-This is a debug message produced by the authoritative server when it accesses a
-database data source, listing the file that is being accessed.
-
-% AUTH_DNS_SERVICES_CREATED DNS services created
-This is a debug message indicating that the component that will handling
-incoming queries for the authoritative server (DNSServices) has been
-successfully created. It is issued during server startup is an indication
-that the initialization is proceeding normally.
-
-% AUTH_HEADER_PARSE_FAIL unable to parse header in received DNS packet: %1
-This is a debug message, generated by the authoritative server when an
-attempt to parse the header of a received DNS packet has failed. (The
-reason for the failure is given in the message.) The server will drop the
-packet.
-
-% AUTH_INVALID_STATISTICS_DATA invalid specification of statistics data specified
-An error was encountered when the authoritative server specified
-statistics data which is invalid for the auth specification file.
-
-% AUTH_LOAD_TSIG loading TSIG keys
-This is a debug message indicating that the authoritative server
-has requested the keyring holding TSIG keys from the configuration
-database. It is issued during server startup is an indication that the
-initialization is proceeding normally.
-
-% AUTH_MEM_DATASRC_DISABLED memory data source is disabled for class %1
-This is a debug message reporting that the authoritative server has
-discovered that the memory data source is disabled for the given class.
-
-% AUTH_MEM_DATASRC_ENABLED memory data source is enabled for class %1
-This is a debug message reporting that the authoritative server has
-discovered that the memory data source is enabled for the given class.
-
-% AUTH_MESSAGE_FORWARD_ERROR failed to forward %1 request from %2: %3
-The authoritative server tried to forward some type DNS request
-message to a separate process (e.g., forwarding dynamic update
-requests to b10-ddns) to handle it, but it failed.  The authoritative
-server returns SERVFAIL to the client on behalf of the separate
-process.  The error could be configuration mismatch between b10-auth
-and the recipient component, or it may be because the requests are
-coming too fast and the recipient process cannot keep up with the
-rate, or some system level failure.  In either case this means the
-BIND 10 system is not working as expected, so the administrator should
-look into the cause and address the issue.  The log message includes
-the client's address (and port), and the error message sent from the
-lower layer that detects the failure.
-
-% AUTH_NOTIFY_QUESTIONS invalid number of questions (%1) in incoming NOTIFY
-This debug message is logged by the authoritative server when it receives
-a NOTIFY packet that contains zero or more than one question. (A valid
-NOTIFY packet contains one question.) The server will return a FORMERR
-error to the sender.
-
-% AUTH_NOTIFY_RRTYPE invalid question RR type (%1) in incoming NOTIFY
-This debug message is logged by the authoritative server when it receives
-a NOTIFY packet that an RR type of something other than SOA in the
-question section. (The RR type received is included in the message.) The
-server will return a FORMERR error to the sender.
-
-% AUTH_NO_XFRIN received NOTIFY but XFRIN session is not running
-This is a debug message produced by the authoritative server when it receives
-a NOTIFY packet but the XFRIN process is not running. The packet will be
-dropped and nothing returned to the sender.
-
-% AUTH_PACKET_PARSE_FAILED unable to parse received DNS packet: %1
-This is a debug message, generated by the authoritative server when an
-attempt to parse a received DNS packet has failed due to something other
-than a protocol error. The reason for the failure is given in the message;
-the server will return a SERVFAIL error code to the sender.
-
-% AUTH_PACKET_PROTOCOL_FAILURE DNS packet protocol error: %1. Returning %2
-This is a debug message, generated by the authoritative server when an
-attempt to parse a received DNS packet has failed due to a protocol error.
-The reason for the failure is given in the message, as is the error code
-that will be returned to the sender.
-
-% AUTH_PACKET_RECEIVED message received:\n%1
-This is a debug message output by the authoritative server when it
-receives a valid DNS packet.
-
-Note: This message includes the packet received, rendered in the form of
-multiple lines of text. For this reason, it is suggested that this log message
-not be routed to the syslog file, where the multiple lines could confuse
-programs that expect a format of one message per line.
-
-% AUTH_PROCESS_FAIL message processing failure: %1
-This message is generated by the authoritative server when it has
-encountered an internal error whilst processing a received packet:
-the cause of the error is included in the message.
-
-The server will return a SERVFAIL error code to the sender of the packet.
-This message indicates a potential error in the server.  Please open a
-bug ticket for this issue.
-
-% AUTH_RECEIVED_COMMAND command '%1' received
-This is a debug message issued when the authoritative server has received
-a command on the command channel.
-
-% AUTH_RECEIVED_NOTIFY received incoming NOTIFY for zone %1/%2 from %3
-This is a debug message reporting that an incoming NOTIFY was received.
-
-% AUTH_RECEIVED_NOTIFY_NOTAUTH received bad NOTIFY for zone %1/%2 from %3
-The authoritative server received a NOTIFY message, but the specified zone
-doesn't match any of the zones served by the server.  The server doesn't
-process the message further, and returns a response with the Rcode being
-NOTAUTH.  Note: RFC 1996 does not specify the server behavior in this case;
-responding with Rcode of NOTAUTH follows BIND 9's behavior.
-
-% AUTH_RESPONSE_FAILURE exception while building response to query: %1
-This is a debug message, generated by the authoritative server when an
-attempt to create a response to a received DNS packet has failed. The
-reason for the failure is given in the log message. A SERVFAIL response
-is sent back. The most likely cause of this is an error in the data
-source implementation; it is either creating bad responses or raising
-exceptions itself.
-
-% AUTH_RESPONSE_FAILURE_UNKNOWN unknown exception while building response to query
-This debug message is similar to AUTH_RESPONSE_FAILURE, but further
-details about the error are unknown, because it was signaled by something
-which is not an exception. This is definitely a bug.
-
-% AUTH_RESPONSE_RECEIVED received response message, ignoring
-This is a debug message, this is output if the authoritative server
-receives a DNS packet with the QR bit set, i.e. a DNS response. The
-server ignores the packet as it only responds to question packets.
-
-% AUTH_SEND_ERROR_RESPONSE sending an error response (%1 bytes):\n%2
-This is a debug message recording that the authoritative server is sending
-an error response to the originator of the query. A previous message will
-have recorded details of the failure.
-
-Note: This message includes the packet sent, rendered in the form of
-multiple lines of text. For this reason, it is suggested that this log message
-not be routed to the syslog file, where the multiple lines could confuse
-programs that expect a format of one message per line.
-
-% AUTH_SEND_NORMAL_RESPONSE sending a normal response (%1 bytes):\n%2
-This is a debug message recording that the authoritative server is sending
-a response to the originator of a query.
-
-Note: This message includes the packet sent, rendered in the form of
-multiple lines of text. For this reason, it is suggested that this log message
-not be routed to the syslog file, where the multiple lines could confuse
-programs that expect a format of one message per line.
-
-% AUTH_SERVER_CREATED server created
-An informational message indicating that the authoritative server process has
-been created and is initializing. The AUTH_SERVER_STARTED message will be
-output when initialization has successfully completed and the server starts
-accepting queries.
-
-% AUTH_SERVER_EXITING exiting
-The authoritative server is exiting.
-
-% AUTH_SERVER_FAILED server failed: %1
-The authoritative server has encountered a fatal error and is terminating. The
-reason for the failure is included in the message.
-
-% AUTH_SERVER_STARTED server started
-Initialization of the authoritative server has completed successfully
-and it is entering the main loop, waiting for queries to arrive.
-
-% AUTH_SHUTDOWN asked to stop, doing so
-This is a debug message indicating the server was asked to shut down and it is
-complying to the request.
-
-% AUTH_SQLITE3 nothing to do for loading sqlite3
-This is a debug message indicating that the authoritative server has
-found that the data source it is loading is an SQLite3 data source,
-so no further validation is needed.
-
-% AUTH_START_DDNS_FORWARDER DDNS UPDATE handling started
-This is a debug message indicating that b10-auth has received a message
-that it should internally forward UPDATE message to b10-ddns. When b10-ddns
-is not running, b10-auth will respond to UPDATE requests with rcode NOTIMP.
-When b10-ddns is running, b10-ddns will handle and respond to the UPDATE
-message.
-
-% AUTH_STOP_DDNS_FORWARDER DDNS UPDATE handling stopped
-This is a debug message indicating that b10-auth has received a message
-that it should stop internally forwarding UPDATE message to b10-ddns.
-b10-auth will no longer forward UPDATE messages to b10-ddns, but will
-respond itself with error code NOTIMP.
-This message is also logged when the forwarding is restarted (for instance
-if b10-ddns is restarted and the internal connection needs to be created
-again), in which case it should be followed by AUTH_START_DDNS_FORWARDER.
-
-% AUTH_UNSUPPORTED_OPCODE unsupported opcode %1 received from %2
-This is a debug message, produced when a received DNS packet being
-processed by the authoritative server has been found to contain an
-unsupported opcode. (The opcode and sender details are included in the
-message.) The server will return an error code of NOTIMPL to the sender.
-
-% AUTH_XFRIN_CHANNEL_CREATED XFRIN session channel created
-This is a debug message indicating that the authoritative server has
-created a channel to the XFRIN (Transfer-in) process.  It is issued
-during server startup is an indication that the initialization is
-proceeding normally.
-
-% AUTH_XFRIN_CHANNEL_ESTABLISHED XFRIN session channel established
-This is a debug message indicating that the authoritative server has
-established communication over the previously-created channel to the
-XFRIN (Transfer-in) process.  It is issued during server startup is an
-indication that the initialization is proceeding normally.
-
-% AUTH_ZONEMGR_COMMS error communicating with zone manager: %1
-This is an internal error during the processing of a NOTIFY request.
-An error (listed in the message) has been encountered whilst communicating
-with the zone manager. The NOTIFY request will not be honored.
-This may be some temporary failure, but is generally an unexpected
-event and is quite likely a bug.  It's probably worth filing a report.
-
-% AUTH_ZONEMGR_ERROR received error response from zone manager: %1
-The zone manager component has been informed of the request,
-but has returned an error response (which is included in the message). The
-NOTIFY request will not be honored.  As of this writing, this can only
-happen due to a bug inside the Zonemgr implementation.  Zonemgr itself
-may log more detailed cause of this, and these are probably worth
-filing a bug report.
-
-% AUTH_ZONEMGR_NOTEXIST received NOTIFY but Zonemgr does not exist
-This is a debug message produced by the authoritative server when it
-receives a NOTIFY message but the Zonemgr component is not running at
-that time.  Not running Zonemgr is completely valid for, e.g., primary
-only servers, so this is not necessarily a problem.  If this message
-is logged even if Zonemgr is supposed to be running, it's encouraged
-to check other logs to identify why that happens.  It may or may not
-be a real problem (for example, if it's immediately after the system
-startup, it's possible that Auth has started up and is running but
-Zonemgr is not yet).  Even if this is indeed an unexpected case,
-Zonemgr should normally be restarted by the Init process, so unless
-this repeats too often it may be negligible in practice (still it's
-worth filing a bug report).  In any case, the authoritative server
-simply drops the NOTIFY message; if it's a temporary failure or
-delayed startup, subsequently resent messages will eventually reach
-Zonemgr.

+ 0 - 978
src/bin/auth/auth_srv.cc

@@ -1,978 +0,0 @@
-// Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include <util/io/socketsession.h>
-
-#include <asiolink/asiolink.h>
-#include <asiolink/io_endpoint.h>
-
-#include <config/ccsession.h>
-
-#include <cc/data.h>
-#include <cc/proto_defs.h>
-
-#include <exceptions/exceptions.h>
-
-#include <util/buffer.h>
-
-#include <dns/edns.h>
-#include <dns/exceptions.h>
-#include <dns/messagerenderer.h>
-#include <dns/name.h>
-#include <dns/question.h>
-#include <dns/opcode.h>
-#include <dns/rcode.h>
-#include <dns/rrset.h>
-#include <dns/rrttl.h>
-#include <dns/message.h>
-#include <dns/tsig.h>
-
-#include <asiodns/dns_service.h>
-
-#include <datasrc/exceptions.h>
-#include <datasrc/client_list.h>
-
-#include <xfr/xfrout_client.h>
-
-#include <auth/common.h>
-#include <auth/auth_config.h>
-#include <auth/auth_srv.h>
-#include <auth/query.h>
-#include <auth/statistics.h>
-#include <auth/auth_log.h>
-#include <auth/datasrc_clients_mgr.h>
-
-#include <boost/bind.hpp>
-#include <boost/lexical_cast.hpp>
-#include <boost/scoped_ptr.hpp>
-
-#include <algorithm>
-#include <cassert>
-#include <iostream>
-#include <vector>
-#include <memory>
-
-#include <sys/types.h>
-#include <netinet/in.h>
-
-using namespace std;
-
-using namespace isc;
-using namespace isc::cc;
-using namespace isc::datasrc;
-using namespace isc::dns;
-using namespace isc::util;
-using namespace isc::util::io;
-using namespace isc::auth;
-using namespace isc::dns::rdata;
-using namespace isc::data;
-using namespace isc::config;
-using namespace isc::xfr;
-using namespace isc::asiolink;
-using namespace isc::asiodns;
-using namespace isc::server_common::portconfig;
-using isc::auth::statistics::Counters;
-using isc::auth::statistics::MessageAttributes;
-
-namespace {
-// A helper class for cleaning up message renderer.
-//
-// A temporary object of this class is expected to be created before starting
-// response message rendering.  On construction, it (re)initialize the given
-// message renderer with the given buffer.  On destruction, it releases
-// the previously set buffer and then release any internal resource in the
-// renderer, no matter what happened during the rendering, especially even
-// when it resulted in an exception.
-//
-// Note: if we need this helper in many other places we might consider making
-// it visible to other modules.  As of this implementation this is the only
-// user of this class, so we hide it within the implementation.
-class RendererHolder {
-public:
-    RendererHolder(MessageRenderer& renderer, OutputBuffer* buffer,
-                   MessageAttributes& stats_attrs) :
-        renderer_(renderer),
-        stats_attrs_(stats_attrs)
-    {
-        renderer.setBuffer(buffer);
-    }
-    ~RendererHolder() {
-        stats_attrs_.setResponseTruncated(renderer_.isTruncated());
-        renderer_.setBuffer(NULL);
-        renderer_.clear();
-    }
-private:
-    MessageRenderer& renderer_;
-    MessageAttributes& stats_attrs_;
-};
-
-// Similar to Renderer holder, this is a very basic RAII-style class
-// that calls clear(Message::PARSE) on the given Message upon destruction
-class MessageHolder {
-public:
-    MessageHolder(Message& message) : message_(message) {}
-    ~MessageHolder() {
-        message_.clear(Message::PARSE);
-    }
-private:
-    Message& message_;
-};
-
-// A helper container of socket session forwarder.
-//
-// This class provides a simple wrapper interface to SocketSessionForwarder
-// so that the caller doesn't have to worry about connection management,
-// exception handling or parameter building.
-//
-// It internally maintains whether the underlying forwarder establishes a
-// connection to the receiver.  On a forwarding request, if the connection
-// hasn't been established yet, it automatically opens a new one, then
-// pushes the session over it.  It also closes the connection on destruction,
-// or a non-recoverable error happens, automatically.  So the only thing
-// the application has to do is to create this object and push any session
-// to be forwarded.
-class SocketSessionForwarderHolder {
-public:
-    /// \brief The constructor.
-    ///
-    /// \param message_name Any string that can identify the type of messages
-    /// to be forwarded via this session.  It will be only used as part of
-    /// log message, so it can be anything, but in practice something like
-    /// "update" or "xfr" is expected.
-    /// \param forwarder The underlying socket session forwarder.
-    SocketSessionForwarderHolder(const string& message_name,
-                                 BaseSocketSessionForwarder& forwarder) :
-        message_name_(message_name), forwarder_(forwarder), connected_(false)
-    {}
-
-    ~SocketSessionForwarderHolder() {
-        if (connected_) {
-            forwarder_.close();
-        }
-    }
-
-    /// \brief Push a socket session corresponding to given IOMessage.
-    ///
-    /// If the connection with the receiver process hasn't been established,
-    /// it automatically establishes one, then push the session over it.
-    ///
-    /// If either connect or push fails, the underlying forwarder object should
-    /// throw an exception.  This method logs the event, and propagates the
-    /// exception to the caller, which will eventually result in SERVFAIL.
-    /// The connection, if established, is automatically closed, so the next
-    /// forward request will trigger reopening a new connection.
-    ///
-    /// \note: Right now, there's no API to retrieve the local address from
-    /// the IOMessage.  Until it's added, we pass the remote address as
-    /// local.
-    ///
-    /// \param io_message The request message to be forwarded as a socket
-    /// session.  It will be converted to the parameters that the underlying
-    /// SocketSessionForwarder expects.
-    void push(const IOMessage& io_message) {
-        const IOEndpoint& remote_ep = io_message.getRemoteEndpoint();
-        const int protocol = remote_ep.getProtocol();
-        const int sock_type = getSocketType(protocol);
-        try {
-            connect();
-            forwarder_.push(io_message.getSocket().getNative(),
-                            remote_ep.getFamily(), sock_type, protocol,
-                            remote_ep.getSockAddr(), remote_ep.getSockAddr(),
-                            io_message.getData(), io_message.getDataSize());
-        } catch (const SocketSessionError& ex) {
-            LOG_ERROR(auth_logger, AUTH_MESSAGE_FORWARD_ERROR).
-                arg(message_name_).arg(remote_ep).arg(ex.what());
-            close();
-            throw;
-        }
-    }
-
-private:
-    const string message_name_;
-    BaseSocketSessionForwarder& forwarder_;
-    bool connected_;
-
-    void connect() {
-        if (!connected_) {
-            forwarder_.connectToReceiver();
-            connected_ = true;
-        }
-    }
-
-    void close() {
-        if (connected_) {
-            forwarder_.close();
-            connected_ = false;
-        }
-    }
-
-    static int getSocketType(int protocol) {
-        switch (protocol) {
-        case IPPROTO_UDP:
-            return (SOCK_DGRAM);
-        case IPPROTO_TCP:
-            return (SOCK_STREAM);
-        default:
-            isc_throw(isc::InvalidParameter,
-                      "Unexpected socket address family: " << protocol);
-        }
-    }
-};
-}
-
-class AuthSrvImpl {
-private:
-    // prohibit copy
-    AuthSrvImpl(const AuthSrvImpl& source);
-    AuthSrvImpl& operator=(const AuthSrvImpl& source);
-public:
-    AuthSrvImpl(AbstractXfroutClient& xfrout_client,
-                BaseSocketSessionForwarder& ddns_forwarder);
-    ~AuthSrvImpl();
-
-    bool processNormalQuery(const IOMessage& io_message,
-                            ConstEDNSPtr remote_edns, Message& message,
-                            OutputBuffer& buffer,
-                            auto_ptr<TSIGContext> tsig_context,
-                            MessageAttributes& stats_attrs);
-    bool processXfrQuery(const IOMessage& io_message, Message& message,
-                         OutputBuffer& buffer,
-                         auto_ptr<TSIGContext> tsig_context,
-                         MessageAttributes& stats_attrs);
-    bool processNotify(const IOMessage& io_message, Message& message,
-                       OutputBuffer& buffer,
-                       auto_ptr<TSIGContext> tsig_context,
-                       MessageAttributes& stats_attrs);
-    bool processUpdate(const IOMessage& io_message);
-
-    IOService io_service_;
-
-    MessageRenderer renderer_;
-    /// Currently non-configurable, but will be.
-    static const uint16_t DEFAULT_LOCAL_UDPSIZE = 4096;
-
-    /// These members are public because AuthSrv accesses them directly.
-    ModuleCCSession* config_session_;
-    AbstractSession* xfrin_session_;
-
-    /// Query counters for statistics
-    Counters counters_;
-
-    /// Addresses we listen on
-    AddressList listen_addresses_;
-
-    /// The TSIG keyring
-    const boost::shared_ptr<TSIGKeyRing>* keyring_;
-
-    /// The data source client list manager
-    auth::DataSrcClientsMgr datasrc_clients_mgr_;
-
-    /// Socket session forwarder for dynamic update requests
-    BaseSocketSessionForwarder& ddns_base_forwarder_;
-
-    /// Holder for the DDNS Forwarder, which is used to send
-    /// DDNS messages to b10-ddns, but can be set to empty if
-    /// b10-ddns is not running
-    boost::scoped_ptr<SocketSessionForwarderHolder> ddns_forwarder_;
-
-    /// \brief Resume the server
-    ///
-    /// This is a wrapper call for DNSServer::resume(done). Query/Response
-    /// statistics counters are incremented in this method.
-    ///
-    /// This method is expected to be called by processMessage()
-    ///
-    /// \param server The DNSServer as passed to processMessage()
-    /// \param message The response as constructed by processMessage()
-    /// \param stats_attrs Object to store message attributes in for use
-    ///                    with statistics
-    /// \param done If true, it indicates there is a response.
-    ///             this value will be passed to server->resume(bool)
-    void resumeServer(isc::asiodns::DNSServer* server,
-                      isc::dns::Message& message,
-                      MessageAttributes& stats_attrs,
-                      const bool done);
-
-    /// Are we currently subscribed to the SegmentReader group?
-    bool readers_group_subscribed_;
-private:
-    bool xfrout_connected_;
-    AbstractXfroutClient& xfrout_client_;
-
-    auth::Query query_;
-};
-
-AuthSrvImpl::AuthSrvImpl(AbstractXfroutClient& xfrout_client,
-                         BaseSocketSessionForwarder& ddns_forwarder) :
-    config_session_(NULL),
-    xfrin_session_(NULL),
-    counters_(),
-    keyring_(NULL),
-    datasrc_clients_mgr_(io_service_),
-    ddns_base_forwarder_(ddns_forwarder),
-    ddns_forwarder_(NULL),
-    readers_group_subscribed_(false),
-    xfrout_connected_(false),
-    xfrout_client_(xfrout_client)
-{}
-
-AuthSrvImpl::~AuthSrvImpl() {
-    if (xfrout_connected_) {
-        xfrout_client_.disconnect();
-        xfrout_connected_ = false;
-    }
-}
-
-// This is a derived class of \c DNSLookup, to serve as a
-// callback in the asiolink module.  It calls
-// AuthSrv::processMessage() on a single DNS message.
-class MessageLookup : public DNSLookup {
-public:
-    MessageLookup(AuthSrv* srv) : server_(srv) {}
-    virtual void operator()(const IOMessage& io_message,
-                            MessagePtr message,
-                            MessagePtr, // Not used here
-                            OutputBufferPtr buffer,
-                            DNSServer* server) const
-    {
-        // Keep a holder on the message, so that it is automatically
-        // cleared if processMessage() is done
-        // This is not done in processMessage itself (which would be
-        // equivalent), to allow tests to inspect the message handling.
-        MessageHolder message_holder(*message);
-        server_->processMessage(io_message, *message, *buffer, server);
-    }
-private:
-    AuthSrv* server_;
-};
-
-// This is a derived class of \c DNSAnswer, to serve as a callback in the
-// asiolink module.  We actually shouldn't do anything in this class because
-// we build complete response messages in the process methods; otherwise
-// the response message will contain trailing garbage.  In future, we should
-// probably even drop the reliance on DNSAnswer.  We don't need the coroutine
-// tricks provided in that framework, and its overhead would be significant
-// in terms of performance consideration for the authoritative server
-// implementation.
-class MessageAnswer : public DNSAnswer {
-public:
-    MessageAnswer(AuthSrv*) {}
-    virtual void operator()(const IOMessage&, MessagePtr,
-                            MessagePtr, OutputBufferPtr) const
-    {}
-};
-
-AuthSrv::AuthSrv(isc::xfr::AbstractXfroutClient& xfrout_client,
-                 isc::util::io::BaseSocketSessionForwarder& ddns_forwarder) :
-    dnss_(NULL)
-{
-    impl_ = new AuthSrvImpl(xfrout_client, ddns_forwarder);
-    dns_lookup_ = new MessageLookup(this);
-    dns_answer_ = new MessageAnswer(this);
-}
-
-void
-AuthSrv::stop() {
-    impl_->io_service_.stop();
-}
-
-AuthSrv::~AuthSrv() {
-    delete impl_;
-    delete dns_lookup_;
-    delete dns_answer_;
-}
-
-namespace {
-class QuestionInserter {
-public:
-    QuestionInserter(Message& message) : message_(message) {}
-    void operator()(const QuestionPtr question) {
-        message_.addQuestion(question);
-    }
-    Message& message_;
-};
-
-void
-makeErrorMessage(MessageRenderer& renderer, Message& message,
-                 OutputBuffer& buffer, const Rcode& rcode,
-                 MessageAttributes& stats_attrs,
-                 std::auto_ptr<TSIGContext> tsig_context =
-                 std::auto_ptr<TSIGContext>())
-{
-    // extract the parameters that should be kept.
-    // XXX: with the current implementation, it's not easy to set EDNS0
-    // depending on whether the query had it.  So we'll simply omit it.
-    const qid_t qid = message.getQid();
-    const bool rd = message.getHeaderFlag(Message::HEADERFLAG_RD);
-    const bool cd = message.getHeaderFlag(Message::HEADERFLAG_CD);
-    const Opcode& opcode = message.getOpcode();
-    vector<QuestionPtr> questions;
-
-    // If this is an error to a query or notify, we should also copy the
-    // question section.
-    if (opcode == Opcode::QUERY() || opcode == Opcode::NOTIFY()) {
-        questions.assign(message.beginQuestion(), message.endQuestion());
-    }
-
-    message.clear(Message::RENDER);
-    message.setQid(qid);
-    message.setOpcode(opcode);
-    message.setHeaderFlag(Message::HEADERFLAG_QR);
-    if (rd) {
-        message.setHeaderFlag(Message::HEADERFLAG_RD);
-    }
-    if (cd) {
-        message.setHeaderFlag(Message::HEADERFLAG_CD);
-    }
-    for_each(questions.begin(), questions.end(), QuestionInserter(message));
-
-    message.setRcode(rcode);
-
-    RendererHolder holder(renderer, &buffer, stats_attrs);
-    message.toWire(renderer, tsig_context.get());
-    stats_attrs.setResponseTSIG(tsig_context.get() != NULL);
-
-    LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_ERROR_RESPONSE)
-              .arg(renderer.getLength()).arg(message);
-}
-}
-
-IOService&
-AuthSrv::getIOService() {
-    return (impl_->io_service_);
-}
-
-isc::auth::DataSrcClientsMgr&
-AuthSrv::getDataSrcClientsMgr() {
-    return (impl_->datasrc_clients_mgr_);
-}
-
-void
-AuthSrv::setXfrinSession(AbstractSession* xfrin_session) {
-    impl_->xfrin_session_ = xfrin_session;
-}
-
-void
-AuthSrv::setConfigSession(ModuleCCSession* config_session) {
-    impl_->config_session_ = config_session;
-}
-
-ModuleCCSession*
-AuthSrv::getConfigSession() const {
-    return (impl_->config_session_);
-}
-
-void
-AuthSrv::processMessage(const IOMessage& io_message, Message& message,
-                        OutputBuffer& buffer, DNSServer* server)
-{
-    InputBuffer request_buffer(io_message.getData(), io_message.getDataSize());
-    MessageAttributes stats_attrs;
-
-    stats_attrs.setRequestIPVersion(
-        io_message.getRemoteEndpoint().getFamily());
-    stats_attrs.setRequestTransportProtocol(
-        io_message.getRemoteEndpoint().getProtocol());
-
-    // First, check the header part.  If we fail even for the base header,
-    // just drop the message.
-    try {
-        message.parseHeader(request_buffer);
-
-        // Ignore all responses.
-        if (message.getHeaderFlag(Message::HEADERFLAG_QR)) {
-            LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_RECEIVED);
-            impl_->resumeServer(server, message, stats_attrs, false);
-            return;
-        }
-    } catch (const isc::Exception& ex) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_HEADER_PARSE_FAIL)
-                  .arg(ex.what());
-        impl_->resumeServer(server, message, stats_attrs, false);
-        return;
-    }
-
-    stats_attrs.setRequestRD(message.getHeaderFlag(Message::HEADERFLAG_RD));
-
-    const Opcode& opcode = message.getOpcode();
-    // Get opcode at this point; for all requests regardless of message body
-    // sanity check.
-    stats_attrs.setRequestOpCode(opcode);
-
-    try {
-        // Parse the message.
-        message.fromWire(request_buffer);
-    } catch (const DNSProtocolError& error) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PROTOCOL_FAILURE)
-                  .arg(error.getRcode().toText()).arg(error.what());
-        makeErrorMessage(impl_->renderer_, message, buffer, error.getRcode(),
-                         stats_attrs);
-        impl_->resumeServer(server, message, stats_attrs, true);
-        return;
-    } catch (const isc::Exception& ex) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_PACKET_PARSE_FAILED)
-                  .arg(ex.what());
-        makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL(),
-                         stats_attrs);
-        impl_->resumeServer(server, message, stats_attrs, true);
-        return;
-    } // other exceptions will be handled at a higher layer.
-
-    LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_PACKET_RECEIVED)
-              .arg(message);
-
-    // Perform further protocol-level validation.
-    // TSIG first
-    // If this is set to something, we know we need to answer with TSIG as well
-    std::auto_ptr<TSIGContext> tsig_context;
-    const TSIGRecord* tsig_record(message.getTSIGRecord());
-    TSIGError tsig_error(TSIGError::NOERROR());
-
-    // Do we do TSIG?
-    // The keyring can be null if we're in test
-    if (impl_->keyring_ != NULL && tsig_record != NULL) {
-        tsig_context.reset(new TSIGContext(tsig_record->getName(),
-                                           tsig_record->getRdata().
-                                                getAlgorithm(),
-                                           **impl_->keyring_));
-        tsig_error = tsig_context->verify(tsig_record, io_message.getData(),
-                                          io_message.getDataSize());
-        stats_attrs.setRequestTSIG(true, tsig_error != TSIGError::NOERROR());
-    }
-
-    if (tsig_error != TSIGError::NOERROR()) {
-        makeErrorMessage(impl_->renderer_, message, buffer,
-                         tsig_error.toRcode(), stats_attrs, tsig_context);
-        impl_->resumeServer(server, message, stats_attrs, true);
-        return;
-    }
-
-    bool send_answer = true;
-    try {
-        // note: This can only be reliable after TSIG check succeeds.
-        ConstEDNSPtr edns = message.getEDNS();
-        if (edns) {
-            stats_attrs.setRequestEDNS0(true);
-            stats_attrs.setRequestDO(edns->getDNSSECAwareness());
-        }
-
-        // note: This can only be reliable after TSIG check succeeds.
-        if (opcode == Opcode::NOTIFY()) {
-            send_answer = impl_->processNotify(io_message, message, buffer,
-                                               tsig_context, stats_attrs);
-        } else if (opcode == Opcode::UPDATE()) {
-            if (impl_->ddns_forwarder_) {
-                send_answer = impl_->processUpdate(io_message);
-            } else {
-                makeErrorMessage(impl_->renderer_, message, buffer,
-                                 Rcode::NOTIMP(), stats_attrs, tsig_context);
-            }
-        } else if (opcode != Opcode::QUERY()) {
-            const IOEndpoint& remote_ep = io_message.getRemoteEndpoint();
-            LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_UNSUPPORTED_OPCODE)
-                .arg(message.getOpcode().toText()).arg(remote_ep);
-            makeErrorMessage(impl_->renderer_, message, buffer,
-                             Rcode::NOTIMP(), stats_attrs, tsig_context);
-        } else if (message.getRRCount(Message::SECTION_QUESTION) != 1) {
-            makeErrorMessage(impl_->renderer_, message, buffer,
-                             Rcode::FORMERR(), stats_attrs, tsig_context);
-        } else {
-            ConstQuestionPtr question = *message.beginQuestion();
-            const RRType& qtype = question->getType();
-            if (qtype == RRType::AXFR()) {
-                send_answer = impl_->processXfrQuery(io_message, message,
-                                                     buffer, tsig_context,
-                                                     stats_attrs);
-            } else if (qtype == RRType::IXFR()) {
-                send_answer = impl_->processXfrQuery(io_message, message,
-                                                     buffer, tsig_context,
-                                                     stats_attrs);
-            } else {
-                send_answer = impl_->processNormalQuery(io_message, edns,
-                                                        message, buffer,
-                                                        tsig_context,
-                                                        stats_attrs);
-            }
-        }
-    } catch (const std::exception& ex) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_FAILURE)
-                  .arg(ex.what());
-        makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL(),
-                         stats_attrs);
-    } catch (...) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RESPONSE_FAILURE_UNKNOWN);
-        makeErrorMessage(impl_->renderer_, message, buffer, Rcode::SERVFAIL(),
-                         stats_attrs);
-    }
-    impl_->resumeServer(server, message, stats_attrs, send_answer);
-}
-
-bool
-AuthSrvImpl::processNormalQuery(const IOMessage& io_message,
-                                ConstEDNSPtr remote_edns, Message& message,
-                                OutputBuffer& buffer,
-                                auto_ptr<TSIGContext> tsig_context,
-                                MessageAttributes& stats_attrs)
-{
-    const bool dnssec_ok = remote_edns && remote_edns->getDNSSECAwareness();
-    const uint16_t remote_bufsize = remote_edns ? remote_edns->getUDPSize() :
-        Message::DEFAULT_MAX_UDPSIZE;
-
-    message.makeResponse();
-    message.setHeaderFlag(Message::HEADERFLAG_AA);
-    message.setRcode(Rcode::NOERROR());
-
-    if (remote_edns) {
-        EDNSPtr local_edns = EDNSPtr(new EDNS());
-        local_edns->setDNSSECAwareness(dnssec_ok);
-        local_edns->setUDPSize(AuthSrvImpl::DEFAULT_LOCAL_UDPSIZE);
-        message.setEDNS(local_edns);
-    }
-
-    // Get access to data source client list through the holder and keep
-    // the holder until the processing and rendering is done to avoid
-    // race with any other thread(s) such as the background loader.
-    auth::DataSrcClientsMgr::Holder datasrc_holder(datasrc_clients_mgr_);
-
-    try {
-        const ConstQuestionPtr question = *message.beginQuestion();
-        const boost::shared_ptr<datasrc::ClientList>
-            list(datasrc_holder.findClientList(question->getClass()));
-        if (list) {
-            const RRType& qtype = question->getType();
-            const Name& qname = question->getName();
-            query_.process(*list, qname, qtype, message, dnssec_ok);
-        } else {
-            makeErrorMessage(renderer_, message, buffer, Rcode::REFUSED(),
-                             stats_attrs);
-            return (true);
-        }
-    } catch (const isc::Exception& ex) {
-        LOG_ERROR(auth_logger, AUTH_PROCESS_FAIL).arg(ex.what());
-        makeErrorMessage(renderer_, message, buffer, Rcode::SERVFAIL(),
-                         stats_attrs);
-        return (true);
-    }
-
-    RendererHolder holder(renderer_, &buffer, stats_attrs);
-    const bool udp_buffer =
-        (io_message.getSocket().getProtocol() == IPPROTO_UDP);
-    renderer_.setLengthLimit(udp_buffer ? remote_bufsize : 65535);
-    message.toWire(renderer_, tsig_context.get());
-    stats_attrs.setResponseTSIG(tsig_context.get() != NULL);
-
-    LOG_DEBUG(auth_logger, DBG_AUTH_MESSAGES, AUTH_SEND_NORMAL_RESPONSE)
-              .arg(renderer_.getLength()).arg(message);
-    return (true);
-    // The message can contain some data from the locked resource. But outside
-    // this method, we touch only the RCode of it, so it should be safe.
-
-    // Lock on datasrc_clients_mgr_ acquired by datasrc_holder is
-    // released here upon its deletion.
-}
-
-bool
-AuthSrvImpl::processXfrQuery(const IOMessage& io_message, Message& message,
-                             OutputBuffer& buffer,
-                             auto_ptr<TSIGContext> tsig_context,
-                             MessageAttributes& stats_attrs)
-{
-    if (io_message.getSocket().getProtocol() == IPPROTO_UDP) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_AXFR_UDP);
-        makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
-                         stats_attrs, tsig_context);
-        return (true);
-    }
-
-    try {
-        if (!xfrout_connected_) {
-            xfrout_client_.connect();
-            xfrout_connected_ = true;
-        }
-        xfrout_client_.sendXfroutRequestInfo(
-            io_message.getSocket().getNative(),
-            io_message.getData(),
-            io_message.getDataSize());
-    } catch (const XfroutError& err) {
-        if (xfrout_connected_) {
-            // disconnect() may trigger an exception, but since we try it
-            // only if we've successfully opened it, it shouldn't happen in
-            // normal condition.  Should this occur, we'll propagate it to the
-            // upper layer.
-            xfrout_client_.disconnect();
-            xfrout_connected_ = false;
-        }
-
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_AXFR_PROBLEM)
-                  .arg(err.what());
-        makeErrorMessage(renderer_, message, buffer, Rcode::SERVFAIL(),
-                         stats_attrs, tsig_context);
-        return (true);
-    }
-
-    return (false);
-}
-
-bool
-AuthSrvImpl::processNotify(const IOMessage& io_message, Message& message,
-                           OutputBuffer& buffer,
-                           std::auto_ptr<TSIGContext> tsig_context,
-                           MessageAttributes& stats_attrs)
-{
-    const IOEndpoint& remote_ep = io_message.getRemoteEndpoint(); // for logs
-
-    // The incoming notify must contain exactly one question for SOA of the
-    // zone name.
-    if (message.getRRCount(Message::SECTION_QUESTION) != 1) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_QUESTIONS)
-                  .arg(message.getRRCount(Message::SECTION_QUESTION));
-        makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
-                         stats_attrs, tsig_context);
-        return (true);
-    }
-    ConstQuestionPtr question = *message.beginQuestion();
-    if (question->getType() != RRType::SOA()) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_NOTIFY_RRTYPE)
-                  .arg(question->getType().toText());
-        makeErrorMessage(renderer_, message, buffer, Rcode::FORMERR(),
-                         stats_attrs, tsig_context);
-        return (true);
-    }
-
-    // According to RFC 1996, rcode should be "no error" and AA bit should be
-    // on, but we don't check these conditions.  This behavior is compatible
-    // with BIND 9.
-
-    // See if we have the specified zone in our data sources; if not return
-    // NOTAUTH, following BIND 9 (this is not specified in RFC 1996).
-    bool is_auth = false;
-    {
-        auth::DataSrcClientsMgr::Holder datasrc_holder(datasrc_clients_mgr_);
-        const boost::shared_ptr<datasrc::ClientList> dsrc_clients =
-            datasrc_holder.findClientList(question->getClass());
-        is_auth = dsrc_clients &&
-            dsrc_clients->find(question->getName(), true, false).exact_match_;
-    }
-    if (!is_auth) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RECEIVED_NOTIFY_NOTAUTH)
-            .arg(question->getName()).arg(question->getClass()).arg(remote_ep);
-        makeErrorMessage(renderer_, message, buffer, Rcode::NOTAUTH(),
-                         stats_attrs, tsig_context);
-        return (true);
-    }
-
-    LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_RECEIVED_NOTIFY)
-        .arg(question->getName()).arg(question->getClass()).arg(remote_ep);
-
-    // xfrin_session_ should have been set and never be replaced except in
-    // tests; otherwise it's an internal bug.  assert() may be too strong,
-    // but processMessage() will catch all exceptions, so there's no better
-    // way.
-    assert(xfrin_session_);
-
-    const string remote_ip_address = remote_ep.getAddress().toText();
-    static const string command_template_start =
-        "{\"command\": [\"notify\", {\"zone_name\" : \"";
-    static const string command_template_master = "\", \"master\" : \"";
-    static const string command_template_rrclass = "\", \"zone_class\" : \"";
-    static const string command_template_end = "\"}]}";
-
-    try {
-        ConstElementPtr notify_command = Element::fromJSON(
-                command_template_start + question->getName().toText() +
-                command_template_master + remote_ip_address +
-                command_template_rrclass + question->getClass().toText() +
-                command_template_end);
-        const unsigned int seq =
-            xfrin_session_->group_sendmsg(notify_command, "Zonemgr",
-                                          CC_INSTANCE_WILDCARD,
-                                          CC_INSTANCE_WILDCARD, true);
-        ConstElementPtr env, answer, parsed_answer;
-        xfrin_session_->group_recvmsg(env, answer, false, seq);
-        int rcode;
-        parsed_answer = parseAnswer(rcode, answer);
-        if (rcode == CC_REPLY_NO_RECPT) {
-            // This can happen when Zonemgr is not running.  When we support
-            // notification-based membership framework, we should check if it's
-            // supposed to be running and shouldn't even send the command if
-            // not.  Until then, we log this event at the debug level as we
-            // don't know whether it's a real trouble or intentional
-            // configuration.  (Also, when it's done, maybe we should simply
-            // propagate the exception and return SERVFAIL to suppress further
-            // NOTIFY).
-            LOG_DEBUG(auth_logger, DBG_AUTH_DETAIL, AUTH_ZONEMGR_NOTEXIST);
-            return (false);
-        } else if (rcode != CC_REPLY_SUCCESS) {
-            LOG_ERROR(auth_logger, AUTH_ZONEMGR_ERROR)
-                      .arg(parsed_answer->str());
-            return (false);
-        }
-    } catch (const isc::Exception& ex) {
-        LOG_ERROR(auth_logger, AUTH_ZONEMGR_COMMS).arg(ex.what());
-        return (false);
-    }
-
-    message.makeResponse();
-    message.setHeaderFlag(Message::HEADERFLAG_AA);
-    message.setRcode(Rcode::NOERROR());
-
-    RendererHolder holder(renderer_, &buffer, stats_attrs);
-    message.toWire(renderer_, tsig_context.get());
-    stats_attrs.setResponseTSIG(tsig_context.get() != NULL);
-    return (true);
-}
-
-bool
-AuthSrvImpl::processUpdate(const IOMessage& io_message)
-{
-    // Push the update request to a separate process via the forwarder.
-    // On successful push, the request shouldn't be responded from b10-auth,
-    // so we return false.
-    ddns_forwarder_->push(io_message);
-    return (false);
-}
-
-void
-AuthSrvImpl::resumeServer(DNSServer* server, Message& message,
-                          MessageAttributes& stats_attrs,
-                          const bool done) {
-    counters_.inc(stats_attrs, message, done);
-    server->resume(done);
-}
-
-ConstElementPtr
-AuthSrv::updateConfig(ConstElementPtr new_config) {
-    try {
-        // the ModuleCCSession has already checked if we have
-        // the correct ElementPtr type as specified in our .spec file
-        if (new_config) {
-            configureAuthServer(*this, new_config);
-        }
-        return (isc::config::createAnswer());
-    } catch (const isc::Exception& error) {
-        LOG_ERROR(auth_logger, AUTH_CONFIG_UPDATE_FAIL).arg(error.what());
-        return (isc::config::createAnswer(1, error.what()));
-    }
-}
-
-ConstElementPtr AuthSrv::getStatistics() const {
-    return (impl_->counters_.get());
-}
-
-const AddressList&
-AuthSrv::getListenAddresses() const {
-    return (impl_->listen_addresses_);
-}
-
-void
-AuthSrv::setListenAddresses(const AddressList& addresses) {
-    // For UDP servers we specify the "SYNC_OK" option because in our usage
-    // it can act in the synchronous mode.
-    installListenAddresses(addresses, impl_->listen_addresses_, *dnss_,
-                           DNSService::SERVER_SYNC_OK);
-}
-
-void
-AuthSrv::setDNSService(isc::asiodns::DNSServiceBase& dnss) {
-    dnss_ = &dnss;
-}
-
-void
-AuthSrv::setTSIGKeyRing(const boost::shared_ptr<TSIGKeyRing>* keyring) {
-    impl_->keyring_ = keyring;
-}
-
-void
-AuthSrv::createDDNSForwarder() {
-    LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_START_DDNS_FORWARDER);
-    impl_->ddns_forwarder_.reset(
-        new SocketSessionForwarderHolder("update",
-                                         impl_->ddns_base_forwarder_));
-}
-
-void
-AuthSrv::destroyDDNSForwarder() {
-    if (impl_->ddns_forwarder_) {
-        LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_STOP_DDNS_FORWARDER);
-        impl_->ddns_forwarder_.reset();
-    }
-}
-
-void
-AuthSrv::setTCPRecvTimeout(size_t timeout) {
-    dnss_->setTCPRecvTimeout(timeout);
-}
-
-namespace {
-
-bool
-hasMappedSegment(auth::DataSrcClientsMgr& mgr) {
-    auth::DataSrcClientsMgr::Holder holder(mgr);
-    const std::vector<dns::RRClass>& classes(holder.getClasses());
-    BOOST_FOREACH(const dns::RRClass& rrclass, classes) {
-        const boost::shared_ptr<datasrc::ConfigurableClientList>&
-            list(holder.findClientList(rrclass));
-        const std::vector<DataSourceStatus>& states(list->getStatus());
-        BOOST_FOREACH(const datasrc::DataSourceStatus& status, states) {
-            if (status.getSegmentState() != datasrc::SEGMENT_UNUSED &&
-                status.getSegmentType() == "mapped")
-                // We use some segment and it's not a local one, so it
-                // must be remote.
-                return true;
-        }
-    }
-    // No remote segment found in any of the lists
-    return false;
-}
-
-}
-
-void
-AuthSrv::listsReconfigured() {
-    const bool has_remote = hasMappedSegment(impl_->datasrc_clients_mgr_);
-    if (has_remote && !impl_->readers_group_subscribed_) {
-        impl_->config_session_->subscribe("SegmentReader");
-        impl_->config_session_->
-            setUnhandledCallback(boost::bind(&AuthSrv::foreignCommand, this,
-                                             _1, _2, _3));
-        impl_->readers_group_subscribed_ = true;
-    } else if (!has_remote && impl_->readers_group_subscribed_) {
-        impl_->config_session_->unsubscribe("SegmentReader");
-        impl_->config_session_->
-            setUnhandledCallback(isc::config::ModuleCCSession::
-                                 UnhandledCallback());
-        impl_->readers_group_subscribed_ = false;
-    }
-}
-
-void
-AuthSrv::reconfigureDone(ConstElementPtr params) {
-    // ACK the segment
-    impl_->config_session_->
-        groupSendMsg(isc::config::createCommand("segment_info_update_ack",
-                                                params), "MemMgr");
-}
-
-void
-AuthSrv::foreignCommand(const std::string& command, const std::string&,
-                        const ConstElementPtr& params)
-{
-    if (command == "segment_info_update") {
-        impl_->datasrc_clients_mgr_.
-            segmentInfoUpdate(params, boost::bind(&AuthSrv::reconfigureDone,
-                                                  this, params));
-    }
-}

+ 0 - 297
src/bin/auth/auth_srv.h

@@ -1,297 +0,0 @@
-// Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef AUTH_SRV_H
-#define AUTH_SRV_H 1
-
-#include <config/ccsession.h>
-
-#include <datasrc/factory.h>
-#include <datasrc/client_list.h>
-#include <datasrc/datasrc_config.h>
-
-#include <dns/message.h>
-#include <dns/opcode.h>
-#include <util/buffer.h>
-
-#include <asiodns/dns_server.h>
-#include <asiodns/dns_service.h>
-#include <asiodns/dns_lookup.h>
-#include <asiodns/dns_answer.h>
-#include <asiolink/io_message.h>
-#include <asiolink/io_service.h>
-#include <asiolink/simple_callback.h>
-
-#include <asiolink/asiolink.h>
-#include <server_common/portconfig.h>
-
-#include <auth/statistics.h>
-#include <auth/datasrc_clients_mgr.h>
-
-#include <boost/shared_ptr.hpp>
-
-namespace isc {
-namespace util {
-namespace io {
-class BaseSocketSessionForwarder;
-}
-namespace thread {
-class Mutex;
-}
-}
-namespace datasrc {
-class ConfigurableClientList;
-}
-namespace xfr {
-class AbstractXfroutClient;
-}
-namespace dns {
-class TSIGKeyRing;
-}
-}
-
-
-/// \brief The implementation class for the \c AuthSrv class using the pimpl
-/// idiom.
-class AuthSrvImpl;
-
-/// \brief The authoritative nameserver class.
-///
-/// \c AuthSrv is a concrete class that implements authoritative DNS server
-/// protocol processing.
-/// An \c AuthSrv object is primarily responsible for handling incoming DNS
-/// requests: It parses the request and dispatches subsequent processing to
-/// the corresponding module (which may be an internal library or a separate
-/// process) depending on the request type.  For normal queries, the
-/// \c AuthSrv object searches configured data sources for the answer to the
-/// query, and builds a response containing the answer.
-///
-/// This class uses the "pimpl" idiom, and hides detailed implementation
-/// through the \c impl_ pointer (which points to an instance of the
-/// \c AuthSrvImpl class).  An \c AuthSrv object is supposed to exist for quite
-/// a long period, and only a few \c AuthSrv objects will be created (in fact,
-/// in this current implementation there will only be one object), so the
-/// construction overhead of this approach should be acceptable.
-///
-/// The design of this class is still in flux.  It's quite likely to change
-/// in future versions.
-///
-class AuthSrv {
-    ///
-    /// \name Constructors, Assignment Operator and Destructor.
-    ///
-    /// Note: The copy constructor and the assignment operator are
-    /// intentionally defined as private.
-    //@{
-private:
-    AuthSrv(const AuthSrv& source);
-    AuthSrv& operator=(const AuthSrv& source);
-public:
-    /// The constructor.
-    ///
-    /// \param xfrout_client Communication interface with a separate xfrout
-    /// process.  It's normally a reference to an xfr::XfroutClient object,
-    /// but can refer to a local mock object for testing (or other
-    /// experimental) purposes.
-    /// \param ddns_forwarder Forwarder to which DDNS UPDATE requests
-    ///                       are passed to
-    AuthSrv(isc::xfr::AbstractXfroutClient& xfrout_client,
-            isc::util::io::BaseSocketSessionForwarder& ddns_forwarder);
-    ~AuthSrv();
-    //@}
-
-    /// Stop the server.
-    ///
-    /// It stops the internal event loop of the server and subsequently
-    /// returns the control to the top level context.
-    ///
-    /// This method should never throw an exception.
-    void stop();
-
-    /// \brief Process an incoming DNS message, then signal 'server' to resume
-    ///
-    /// A DNS query (or other message) has been received by a \c DNSServer
-    /// object.  Find an answer, then post the \c DNSServer object on the
-    /// I/O service queue and return.  When the server resumes, it can
-    /// send the reply.
-    ///
-    /// \param io_message The raw message received
-    /// \param message the \c Message object
-    /// \param buffer an \c OutputBuffer for the resposne
-    /// \param server Pointer to the \c DNSServer
-    ///
-    /// \throw isc::Unexpected Protocol type of \a message is unexpected
-    void processMessage(const isc::asiolink::IOMessage& io_message,
-                        isc::dns::Message& message,
-                        isc::util::OutputBuffer& buffer,
-                        isc::asiodns::DNSServer* server);
-
-    /// \brief Updates the configuration for the \c AuthSrv object.
-    ///
-    /// On success this method returns a data \c Element (in the form of a
-    /// pointer like object) indicating the successful result,
-    /// i.e., {"result": [0]}.
-    /// Otherwise, it returns a data \c Element explaining the error:
-    /// {"result": [1, <error-description>]}.
-    ///
-    /// This method is mostly exception free (error conditions are represented
-    /// via the return value).  But it may still throw a standard exception
-    /// if memory allocation fails inside the method.
-    /// When a standard exception is thrown or an implementation specific
-    /// exception is triggered and caught internally, this function provides
-    /// the strong exception guarantee: Unless everything succeeds, currently
-    /// installed data source (if any) won't be replaced.
-    ///
-    /// \param config An immutable pointer-like object to a data \c Element,
-    /// possibly containing the data source information to be used.
-    /// \return An immutable pointer-like object to a data \c Element
-    /// containing the result of the update operation.
-    isc::data::ConstElementPtr updateConfig(isc::data::ConstElementPtr config);
-
-    /// \brief Returns the command and configuration session for the
-    /// \c AuthSrv.
-    ///
-    /// This method never throws an exception.
-    ///
-    /// \return A pointer to \c ModuleCCSession object stored in the
-    /// \c AuthSrv object.  In this implementation it could be NULL.
-    isc::config::ModuleCCSession* getConfigSession() const;
-
-    /// \brief Set the command and configuration session for the \c AuthSrv.
-    ///
-    /// Note: this interface is tentative.  We'll revisit the ASIO and session
-    /// frameworks, at which point the session will probably be passed on
-    /// construction of the server.
-    /// In the current implementation, this method is expected to be called
-    /// exactly once as part of initialization.  If this method is called
-    /// multiple times, previously specified session is silently overridden.
-    ///
-    /// This method never throws an exception.
-    ///
-    /// \param config_session A pointer to \c ModuleCCSession object to receive
-    /// control commands and configuration updates.
-    void setConfigSession(isc::config::ModuleCCSession* config_session);
-
-    /// \brief Return this object's ASIO IO Service queue
-    isc::asiolink::IOService& getIOService();
-
-    /// \brief Return pointer to the DNS Lookup callback function
-    isc::asiodns::DNSLookup* getDNSLookupProvider() const { return (dns_lookup_); }
-
-    /// \brief Return pointer to the DNS Answer callback function
-    isc::asiodns::DNSAnswer* getDNSAnswerProvider() const { return (dns_answer_); }
-
-    /// \brief Return data source clients manager.
-    ///
-    /// \throw None
-    isc::auth::DataSrcClientsMgr& getDataSrcClientsMgr();
-
-    /// \brief Set the communication session with a separate process for
-    /// outgoing zone transfers.
-    ///
-    /// Note: this interface is tentative.  We'll revisit the ASIO and session
-    /// frameworks, at which point the session will probably be passed on
-    /// construction of the server.
-    ///
-    /// \param xfrin_session A Session object over which NOTIFY message
-    /// information is exchanged with a XFRIN handler.
-    /// The session must be established before setting in the server
-    /// object.
-    /// Ownership isn't transferred: the caller is responsible for keeping
-    /// this object to be valid while the server object is working and for
-    /// disconnecting the session and destroying the object when the server
-    /// is shutdown.
-    ///
-    void setXfrinSession(isc::cc::AbstractSession* xfrin_session);
-
-    /// \brief Returns statistics data
-    ///
-    /// This function can throw an exception from
-    /// Counters::get().
-    ///
-    /// \return JSON format statistics data.
-    isc::data::ConstElementPtr getStatistics() const;
-
-    /**
-     * \brief Set and get the addresses we listen on.
-     */
-    void setListenAddresses(const isc::server_common::portconfig::AddressList&
-                            addresses);
-    const isc::server_common::portconfig::AddressList& getListenAddresses()
-        const;
-
-    /// \brief Assign an ASIO DNS Service queue to this Auth object
-    void setDNSService(isc::asiodns::DNSServiceBase& dnss);
-
-    /// \brief Sets the keyring used for verifying and signing
-    ///
-    /// The parameter is pointer to shared pointer, because the automatic
-    /// reloading routines of tsig keys replace the actual keyring object.
-    /// It is expected the pointer will point to some statically-allocated
-    /// object, it doesn't take ownership of it.
-    void setTSIGKeyRing(const boost::shared_ptr<isc::dns::TSIGKeyRing>*
-                        keyring);
-
-    /// \brief Create the internal forwarder for DDNS update messages
-    ///
-    /// Until this method is called (it is called when the
-    /// start_ddns_forwarder command is sent to b10-auth), b10-auth will
-    /// respond to UPDATE messages with a NOTIMP rcode.
-    /// If the internal forwarder was already created, it is destroyed and
-    /// created again. This is useful for instance when b10-ddns is shut
-    /// down and restarted.
-    void createDDNSForwarder();
-
-    /// \brief Destroy the internal forwarder for DDNS update messages
-    ///
-    /// After this method has been called (it is called when the
-    /// stop_ddns_forwarder command is sent to b10-auth), DDNS Update
-    /// messages are no longer forwarded internally, but b10-auth will
-    /// immediately respond with a NOTIMP rcode.
-    /// If there was no forwarder yet, this method does nothing.
-    void destroyDDNSForwarder();
-
-    /// \brief Sets the timeout for incoming TCP connections
-    ///
-    /// Incoming TCP connections that have not sent their data
-    /// within this time are dropped.
-    ///
-    /// \param timeout The timeout (in milliseconds). If se to
-    /// zero, no timeouts are used, and the connection will remain
-    /// open forever.
-    void setTCPRecvTimeout(size_t timeout);
-
-    /// \brief Notify the authoritative server that the client lists were
-    ///     reconfigured.
-    ///
-    /// This is to be called when the work thread finishes reconfiguration
-    /// of the data sources. It involeves some book keeping and asking the
-    /// memory manager for segments, if some are remotely mapped.
-    void listsReconfigured();
-
-private:
-    void reconfigureDone(isc::data::ConstElementPtr request);
-    void foreignCommand(const std::string& command, const std::string&,
-                        const isc::data::ConstElementPtr& params);
-    AuthSrvImpl* impl_;
-    isc::asiodns::DNSLookup* dns_lookup_;
-    isc::asiodns::DNSAnswer* dns_answer_;
-    isc::asiodns::DNSServiceBase* dnss_;
-};
-
-#endif // AUTH_SRV_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 327
src/bin/auth/b10-auth.xml.pre

@@ -1,327 +0,0 @@
-<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
-               "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
-	       [<!ENTITY mdash "&#8212;">]>
-<!--
- - Copyright (C) 2010-2012  Internet Systems Consortium, Inc. ("ISC")
- -
- - Permission to use, copy, modify, and/or distribute this software for any
- - purpose with or without fee is hereby granted, provided that the above
- - copyright notice and this permission notice appear in all copies.
- -
- - THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
- - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- - AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
- - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
- - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- - PERFORMANCE OF THIS SOFTWARE.
--->
-
-<refentry>
-
-  <refentryinfo>
-    <date>July 16, 2013</date>
-  </refentryinfo>
-
-  <refmeta>
-    <refentrytitle>b10-auth</refentrytitle>
-    <manvolnum>8</manvolnum>
-    <refmiscinfo>BIND10</refmiscinfo>
-  </refmeta>
-
-  <refnamediv>
-    <refname>b10-auth</refname>
-    <refpurpose>Authoritative DNS server</refpurpose>
-  </refnamediv>
-
-  <docinfo>
-    <copyright>
-      <year>2010-2012</year>
-      <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
-    </copyright>
-  </docinfo>
-
-  <refsynopsisdiv>
-    <cmdsynopsis>
-      <command>b10-auth</command>
-      <arg><option>-v</option></arg>
-    </cmdsynopsis>
-  </refsynopsisdiv>
-
-  <refsect1>
-    <title>DESCRIPTION</title>
-    <para>The <command>b10-auth</command> daemon provides the BIND 10
-      authoritative DNS server.
-      Normally it is started by the
-      <citerefentry><refentrytitle>b10-init</refentrytitle><manvolnum>8</manvolnum></citerefentry>
-      process.
-    </para>
-
-    <para>
-      This daemon communicates with other BIND 10 components over a
-      <citerefentry><refentrytitle>b10-msgq</refentrytitle><manvolnum>8</manvolnum></citerefentry>
-      C-Channel connection.  If this connection is not established,
-      <command>b10-auth</command> will exit.
-<!-- TODO what if msgq connection closes later, will b10-auth exit? -->
-      It receives its configurations from
-<citerefentry><refentrytitle>b10-cfgmgr</refentrytitle><manvolnum>8</manvolnum></citerefentry>.
-
-    </para>
-
-<!-- TODO: mention xfrin, xfrout, zonemgr ? -->
-
-  </refsect1>
-
-  <refsect1>
-    <title>OPTIONS</title>
-
-    <para>The arguments are as follows:</para>
-
-    <variablelist>
-      <varlistentry>
-        <term><option>-v</option></term>
-        <listitem><para>
-          Enable verbose logging mode. This enables logging of
-          diagnostic messages at the maximum debug level.
-        </para></listitem>
-      </varlistentry>
-
-    </variablelist>
-
-  </refsect1>
-
-  <refsect1>
-    <title>CONFIGURATION AND COMMANDS</title>
-    <para>
-      The configurable settings are:
-    </para>
-
-    <para>
-      <varname>database_file</varname> defines the path to the
-      SQLite3 zone file when using the sqlite datasource.
-      The default is
-      <filename>@@LOCALSTATEDIR@@/bind10/zone.sqlite3</filename>.
-    </para>
-
-    <para>
-      <varname>datasources</varname> configures data sources.
-      The list items include:
-      <varname>type</varname> to define the required data source type
-      (such as <quote>memory</quote>);
-      <varname>class</varname> to optionally select the class
-      (it defaults to <quote>IN</quote>);
-      and
-      <varname>zones</varname> to define the
-      <varname>file</varname> path name,
-      <varname>origin</varname> (default domain), and optional
-      <varname>filetype</varname>.
-      By default, <varname>zones</varname> is empty.
-      For the in-memory data source (i.e., the <varname>type</varname>
-      is <quote>memory</quote>), the optional <varname>filetype</varname>
-      configuration item for <varname>zones</varname> can be
-      specified so the in-memory zone data can be built from another
-      data source that is based on a database backend (in practice
-      with current implementation, it would be an SQLite3 database
-      file for the SQLite3 data source).
-      See the <citetitle>BIND 10 Guide</citetitle> for configuration
-      details.
-
-      <note><simpara>
-        Only the IN class is supported at this time.
-        By default, the memory data source is disabled.
-        Also, currently the zone file must be canonical such as
-        generated by <command>named-compilezone -D</command>.
-      </simpara></note>
-    </para>
-
-    <para>
-      <varname>listen_on</varname> is a list of addresses and ports for
-      <command>b10-auth</command> to listen on.
-      The list items are the <varname>address</varname> string
-      and <varname>port</varname> number.
-      By default, <command>b10-auth</command> listens on port 53
-      on the IPv6 (::) and IPv4 (0.0.0.0) wildcard addresses.
-    </para>
-
-    <para>
-      <varname>tcp_recv_timeout</varname> is the timeout used on
-      incoming TCP connections, in milliseconds. If the query
-      is not sent within this time, the connection is closed.
-      Setting this to 0 will disable TCP timeouts completely.
-      The default is 5000 (five seconds).
-    </para>
-
-<!-- TODO: formating -->
-    <para>
-      The configuration commands are:
-    </para>
-
-    <para>
-      <command>getstats</command> tells <command>b10-auth</command>
-      to report its defined statistics data in JSON format.
-      It will not report about unused counters.
-      This is used by the
-      <citerefentry><refentrytitle>b10-stats</refentrytitle><manvolnum>8</manvolnum></citerefentry> daemon.
-      (The <command>sendstats</command> command is deprecated.)
-    </para>
-
-    <para>
-      <command>loadzone</command> tells <command>b10-auth</command>
-      to load or reload a zone file. The arguments include:
-      <varname>class</varname> which optionally defines the class
-      (it defaults to <quote>IN</quote>);
-      <varname>origin</varname> is the domain name of the zone;
-      and
-      <varname>datasrc</varname> optionally defines the type of datasource
-      (it defaults to <quote>memory</quote>).
-
-      <note><simpara>
-        In this development version, currently this only supports the
-        IN class and the memory data source.
-      </simpara></note>
-    </para>
-
-    <para>
-      <command>getstats</command> tells <command>b10-auth</command>
-      to send its statistics data.
-    </para>
-
-    <para>
-      <command>shutdown</command> exits <command>b10-auth</command>.
-      This has an optional <varname>pid</varname> argument to
-      select the process ID to stop.
-      (Note that the b10-init process may restart this service
-      if configured.)
-    </para>
-
-    <para>
-      <command>start_ddns_forwarder</command> starts (or restarts) the
-      internal forwarding of DDNS Update messages.
-      This is used by the
-      <citerefentry><refentrytitle>b10-ddns</refentrytitle><manvolnum>8</manvolnum></citerefentry>
-      daemon to tell <command>b10-auth</command> that DDNS Update
-      messages can be forwarded.
-      <note><simpara>This is not expected to be called by administrators;
-        it will be removed as a public command in the future.</simpara></note>
-    </para>
-
-    <para>
-      <command>stop_ddns_forwarder</command> stops the internal
-      forwarding of DDNS Update messages.
-      This is used by the
-      <citerefentry><refentrytitle>b10-ddns</refentrytitle><manvolnum>8</manvolnum></citerefentry>
-      daemon to tell <command>b10-auth</command> that DDNS Update
-      messages should not be forwarded.
-      <note><simpara>This is not expected to be called by administrators;
-        it will be removed as a public command in the future.</simpara></note>
-    </para>
-
-  </refsect1>
-
-  <refsect1>
-    <title>STATISTICS DATA</title>
-
-    <para>
-      The statistics data collected by the <command>b10-stats</command>
-      daemon for <quote>Auth</quote> include:
-    </para>
-
-<!-- ### STATISTICS DATA PLACEHOLDER ### -->
-
-    <note>
-      <para>
-        Opcode of a request message will not be counted if:
-        <itemizedlist>
-          <listitem><para>
-            The request message is too short to parse the message header
-          </para></listitem>
-          <listitem><para>
-            The request message is a response (i.e. QR bit is set)
-          </para></listitem>
-        </itemizedlist>
-      </para>
-
-      <para>
-        Request attributes except for opcode will not be counted if TSIG
-        validation failed as they are not reliable.
-        We always count opcode mainly for compatibility with BIND 9,
-        but remember that if there's any error related to TSIG, some
-        of the counted opcode may not be trustworthy.
-      </para>
-
-      <para>
-        The <quote>qryrecursion</quote> counter is limited to queries
-        (requests of opcode 0) even though the RD bit is not specific
-        to queries.  In practice, this bit is generally just ignored for
-        other types of requests, while DNS servers behave differently
-        for queries depending on this bit.  It is also known that
-        some authoritative-only servers receive a non negligible
-        number of queries with the RD bit being set, so it would be
-        of particular interest to have a specific counters for such
-        requests.
-      </para>
-
-      <para>
-        There are two request counters related to EDNS:
-        <quote>request.edns0</quote> and <quote>request.badednsver</quote>.
-        The latter is a counter of requests with unsupported EDNS version:
-        other than version 0 in the current implementation. Therefore, total
-        number of requests with EDNS is a sum of <quote>request.edns0</quote>
-        and <quote>request.badednsver</quote>.
-      </para>
-    </note>
-
-  </refsect1>
-
-  <refsect1>
-    <title>FILES</title>
-    <para>
-      <filename>@@LOCALSTATEDIR@@/bind10/zone.sqlite3</filename>
-      &mdash; Location for the SQLite3 zone database
-      when <emphasis>database_file</emphasis> configuration is not
-      defined.
-    </para>
-  </refsect1>
-
-  <refsect1>
-    <title>SEE ALSO</title>
-    <para>
-      <citerefentry>
-        <refentrytitle>b10-cfgmgr</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>b10-ddns</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>b10-init</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>b10-loadzone</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>b10-msgq</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>b10-stats</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>b10-zonemgr</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citerefentry>
-        <refentrytitle>bind10</refentrytitle><manvolnum>8</manvolnum>
-      </citerefentry>,
-      <citetitle>BIND 10 Guide</citetitle>.
-    </para>
-  </refsect1>
-
-  <refsect1>
-    <title>HISTORY</title>
-    <para>
-      The <command>b10-auth</command> daemon was first coded in October 2009.
-    </para>
-  </refsect1>
-</refentry><!--
- - Local variables:
- - mode: sgml
- - End:
--->

+ 0 - 1
src/bin/auth/benchmarks/.gitignore

@@ -1 +0,0 @@
-/query_bench

+ 0 - 39
src/bin/auth/benchmarks/Makefile.am

@@ -1,39 +0,0 @@
-AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
-AM_CPPFLAGS += -I$(top_srcdir)/src/bin -I$(top_builddir)/src/bin
-AM_CPPFLAGS += $(BOOST_INCLUDES)
-
-AM_CXXFLAGS = $(B10_CXXFLAGS)
-
-if USE_STATIC_LINK
-AM_LDFLAGS = -static
-endif
-
-CLEANFILES = *.gcno *.gcda
-
-noinst_PROGRAMS = query_bench
-query_bench_SOURCES = query_bench.cc
-query_bench_SOURCES += ../query.h  ../query.cc
-query_bench_SOURCES += ../auth_srv.h ../auth_srv.cc
-query_bench_SOURCES += ../auth_config.h ../auth_config.cc
-query_bench_SOURCES += ../statistics.h ../statistics.cc ../statistics_items.h
-query_bench_SOURCES += ../auth_log.h ../auth_log.cc
-query_bench_SOURCES += ../datasrc_config.h ../datasrc_config.cc
-
-nodist_query_bench_SOURCES = ../auth_messages.h ../auth_messages.cc
-
-query_bench_LDADD = $(top_builddir)/src/lib/dns/libb10-dns++.la
-query_bench_LDADD += $(top_builddir)/src/lib/util/libb10-util.la
-query_bench_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
-query_bench_LDADD += $(top_builddir)/src/lib/bench/libb10-bench.la
-query_bench_LDADD += $(top_builddir)/src/lib/datasrc/libb10-datasrc.la
-query_bench_LDADD += $(top_builddir)/src/lib/config/libb10-cfgclient.la
-query_bench_LDADD += $(top_builddir)/src/lib/cc/libb10-cc.la
-query_bench_LDADD += $(top_builddir)/src/lib/xfr/libb10-xfr.la
-query_bench_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
-query_bench_LDADD += $(top_builddir)/src/lib/nsas/libb10-nsas.la
-query_bench_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
-query_bench_LDADD += $(top_builddir)/src/lib/server_common/libb10-server-common.la
-query_bench_LDADD += $(top_builddir)/src/lib/asiodns/libb10-asiodns.la
-query_bench_LDADD += $(top_builddir)/src/lib/util/threads/libb10-threads.la
-query_bench_LDADD += $(SQLITE_LIBS)
-

+ 0 - 305
src/bin/auth/benchmarks/query_bench.cc

@@ -1,305 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include <bench/benchmark.h>
-#include <bench/benchmark_util.h>
-
-#include <util/buffer.h>
-
-#include <dns/message.h>
-#include <dns/name.h>
-#include <dns/question.h>
-#include <dns/rrclass.h>
-
-#include <log/logger_support.h>
-#include <xfr/xfrout_client.h>
-
-#include <util/unittests/mock_socketsession.h>
-
-#include <auth/auth_srv.h>
-#include <auth/auth_config.h>
-#include <auth/datasrc_config.h>
-#include <auth/datasrc_clients_mgr.h>
-#include <auth/query.h>
-
-#include <asiodns/asiodns.h>
-#include <asiolink/asiolink.h>
-
-#include <boost/shared_ptr.hpp>
-
-#include <stdlib.h>
-
-#include <iostream>
-#include <vector>
-
-using namespace std;
-using namespace isc;
-using namespace isc::data;
-using namespace isc::auth;
-using namespace isc::dns;
-using namespace isc::log;
-using namespace isc::util;
-using namespace isc::util::unittests;
-using namespace isc::xfr;
-using namespace isc::bench;
-using namespace isc::asiodns;
-using namespace isc::asiolink;
-
-namespace {
-// Commonly used constant:
-XfroutClient xfrout_client("dummy_path"); // path doesn't matter
-
-// Just something to pass as the server to resume
-class DummyServer : public DNSServer {
-    public:
-        virtual void operator()(asio::error_code, size_t) {}
-        virtual void resume(const bool) {}
-        virtual DNSServer* clone() {
-            return (new DummyServer(*this));
-        }
-};
-
-class QueryBenchMark {
-protected:
-    // Maintain dynamically generated objects via shared pointers because
-    // QueryBenchMark objects will be copied.
-    typedef boost::shared_ptr<AuthSrv> AuthSrvPtr;
-private:
-    typedef boost::shared_ptr<const IOEndpoint> IOEndpointPtr;
-protected:
-    QueryBenchMark(const BenchQueries& queries, Message& query_message,
-                   OutputBuffer& buffer) :
-        server_(new AuthSrv(xfrout_client, ddns_forwarder)),
-        queries_(queries),
-        query_message_(query_message),
-        buffer_(buffer),
-        dummy_socket(IOSocket::getDummyUDPSocket()),
-        dummy_endpoint(IOEndpointPtr(IOEndpoint::create(IPPROTO_UDP,
-                                                        IOAddress("192.0.2.1"),
-                                                        53210)))
-    {}
-public:
-    unsigned int run() {
-        BenchQueries::const_iterator query;
-        const BenchQueries::const_iterator query_end = queries_.end();
-        DummyServer server;
-        for (query = queries_.begin(); query != query_end; ++query) {
-            IOMessage io_message(&(*query)[0], (*query).size(), dummy_socket,
-                                 *dummy_endpoint);
-            query_message_.clear(Message::PARSE);
-            buffer_.clear();
-            server_->processMessage(io_message, query_message_, buffer_,
-                                    &server);
-        }
-
-        return (queries_.size());
-    }
-private:
-    MockSocketSessionForwarder ddns_forwarder;
-protected:
-    AuthSrvPtr server_;
-private:
-    const BenchQueries& queries_;
-    Message& query_message_;
-    OutputBuffer& buffer_;
-    IOSocket& dummy_socket;
-    IOEndpointPtr dummy_endpoint;
-};
-
-class Sqlite3QueryBenchMark  : public QueryBenchMark {
-public:
-    Sqlite3QueryBenchMark(const char* const datasrc_file,
-                          const BenchQueries& queries,
-                          Message& query_message,
-                          OutputBuffer& buffer) :
-        QueryBenchMark(queries, query_message, buffer)
-    {
-        // Note: setDataSrcClientLists() may be deprecated, but until then
-        // we use it because we want to be synchronized with the server.
-        server_->getDataSrcClientsMgr().setDataSrcClientLists(
-            configureDataSource(
-                Element::fromJSON("{\"IN\":"
-                                  "  [{\"type\": \"sqlite3\","
-                                  "    \"params\": {"
-                                  "      \"database_file\": \"" +
-                                  string(datasrc_file) + "\"}}]}")));
-    }
-};
-
-class MemoryQueryBenchMark  : public QueryBenchMark {
-public:
-    MemoryQueryBenchMark(const char* const zone_file,
-                         const char* const zone_origin,
-                         const BenchQueries& queries,
-                         Message& query_message,
-                         OutputBuffer& buffer) :
-        QueryBenchMark(queries, query_message, buffer)
-    {
-        server_->getDataSrcClientsMgr().setDataSrcClientLists(
-            configureDataSource(
-                Element::fromJSON("{\"IN\":"
-                                  "  [{\"type\": \"MasterFiles\","
-                                  "    \"cache-enable\": true, "
-                                  "    \"params\": {\"" +
-                                  string(zone_origin) + "\": \"" +
-                                  string(zone_file) + "\"}}]}")));
-    }
-};
-
-void
-printQPSResult(unsigned int iteration, double duration,
-            double iteration_per_second)
-{
-    cout.precision(6);
-    cout << "Processed " << iteration << " queries in "
-         << fixed << duration << "s";
-    cout.precision(2);
-    cout << " (" << fixed << iteration_per_second << "qps)" << endl;
-}
-}
-
-namespace isc {
-namespace bench {
-template<>
-void
-BenchMark<Sqlite3QueryBenchMark>::printResult() const {
-    printQPSResult(getIteration(), getDuration(), getIterationPerSecond());
-}
-
-template<>
-void
-BenchMark<MemoryQueryBenchMark>::printResult() const {
-    printQPSResult(getIteration(), getDuration(), getIterationPerSecond());
-}
-}
-}
-
-namespace {
-const int ITERATION_DEFAULT = 1;
-enum DataSrcType {
-    SQLITE3,
-    MEMORY
-};
-
-void
-usage() {
-    cerr <<
-        "Usage: query_bench [-d] [-n iterations] [-t datasrc_type] [-o origin]"
-        " datasrc_file query_datafile\n"
-        "  -d Enable debug logging to stdout\n"
-        "  -n Number of iterations per test case (default: "
-         << ITERATION_DEFAULT << ")\n"
-        "  -t Type of data source: sqlite3|memory (default: sqlite3)\n"
-        "  -o Origin name of datasrc_file necessary for \"memory\", "
-        "ignored for others\n"
-        "  datasrc_file: sqlite3 DB file for \"sqlite3\", "
-        "textual master file for \"memory\" datasrc\n"
-        "  query_datafile: queryperf style input data"
-         << endl;
-    exit (1);
-}
-}
-
-int
-main(int argc, char* argv[]) {
-    int ch;
-    int iteration = ITERATION_DEFAULT;
-    const char* opt_datasrc_type = "sqlite3";
-    const char* origin = NULL;
-    bool debug_log = false;
-    while ((ch = getopt(argc, argv, "dn:t:o:")) != -1) {
-        switch (ch) {
-        case 'n':
-            iteration = atoi(optarg);
-            break;
-        case 't':
-            opt_datasrc_type = optarg;
-            break;
-        case 'o':
-            origin = optarg;
-            break;
-        case 'd':
-            debug_log = true;
-            break;
-        case '?':
-        default:
-            usage();
-        }
-    }
-    argc -= optind;
-    argv += optind;
-    if (argc < 2) {
-        usage();
-    }
-    const char* const datasrc_file = argv[0];
-    const char* const query_data_file = argv[1];
-
-    // By default disable logging to avoid unwanted noise.
-    initLogger("query-bench", debug_log ? isc::log::DEBUG : isc::log::NONE,
-               isc::log::MAX_DEBUG_LEVEL, NULL);
-
-    DataSrcType datasrc_type = SQLITE3;
-    if (strcmp(opt_datasrc_type, "sqlite3") == 0) {
-        ;                       // no need to override
-    } else if (strcmp(opt_datasrc_type, "memory") == 0) {
-        datasrc_type = MEMORY;
-    } else {
-        cerr << "Unknown data source type: " << datasrc_type << endl;
-        return (1);
-    }
-
-    if (datasrc_type == MEMORY && origin == NULL) {
-        cerr << "'-o Origin' is missing for memory data source " << endl;
-        return (1);
-    }
-
-    try {
-        BenchQueries queries;
-        loadQueryData(query_data_file, queries, RRClass::IN());
-        OutputBuffer buffer(4096);
-        Message message(Message::PARSE);
-
-        cout << "Parameters:" << endl;
-        cout << "  Iterations: " << iteration << endl;
-        cout << "  Data Source: type=" << opt_datasrc_type << ", file=" <<
-            datasrc_file << endl;
-        if (origin != NULL) {
-            cout << "  Origin: " << origin << endl;
-        }
-        cout << "  Query data: file=" << query_data_file << " ("
-             << queries.size() << " queries)" << endl << endl;
-
-        switch (datasrc_type) {
-        case SQLITE3:
-            cout << "Benchmark with SQLite3" << endl;
-            BenchMark<Sqlite3QueryBenchMark>(
-                iteration, Sqlite3QueryBenchMark(datasrc_file, queries,
-                                                 message, buffer));
-            break;
-        case MEMORY:
-            cout << "Benchmark with In Memory Data Source" << endl;
-            BenchMark<MemoryQueryBenchMark>(
-                iteration, MemoryQueryBenchMark(datasrc_file, origin, queries,
-                                                message, buffer));
-            break;
-        }
-    } catch (const std::exception& ex) {
-        cout << "Test unexpectedly failed: " << ex.what() << endl;
-        return (1);
-    }
-
-    return (0);
-}

+ 0 - 224
src/bin/auth/command.cc

@@ -1,224 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <auth/command.h>
-#include <auth/auth_log.h>
-#include <auth/auth_srv.h>
-#include <auth/datasrc_clients_mgr.h>
-
-#include <cc/data.h>
-#include <datasrc/client_list.h>
-#include <config/ccsession.h>
-#include <exceptions/exceptions.h>
-#include <dns/rrclass.h>
-
-#include <string>
-
-#include <boost/scoped_ptr.hpp>
-#include <boost/shared_ptr.hpp>
-
-#include <sys/types.h>
-#include <unistd.h>
-
-using boost::scoped_ptr;
-using namespace isc::auth;
-using namespace isc::config;
-using namespace isc::data;
-using namespace isc::datasrc;
-using namespace isc::dns;
-using namespace std;
-
-namespace {
-/// An exception that is thrown if an error occurs while handling a command
-/// on an \c AuthSrv object.
-///
-/// Currently it's only used internally, since \c execAuthServerCommand()
-/// (which is the only interface to this module) catches all \c isc::
-/// exceptions and converts them.
-class AuthCommandError : public isc::Exception {
-public:
-    AuthCommandError(const char* file, size_t line, const char* what) :
-        isc::Exception(file, line, what) {}
-};
-
-/// An abstract base class that represents a single command identifier
-/// for an \c AuthSrv object.
-///
-/// Each of derived classes of \c AuthCommand, which are hidden inside the
-/// implementation, corresponds to a command executed on \c AuthSrv, such as
-/// "shutdown".  The derived class is responsible to execute the corresponding
-/// command with the given command arguments (if any) in its \c exec()
-/// method.
-///
-/// In the initial implementation the existence of the command classes is
-/// hidden inside the implementation since the only public interface is
-/// \c execAuthServerCommand(), which does not expose this class.
-/// In future, we may want to make this framework more dynamic, i.e.,
-/// registering specific derived classes run time outside of this
-/// implementation.  If and when that happens the definition of the abstract
-/// class will be published.
-class AuthCommand {
-    ///
-    /// \name Constructors and Destructor
-    ///
-    /// Note: The copy constructor and the assignment operator are
-    /// intentionally defined as private to make it explicit that this is a
-    /// pure base class.
-    //@{
-private:
-    AuthCommand(const AuthCommand& source);
-    AuthCommand& operator=(const AuthCommand& source);
-protected:
-    /// \brief The default constructor.
-    ///
-    /// This is intentionally defined as \c protected as this base class should
-    /// never be instantiated (except as part of a derived class).
-    AuthCommand() {}
-public:
-    /// The destructor.
-    virtual ~AuthCommand() {}
-    //@}
-
-    /// Execute a single control command.
-    ///
-    /// Specific derived methods can throw exceptions.  When called via
-    /// \c execAuthServerCommand(), all BIND 10 exceptions are caught
-    /// and converted into an error code.
-    /// The derived method may also throw an exception of class
-    /// \c AuthCommandError when it encounters an internal error, such as
-    /// semantics error on the command arguments.
-    ///
-    /// This method should return the execution result in the form of
-    /// \c ConstElementPtr.  It will be transparently used as the return
-    /// value from the command handler called from the corresponding
-    /// \c CCSession object.  For a successful completion of the command,
-    /// it should suffice to return the return value of
-    /// \c isc::config::createAnswer() with no argument.
-    ///
-    /// \param server The \c AuthSrv object on which the command is executed.
-    /// \param args Command specific argument.
-    /// \return Command execution result.
-    virtual ConstElementPtr exec(AuthSrv& server,
-                                 isc::data::ConstElementPtr args) = 0;
-};
-
-// Handle the "shutdown" command. An optional parameter "pid" is used to
-// see if it is really for our instance.
-class ShutdownCommand : public AuthCommand {
-public:
-    virtual ConstElementPtr exec(AuthSrv& server,
-                                 isc::data::ConstElementPtr args)
-    {
-        // Is the pid argument provided?
-        if (args && args->contains("pid")) {
-            // If it is, we check it is the same as our PID
-
-            // This might throw in case the type is not an int, but that's
-            // OK, as it'll get converted to an error on higher level.
-            const int pid(args->get("pid")->intValue());
-            const pid_t my_pid(getpid());
-            if (my_pid != pid) {
-                // It is not for us
-                //
-                // Note that this is completely expected situation, if
-                // there are multiple instances of the server running and
-                // another instance is being shut down, we get the message
-                // too, due to the multicast nature of our message bus.
-                return (createAnswer());
-            }
-        }
-        LOG_DEBUG(auth_logger, DBG_AUTH_SHUT, AUTH_SHUTDOWN);
-        server.stop();
-        return (createAnswer());
-    }
-};
-
-// Handle the "getstats" command.  The argument is a list.
-class GetStatsCommand : public AuthCommand {
-public:
-    virtual ConstElementPtr exec(AuthSrv& server, isc::data::ConstElementPtr) {
-        return (createAnswer(0, server.getStatistics()));
-    }
-};
-
-class StartDDNSForwarderCommand : public AuthCommand {
-public:
-    virtual ConstElementPtr exec(AuthSrv& server,
-                                 isc::data::ConstElementPtr) {
-        server.createDDNSForwarder();
-        return (createAnswer());
-    }
-};
-
-class StopDDNSForwarderCommand : public AuthCommand {
-public:
-    virtual ConstElementPtr exec(AuthSrv& server,
-                                 isc::data::ConstElementPtr) {
-        server.destroyDDNSForwarder();
-        return (createAnswer());
-    }
-};
-
-// Handle the "loadzone" command.
-class LoadZoneCommand : public AuthCommand {
-public:
-    virtual ConstElementPtr exec(AuthSrv& server,
-                                 isc::data::ConstElementPtr args)
-    {
-        server.getDataSrcClientsMgr().loadZone(args);
-        return (createAnswer());
-    }
-};
-
-// The factory of command objects.
-AuthCommand*
-createAuthCommand(const string& command_id) {
-    // For the initial implementation we use a naive if-else blocks
-    // (see also createAuthConfigParser())
-    if (command_id == "shutdown") {
-        return (new ShutdownCommand());
-    } else if (command_id == "getstats") {
-        return (new GetStatsCommand());
-    } else if (command_id == "loadzone") {
-        return (new LoadZoneCommand());
-    } else if (command_id == "start_ddns_forwarder") {
-        return (new StartDDNSForwarderCommand());
-    } else if (command_id == "stop_ddns_forwarder") {
-        return (new StopDDNSForwarderCommand());
-    } else if (false && command_id == "_throw_exception") {
-        // This is for testing purpose only and should not appear in the
-        // actual configuration syntax.
-        // XXX: ModuleCCSession doesn't seem to validate commands (unlike
-        // config), so we should disable this case for now.
-        throw runtime_error("throwing for test");
-    }
-
-    isc_throw(AuthCommandError, "Unknown command identifier: " << command_id);
-}
-} // end of unnamed namespace
-
-ConstElementPtr
-execAuthServerCommand(AuthSrv& server, const string& command_id,
-                      ConstElementPtr args)
-{
-    LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_RECEIVED_COMMAND).arg(command_id);
-    try {
-        return (scoped_ptr<AuthCommand>(
-                    createAuthCommand(command_id))->exec(server, args));
-    } catch (const isc::Exception& ex) {
-        LOG_ERROR(auth_logger, AUTH_COMMAND_FAILED).arg(command_id)
-                                                   .arg(ex.what());
-        return (createAnswer(1, ex.what()));
-    }
-}

+ 0 - 61
src/bin/auth/command.h

@@ -1,61 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <string>
-
-#include <cc/data.h>
-
-#ifndef COMMAND_H
-#define COMMAND_H 1
-
-class AuthSrv;
-
-/// Execute a control command on \c AuthSrv
-///
-/// It executes the operation identified by \c command_id with arguments
-/// \c args on \c server, and returns the result in the form of the standard
-/// command/config answer message (see \c isc::config::createAnswer()).
-///
-/// This method internally performs minimal validation on \c command_id and
-/// \c args to not cause a surprising result such as a crash, but it is
-/// generally expected that the caller has performed syntax level validation
-/// based on the command specification for the authoritative server.
-/// For example, the caller is responsible \c command_id is a valid command
-/// name for the authoritative server.
-///
-/// The execution of the command may internally trigger an exception; for
-/// instance, if a string that is expected to be a valid domain name is bogus,
-/// the underlying DNS library will throw an exception.  These internal
-/// exceptions will be caught inside this function, and will be converted
-/// to a return value with a non 0 error code.
-/// However, exceptions thrown outside of BIND 10 modules (including standard
-/// exceptions) are expected to be handled at a higher layer, and will be
-/// propagated to the caller.  In particular if memory allocation fails and
-/// \c std::bad_alloc is thrown it will be propagated.
-///
-/// \param server The \c AuthSrv object on which the command is executed.
-/// \param command_id The identifier of the command (such as "shutdown")
-/// \param args Command specific argument in a map type of
-/// \c isc::data::Element, or a \c NULL \c ElementPtr if the argument isn't
-/// specified.
-/// \return The result of the command operation.
-isc::data::ConstElementPtr
-execAuthServerCommand(AuthSrv& server, const std::string& command_id,
-                      isc::data::ConstElementPtr args);
-
-#endif // COMMAND_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 60
src/bin/auth/common.cc

@@ -1,60 +0,0 @@
-// Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <string>
-
-#include <auth/common.h>
-#include <auth/spec_config.h>
-#include <stdlib.h>
-
-using std::string;
-
-string
-getXfroutSocketPath() {
-    if (getenv("B10_FROM_BUILD") != NULL) {
-        if (getenv("B10_FROM_SOURCE_LOCALSTATEDIR") != NULL) {
-            return (string(getenv("B10_FROM_SOURCE_LOCALSTATEDIR")) +
-                    "/auth_xfrout_conn");
-        } else {
-            return (string(getenv("B10_FROM_BUILD")) + "/auth_xfrout_conn");
-        }
-    } else {
-        if (getenv("BIND10_XFROUT_SOCKET_FILE") != NULL) {
-            return (getenv("BIND10_XFROUT_SOCKET_FILE"));
-        } else {
-            return (UNIX_XFROUT_SOCKET_FILE);
-        }
-    }
-}
-
-string
-getDDNSSocketPath() {
-    if (getenv("B10_FROM_BUILD") != NULL) {
-        if (getenv("B10_FROM_SOURCE_LOCALSTATEDIR") != NULL) {
-            return (string(getenv("B10_FROM_SOURCE_LOCALSTATEDIR")) +
-                    "/ddns_socket");
-        } else {
-            return (string(getenv("B10_FROM_BUILD")) + "/ddns_socket");
-        }
-    } else {
-        if (getenv("BIND10_DDNS_SOCKET_FILE") != NULL) {
-            return (getenv("BIND10_DDNS_SOCKET_FILE"));
-        } else {
-            return (UNIX_DDNS_SOCKET_FILE);
-        }
-    }
-}
-
-const char* const AUTH_NAME = "b10-auth";
-const char* const AUTH_STARTED_NOTIFICATION = "auth_started";

+ 0 - 69
src/bin/auth/common.h

@@ -1,69 +0,0 @@
-// Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef COMMON_H
-#define COMMON_H 1
-
-#include <stdexcept>
-#include <string>
-
-/// An exception class that is thrown in an unrecoverable error condition.
-///
-/// This exception should not be caught except at the highest level of
-/// the application only for terminating the program gracefully, and so
-/// it cannot be a derived class of \c isc::Exception.
-class FatalError : public std::runtime_error {
-public:
-    FatalError(const std::string& what) : std::runtime_error(what)
-    {}
-};
-
-/// \short Get the path of socket to talk to xfrout
-///
-/// It takes some environment variables into account (B10_FROM_BUILD,
-/// B10_FROM_SOURCE_LOCALSTATEDIR and BIND10_XFROUT_SOCKET_FILE). It
-/// also considers the installation prefix.
-///
-/// The logic should be the same as in b10-xfrout, so they find each other.
-std::string getXfroutSocketPath();
-
-/// \brief Get the path of socket to talk to ddns
-///
-/// It takes some environment variables into account (B10_FROM_BUILD,
-/// B10_FROM_SOURCE_LOCALSTATEDIR and BIND10_DDNS_SOCKET_FILE). It
-/// also considers the installation prefix.
-///
-/// The logic should be the same as in b10-ddns, so they find each other.
-///
-/// Note: eventually we should find a better way so that we don't have to
-/// repeat the same magic value (and how to tweak it with some magic
-/// environment variable) twice, at which point this function may be able
-/// to be deprecated.
-std::string getDDNSSocketPath();
-
-/// \brief The name used when identifieng the process
-///
-/// This is currently b10-auth, but it can be changed easily in one place.
-extern const char* const AUTH_NAME;
-
-/// \brief Notification string that is used to inform auth is starting
-///
-/// This is sent to interested modules (currently only b10-ddns)
-extern const char* const AUTH_STARTED_NOTIFICATION;
-
-#endif // COMMON_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 922
src/bin/auth/datasrc_clients_mgr.h

@@ -1,922 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef DATASRC_CLIENTS_MGR_H
-#define DATASRC_CLIENTS_MGR_H 1
-
-#include <util/threads/thread.h>
-#include <util/threads/sync.h>
-
-#include <log/logger_support.h>
-#include <log/log_dbglevels.h>
-
-#include <dns/rrclass.h>
-
-#include <cc/data.h>
-
-#include <datasrc/exceptions.h>
-#include <datasrc/client_list.h>
-#include <datasrc/memory/zone_writer.h>
-
-#include <asiolink/io_service.h>
-#include <asiolink/local_socket.h>
-
-#include <auth/auth_log.h>
-#include <auth/datasrc_config.h>
-
-#include <boost/array.hpp>
-#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/noncopyable.hpp>
-#include <boost/function.hpp>
-#include <boost/foreach.hpp>
-
-#include <exception>
-#include <cassert>
-#include <cerrno>
-#include <list>
-#include <utility>
-#include <sys/types.h>
-#include <sys/socket.h>
-
-namespace isc {
-namespace auth {
-
-/// \brief An exception that is thrown if initial checks for a command fail
-///
-/// This is raised *before* the command to the thread is constructed and
-/// sent, so the application can still handle them (and therefore it is
-/// public, as opposed to InternalCommandError).
-///
-/// And example of its use is currently in loadZone().
-class CommandError : public isc::Exception {
-public:
-    CommandError(const char* file, size_t line, const char* what) :
-        isc::Exception(file, line, what) {}
-};
-
-namespace datasrc_clientmgr_internal {
-// This namespace is essentially private for DataSrcClientsMgr(Base) and
-// DataSrcClientsBuilder(Base).  This is exposed in the public header
-// only because these classes are templated (for testing purposes) and
-// class internal has to be defined here.
-
-/// \brief ID of commands from the DataSrcClientsMgr to DataSrcClientsBuilder.
-enum CommandID {
-    NOOP,         ///< Do nothing.  Only useful for tests; no argument
-    RECONFIGURE,  ///< Reconfigure the datasource client lists,
-                  ///  the argument to the command is the full new
-                  ///  datasources configuration.
-    LOADZONE,     ///< Load a new version of zone into a memory,
-                  ///  the argument to the command is a map containing 'class'
-                  ///  and 'origin' elements, both should have been validated.
-    SEGMENT_INFO_UPDATE, ///< The memory manager sent an update about segments.
-    SHUTDOWN,     ///< Shutdown the builder; no argument
-    NUM_COMMANDS
-};
-
-/// \brief Callback to be called when the command is completed.
-typedef boost::function<void ()> FinishedCallback;
-
-/// \brief The data type passed from DataSrcClientsMgr to
-///     DataSrcClientsBuilder.
-///
-/// This just holds the data items together, no logic or protection
-/// is present here.
-struct Command {
-    /// \brief Constructor
-    ///
-    /// It just initializes the member variables of the same names
-    /// as the parameters.
-    Command(CommandID id, const data::ConstElementPtr& params,
-            const FinishedCallback& callback) :
-        id(id),
-        params(params),
-        callback(callback)
-    {}
-    /// \brief The command to execute
-    CommandID id;
-    /// \brief Argument of the command.
-    ///
-    /// If the command takes no argument, it should be null pointer.
-    ///
-    /// This may be a null pointer if the command takes no parameters.
-    data::ConstElementPtr params;
-    /// \brief A callback to be called once the command finishes.
-    ///
-    /// This may be an empty boost::function. In such case, no callback
-    /// will be called after completion.
-    FinishedCallback callback;
-};
-
-} // namespace datasrc_clientmgr_internal
-
-/// \brief Frontend to the manager object for data source clients.
-///
-/// This class provides interfaces for configuring and updating a set of
-/// data source clients "in the background".  The user of this class can
-/// assume any operation on this class can be done effectively non-blocking,
-/// not suspending any delay-sensitive operations such as DNS query
-/// processing.  The only exception is the time when this class object
-/// is destroyed (normally as a result of an implicit call to the destructor);
-/// in the current implementation it can take time depending on what is
-/// running "in the background" at the time of the call.
-///
-/// Internally, an object of this class invokes a separate thread to perform
-/// time consuming operations such as loading large zone data into memory,
-/// but such details are completely hidden from the user of this class.
-///
-/// This class is templated only so that we can test the class without
-/// involving actual threads or mutex.  Normal applications will only
-/// need one specific specialization that has a typedef of
-/// \c DataSrcClientsMgr.
-template <typename ThreadType, typename BuilderType, typename MutexType,
-          typename CondVarType>
-class DataSrcClientsMgrBase : boost::noncopyable {
-private:
-    typedef std::map<dns::RRClass,
-                     boost::shared_ptr<datasrc::ConfigurableClientList> >
-    ClientListsMap;
-
-    class FDGuard : boost::noncopyable {
-    public:
-        FDGuard(DataSrcClientsMgrBase *mgr) :
-            mgr_(mgr)
-        {}
-        ~FDGuard() {
-            if (mgr_->read_fd_ != -1) {
-                close(mgr_->read_fd_);
-            }
-            if (mgr_->write_fd_ != -1) {
-                close(mgr_->write_fd_);
-            }
-        }
-    private:
-        DataSrcClientsMgrBase* mgr_;
-    };
-    friend class FDGuard;
-
-public:
-    /// \brief Thread-safe accessor to the data source client lists.
-    ///
-    /// This class provides a simple wrapper for searching the client lists
-    /// stored in the DataSrcClientsMgr in a thread-safe manner.
-    /// It ensures the result of \c getClientList() can be used without
-    /// causing a race condition with other threads that can possibly use
-    /// the same manager throughout the lifetime of the holder object.
-    ///
-    /// This also means the holder object is expected to have a short lifetime.
-    /// The application shouldn't try to keep it unnecessarily long.
-    /// It's normally expected to create the holder object on the stack
-    /// of a small scope and automatically let it be destroyed at the end
-    /// of the scope.
-    class Holder {
-    public:
-        Holder(DataSrcClientsMgrBase& mgr) :
-            mgr_(mgr), locker_(mgr_.map_mutex_)
-        {}
-
-        /// \brief Find a data source client list of a specified RR class.
-        ///
-        /// It returns a pointer to the list stored in the manager if found,
-        /// otherwise it returns NULL.  The manager keeps the ownership of
-        /// the pointed object.  Also, it's not safe to get access to the
-        /// object beyond the scope of the holder object.
-        ///
-        /// \note Since the ownership isn't transferred the return value
-        /// could be a bare pointer (and it's probably better in several
-        /// points).  Unfortunately, some unit tests currently don't work
-        /// unless this method effectively shares the ownership with the
-        /// tests.  That's the only reason why we return a shared pointer
-        /// for now.  We should eventually fix it and change the return value
-        /// type (see Trac ticket #2395).  Other applications must not
-        /// assume the ownership is actually shared.
-        boost::shared_ptr<datasrc::ConfigurableClientList> findClientList(
-            const dns::RRClass& rrclass)
-        {
-            const ClientListsMap::const_iterator
-                it = mgr_.clients_map_->find(rrclass);
-            if (it == mgr_.clients_map_->end()) {
-                return (boost::shared_ptr<datasrc::ConfigurableClientList>());
-            } else {
-                return (it->second);
-            }
-        }
-        /// \brief Return list of classes that are present.
-        ///
-        /// Get the list of classes for which there's a client list. It is
-        /// returned in form of a vector, copied from the internals. As the
-        /// number of classes in there is expected to be small, it is not
-        /// a performance issue.
-        ///
-        /// \return The list of classes.
-        /// \throw std::bad_alloc for problems allocating the result.
-        std::vector<dns::RRClass> getClasses() const {
-            std::vector<dns::RRClass> result;
-            for (ClientListsMap::const_iterator it =
-                 mgr_.clients_map_->begin(); it != mgr_.clients_map_->end();
-                 ++it) {
-                result.push_back(it->first);
-            }
-            return (result);
-        }
-    private:
-        DataSrcClientsMgrBase& mgr_;
-        typename MutexType::Locker locker_;
-    };
-
-    /// \brief Constructor.
-    ///
-    /// It internally invokes a separate thread and waits for further
-    /// operations from the user application.
-    ///
-    /// This method is basically exception free except in case of really
-    /// rare system-level errors.  When that happens the only reasonable
-    /// action that the application can take would be to terminate the program
-    /// in practice.
-    ///
-    /// \throw std::bad_alloc internal memory allocation failure.
-    /// \throw isc::Unexpected general unexpected system errors.
-    DataSrcClientsMgrBase(asiolink::IOService& service) :
-        clients_map_(new ClientListsMap),
-        fd_guard_(new FDGuard(this)),
-        read_fd_(-1), write_fd_(-1),
-        builder_(&command_queue_, &callback_queue_, &cond_, &queue_mutex_,
-                 &clients_map_, &map_mutex_, createFds()),
-        builder_thread_(boost::bind(&BuilderType::run, &builder_)),
-        wakeup_socket_(service, read_fd_)
-    {
-        // Schedule wakeups when callbacks are pushed.
-        wakeup_socket_.asyncRead(
-            boost::bind(&DataSrcClientsMgrBase::processCallbacks, this, _1),
-            buffer, 1);
-    }
-
-    /// \brief The destructor.
-    ///
-    /// It tells the internal thread to stop and waits for it completion.
-    /// In the current implementation, it can block for some unpredictably
-    /// long period depending on what the thread is doing at that time
-    /// (in future we may want to implement a rapid way of killing the thread
-    /// and/or provide a separate interface for waiting so that the application
-    /// can choose the timing).
-    ///
-    /// The waiting operation can result in an exception, but this method
-    /// catches any of them so this method itself is exception free.
-    ~DataSrcClientsMgrBase() {
-        // We share class member variables with the builder, which will be
-        // invalidated after the call to the destructor, so we need to make
-        // sure the builder thread is terminated.  Depending on the timing
-        // this could take a long time; if we don't want that to happen in
-        // this context, we may want to introduce a separate 'shutdown()'
-        // method.
-        // Also, since we don't want to propagate exceptions from a destructor,
-        // we catch any possible ones.  In fact the only really expected one
-        // is Thread::UncaughtException when the builder thread died due to
-        // an exception.  We specifically log it and just ignore others.
-        try {
-            sendCommand(datasrc_clientmgr_internal::SHUTDOWN,
-                        data::ConstElementPtr());
-            builder_thread_.wait();
-        } catch (const util::thread::Thread::UncaughtException& ex) {
-            // technically, logging this could throw, which will be propagated.
-            // But such an exception would be a fatal one anyway, so we
-            // simply let it go through.
-            LOG_ERROR(auth_logger, AUTH_DATASRC_CLIENTS_SHUTDOWN_ERROR).
-                arg(ex.what());
-        } catch (...) {
-            LOG_ERROR(auth_logger,
-                      AUTH_DATASRC_CLIENTS_SHUTDOWN_UNEXPECTED_ERROR);
-        }
-
-        processCallbacks(); // Any leftover callbacks
-        cleanup();              // see below
-    }
-
-    /// \brief Handle new full configuration for data source clients.
-    ///
-    /// This method simply passes the new configuration to the builder
-    /// and immediately returns.  This method is basically exception free
-    /// as long as the caller passes a non NULL value for \c config_arg;
-    /// it doesn't validate the argument further.
-    ///
-    /// \brief isc::InvalidParameter config_arg is NULL.
-    /// \brief std::bad_alloc
-    ///
-    /// \param config_arg The new data source configuration.  Must not be NULL.
-    /// \param callback Called once the reconfigure command completes. It is
-    ///     called in the main thread (not in the work one). It should be
-    ///     exceptionless.
-    void reconfigure(const data::ConstElementPtr& config_arg,
-                     const datasrc_clientmgr_internal::FinishedCallback&
-                     callback = datasrc_clientmgr_internal::FinishedCallback())
-    {
-        if (!config_arg) {
-            isc_throw(InvalidParameter, "Invalid null config argument");
-        }
-        sendCommand(datasrc_clientmgr_internal::RECONFIGURE, config_arg,
-                    callback);
-        reconfigureHook();      // for test's customization
-    }
-
-    /// \brief Set the underlying data source client lists to new lists.
-    ///
-    /// This is provided only for some existing tests until we support a
-    /// cleaner way to use faked data source clients.  Non test code or
-    /// newer tests must not use this.
-    void setDataSrcClientLists(datasrc::ClientListMapPtr new_lists) {
-        typename MutexType::Locker locker(map_mutex_);
-        clients_map_ = new_lists;
-    }
-
-    /// \brief Instruct internal thread to (re)load a zone
-    ///
-    /// \param args Element argument that should be a map of the form
-    /// { "class": "IN", "origin": "example.com" }
-    /// (but class is optional and will default to IN)
-    /// \param callback Called once the loadZone command completes. It
-    ///     is called in the main thread, not in the work thread. It should
-    ///     be exceptionless.
-    ///
-    /// \exception CommandError if the args value is null, or not in
-    ///                                 the expected format, or contains
-    ///                                 a bad origin or class string
-    void
-    loadZone(const data::ConstElementPtr& args,
-             const datasrc_clientmgr_internal::FinishedCallback& callback =
-             datasrc_clientmgr_internal::FinishedCallback())
-    {
-        if (!args) {
-            isc_throw(CommandError, "loadZone argument empty");
-        }
-        if (args->getType() != isc::data::Element::map) {
-            isc_throw(CommandError, "loadZone argument not a map");
-        }
-        if (!args->contains("origin")) {
-            isc_throw(CommandError,
-                      "loadZone argument has no 'origin' value");
-        }
-        // Also check if it really is a valid name
-        try {
-            dns::Name(args->get("origin")->stringValue());
-        } catch (const isc::Exception& exc) {
-            isc_throw(CommandError, "bad origin: " << exc.what());
-        }
-
-        if (args->get("origin")->getType() != data::Element::string) {
-            isc_throw(CommandError,
-                      "loadZone argument 'origin' value not a string");
-        }
-        if (args->contains("class")) {
-            if (args->get("class")->getType() != data::Element::string) {
-                isc_throw(CommandError,
-                          "loadZone argument 'class' value not a string");
-            }
-            // Also check if it is a valid class
-            try {
-                dns::RRClass(args->get("class")->stringValue());
-            } catch (const isc::Exception& exc) {
-                isc_throw(CommandError, "bad class: " << exc.what());
-            }
-        }
-
-        // Note: we could do some more advanced checks here,
-        // e.g. check if the zone is known at all in the configuration.
-        // For now these are skipped, but one obvious way to
-        // implement it would be to factor out the code from
-        // the start of doLoadZone(), and call it here too
-
-        sendCommand(datasrc_clientmgr_internal::LOADZONE, args, callback);
-    }
-
-    void segmentInfoUpdate(const data::ConstElementPtr& args,
-                           const datasrc_clientmgr_internal::FinishedCallback&
-                           callback =
-                           datasrc_clientmgr_internal::FinishedCallback()) {
-        // Some minimal validation
-        if (!args) {
-            isc_throw(CommandError, "segmentInfoUpdate argument empty");
-        }
-        if (args->getType() != isc::data::Element::map) {
-            isc_throw(CommandError, "segmentInfoUpdate argument not a map");
-        }
-        const char* params[] = {
-            "data-source-name",
-            "data-source-class",
-            "segment-params",
-            NULL
-        };
-        for (const char** param = params; *param; ++param) {
-            if (!args->contains(*param)) {
-                isc_throw(CommandError,
-                          "segmentInfoUpdate argument has no '" << param <<
-                          "' value");
-            }
-        }
-
-
-        sendCommand(datasrc_clientmgr_internal::SEGMENT_INFO_UPDATE, args,
-                    callback);
-    }
-
-private:
-    // This is expected to be called at the end of the destructor.  It
-    // actually does nothing, but provides a customization point for
-    // specialized class for tests so that the tests can inspect the last
-    // state of the class.
-    void cleanup() {}
-
-    // same as cleanup(), for reconfigure().
-    void reconfigureHook() {}
-
-    void sendCommand(datasrc_clientmgr_internal::CommandID command,
-                     const data::ConstElementPtr& arg,
-                     const datasrc_clientmgr_internal::FinishedCallback&
-                     callback = datasrc_clientmgr_internal::FinishedCallback())
-    {
-        // The lock will be held until the end of this method.  Only
-        // push_back has to be protected, but we can avoid having an extra
-        // block this way.
-        typename MutexType::Locker locker(queue_mutex_);
-        command_queue_.push_back(
-            datasrc_clientmgr_internal::Command(command, arg, callback));
-        cond_.signal();
-    }
-
-    int createFds() {
-        int fds[2];
-        int result = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
-        if (result != 0) {
-            isc_throw(Unexpected, "Can't create socket pair: " <<
-                      strerror(errno));
-        }
-        read_fd_ = fds[0];
-        write_fd_ = fds[1];
-        return write_fd_;
-    }
-
-    void processCallbacks(const std::string& error = std::string()) {
-        // Schedule the next read.
-        wakeup_socket_.asyncRead(
-            boost::bind(&DataSrcClientsMgrBase::processCallbacks, this, _1),
-            buffer, 1);
-        if (!error.empty()) {
-            // Generally, there should be no errors (as we are the other end
-            // as well), but check just in case.
-            isc_throw(Unexpected, error);
-        }
-
-        // Steal the callbacks into local copy.
-        std::list<datasrc_clientmgr_internal::FinishedCallback> queue;
-        {
-            typename MutexType::Locker locker(queue_mutex_);
-            queue.swap(callback_queue_);
-        }
-
-        // Execute the callbacks
-        BOOST_FOREACH(const datasrc_clientmgr_internal::FinishedCallback&
-                      callback, queue) {
-            callback();
-        }
-    }
-
-    //
-    // The following are shared with the builder.
-    //
-    // The list is used as a one-way queue: back-in, front-out
-    std::list<datasrc_clientmgr_internal::Command> command_queue_;
-    // Similar to above, for the callbacks that are ready to be called.
-    // While the command queue is for sending commands from the main thread
-    // to the work thread, this one is for the other direction. Protected
-    // by the same mutex (queue_mutex_).
-    std::list<datasrc_clientmgr_internal::FinishedCallback> callback_queue_;
-    CondVarType cond_;          // condition variable for queue operations
-    MutexType queue_mutex_;     // mutex to protect the queue
-    datasrc::ClientListMapPtr clients_map_;
-                                // map of actual data source client objects
-    boost::scoped_ptr<FDGuard> fd_guard_; // A guard to close the fds.
-    int read_fd_, write_fd_;    // Descriptors for wakeup
-    MutexType map_mutex_;       // mutex to protect the clients map
-
-    BuilderType builder_;
-    ThreadType builder_thread_; // for safety this should be placed last
-    isc::asiolink::LocalSocket wakeup_socket_; // For integration of read_fd_
-                                               // to the asio loop
-    char buffer[1];   // Buffer for the wakeup socket.
-};
-
-namespace datasrc_clientmgr_internal {
-
-/// \brief A class that maintains a set of data source clients.
-///
-/// An object of this class is supposed to run on a dedicated thread, whose
-/// main function is a call to its \c run() method.  It runs in a loop
-/// waiting for commands from the manager and handles each command (including
-/// reloading a new version of zone data into memory or fully reconfiguration
-/// of specific set of data source clients).  When it receives a SHUTDOWN
-/// command, it exits from the loop, which will terminate the thread.
-///
-/// While this class is defined in a publicly visible namespace, it's
-/// essentially private to \c DataSrcClientsMgr.  Except for tests,
-/// applications should not directly access this class.
-///
-/// This class is templated so that we can test it without involving actual
-/// threads or locks.
-template <typename MutexType, typename CondVarType>
-class DataSrcClientsBuilderBase : boost::noncopyable {
-private:
-    typedef std::map<dns::RRClass,
-                     boost::shared_ptr<datasrc::ConfigurableClientList> >
-    ClientListsMap;
-
-public:
-    /// \brief Internal errors in handling commands.
-    ///
-    /// This exception is expected to be caught within the
-    /// \c DataSrcClientsBuilder implementation, but is defined as public
-    /// so tests can be checked it.
-    class InternalCommandError : public isc::Exception {
-    public:
-        InternalCommandError(const char* file, size_t line, const char* what) :
-            isc::Exception(file, line, what) {}
-    };
-
-    /// \brief Constructor.
-    ///
-    /// It simply sets up a local copy of shared data with the manager.
-    ///
-    /// \throw None
-    DataSrcClientsBuilderBase(std::list<Command>* command_queue,
-                              std::list<FinishedCallback>* callback_queue,
-                              CondVarType* cond, MutexType* queue_mutex,
-                              datasrc::ClientListMapPtr* clients_map,
-                              MutexType* map_mutex,
-                              int wake_fd
-        ) :
-        command_queue_(command_queue), callback_queue_(callback_queue),
-        cond_(cond), queue_mutex_(queue_mutex),
-        clients_map_(clients_map), map_mutex_(map_mutex), wake_fd_(wake_fd)
-    {}
-
-    /// \brief The main loop.
-    void run();
-
-    /// \brief Handle one command from the manager.
-    ///
-    /// This is a dedicated subroutine of run() and is essentially private,
-    /// but is defined as a separate public method so we can test each
-    /// command test individually.  In any case, this class itself is
-    /// generally considered private.
-    ///
-    /// \return true if the builder should keep running; false otherwise.
-    bool handleCommand(const Command& command);
-
-private:
-    // NOOP command handler.  We use this so tests can override it; the default
-    // implementation really does nothing.
-    void doNoop() {}
-
-    void doReconfigure(const data::ConstElementPtr& config) {
-        if (config) {
-            LOG_INFO(auth_logger,
-                     AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_STARTED);
-            try {
-                // Define new_clients_map outside of the block that
-                // has the lock scope; this way, after the swap,
-                // the lock is guaranteed to be released before
-                // the old data is destroyed, minimizing the lock
-                // duration.
-                datasrc::ClientListMapPtr new_clients_map =
-                    configureDataSource(config);
-                {
-                    typename MutexType::Locker locker(*map_mutex_);
-                    new_clients_map.swap(*clients_map_);
-                } // lock is released by leaving scope
-                LOG_INFO(auth_logger,
-                         AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_SUCCESS);
-            } catch (const datasrc::ConfigurableClientList::ConfigurationError&
-                     config_error) {
-                LOG_ERROR(auth_logger,
-                    AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_CONFIG_ERROR).
-                    arg(config_error.what());
-            } catch (const datasrc::DataSourceError& ds_error) {
-                LOG_ERROR(auth_logger,
-                    AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_DATASRC_ERROR).
-                    arg(ds_error.what());
-            } catch (const isc::Exception& isc_error) {
-                LOG_ERROR(auth_logger,
-                    AUTH_DATASRC_CLIENTS_BUILDER_RECONFIGURE_ERROR).
-                    arg(isc_error.what());
-            }
-            // other exceptions are propagated, see
-            // http://bind10.isc.org/ticket/2210#comment:13
-
-            // old clients_map_ data is released by leaving scope
-        }
-    }
-
-    void doSegmentUpdate(const isc::data::ConstElementPtr& arg) {
-        try {
-            const isc::dns::RRClass
-                rrclass(arg->get("data-source-class")->stringValue());
-            const std::string&
-                name(arg->get("data-source-name")->stringValue());
-            const isc::data::ConstElementPtr& segment_params =
-                arg->get("segment-params");
-            typename MutexType::Locker locker(*map_mutex_);
-            const boost::shared_ptr<isc::datasrc::ConfigurableClientList>&
-                list = (**clients_map_)[rrclass];
-            if (!list) {
-                LOG_FATAL(auth_logger,
-                          AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_UNKNOWN_CLASS)
-                    .arg(rrclass);
-                std::terminate();
-            }
-            if (!list->resetMemorySegment(name,
-                    isc::datasrc::memory::ZoneTableSegment::READ_ONLY,
-                    segment_params)) {
-                LOG_FATAL(auth_logger,
-                          AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_NO_DATASRC)
-                    .arg(rrclass).arg(name);
-                std::terminate();
-            }
-        } catch (const isc::dns::InvalidRRClass& irce) {
-            LOG_FATAL(auth_logger,
-                      AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_BAD_CLASS)
-                .arg(arg->get("data-source-class"));
-            std::terminate();
-        } catch (const isc::Exception& e) {
-            LOG_FATAL(auth_logger,
-                      AUTH_DATASRC_CLIENTS_BUILDER_SEGMENT_ERROR)
-                .arg(e.what());
-            std::terminate();
-        }
-    }
-
-    void doLoadZone(const isc::data::ConstElementPtr& arg);
-    boost::shared_ptr<datasrc::memory::ZoneWriter> getZoneWriter(
-        datasrc::ConfigurableClientList& client_list,
-        const dns::RRClass& rrclass, const dns::Name& origin);
-
-    // The following are shared with the manager
-    std::list<Command>* command_queue_;
-    std::list<FinishedCallback> *callback_queue_;
-    CondVarType* cond_;
-    MutexType* queue_mutex_;
-    datasrc::ClientListMapPtr* clients_map_;
-    MutexType* map_mutex_;
-    int wake_fd_;
-};
-
-// Shortcut typedef for normal use
-typedef DataSrcClientsBuilderBase<util::thread::Mutex, util::thread::CondVar>
-DataSrcClientsBuilder;
-
-template <typename MutexType, typename CondVarType>
-void
-DataSrcClientsBuilderBase<MutexType, CondVarType>::run() {
-    LOG_INFO(auth_logger, AUTH_DATASRC_CLIENTS_BUILDER_STARTED);
-
-    try {
-        bool keep_running = true;
-        while (keep_running) {
-            std::list<Command> current_commands;
-            {
-                // Move all new commands to local queue under the protection of
-                // queue_mutex_.
-                typename MutexType::Locker locker(*queue_mutex_);
-                while (command_queue_->empty()) {
-                    cond_->wait(*queue_mutex_);
-                }
-                current_commands.swap(*command_queue_);
-            } // the lock is released here.
-
-            while (keep_running && !current_commands.empty()) {
-                try {
-                    keep_running = handleCommand(current_commands.front());;
-                } catch (const InternalCommandError& e) {
-                    LOG_ERROR(auth_logger,
-                              AUTH_DATASRC_CLIENTS_BUILDER_COMMAND_ERROR).
-                        arg(e.what());
-                }
-                if (current_commands.front().callback) {
-                    // Lock the queue
-                    typename MutexType::Locker locker(*queue_mutex_);
-                    callback_queue_->
-                        push_back(current_commands.front().callback);
-                    // Wake up the other end. If it would block, there are data
-                    // and it'll wake anyway.
-                    int result = send(wake_fd_, "w", 1, MSG_DONTWAIT);
-                    if (result == -1 &&
-                        (errno != EWOULDBLOCK && errno != EAGAIN)) {
-                        // Note: the strerror might not be thread safe, as
-                        // subsequent call to it might change the returned
-                        // string. But that is unlikely and strerror_r is
-                        // not portable and we are going to terminate anyway,
-                        // so that's better than nothing.
-                        //
-                        // Also, this error handler is not tested. It should
-                        // be generally impossible to happen, so it is hard
-                        // to trigger in controlled way.
-                        LOG_FATAL(auth_logger,
-                                  AUTH_DATASRC_CLIENTS_BUILDER_WAKE_ERR).
-                            arg(strerror(errno));
-                        std::terminate();
-                    }
-                }
-                current_commands.pop_front();
-            }
-        }
-
-        LOG_INFO(auth_logger, AUTH_DATASRC_CLIENTS_BUILDER_STOPPED);
-    } catch (const std::exception& ex) {
-        // We explicitly catch exceptions so we can log it as soon as possible.
-        LOG_FATAL(auth_logger, AUTH_DATASRC_CLIENTS_BUILDER_FAILED).
-            arg(ex.what());
-        std::terminate();
-    } catch (...) {
-        LOG_FATAL(auth_logger, AUTH_DATASRC_CLIENTS_BUILDER_FAILED_UNEXPECTED);
-        std::terminate();
-    }
-}
-
-template <typename MutexType, typename CondVarType>
-bool
-DataSrcClientsBuilderBase<MutexType, CondVarType>::handleCommand(
-    const Command& command)
-{
-    const CommandID cid = command.id;
-    if (cid >= NUM_COMMANDS) {
-        // This shouldn't happen except for a bug within this file.
-        isc_throw(Unexpected, "internal bug: invalid command, ID: " << cid);
-    }
-
-    const boost::array<const char*, NUM_COMMANDS> command_desc = {
-        {"NOOP", "RECONFIGURE", "LOADZONE", "SEGMENT_INFO_UPDATE", "SHUTDOWN"}
-    };
-    LOG_DEBUG(auth_logger, DBGLVL_TRACE_BASIC,
-              AUTH_DATASRC_CLIENTS_BUILDER_COMMAND).arg(command_desc.at(cid));
-    switch (command.id) {
-    case RECONFIGURE:
-        doReconfigure(command.params);
-        break;
-    case LOADZONE:
-        doLoadZone(command.params);
-        break;
-    case SEGMENT_INFO_UPDATE:
-        doSegmentUpdate(command.params);
-        break;
-    case SHUTDOWN:
-        return (false);
-    case NOOP:
-        doNoop();
-        break;
-    case NUM_COMMANDS:
-        assert(false);          // we rejected this case above
-    }
-    return (true);
-}
-
-template <typename MutexType, typename CondVarType>
-void
-DataSrcClientsBuilderBase<MutexType, CondVarType>::doLoadZone(
-    const isc::data::ConstElementPtr& arg)
-{
-    // We assume some basic level validation as this method can only be
-    // called via the manager in practice.  manager is expected to do the
-    // minimal validation.
-    assert(arg);
-    assert(arg->get("origin"));
-
-    // TODO: currently, we hardcode IN as the default for the optional
-    // 'class' argument. We should really derive this from the specification,
-    // but at the moment the config/command API does not allow that to be
-    // done easily. Once that is in place (tickets have yet to be created,
-    // as we need to do a tiny bit of design work for that), this
-    // code can be replaced with the original part:
-    // assert(arg->get("class"));
-    // const dns::RRClass(arg->get("class")->stringValue());
-    isc::data::ConstElementPtr class_elem = arg->get("class");
-    const dns::RRClass rrclass(class_elem ?
-                                dns::RRClass(class_elem->stringValue()) :
-                                dns::RRClass::IN());
-    const dns::Name origin(arg->get("origin")->stringValue());
-    ClientListsMap::iterator found = (*clients_map_)->find(rrclass);
-    if (found == (*clients_map_)->end()) {
-        isc_throw(InternalCommandError, "failed to load a zone " << origin <<
-                  "/" << rrclass << ": not configured for the class");
-    }
-
-    boost::shared_ptr<datasrc::ConfigurableClientList> client_list =
-        found->second;
-    assert(client_list);
-
-    try {
-        boost::shared_ptr<datasrc::memory::ZoneWriter> zwriter =
-            getZoneWriter(*client_list, rrclass, origin);
-        if (!zwriter) {
-            return;
-        }
-
-        zwriter->load(); // this can take time but doesn't cause a race
-        {   // install() can cause a race and must be in a critical section
-            typename MutexType::Locker locker(*map_mutex_);
-            zwriter->install();
-        }
-        LOG_DEBUG(auth_logger, DBG_AUTH_OPS,
-                  AUTH_DATASRC_CLIENTS_BUILDER_LOAD_ZONE)
-            .arg(origin).arg(rrclass);
-
-        // same as load(). We could let the destructor do it, but do it
-        // ourselves explicitly just in case.
-        zwriter->cleanup();
-    } catch (const InternalCommandError& ex) {
-        throw;     // this comes from getZoneWriter.  just let it go through.
-    } catch (const isc::Exception& ex) {
-        // We catch our internal exceptions (which will be just ignored) and
-        // propagated others (which should generally be considered fatal and
-        // will make the thread terminate)
-        isc_throw(InternalCommandError, "failed to load a zone " << origin <<
-                  "/" << rrclass << ": error occurred in reload: " <<
-                  ex.what());
-    }
-}
-
-// A dedicated subroutine of doLoadZone().  Separated just for keeping the
-// main method concise.
-template <typename MutexType, typename CondVarType>
-boost::shared_ptr<datasrc::memory::ZoneWriter>
-DataSrcClientsBuilderBase<MutexType, CondVarType>::getZoneWriter(
-    datasrc::ConfigurableClientList& client_list,
-    const dns::RRClass& rrclass, const dns::Name& origin)
-{
-    // getCachedZoneWriter() could get access to an underlying data source
-    // that can cause a race condition with the main thread using that data
-    // source for lookup.  So we need to protect the access here.
-    datasrc::ConfigurableClientList::ZoneWriterPair writerpair;
-    {
-        typename MutexType::Locker locker(*map_mutex_);
-        writerpair = client_list.getCachedZoneWriter(origin, false);
-    }
-
-    switch (writerpair.first) {
-    case datasrc::ConfigurableClientList::ZONE_SUCCESS:
-        assert(writerpair.second);
-        return (writerpair.second);
-    case datasrc::ConfigurableClientList::ZONE_NOT_FOUND:
-        isc_throw(InternalCommandError, "failed to load zone " << origin
-                  << "/" << rrclass << ": not found in any configured "
-                  "data source.");
-    case datasrc::ConfigurableClientList::ZONE_NOT_CACHED:
-        LOG_DEBUG(auth_logger, DBG_AUTH_OPS,
-                  AUTH_DATASRC_CLIENTS_BUILDER_LOAD_ZONE_NOCACHE)
-            .arg(origin).arg(rrclass);
-        break;                  // return NULL below
-    case datasrc::ConfigurableClientList::CACHE_NOT_WRITABLE:
-        // This is an internal error. Auth server should skip reloading zones
-        // on non writable caches.
-        isc_throw(InternalCommandError, "failed to load zone " << origin
-                  << "/" << rrclass << ": internal failure, in-memory cache "
-                  "is not writable");
-    case datasrc::ConfigurableClientList::CACHE_DISABLED:
-        // This is an internal error. Auth server must have the cache
-        // enabled.
-        isc_throw(InternalCommandError, "failed to load zone " << origin
-                  << "/" << rrclass << ": internal failure, in-memory cache "
-                  "is somehow disabled");
-    default:                    // other cases can really never happen
-        isc_throw(Unexpected, "Impossible result in getting data source "
-                  "ZoneWriter: " << writerpair.first);
-    }
-
-    return (boost::shared_ptr<datasrc::memory::ZoneWriter>());
-}
-} // namespace datasrc_clientmgr_internal
-
-/// \brief Shortcut type for normal data source clients manager.
-///
-/// In fact, for non test applications this is the only type of this kind
-/// to be considered.
-typedef DataSrcClientsMgrBase<
-    util::thread::Thread,
-    datasrc_clientmgr_internal::DataSrcClientsBuilder,
-    util::thread::Mutex, util::thread::CondVar> DataSrcClientsMgr;
-} // namespace auth
-} // namespace isc
-
-#endif  // DATASRC_CLIENTS_MGR_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 24
src/bin/auth/datasrc_config.cc

@@ -1,24 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <cc/data.h>
-#include "datasrc_config.h"
-
-// This is a trivial specialization for the commonly used version.
-// Defined in .cc to avoid accidental creation of multiple copies.
-isc::datasrc::ClientListMapPtr
-configureDataSource(const isc::data::ConstElementPtr& config) {
-    return (configureDataSourceGeneric<
-            isc::datasrc::ConfigurableClientList>(config));
-}

+ 0 - 82
src/bin/auth/datasrc_config.h

@@ -1,82 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef AUTH_DATASRC_CONFIG_H
-#define AUTH_DATASRC_CONFIG_H
-
-#include <cc/data.h>
-#include <datasrc/client_list.h>
-
-#include <boost/shared_ptr.hpp>
-
-#include <utility>
-#include <map>
-
-/// \brief Configure data source client lists
-///
-/// This will hook into the data_sources module configuration and it will
-/// return a new set (in the form of a shared pointer to map) of data source
-/// client lists corresponding to the configuration.
-///
-/// This function is templated. This is simply because of easier testing.
-/// You don't need to pay attention to it, use the configureDataSource
-/// specialization instead.
-///
-/// \note In future we may want to make the reconfiguration more efficient
-/// by only creating newly configured data and just moving the rest from
-/// the running configuration if they are used in the new configuration
-/// without any parameter change.  We could probably do it by passing
-/// the old lists in addition to the new config, but further details are
-/// still to be defined yet.  It will surely require changes in the
-/// data source library, too.  So, right now, we don't introduce the
-/// possibility in the function interface.  If and when we decide to introduce
-/// the optimization, we'll extend the interface.
-///
-/// \param config The configuration value to parse. It is in the form
-///     as an update from the config manager.
-/// \return A map from RR classes to configured lists.
-/// \throw ConfigurationError if the config element is not in the expected
-///        format (A map of lists)
-template<class List>
-boost::shared_ptr<std::map<isc::dns::RRClass,
-                           boost::shared_ptr<List> > > // = ListMap below
-configureDataSourceGeneric(const isc::data::ConstElementPtr& config) {
-    typedef boost::shared_ptr<List> ListPtr;
-    typedef std::map<std::string, isc::data::ConstElementPtr> Map;
-    typedef std::map<isc::dns::RRClass, ListPtr> ListMap;
-
-    boost::shared_ptr<ListMap> new_lists(new ListMap);
-
-    const Map& map(config->mapValue());
-    for (Map::const_iterator it(map.begin()); it != map.end(); ++it) {
-        const isc::dns::RRClass rrclass(it->first);
-        ListPtr list(new List(rrclass));
-        list->configure(it->second, true);
-        new_lists->insert(std::pair<isc::dns::RRClass, ListPtr>(rrclass,
-                                                                list));
-    }
-
-    return (new_lists);
-}
-
-/// \brief Concrete version of configureDataSource() for the
-///     use with authoritative server implementation.
-isc::datasrc::ClientListMapPtr
-configureDataSource(const isc::data::ConstElementPtr& config);
-
-#endif  // AUTH_DATASRC_CONFIG_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 385
src/bin/auth/gen-statisticsitems.py.pre.in

@@ -1,385 +0,0 @@
-#!@PYTHON@
-
-# Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-#
-# Permission to use, copy, modify, and/or distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-# PERFORMANCE OF THIS SOFTWARE.
-
-"""\
-This script generates spec file, docbook XML and some part of statistics code
-from statistics_msg_items.def.
-"""
-
-import os
-import re
-import sys
-import json
-from xml.etree import ElementTree
-
-item_list = []
-localstatedir = '@@LOCALSTATEDIR@@'
-builddir = '@builddir@'
-srcdir = '@srcdir@'
-pre_suffix = '.pre'
-
-xmldocument_command_name = 'b10-auth'
-
-def need_generate(filepath, prepath, mtime):
-    '''Check if we need to generate the specified file.
-
-    To avoid unnecessary compilation, we skip (re)generating the file when
-    the file already exists and newer than the base file, and definition file
-    specified with mtime.
-    '''
-    if os.path.exists(filepath) and\
-        (os.path.getmtime(filepath) > mtime and
-         os.path.getmtime(filepath) > os.path.getmtime(prepath)):
-        return False
-    return True
-
-def import_definitions():
-    '''Load statsitics items definitions from statistics_msg_items.def.
-
-    statistics_msg_items.def defines a tree of message statistics items.
-    Syntax:
-        Each line describes a node; branch node for subset of counters,
-        leaf node for a counter item.
-        Each fields are separated with one or more field separator (Tab).
-        Field separator in the head of a line is ignored.
-
-        branch node:
-        (item name)\t+(internal branch name)\t+(description of the item)\t+'='
-        leaf node:
-        (item name)\t+(internal item counter name)\t+(description of the item)
-
-        Branch nodes contain leaf nodes and/or branch nodes. The end of
-        a branch node is indicated with ';' as item name (first column).
-
-        Internal branch name and internal item counter name must be unique.
-
-    Returns mtime of statistics_msg_items.def. It will be used to check
-    auto-generated files need to be regenerated.
-    '''
-    global item_list
-
-    items_definition_file = srcdir + os.sep + 'statistics_msg_items.def'
-    with open(items_definition_file, 'r') as item_definition:
-        re_splitter = re.compile('\t+')
-        l = item_list
-        lp = None
-        for line in item_definition.readlines():
-            element = re_splitter.split(line.rstrip())
-            # pop first element if it is empty to skip indent
-            if element[0] == '':
-                element.pop(0)
-
-            # last element is '=': a branch node definition.
-            if element[-1] == '=':
-                l.append({'name': element[0], 'child': [], 'index': element[1],
-                          'description': element[2], 'parent': lp})
-                lp = l
-                l = l[-1]['child']
-            # last element is ';': end of a branch node.
-            elif element[-1] == ';':
-                l = lp
-                lp = l[-1]['parent']
-            # otherwise, a leaf node definition.
-            else:
-                l.append({'name': element[0], 'child': None,
-                          'index': element[1], 'description': element[2],
-                          'parent': lp})
-    return os.path.getmtime(items_definition_file)
-
-def generate_specfile(specfile, def_mtime):
-    '''Generate spec in specfile from skeleton (specfille+'.pre').
-    If the specfile is newer than both skeleton and def_mtime, file generation
-    will be skipped.
-
-    This method reads the content of skeleton and appends statistics items
-    definition into { "module_spec": { "statistics": } }.
-    LOCALSTATEDIR is also expanded.
-
-    Returns nothing.
-    '''
-
-    def convert_list(items, prefix=''):
-        spec_list = []
-        default_map = {}
-        for item in items:
-            full_item_name = prefix + item['name']
-            if item['child'] is None:
-                default_map[item['name']] = 0
-                spec_list.append({
-                        'item_name': item['name'],
-                        'item_optional': False,
-                        'item_type': 'integer',
-                        'item_default': 0,
-                        'item_title': full_item_name,
-                        'item_description': item['description'],
-                    })
-            else:
-                child_spec_list, child_default_map = \
-                    convert_list(item['child'], full_item_name + '.')
-                spec_list.append({
-                        'item_name': item['name'],
-                        'item_type': 'map',
-                        'item_optional': False,
-                        'item_title': full_item_name,
-                        'item_description': item['description'],
-                        'item_default': child_default_map,
-                        'map_item_spec': child_spec_list,
-                    })
-                default_map[item['name']] = child_default_map
-        return spec_list, default_map
-
-    item_spec_list, item_default_map = convert_list(item_list)
-
-    statistics_spec_list = [{
-        'item_name': 'zones',
-        'item_type': 'named_set',
-        'item_optional': False,
-        'item_title': 'Zone statistics',
-        'item_description':
-                'Zone statistics items. ' +
-                "Items for all zones are stored in '_SERVER_'.",
-        'item_default': { '_SERVER_': item_default_map },
-        'named_set_item_spec': {
-            'item_name': 'zone',
-            'item_type': 'map',
-            'item_optional': False,
-            'item_default': {},
-            'map_item_spec': item_spec_list,
-            },
-        }]
-
-    if need_generate(builddir+os.sep+specfile,
-                     builddir+os.sep+specfile+pre_suffix, def_mtime):
-        with open(builddir+os.sep+specfile+pre_suffix, 'r') as stats_pre:
-            # split LOCALSTATEDIR to avoid substitution
-            stats_pre_json = \
-                json.loads(stats_pre.read().replace('@@LOCAL'+'STATEDIR@@',
-                                                    localstatedir))
-        stats_pre_json['module_spec']['statistics'] = statistics_spec_list
-        statistics_spec_json = json.dumps(stats_pre_json, sort_keys=True,
-                                          indent=2)
-        with open(builddir+os.sep+specfile, 'w') as stats_spec:
-            stats_spec.write(statistics_spec_json)
-    else:
-        print('skip generating ' + specfile)
-    return
-
-def generate_docfile(docfile, def_mtime):
-    '''Generate docbook XML in docfile from skeleton (docfile+'.pre').
-    If the docfile is newer than both skeleton and def_mtime, file generation
-    will be skipped.
-
-    This method reads the content of skeleton and replaces
-    <!-- ### STATISTICS DATA PLACEHOLDER ### --> with statistics items
-    definition. LOCALSTATEDIR is also expanded.
-
-    Returns nothing.
-    '''
-    def convert_list(items, tree, prefix=''):
-        '''
-        Build XML tree from items.
-            <varlistentry>
-              <term>##item_full_name##</term>
-              <listitem><simpara>##item_description##</simpara></listitem>
-            </varlistentry>
-        xmldocument_command_name in item_description is put inside <command>
-        element.
-        '''
-        for item in items:
-            full_item_name = prefix + item['name']
-            if item['child'] is None:
-                # the item is a leaf node: build varlistentry
-                child_element = ElementTree.SubElement(tree, 'varlistentry')
-                term = ElementTree.SubElement(child_element, 'term')
-                term.text = full_item_name
-                list_item = ElementTree.SubElement(child_element, 'listitem')
-                sim_para = ElementTree.SubElement(list_item, 'simpara')
-                sim_para.text = ''
-                prev = None
-                # put xmldocument_command_name in <command> node
-                for word in item['description'].split():
-                    if word == xmldocument_command_name:
-                        command = ElementTree.SubElement(sim_para, 'command')
-                        command.text = word
-                        # at this point command.tail is None
-                        # append a space as trailing text for the next word
-                        # so it can be concatenated with trailing words
-                        command.tail = ' '
-                        prev = command
-                    else:
-                        if prev is None:
-                            sim_para.text += word + ' '
-                        else:
-                            prev.tail += word + ' '
-                # remove trailing whitespaces at the end of the description
-                if prev is None:
-                    sim_para.text = sim_para.text.rstrip()
-                else:
-                    prev.tail = prev.tail.rstrip()
-            else:
-                # the item is a branch node: call myself for child nodes
-                convert_list(item['child'], tree, full_item_name + '.')
-        return
-
-    if need_generate(builddir+os.sep+docfile,
-                     srcdir+os.sep+docfile+pre_suffix, def_mtime):
-        with open(srcdir+os.sep+docfile+pre_suffix, 'r') as doc_pre:
-            # split LOCALSTATEDIR to avoid substitution
-            doc_pre_xml = doc_pre.read().replace('@@LOCAL'+'STATEDIR@@',
-                                                 localstatedir)
-
-        variable_tree = ElementTree.Element('variablelist')
-        convert_list(item_list, variable_tree)
-        pretty_xml = ElementTree.tostring(variable_tree)
-        if not isinstance(pretty_xml, str):
-            pretty_xml = pretty_xml.decode('utf-8')
-        # put newline around <variablelist> and <varlistentry> element
-        pretty_xml = \
-            re.sub(r'(</?var(?:iablelist|listentry)>)', r'\1\n', pretty_xml)
-        # indent <term> and <listitem>
-        pretty_xml = \
-            re.sub(r'(<(?:term|listitem)>)', r'  \1', pretty_xml)
-        # put newline after </term> and </listitem>
-        pretty_xml = \
-            re.sub(r'(</(?:term|listitem)>)', r'\1\n', pretty_xml)
-
-        with open(builddir+os.sep+docfile, 'w') as doc:
-            doc.write(doc_pre_xml.replace(
-                '<!-- ### STATISTICS DATA PLACEHOLDER ### -->',
-                pretty_xml))
-    else:
-        print('skip generating ' + docfile)
-    return
-
-def generate_cxx(itemsfile, ccfile, utfile, def_mtime):
-    '''Generate some part of statistics code in itemsfile, ccfile, utfile from
-    skeleton (itemsfile+'.pre', ccfile+'.pre', utfile+'.pre').
-    If the file is newer than both skeleton and def_mtime, file generation
-    will be skipped.
-
-    This method reads the content of skeleton and replaces
-    // ### STATISTICS ITEMS DEFINITION ### with statistics items definition in
-    ccfile and utfile,
-    // ### STATISTICS ITEMS DECLARATION ### with statistics items declaration
-    in itemsfile.
-
-    Returns nothing.
-    '''
-    msg_counter_types = ['enum MSGCounterType {']
-    item_names =  ['// using -1 as counter_id to state it is not a '
-                   + 'counter item']
-    item_names += ['const int NOT_ITEM = -1;', '']
-
-    def convert_list(items, item_head, msg_counter_types, item_names):
-        '''Convert item tree to a set of C++ code fragment in given lists.
-
-        This method recursively builds two lists:
-        - msg_counter_types consists of strings for all leaf items, each
-          defines one enum element with a comment, e.g.
-          COUNTER_ITEM, ///< item's description
-        - item_names consists of tuples of three elements, depending on
-          whether it's a leaf element (no child from it) or not:
-          (leaf)   ( "item_name", NULL, COUNTER_ITEM )
-          (branch) ( "item_name", CHILD_NAME, NOT_ITEM )
-
-        Each single call to this function builds a C++ structure beginning
-        with the given item_head, which is a string that reads like
-        'const struct CounterSpec some_counters[] = {'
-        followed by the item_names tuples corresponding to that level.
-        If some of the items of this level have a child, recursive calls
-        to this function extends msg_counter_types and item_names.
-        item_names for this level will be concatenated at the end end of
-        the given item_names.
-
-        '''
-        item_names_current = [item_head]
-        for item in items:
-            item_spec = '    { "' + item['name'] + '", '
-            if item['child'] is None:
-                item_spec += 'NULL, ' + item['index']
-                msg_counter_types.append('    ' + item['index'] + ',    ' +
-                                         '///< ' + item['description'])
-            else:
-                item_spec += item['index'] + ', NOT_ITEM'
-                child_head = 'const struct CounterSpec ' + \
-                    item['index'] + '[] = {'
-                convert_list(item['child'], child_head,
-                             msg_counter_types, item_names)
-            item_names_current.append(item_spec + ' },')
-
-        item_names_current.append('    { NULL, NULL, NOT_ITEM }\n};')
-        item_names.extend(item_names_current)
-
-    convert_list(item_list, 'const struct CounterSpec msg_counter_tree[] = {',
-                 msg_counter_types, item_names)
-    msg_counter_types.extend([
-            '    // End of counter types',
-            '    MSG_COUNTER_TYPES  ///< The number of defined counters',
-            '};'])
-
-    item_decls = '\n'.join(msg_counter_types)
-    item_defs = '\n'.join(item_names)
-
-    if need_generate(builddir+os.sep+itemsfile,
-                     srcdir+os.sep+itemsfile+pre_suffix, def_mtime):
-        with open(srcdir+os.sep+itemsfile+pre_suffix, 'r') \
-            as statistics_items_h_pre:
-            items_pre = statistics_items_h_pre.read()
-
-        with open(builddir+os.sep+itemsfile, 'w') as statistics_items_h:
-            statistics_items_h.write(items_pre.replace(
-                '// ### STATISTICS ITEMS DECLARATION ###', item_decls))
-    else:
-        print('skip generating ' + itemsfile)
-
-    if need_generate(builddir+os.sep+ccfile,
-                     srcdir+os.sep+ccfile+pre_suffix, def_mtime):
-        with open(srcdir+os.sep+ccfile+pre_suffix, 'r') as statistics_cc_pre:
-            items_pre = statistics_cc_pre.read()
-
-        with open(builddir+os.sep+ccfile, 'w') as statistics_cc:
-            statistics_cc.write(items_pre.replace(
-                '// ### STATISTICS ITEMS DEFINITION ###', item_defs))
-    else:
-        print('skip generating ' + ccfile)
-
-    if need_generate(builddir+os.sep+utfile,
-                     srcdir+os.sep+utfile+pre_suffix, def_mtime):
-        with open(srcdir+os.sep+utfile+pre_suffix, 'r') \
-            as statistics_ut_cc_pre:
-            items_pre = statistics_ut_cc_pre.read()
-
-        with open(builddir+os.sep+utfile, 'w') as statistics_ut_cc:
-            statistics_ut_cc.write(items_pre.replace(
-                '// ### STATISTICS ITEMS DEFINITION ###', item_defs))
-    else:
-        print('skip generating ' + utfile)
-
-    return
-
-if __name__ == "__main__":
-    try:
-        def_mtime = import_definitions()
-        generate_specfile('auth.spec', def_mtime)
-        generate_docfile('b10-auth.xml', def_mtime)
-        generate_cxx('statistics_items.h',
-                     'statistics.cc',
-                     'tests'+os.sep+'statistics_unittest.cc',
-                     def_mtime)
-    except:
-        sys.stderr.write('File generation failed due to exception: %s\n' %
-                         sys.exc_info()[1])
-        exit(1)

+ 0 - 270
src/bin/auth/main.cc

@@ -1,270 +0,0 @@
-// Copyright (C) 2009-2011  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include <exceptions/exceptions.h>
-
-#include <util/buffer.h>
-#include <util/io/socketsession.h>
-
-#include <dns/message.h>
-#include <dns/messagerenderer.h>
-
-#include <cc/session.h>
-#include <cc/data.h>
-#include <config/ccsession.h>
-
-#include <xfr/xfrout_client.h>
-
-#include <auth/spec_config.h>
-#include <auth/common.h>
-#include <auth/auth_config.h>
-#include <auth/command.h>
-#include <auth/auth_srv.h>
-#include <auth/auth_log.h>
-#include <auth/datasrc_config.h>
-#include <auth/datasrc_clients_mgr.h>
-
-#include <asiodns/asiodns.h>
-#include <asiolink/asiolink.h>
-#include <log/logger_support.h>
-#include <server_common/keyring.h>
-#include <server_common/socket_request.h>
-
-#include <boost/bind.hpp>
-#include <boost/scoped_ptr.hpp>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <stdlib.h>
-#include <errno.h>
-
-#include <cassert>
-#include <iostream>
-
-using namespace std;
-using namespace isc::asiodns;
-using namespace isc::asiolink;
-using namespace isc::auth;
-using namespace isc::cc;
-using namespace isc::config;
-using namespace isc::data;
-using namespace isc::dns;
-using namespace isc::log;
-using namespace isc::util;
-using namespace isc::util::io;
-using namespace isc::xfr;
-
-namespace {
-
-/* need global var for config/command handlers.
- * todo: turn this around, and put handlers in the authserver
- * class itself? */
-AuthSrv* auth_server;
-
-ConstElementPtr
-my_config_handler(ConstElementPtr new_config) {
-    return (auth_server->updateConfig(new_config));
-}
-
-ConstElementPtr
-my_command_handler(const string& command, ConstElementPtr args) {
-    assert(auth_server != NULL);
-    return (execAuthServerCommand(*auth_server, command, args));
-}
-
-void
-datasrcConfigHandler(AuthSrv* server, bool* first_time,
-                     ModuleCCSession* config_session, const std::string&,
-                     isc::data::ConstElementPtr config,
-                     const isc::config::ConfigData&)
-{
-    assert(server != NULL);
-
-    // Note: remote config handler is requested to be exception free.
-    // While the code below is not 100% exception free, such an exception
-    // is really fatal and the server should actually stop.  So we don't
-    // bother to catch them; the exception would be propagated to the
-    // top level of the server and terminate it.
-
-    if (*first_time) {
-        // HACK: The default is not passed to the handler in the first
-        // callback. This one will get the default (or, current value).
-        // Further updates will work the usual way.
-        assert(config_session != NULL);
-        *first_time = false;
-        server->getDataSrcClientsMgr().reconfigure(
-            config_session->getRemoteConfigValue("data_sources", "classes"),
-            boost::bind(&AuthSrv::listsReconfigured, server));
-    } else if (config->contains("classes")) {
-        server->getDataSrcClientsMgr().reconfigure(config->get("classes"),
-            boost::bind(&AuthSrv::listsReconfigured, server));
-    }
-}
-
-void
-usage() {
-    cerr << "Usage:  b10-auth [-v]"
-         << endl;
-    cerr << "\t-v: verbose logging (debug-level)" << endl;
-    exit(1);
-}
-
-} // end of anonymous namespace
-
-int
-main(int argc, char* argv[]) {
-    int ch;
-    bool verbose = false;
-
-    while ((ch = getopt(argc, argv, ":nu:v")) != -1) {
-        switch (ch) {
-        case 'v':
-            verbose = true;
-            break;
-        case '?':
-        default:
-            usage();
-        }
-    }
-
-    if (argc - optind > 0) {
-        usage();
-    }
-
-    // Initialize logging.  If verbose, we'll use maximum verbosity.
-    isc::log::initLogger(AUTH_NAME,
-                         (verbose ? isc::log::DEBUG : isc::log::INFO),
-                         isc::log::MAX_DEBUG_LEVEL, NULL, true);
-
-    int ret = 0;
-
-    // XXX: we should eventually pass io_service here.
-    boost::scoped_ptr<AuthSrv> auth_server_; // placeholder
-    boost::scoped_ptr<Session> cc_session;
-    boost::scoped_ptr<Session> xfrin_session;
-    bool xfrin_session_established = false; // XXX (see Trac #287)
-    boost::scoped_ptr<ModuleCCSession> config_session;
-    XfroutClient xfrout_client(getXfroutSocketPath());
-    SocketSessionForwarder ddns_forwarder(getDDNSSocketPath());
-    try {
-        string specfile;
-        if (getenv("B10_FROM_BUILD")) {
-            specfile = string(getenv("B10_FROM_BUILD")) +
-                "/src/bin/auth/auth.spec";
-        } else {
-            specfile = string(AUTH_SPECFILE_LOCATION);
-        }
-
-        auth_server_.reset(new AuthSrv(xfrout_client, ddns_forwarder));
-        auth_server = auth_server_.get();
-        LOG_INFO(auth_logger, AUTH_SERVER_CREATED);
-
-        IOService& io_service = auth_server->getIOService();
-        DNSLookup* lookup = auth_server->getDNSLookupProvider();
-        DNSAnswer* answer = auth_server->getDNSAnswerProvider();
-
-        DNSService dns_service(io_service, lookup, answer);
-        auth_server->setDNSService(dns_service);
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_DNS_SERVICES_CREATED);
-
-        cc_session.reset(new Session(io_service.get_io_service()));
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_CONFIG_CHANNEL_CREATED);
-        // Initialize the Socket Requestor
-        isc::server_common::initSocketRequestor(*cc_session, AUTH_NAME);
-
-        // We delay starting listening to new commands/config just before we
-        // go into the main loop to avoid confusion due to mixture of
-        // synchronous and asynchronous operations (this would happen in
-        // initial communication with b10-init that takes place in
-        // updateConfig() for listen_on and in initializing TSIG keys below).
-        // Until then all operations on the CC session will take place
-        // synchronously.
-        config_session.reset(new ModuleCCSession(specfile, *cc_session,
-                                                 my_config_handler,
-                                                 my_command_handler, false));
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_CONFIG_CHANNEL_ESTABLISHED);
-
-        xfrin_session.reset(new Session(io_service.get_io_service()));
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_XFRIN_CHANNEL_CREATED);
-        xfrin_session->establish(NULL);
-        xfrin_session_established = true;
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_XFRIN_CHANNEL_ESTABLISHED);
-
-        auth_server->setXfrinSession(xfrin_session.get());
-
-        // Configure the server.  configureAuthServer() is expected to install
-        // all initial configurations, but as a short term workaround we
-        // handle the traditional "database_file" setup by directly calling
-        // updateConfig().
-        // if server load configure failed, we won't exit, give user second
-        // chance to correct the configure.
-        auth_server->setConfigSession(config_session.get());
-        try {
-            configureAuthServer(*auth_server, config_session->getFullConfig());
-            auth_server->updateConfig(ElementPtr());
-        } catch (const AuthConfigError& ex) {
-            LOG_ERROR(auth_logger, AUTH_CONFIG_LOAD_FAIL).arg(ex.what());
-        }
-
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_LOAD_TSIG);
-        isc::server_common::initKeyring(*config_session);
-        auth_server->setTSIGKeyRing(&isc::server_common::keyring);
-
-        // Start the data source configuration.  We pass first_time and
-        // config_session for the hack described in datasrcConfigHandler.
-        bool first_time = true;
-        config_session->addRemoteConfig("data_sources",
-                                        boost::bind(datasrcConfigHandler,
-                                                    auth_server, &first_time,
-                                                    config_session.get(),
-                                                    _1, _2, _3),
-                                        false);
-
-        // Now start asynchronous read.
-        config_session->start();
-        LOG_DEBUG(auth_logger, DBG_AUTH_START, AUTH_CONFIG_CHANNEL_STARTED);
-
-        // Successfully initialized.
-        LOG_INFO(auth_logger, AUTH_SERVER_STARTED);
-
-        // Ping any interested module that (a new) auth is up
-        // Currently, only the DDNS module is notified, but we could consider
-        // make an announcement channel for these (one-way) messages
-        cc_session->group_sendmsg(
-            isc::config::createCommand(AUTH_STARTED_NOTIFICATION), "DDNS");
-        io_service.run();
-    } catch (const std::exception& ex) {
-        LOG_FATAL(auth_logger, AUTH_SERVER_FAILED).arg(ex.what());
-        ret = 1;
-    }
-
-    if (xfrin_session_established) {
-        xfrin_session->disconnect();
-    }
-
-    // If we haven't registered callback for data sources, this will be just
-    // no-op.
-    if (config_session != NULL) {
-        config_session->removeRemoteConfig("data_sources");
-    }
-
-    LOG_INFO(auth_logger, AUTH_SERVER_EXITING);
-
-    return (ret);
-}

+ 0 - 604
src/bin/auth/query.cc

@@ -1,604 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <dns/message.h>
-#include <dns/rcode.h>
-#include <dns/rrtype.h>
-#include <dns/rrset.h>
-#include <dns/rdataclass.h>
-
-#include <datasrc/client.h>
-#include <datasrc/client_list.h>
-
-#include <auth/query.h>
-
-#include <boost/foreach.hpp>
-#include <boost/bind.hpp>
-#include <boost/function.hpp>
-
-#include <cassert>
-#include <algorithm>            // for std::max
-#include <functional>
-#include <vector>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::datasrc;
-using namespace isc::dns::rdata;
-
-namespace isc {
-namespace auth {
-
-void
-Query::ResponseCreator::addRRset(isc::dns::Message& message,
-                                 const isc::dns::Message::Section section,
-                                 const ConstRRsetPtr& rrset)
-{
-    /// Is this RRset already in the list of RRsets added to the message?
-    const std::vector<const AbstractRRset*>::const_iterator i =
-        std::find_if(added_.begin(), added_.end(),
-                     std::bind1st(Query::ResponseCreator::IsSameKind(),
-                                  rrset.get()));
-    if (i == added_.end()) {
-        // No - add it to both the message and the list of RRsets processed.
-        // The const-cast is wrong, but the message interface seems to insist.
-        message.addRRset(section,
-                         boost::const_pointer_cast<AbstractRRset>(rrset));
-        added_.push_back(rrset.get());
-    }
-}
-
-void
-Query::ResponseCreator::create(Message& response,
-                               const vector<ConstRRsetPtr>& answers,
-                               const vector<ConstRRsetPtr>& authorities,
-                               const vector<ConstRRsetPtr>& additionals)
-{
-    // Inserter should be reset each time the query is reset, so should be
-    // empty at this point.
-    assert(added_.empty());
-
-    // Add the RRsets to the message.  The order of sections is important,
-    // as the ResponseCreator remembers RRsets added and will not add
-    // duplicates.  Adding in the order answer, authory, additional will
-    // guarantee that if there are duplicates, the single RRset added will
-    // appear in the most important section.
-    BOOST_FOREACH(const ConstRRsetPtr& rrset, answers) {
-        addRRset(response, Message::SECTION_ANSWER, rrset);
-    }
-    BOOST_FOREACH(const ConstRRsetPtr& rrset, authorities) {
-        addRRset(response, Message::SECTION_AUTHORITY, rrset);
-    }
-    BOOST_FOREACH(const ConstRRsetPtr& rrset, additionals) {
-        addRRset(response, Message::SECTION_ADDITIONAL, rrset);
-    }
-}
-
-void
-Query::addSOA(ZoneFinder& finder) {
-    // This method is always called in finding SOA for a negative response,
-    // so we specify the use of min(RRTTL, SOA MINTTL) as specified in
-    // Section 3 of RFC2308.
-    ZoneFinderContextPtr soa_ctx = finder.findAtOrigin(RRType::SOA(), true,
-                                                       dnssec_opt_);
-    if (soa_ctx->code != ZoneFinder::SUCCESS) {
-        isc_throw(NoSOA, "There's no SOA record in zone " <<
-            finder.getOrigin().toText());
-    } else {
-        authorities_.push_back(soa_ctx->rrset);
-    }
-}
-
-// Note: unless the data source client implementation or the zone content
-// is broken, 'nsec' should be a valid NSEC RR.  Likewise, the call to
-// find() in this method should result in NXDOMAIN and an NSEC RR that proves
-// the non existent of matching wildcard.  If these assumptions aren't met
-// due to a buggy data source implementation or a broken zone, we'll let
-// underlying libdns++ modules throw an exception, which would result in
-// either an SERVFAIL response or just ignoring the query.  We at least prevent
-// a complete crash due to such broken behavior.
-void
-Query::addNXDOMAINProofByNSEC(ZoneFinder& finder, ConstRRsetPtr nsec) {
-    if (nsec->getRdataCount() == 0) {
-        isc_throw(BadNSEC, "NSEC for NXDOMAIN is empty");
-    }
-
-    // Add the NSEC proving NXDOMAIN to the authority section.
-    authorities_.push_back(nsec);
-
-    // Next, identify the best possible wildcard name that would match
-    // the query name.  It's the longer common suffix with the qname
-    // between the owner or the next domain of the NSEC that proves NXDOMAIN,
-    // prefixed by the wildcard label, "*".  For example, for query name
-    // a.b.example.com, if the NXDOMAIN NSEC is
-    // b.example.com. NSEC c.example.com., the longer suffix is b.example.com.,
-    // and the best possible wildcard is *.b.example.com.  If the NXDOMAIN
-    // NSEC is a.example.com. NSEC c.b.example.com., the longer suffix
-    // is the next domain of the NSEC, and we get the same wildcard name.
-    const int qlabels = qname_->getLabelCount();
-    const int olabels = qname_->compare(nsec->getName()).getCommonLabels();
-    const int nlabels = qname_->compare(
-        dynamic_cast<const generic::NSEC&>(nsec->getRdataIterator()->
-                                           getCurrent()).
-        getNextName()).getCommonLabels();
-    const int common_labels = std::max(olabels, nlabels);
-    const Name wildname(Name("*").concatenate(qname_->split(qlabels -
-                                                           common_labels)));
-
-    // Confirm the wildcard doesn't exist (this should result in NXDOMAIN;
-    // otherwise we shouldn't have got NXDOMAIN for the original query in
-    // the first place).
-    ConstZoneFinderContextPtr fcontext =
-        finder.find(wildname, RRType::NSEC(), dnssec_opt_);
-    if (fcontext->code != ZoneFinder::NXDOMAIN || !fcontext->rrset ||
-        fcontext->rrset->getRdataCount() == 0) {
-        isc_throw(BadNSEC, "Unexpected result for wildcard NXDOMAIN proof");
-    }
-
-    // Add the (no-) wildcard proof.  This can be the same NSEC we already
-    // added, but we'd add it here anyway; duplicate checks will take place
-    // later in a unified manner.
-    authorities_.push_back(fcontext->rrset);
-}
-
-uint8_t
-Query::addClosestEncloserProof(ZoneFinder& finder, const Name& name,
-                               bool exact_ok, bool add_closest)
-{
-    const ZoneFinder::FindNSEC3Result result = finder.findNSEC3(name, true);
-
-    // Validity check (see the method description).  Note that a completely
-    // broken findNSEC3 implementation could even return NULL RRset in
-    // closest_proof.  We don't explicitly check such case; addRRset() will
-    // throw an exception, and it will be converted to SERVFAIL at the caller.
-    if (!exact_ok && !result.next_proof) {
-        isc_throw(BadNSEC3, "Matching NSEC3 found for a non existent name: "
-                  << qname_);
-    }
-
-    if (add_closest) {
-        authorities_.push_back(result.closest_proof);
-    }
-    if (result.next_proof) {
-        authorities_.push_back(result.next_proof);
-    }
-    return (result.closest_labels);
-}
-
-void
-Query::addNSEC3ForName(ZoneFinder& finder, const Name& name, bool match) {
-    const ZoneFinder::FindNSEC3Result result = finder.findNSEC3(name, false);
-
-    // See the comment for addClosestEncloserProof().  We don't check a
-    // totally bogus case where closest_proof is NULL here.
-    if (match != result.matched) {
-        isc_throw(BadNSEC3, "Unexpected "
-                  << (result.matched ? "matching" : "covering")
-                  << " NSEC3 found for " << name);
-    }
-    authorities_.push_back(result.closest_proof);
-}
-
-void
-Query::addNXDOMAINProofByNSEC3(ZoneFinder& finder) {
-    // Firstly get the NSEC3 proves for Closest Encloser Proof
-    // See Section 7.2.1 of RFC 5155.
-    const uint8_t closest_labels =
-        addClosestEncloserProof(finder, *qname_, false);
-
-    // Next, construct the wildcard name at the closest encloser, i.e.,
-    // '*' followed by the closest encloser, and add NSEC3 for it.
-    const Name wildname(Name("*").concatenate(
-               qname_->split(qname_->getLabelCount() - closest_labels)));
-    addNSEC3ForName(finder, wildname, false);
-}
-
-void
-Query::addWildcardProof(ZoneFinder& finder,
-                        const ZoneFinder::Context& db_context)
-{
-    if (db_context.isNSECSigned()) {
-        // Case for RFC4035 Section 3.1.3.3.
-        //
-        // The query name shouldn't exist in the zone if there were no wildcard
-        // substitution.  Confirm that by specifying NO_WILDCARD.  It should
-        // result in NXDOMAIN and an NSEC RR that proves it should be returned.
-        ConstZoneFinderContextPtr fcontext =
-            finder.find(*qname_, RRType::NSEC(),
-                        dnssec_opt_ | ZoneFinder::NO_WILDCARD);
-        if (fcontext->code != ZoneFinder::NXDOMAIN || !fcontext->rrset ||
-            fcontext->rrset->getRdataCount() == 0) {
-            isc_throw(BadNSEC,
-                      "Unexpected NSEC result for wildcard proof");
-        }
-        authorities_.push_back(fcontext->rrset);
-    } else if (db_context.isNSEC3Signed()) {
-        // Case for RFC 5155 Section 7.2.6.
-        //
-        // Note that the closest encloser must be the immediate ancestor
-        // of the matching wildcard, so NSEC3 for its next closer (and only
-        // that NSEC3) is what we are expected to provided per the RFC (if
-        // this assumption isn't met the zone is broken anyway).
-        addClosestEncloserProof(finder, *qname_, false, false);
-    }
-}
-
-void
-Query::addWildcardNXRRSETProof(ZoneFinder& finder, ConstRRsetPtr nsec) {
-    // There should be one NSEC RR which was found in the zone to prove
-    // that there is not matched <QNAME,QTYPE> via wildcard expansion.
-    if (nsec->getRdataCount() == 0) {
-        isc_throw(BadNSEC, "NSEC for WILDCARD_NXRRSET is empty");
-    }
-
-    ConstZoneFinderContextPtr fcontext =
-        finder.find(*qname_, RRType::NSEC(),
-                    dnssec_opt_ | ZoneFinder::NO_WILDCARD);
-    if (fcontext->code != ZoneFinder::NXDOMAIN || !fcontext->rrset ||
-        fcontext->rrset->getRdataCount() == 0) {
-        isc_throw(BadNSEC, "Unexpected result for no match QNAME proof");
-    }
-
-    authorities_.push_back(fcontext->rrset);
-}
-
-void
-Query::addDS(ZoneFinder& finder, const Name& dname) {
-    ConstZoneFinderContextPtr ds_context =
-        finder.find(dname, RRType::DS(), dnssec_opt_);
-    if (ds_context->code == ZoneFinder::SUCCESS) {
-        authorities_.push_back(ds_context->rrset);
-    } else if (ds_context->code == ZoneFinder::NXRRSET &&
-               ds_context->isNSECSigned()) {
-        addNXRRsetProof(finder, *ds_context);
-    } else if (ds_context->code == ZoneFinder::NXRRSET &&
-               ds_context->isNSEC3Signed()) {
-        // Add no DS proof with NSEC3 as specified in RFC 5155 Section 7.2.7.
-        addClosestEncloserProof(finder, dname, true);
-    } else if (ds_context->code != ZoneFinder::NXRRSET) {
-        // We know this domain should exist, so the result must be NXRRSET.
-        // If not, the zone is broken, so we'll return SERVFAIL by triggering
-        // an exception.
-        isc_throw(BadDS, "Unexpected result for DS lookup for delegation");
-    }
-}
-
-void
-Query::addNXRRsetProof(ZoneFinder& finder,
-                       const ZoneFinder::Context& db_context)
-{
-    if (db_context.isNSECSigned() && db_context.rrset) {
-        authorities_.push_back(db_context.rrset);
-        if (db_context.isWildcard()) {
-            addWildcardNXRRSETProof(finder, db_context.rrset);
-        }
-    } else if (db_context.isNSEC3Signed() && !db_context.isWildcard()) {
-        // Section 7.2.3 and 7.2.4 of RFC 5155 with clarification by errata
-        // http://www.rfc-editor.org/errata_search.php?rfc=5155&eid=3441
-        // In the end, these two cases are basically the same: if the qname is
-        // equal to or derived from insecure delegation covered by an Opt-Out
-        // NSEC3 RR, include the closest provable encloser proof; otherwise we
-        // have a matching NSEC3, so we include it.
-        //
-        // Note: This implementation does not check in the former case whether
-        // the NSEC3 for the next closer has Opt-Out bit on; this must be the
-        // case as long as the zone is correctly signed, and if it's broken
-        // we'd just return what we are given and have the validator detect it.
-        addClosestEncloserProof(finder, *qname_, true);
-    } else if (db_context.isNSEC3Signed() && db_context.isWildcard()) {
-        // Case for RFC 5155 Section 7.2.5: add closest encloser proof for the
-        // qname, construct the matched wildcard name and add NSEC3 for it.
-        const uint8_t closest_labels =
-            addClosestEncloserProof(finder, *qname_, false);
-        const Name wname = Name("*").concatenate(
-            qname_->split(qname_->getLabelCount() - closest_labels));
-        addNSEC3ForName(finder, wname, true);
-    }
-}
-
-void
-Query::addAuthAdditional(ZoneFinder& finder,
-                         vector<ConstRRsetPtr>& additionals)
-{
-    // Fill in authority and addtional sections.
-    ConstZoneFinderContextPtr ns_context =
-        finder.findAtOrigin(RRType::NS(), false, dnssec_opt_);
-
-    // zone origin name should have NS records
-    if (ns_context->code != ZoneFinder::SUCCESS) {
-        isc_throw(NoApexNS, "There's no apex NS records in zone " <<
-                  finder.getOrigin().toText());
-    }
-    authorities_.push_back(ns_context->rrset);
-    ns_context->getAdditional(A_AND_AAAA(), additionals);
-}
-
-namespace {
-// A simple wrapper for DataSourceClient::findZone().  Normally we can simply
-// check the closest zone to the qname, but for type DS query we need to
-// look into the parent zone.  Nevertheless, if there is no "parent" (i.e.,
-// the qname consists of a single label, which also means it's the root name),
-// we should search the deepest zone we have (which should be the root zone;
-// otherwise it's a query error).
-ClientList::FindResult
-findZone(const ClientList& list, const Name& qname, RRType qtype) {
-    if (qtype != RRType::DS() || qname.getLabelCount() == 1) {
-        return (list.find(qname));
-    }
-    return (list.find(qname.split(1)));
-}
-}
-
-void
-Query::process(datasrc::ClientList& client_list,
-               const isc::dns::Name& qname, const isc::dns::RRType& qtype,
-               isc::dns::Message& response, bool dnssec)
-{
-    // Set up the cleaner object so internal pointers and vectors are
-    // always reset after scope leaves this method
-    QueryCleaner cleaner(*this);
-
-    // Set up query parameters for the rest of the (internal) methods
-    initialize(client_list, qname, qtype, response, dnssec);
-
-    // Found a zone which is the nearest ancestor to QNAME
-    const ClientList::FindResult result = findZone(*client_list_, *qname_,
-                                                   *qtype_);
-
-    // If we have no matching authoritative zone for the query name, return
-    // REFUSED.  In short, this is to be compatible with BIND 9, but the
-    // background discussion is not that simple.  See the relevant topic
-    // at the BIND 10 developers' ML:
-    // https://lists.isc.org/mailman/htdig/bind10-dev/2010-December/001633.html
-    if (result.dsrc_client_ == NULL) {
-        // If we tried to find a "parent zone" for a DS query and failed,
-        // we may still have authority at the child side.  If we do, the query
-        // has to be handled there.
-        if (*qtype_ == RRType::DS() && qname_->getLabelCount() > 1 &&
-            processDSAtChild()) {
-            return;
-        }
-        response_->setHeaderFlag(Message::HEADERFLAG_AA, false);
-        response_->setRcode(Rcode::REFUSED());
-        return;
-    } else if (!result.finder_) {
-        // We found a matching zone in a data source but its data are not
-        // available.
-        response_->setHeaderFlag(Message::HEADERFLAG_AA, false);
-        response_->setRcode(Rcode::SERVFAIL());
-        return;
-    }
-
-    if (qtype == RRType::RRSIG()) {
-        // We will not serve RRSIGs directly. See #2226 and the
-        // following thread for discussion why:
-        // http://www.ietf.org/mail-archive/web/dnsext/current/msg07123.html
-        // RRSIGs go together with their covered RRset.
-        response_->setHeaderFlag(Message::HEADERFLAG_AA);
-        response_->setRcode(Rcode::REFUSED());
-        return;
-    }
-
-    ZoneFinder& zfinder = *result.finder_;
-
-    // We have authority for a zone that contain the query name (possibly
-    // indirectly via delegation).  Look into the zone.
-    response_->setHeaderFlag(Message::HEADERFLAG_AA);
-    response_->setRcode(Rcode::NOERROR());
-    boost::function0<ZoneFinderContextPtr> find;
-    const bool qtype_is_any = (*qtype_ == RRType::ANY());
-    if (qtype_is_any) {
-        find = boost::bind(&ZoneFinder::findAll, &zfinder, *qname_,
-                           boost::ref(answers_), dnssec_opt_);
-    } else {
-        find = boost::bind(&ZoneFinder::find, &zfinder, *qname_, *qtype_,
-                           dnssec_opt_);
-    }
-    ZoneFinderContextPtr db_context(find());
-    switch (db_context->code) {
-        case ZoneFinder::DNAME: {
-            // First, put the dname into the answer
-            answers_.push_back(db_context->rrset);
-            /*
-             * Empty DNAME should never get in, as it is impossible to
-             * create one in master file.
-             *
-             * FIXME: Other way to prevent this should be done
-             */
-            assert(db_context->rrset->getRdataCount() > 0);
-            // Get the data of DNAME
-            RdataIteratorPtr rit = db_context->rrset->getRdataIterator();
-            const rdata::generic::DNAME& dname(
-                dynamic_cast<const rdata::generic::DNAME&>(rit->getCurrent()));
-            // The yet unmatched prefix dname
-            const Name prefix(qname_->split(0, qname_->getLabelCount() -
-                db_context->rrset->getName().getLabelCount()));
-            // If we put it together, will it be too long?
-            // (The prefix contains trailing ., which will be removed
-            if (prefix.getLength() - Name::ROOT_NAME().getLength() +
-                dname.getDname().getLength() > Name::MAX_WIRE) {
-                /*
-                 * In case the synthesized name is too long, section 4.1
-                 * of RFC 2672 mandates we return YXDOMAIN.
-                 */
-                response_->setRcode(Rcode::YXDOMAIN());
-                break;
-            }
-            // The new CNAME we are creating (it will be unsigned even
-            // with DNSSEC, the DNAME is signed and it can be validated
-            // by that)
-            RRsetPtr cname(new RRset(*qname_, db_context->rrset->getClass(),
-                RRType::CNAME(), db_context->rrset->getTTL()));
-            // Construct the new target by replacing the end
-            cname->addRdata(rdata::generic::CNAME(qname_->split(0,
-                qname_->getLabelCount() -
-                db_context->rrset->getName().getLabelCount()).
-                concatenate(dname.getDname())));
-            answers_.push_back(cname);
-            break;
-        }
-        case ZoneFinder::CNAME:
-            /*
-             * We don't do chaining yet. Therefore handling a CNAME is
-             * mostly the same as handling SUCCESS, but we didn't get
-             * what we expected. It means no exceptions in ANY or NS
-             * on the origin (though CNAME in origin is probably
-             * forbidden anyway).
-             *
-             * So, just put it there.
-             */
-            answers_.push_back(db_context->rrset);
-
-            // If the answer is a result of wildcard substitution,
-            // add a proof that there's no closer name.
-            if (dnssec_ && db_context->isWildcard()) {
-                addWildcardProof(*result.finder_, *db_context);
-            }
-            break;
-        case ZoneFinder::SUCCESS:
-            // If query type is ANY, the rrs have already been added
-            if (!qtype_is_any) {
-                answers_.push_back(db_context->rrset);
-            }
-
-            // Retrieve additional records for the answer
-            db_context->getAdditional(A_AND_AAAA(), additionals_);
-
-            // If apex NS records haven't been provided in the answer
-            // section, insert apex NS records into the authority section
-            // and AAAA/A RRS of each of the NS RDATA into the additional
-            // section.
-            // Checking the findZone() is a lightweight check to see if
-            // qname is the zone origin.
-            if (!result.exact_match_ ||
-                db_context->code != ZoneFinder::SUCCESS ||
-                (*qtype_ != RRType::NS() && !qtype_is_any))
-            {
-                addAuthAdditional(*result.finder_, additionals_);
-            }
-
-            // If the answer is a result of wildcard substitution,
-            // add a proof that there's no closer name.
-            if (dnssec_ && db_context->isWildcard()) {
-                addWildcardProof(*result.finder_, *db_context);
-            }
-            break;
-        case ZoneFinder::DELEGATION:
-            // If a DS query resulted in delegation, we also need to check
-            // if we are an authority of the child, too.  If so, we need to
-            // complete the process in the child as specified in Section
-            // 2.2.1.2. of RFC3658.
-            if (*qtype_ == RRType::DS() && processDSAtChild()) {
-                return;
-            }
-
-            response_->setHeaderFlag(Message::HEADERFLAG_AA, false);
-            authorities_.push_back(db_context->rrset);
-            // Retrieve additional records for the name servers
-            db_context->getAdditional(A_AND_AAAA(), additionals_);
-
-            // If DNSSEC is requested, see whether there is a DS
-            // record for this delegation.
-            if (dnssec_) {
-                addDS(*result.finder_, db_context->rrset->getName());
-            }
-            break;
-        case ZoneFinder::NXDOMAIN:
-            response_->setRcode(Rcode::NXDOMAIN());
-            addSOA(*result.finder_);
-            if (dnssec_) {
-                if (db_context->isNSECSigned() && db_context->rrset) {
-                    addNXDOMAINProofByNSEC(zfinder, db_context->rrset);
-                } else if (db_context->isNSEC3Signed()) {
-                    addNXDOMAINProofByNSEC3(zfinder);
-                }
-            }
-            break;
-        case ZoneFinder::NXRRSET:
-            addSOA(*result.finder_);
-            if (dnssec_) {
-                addNXRRsetProof(zfinder, *db_context);
-            }
-            break;
-        default:
-            // This is basically a bug of the data source implementation,
-            // but could also happen in the middle of development where
-            // we try to add a new result code.
-            isc_throw(isc::NotImplemented, "Unknown result code");
-            break;
-    }
-
-    response_creator_.create(*response_, answers_, authorities_, additionals_);
-}
-
-void
-Query::initialize(datasrc::ClientList& client_list,
-                  const isc::dns::Name& qname, const isc::dns::RRType& qtype,
-                  isc::dns::Message& response, bool dnssec)
-{
-    client_list_ = &client_list;
-    qname_ = &qname;
-    qtype_ = &qtype;
-    response_ = &response;
-    dnssec_ = dnssec;
-    dnssec_opt_ = (dnssec ? isc::datasrc::ZoneFinder::FIND_DNSSEC :
-                   isc::datasrc::ZoneFinder::FIND_DEFAULT);
-}
-
-void
-Query::reset() {
-    client_list_ = NULL;
-    qname_ = NULL;
-    qtype_ = NULL;
-    response_ = NULL;
-    answers_.clear();
-    authorities_.clear();
-    additionals_.clear();
-    response_creator_.clear();
-}
-
-bool
-Query::processDSAtChild() {
-    const ClientList::FindResult zresult = client_list_->find(*qname_, true);
-
-    if (zresult.dsrc_client_ == NULL) {
-        return (false);
-    }
-
-    // We are receiving a DS query at the child side of the owner name,
-    // where the DS isn't supposed to belong.  We should return a "no data"
-    // response as described in Section 3.1.4.1 of RFC4035 and Section
-    // 2.2.1.1 of RFC 3658.  find(DS) should result in NXRRSET, in which
-    // case (and if DNSSEC is required) we also add the proof for that,
-    // but even if find() returns an unexpected result, we don't bother.
-    // The important point in this case is to return SOA so that the resolver
-    // that happens to contact us can hunt for the appropriate parent zone
-    // by seeing the SOA.
-    response_->setHeaderFlag(Message::HEADERFLAG_AA);
-    response_->setRcode(Rcode::NOERROR());
-    addSOA(*zresult.finder_);
-    ConstZoneFinderContextPtr ds_context =
-        zresult.finder_->find(*qname_, RRType::DS(), dnssec_opt_);
-    if (ds_context->code == ZoneFinder::NXRRSET) {
-        if (dnssec_) {
-            addNXRRsetProof(*zresult.finder_, *ds_context);
-        }
-    }
-
-    response_creator_.create(*response_, answers_, authorities_, additionals_);
-    return (true);
-}
-
-}
-}

+ 0 - 510
src/bin/auth/query.h

@@ -1,510 +0,0 @@
-/*
- * Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
- *
- * Permission to use, copy, modify, and/or distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
- * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
- * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
- * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- */
-
-#include <exceptions/exceptions.h>
-#include <dns/rrset.h>
-#include <datasrc/zone.h>
-
-#include <boost/noncopyable.hpp>
-
-#include <functional>
-#include <vector>
-
-namespace isc {
-namespace dns {
-class Message;
-class Name;
-class RRType;
-class RRset;
-}
-
-namespace datasrc {
-class ClientList;
-}
-
-namespace auth {
-
-/// The \c Query class represents a standard DNS query that encapsulates
-/// processing logic to answer the query.
-///
-/// Many of the design details for this class are still in flux.
-/// We'll revisit and update them as we add more functionality, for example:
-/// - as a related point, we may have to pass the RR class of the query.
-///   in the initial implementation the RR class is an attribute of
-///   datasource and omitted.  It's not clear if this assumption holds with
-///   generic data sources.  On the other hand, it will help keep
-///   implementation simpler, and we might rather want to modify the design
-///   of the data source on this point.
-/// - return value of process().  rather than or in addition to setting the
-///   Rcode, we might use it as a return value of \c process().
-/// - we'll have to be able to specify whether DNSSEC is requested.
-///   It's an open question whether it should be in the constructor or via a
-///   separate attribute setter.
-/// - likewise, we'll eventually need to do per zone access control, for which
-///   we need querier's information such as its IP address.
-///
-/// <b>Note:</b> The class name is intentionally the same as the one used in
-/// the datasrc library.  This is because the plan is to eventually merge
-/// the two classes.  We could give it a different name such as "AuthQuery"
-/// to avoid possible ambiguity, but it may sound redundant in that it's
-/// obvious that this class is for authoritative queries.
-/// Since the interfaces are very different for now and it's less
-/// likely to misuse one of the classes instead of the other
-/// accidentally, and since it's considered a temporary development state,
-/// we keep this name at the moment.
-class Query : boost::noncopyable {
-private:
-    /// \brief Initial reserved size for the vectors in Query
-    ///
-    /// The value is larger than we expect the vectors to even become, and
-    /// has been chosen arbitrarily. The reason to set them quite high is
-    /// to prevent reallocation on addition.
-    static const size_t RESERVE_RRSETS = 64;
-
-    /// \brief Adds a SOA.
-    ///
-    /// Adds a SOA of the zone into the authority zone of response_.
-    /// Can throw NoSOA.
-    ///
-    void addSOA(isc::datasrc::ZoneFinder& finder);
-
-    /// \brief Adds the DS rrset for the given name, if available
-    ///
-    /// This is intended to be called when returning a delegation, and
-    /// if DNSSEC data is requested. If the DS record is not found
-    /// (signaled by find() returning NXRRSET), and the zone is signed
-    /// with NSEC, an NSEC denial of existence proof is added.
-    ///
-    /// \exception BadDS raised if find() returns anything other than
-    ///                  SUCCESS or NXRRSET when searching for the DS
-    ///                  record.
-    /// \param finder The ZoneFinder where the delegation was found
-    /// \param ds_name The name of the delegation RRset
-    void addDS(isc::datasrc::ZoneFinder& finder,
-               const isc::dns::Name& ds_name);
-
-    /// \brief Adds NSEC(3) denial proof for the given NXRRset result
-    ///
-    /// If available, NSEC or NSEC3 records are added to the authority
-    /// section (depending on whether isNSECSigned() or isNSEC3Signed()
-    /// returns true).
-    ///
-    /// \param finder The ZoneFinder that was used to search for the missing
-    ///               data
-    /// \param db_result The ZoneFinder::FindResult returned by find()
-    void addNXRRsetProof(isc::datasrc::ZoneFinder& finder,
-                         const isc::datasrc::ZoneFinder::Context& db_context);
-
-    /// Add NSEC RRs that prove an NXDOMAIN result.
-    ///
-    /// This corresponds to Section 3.1.3.2 of RFC 4035.
-    void addNXDOMAINProofByNSEC(isc::datasrc::ZoneFinder& finder,
-                                isc::dns::ConstRRsetPtr nsec);
-
-    /// Add NSEC3 RRs that prove an NXDOMAIN result.
-    ///
-    /// This corresponds to Section 7.2.2 of RFC 5155.
-    void addNXDOMAINProofByNSEC3(isc::datasrc::ZoneFinder& finder);
-
-    /// Add NSEC or NSEC3 RRs that prove a wildcard answer is the best one.
-    ///
-    /// This corresponds to Section 3.1.3.3 of RFC 4035 and Section 7.2.6
-    /// of RFC5155.
-    void addWildcardProof(
-        isc::datasrc::ZoneFinder& finder,
-        const isc::datasrc::ZoneFinder::Context& db_context);
-
-    /// \brief Adds one NSEC RR proved no matched QNAME,one NSEC RR proved no
-    /// matched <QNAME,QTYPE> through wildcard extension.
-    ///
-    /// Add NSEC RRs that prove an WILDCARD_NXRRSET result.
-    /// This corresponds to Section 3.1.3.4 of RFC 4035.
-    /// \param finder The ZoneFinder through which the authority data for the
-    /// query is to be found.
-    /// \param nsec The RRset (NSEC RR) which proved that there is no matched 
-    /// <QNAME,QTTYPE>.
-    void addWildcardNXRRSETProof(isc::datasrc::ZoneFinder& finder,
-                                 isc::dns::ConstRRsetPtr nsec);
-
-    /// \brief Look up a zone's NS RRset and their address records for an
-    /// authoritative answer, and add them to the additional section.
-    ///
-    /// On returning an authoritative answer, insert a zone's NS into the
-    /// authority section and AAAA/A RRs of each of the NS RDATA into the
-    /// additional section.
-    ///
-    /// <b>Notes to developer:</b>
-    ///
-    /// We should omit address records which has already been provided in the
-    /// answer section from the additional.
-    ///
-    /// For now, in order to optimize the additional section processing, we
-    /// include AAAA/A RRs under a zone cut in additional section. (BIND 9
-    /// excludes under-cut RRs; NSD include them.)
-    ///
-    /// \param finder The \c ZoneFinder through which the NS and additional
-    /// data for the query are to be found.
-    void addAuthAdditional(isc::datasrc::ZoneFinder& finder,
-                           std::vector<isc::dns::ConstRRsetPtr>& additionals);
-
-    /// \brief Process a DS query possible at the child side of zone cut.
-    ///
-    /// This private method is a subroutine of process(), and is called if
-    /// there's a possibility that this server has authority for the child
-    /// side of the DS's owner name (and it's detected that the server at
-    /// least doesn't have authority at the parent side).  This method
-    /// first checks if it has authority for the child, and if does,
-    /// just build a "no data" response with SOA for the zone origin
-    /// (possibly with a proof for the no data) as specified in Section
-    /// 2.2.1.1 of RFC3658.
-    ///
-    /// It returns true if this server has authority of the child; otherwise
-    /// it returns false.  In the former case, the caller is expected to
-    /// terminate the query processing, because it should have been completed
-    /// within this method.
-    bool processDSAtChild();
-
-    /// \brief Add NSEC3 to the response for a closest encloser proof for a
-    /// given name.
-    ///
-    /// This method calls \c findNSEC3() of the given zone finder for the
-    /// given name in the recursive mode, and adds the returned NSEC3(s) to
-    /// the authority section of the response message associated with the
-    /// \c Query object.
-    ///
-    /// It returns the number of labels of the closest encloser (returned via
-    /// the \c findNSEC3() call) in case the caller needs to use that value
-    /// for subsequent processing, i.e, constructing the best possible wildcard
-    /// name that (would) match the query name.
-    ///
-    /// Unless \c exact_ok is true, \c name is expected to be non existent,
-    /// in which case findNSEC3() in the recursive mode must return both
-    /// closest and next proofs.  If the latter is NULL, it means a run time
-    /// collision (or the zone is broken in other way), and this method throws
-    /// a BadNSEC3 exception.
-    ///
-    /// If \c exact_ok is true, this method takes into account the case
-    /// where the name exists and may or may not be at a zone cut to an
-    /// optout zone.  In this case, depending on whether the zone is optout
-    /// or not, findNSEC3() may return non-NULL or NULL next_proof
-    /// (respectively).  This method adds the next proof if and only if
-    /// findNSEC3() returns non NULL value for it.  The Opt-Out flag
-    /// must be set or cleared accordingly, but this method doesn't check that
-    /// in this level (as long as the zone is signed validly and findNSEC3()
-    /// for the data source is implemented as documented, the condition
-    /// should be met; otherwise we'd let the validator detect the error).
-    ///
-    /// By default this method always adds the closest proof.
-    /// If \c add_closest is false, it only adds the next proof to the message.
-    /// This correspond to the case of "wildcard answer responses" as described
-    /// in Section 7.2.6 of RFC5155.
-    uint8_t addClosestEncloserProof(isc::datasrc::ZoneFinder& finder,
-                                    const isc::dns::Name& name, bool exact_ok,
-                                    bool add_closest = true);
-
-    /// \brief Add matching or covering NSEC3 to the response for a give name.
-    ///
-    /// This method calls \c findNSEC3() of the given zone finder for the
-    /// given name in the non recursive mode, and adds the returned NSEC3 to
-    /// the authority section of the response message associated with the
-    /// \c Query object.
-    ///
-    /// Depending on the caller's context, the returned NSEC3 is one and
-    /// only one of matching or covering NSEC3.  If \c match is true the
-    /// returned NSEC3 must be a matching one; otherwise it must be a covering
-    /// one.  If this assumption isn't met this method throws a BadNSEC3
-    /// exception (if it must be a matching NSEC3 but is not, it means a broken
-    /// zone, maybe with incorrect optout NSEC3s; if it must be a covering
-    /// NSEC3 but is not, it means a run time collision; or the \c findNSEC3()
-    /// implementation is broken for both cases.)
-    void addNSEC3ForName(isc::datasrc::ZoneFinder& finder,
-                         const isc::dns::Name& name, bool match);
-
-    /// Set up the Query object for a new query lookup
-    ///
-    /// This is the first step of the process() method, and initializes
-    /// the member data
-    ///
-    /// \param client_list The datasource list wherein the answer to the query
-    /// is to be found.
-    /// \param qname The query name
-    /// \param qtype The RR type of the query
-    /// \param response The response message to store the answer to the query.
-    /// \param dnssec If the answer should include signatures and NSEC/NSEC3 if
-    ///     possible.
-    void initialize(datasrc::ClientList& client_list,
-                    const isc::dns::Name& qname, const isc::dns::RRType& qtype,
-                    isc::dns::Message& response, bool dnssec = false);
-
-    /// \brief Resets any partly built response data, and internal pointers
-    ///
-    /// Called by the QueryCleaner object upon its destruction
-    void reset();
-
-    /// \brief Internal class used for cleanup of Query members
-    ///
-    /// The process() call creates an object of this class, which
-    /// upon its destruction, calls Query::reset(), so that outside
-    /// of single calls to process(), the query state is always clean.
-    class QueryCleaner {
-    public:
-        QueryCleaner(isc::auth::Query& query) : query_(query) {}
-        ~QueryCleaner() { query_.reset(); }
-    private:
-        isc::auth::Query& query_;
-    };
-
-protected:
-    // Following methods declared protected so they can be accessed
-    // by unit tests.
-
-    void createResponse();
-
-public:
-    /// Default constructor.
-    ///
-    /// Query parameters will be set by the call to process()
-    ///
-    Query() :
-        client_list_(NULL), qname_(NULL), qtype_(NULL),
-        dnssec_(false), dnssec_opt_(isc::datasrc::ZoneFinder::FIND_DEFAULT),
-        response_(NULL)
-    {
-        answers_.reserve(RESERVE_RRSETS);
-        authorities_.reserve(RESERVE_RRSETS);
-        additionals_.reserve(RESERVE_RRSETS);
-
-        a_and_aaaa_.push_back(isc::dns::RRType::A());
-        a_and_aaaa_.push_back(isc::dns::RRType::AAAA());
-    }
-
-
-    /// Process the query.
-    ///
-    /// This method first identifies the zone that best matches the query
-    /// name (and in some cases RR type when the search is dependent on the
-    /// type) and then searches the zone for an entry that best matches the
-    /// query name.
-    /// It then updates the response message accordingly; for example, a
-    /// successful search would result in adding a corresponding RRset to
-    /// the answer section of the response.
-    ///
-    /// If no matching zone is found in the datasource, the RCODE of
-    /// SERVFAIL will be set in the response.
-    /// <b>Note:</b> this is different from the error code that BIND 9 returns
-    /// by default when it's configured as an authoritative-only server (and
-    /// from the behavior of the BIND 10 datasrc library, which was implemented
-    /// to be compatible with BIND 9).
-    /// The difference comes from the fact that BIND 9 returns REFUSED as a
-    /// result of access control check on the use of its cache.
-    /// Since BIND 10's authoritative server doesn't have the notion of cache
-    /// by design, it doesn't make sense to return REFUSED.  On the other hand,
-    /// providing compatible behavior may have its own benefit, so this point
-    /// should be revisited later.
-    ///
-    /// This might throw BadZone or any of its specific subclasses, but that
-    /// shouldn't happen in real-life (as BadZone means wrong data, it should
-    /// have been rejected upon loading).
-    ///
-    /// \param client_list The datasource list wherein the answer to the query
-    /// is to be found.
-    /// \param qname The query name
-    /// \param qtype The RR type of the query
-    /// \param response The response message to store the answer to the query.
-    /// \param dnssec If the answer should include signatures and NSEC/NSEC3 if
-    ///     possible.
-    void process(datasrc::ClientList& client_list,
-                 const isc::dns::Name& qname, const isc::dns::RRType& qtype,
-                 isc::dns::Message& response, bool dnssec = false);
-
-    /// \short Bad zone data encountered.
-    ///
-    /// This is thrown when a process encounters a misconfigured zone in a
-    /// way it can't continue. This throws, not sets the Rcode, because such
-    /// misconfigured zone should not be present in the data source and
-    /// should have been rejected sooner.
-    struct BadZone : public isc::Exception {
-        BadZone(const char* file, size_t line, const char* what) :
-            Exception(file, line, what)
-        {}
-    };
-
-    /// \short Zone is missing its SOA record.
-    ///
-    /// We tried to add a SOA into the authoritative section, but the zone
-    /// does not contain one.
-    struct NoSOA : public BadZone {
-        NoSOA(const char* file, size_t line, const char* what) :
-            BadZone(file, line, what)
-        {}
-    };
-
-    /// \short Zone is missing its apex NS records.
-    ///
-    /// We tried to add apex NS records into the authority section, but the
-    /// zone does not contain any.
-    struct NoApexNS: public BadZone {
-        NoApexNS(const char* file, size_t line, const char* what) :
-            BadZone(file, line, what)
-        {}
-    };
-
-    /// An invalid result is given when a valid NSEC is expected
-    ///
-    /// This can only happen when the underlying data source implementation or
-    /// the zone is broken.  By throwing an exception we treat such cases
-    /// as SERVFAIL.
-    struct BadNSEC : public BadZone {
-        BadNSEC(const char* file, size_t line, const char* what) :
-            BadZone(file, line, what)
-        {}
-    };
-
-    /// An invalid result is given when a valid NSEC3 is expected
-    ///
-    /// This can only happen when the underlying data source implementation or
-    /// the zone is broken.  By throwing an exception we treat such cases
-    /// as SERVFAIL.
-    struct BadNSEC3 : public BadZone {
-        BadNSEC3(const char* file, size_t line, const char* what) :
-            BadZone(file, line, what)
-        {}
-    };
-
-    /// An invalid result is given when a valid DS records (or NXRRSET) is
-    /// expected
-    ///
-    /// This can only happen when the underlying data source implementation
-    /// or the zone is broken. A DS query for a known delegation point should
-    /// either result in SUCCESS (if available) or NXRRSET
-    struct BadDS : public BadZone {
-        BadDS(const char* file, size_t line, const char* what) :
-            BadZone(file, line, what)
-        {}
-    };
-
-    /// \brief Response Creator Class
-    ///
-    /// This is a helper class of Query, and is expected to be used during the
-    /// construction of the response message. This class performs the
-    /// duplicate RRset detection check.  It keeps a list of RRsets added
-    /// to the message and does not add an RRset if it is the same as one
-    /// already added.
-    ///
-    /// This class is essentially private to Query, but is visible to public
-    /// for testing purposes.  It's not expected to be used from a normal
-    /// application.
-    class ResponseCreator {
-    public:
-        /// \brief Constructor
-        ///
-        /// Reserves space for the list of RRsets.  Although the
-        /// ResponseCreator will be used to create a message from the
-        /// contents of the Query object's answers_, authorities_ and
-        /// additionals_ elements, and each of these are sized to
-        /// RESERVE_RRSETS, it is _extremely_ unlikely that all three will be
-        /// filled to capacity.  So we reserve more elements than in each of
-        /// these components, but not three times the amount.
-        ///
-        /// As with the answers_, authorities_ and additionals_ elements, the
-        /// reservation is made in the constructor to avoid dynamic allocation
-        /// of memory.  The ResponseCreator is a member variable of the Query
-        /// object so is constructed once and lasts as long as that object.
-        /// Internal state is cleared through the clear() method.
-        ResponseCreator() {
-            added_.reserve(2 * RESERVE_RRSETS);
-        }
-
-        /// \brief Reset internal state
-        void clear() {
-            added_.clear();
-        }
-
-        /// \brief Complete the response message with filling in the
-        /// response sections.
-        ///
-        /// This is the final step of the Query::process() method, and within
-        /// that method, it should be called before it returns (if any
-        /// response data is to be added)
-        ///
-        /// This will take a message to build and each RRsets for the answer,
-        /// authority, and additional sections, and add them to their
-        /// corresponding sections in the given message.  The RRsets are
-        /// filtered such that a particular RRset appears only once in the
-        /// message. Any RRSIGs attached to the RRsets will be included
-        /// when they are rendered.
-        void create(
-            isc::dns::Message& message,
-            const std::vector<isc::dns::ConstRRsetPtr>& answers_,
-            const std::vector<isc::dns::ConstRRsetPtr>& authorities_,
-            const std::vector<isc::dns::ConstRRsetPtr>& additionals_);
-
-    private:
-        // \brief RRset comparison functor.
-        struct IsSameKind : public std::binary_function<
-                            const isc::dns::AbstractRRset*,
-                            const isc::dns::AbstractRRset*,
-                            bool> {
-            bool operator()(const isc::dns::AbstractRRset* r1,
-                            const isc::dns::AbstractRRset* r2) const {
-                return (r1->isSameKind(*r2));
-            }
-        };
-
-        /// Insertion operation
-        ///
-        /// \param message Message to which the RRset is to be added
-        /// \param section Section of the message in which the RRset is put
-        /// \param rrset Pointer to RRset to be added to the message
-        void addRRset(isc::dns::Message& message,
-                      const isc::dns::Message::Section section,
-                      const isc::dns::ConstRRsetPtr& rrset);
-
-
-    private:
-        /// List of RRsets already added to the message
-        std::vector<const isc::dns::AbstractRRset*> added_;
-    };
-
-private:
-    const isc::datasrc::ClientList* client_list_;
-    const isc::dns::Name* qname_;
-    const isc::dns::RRType* qtype_;
-    bool dnssec_;
-    isc::datasrc::ZoneFinder::FindOptions dnssec_opt_;
-    ResponseCreator response_creator_;
-
-    isc::dns::Message* response_;
-    std::vector<isc::dns::ConstRRsetPtr> answers_;
-    std::vector<isc::dns::ConstRRsetPtr> authorities_;
-    std::vector<isc::dns::ConstRRsetPtr> additionals_;
-
-private:
-    /// \brief Returns a reference to a pre-initialized vector (see the
-    /// \c Query constructor).
-    const std::vector<isc::dns::RRType>& A_AND_AAAA() const {
-        return (a_and_aaaa_);
-    }
-
-    std::vector<isc::dns::RRType> a_and_aaaa_;
-};
-
-}
-}
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 17
src/bin/auth/spec_config.h.pre.in

@@ -1,17 +0,0 @@
-// Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#define AUTH_SPECFILE_LOCATION "@prefix@/share/@PACKAGE@/auth.spec"
-#define UNIX_XFROUT_SOCKET_FILE "@@LOCALSTATEDIR@@/@PACKAGE@/auth_xfrout_conn"
-#define UNIX_DDNS_SOCKET_FILE "@@LOCALSTATEDIR@@/@PACKAGE@/ddns_socket"

+ 0 - 286
src/bin/auth/statistics.cc.pre

@@ -1,286 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <auth/statistics.h>
-#include <auth/statistics_items.h>
-#include <auth/auth_log.h>
-
-#include <cc/data.h>
-
-#include <dns/message.h>
-#include <dns/opcode.h>
-#include <dns/rcode.h>
-
-#include <statistics/counter.h>
-
-#include <boost/optional.hpp>
-
-#include <stdint.h>
-
-using namespace isc::dns;
-using namespace isc::auth;
-using namespace isc::statistics;
-using namespace isc::auth::statistics;
-
-namespace {
-
-/// \brief Fill isc::data::ElementPtr with given counter.
-/// \param counter Counter which stores values to fill
-/// \param type_tree CounterSpec corresponding to counter for building item
-///                  name
-/// \param trees isc::data::ElementPtr to be filled in; caller has ownership of
-///              isc::data::ElementPtr
-void
-fillNodes(const Counter& counter,
-          const struct isc::auth::statistics::CounterSpec type_tree[],
-          isc::data::ElementPtr& trees)
-{
-    using namespace isc::data;
-
-    for (int i = 0; type_tree[i].name != NULL; ++i) {
-        if (type_tree[i].sub_counters != NULL) {
-            isc::data::ElementPtr sub_counters = Element::createMap();
-            trees->set(type_tree[i].name, sub_counters);
-            fillNodes(counter, type_tree[i].sub_counters, sub_counters);
-        } else {
-            trees->set(type_tree[i].name,
-                       Element::create(static_cast<int64_t>(
-                           counter.get(type_tree[i].counter_id) & 0x7fffffffffffffffLL))
-                       );
-        }
-    }
-}
-
-// ### STATISTICS ITEMS DEFINITION ###
-
-} // anonymous namespace
-
-namespace isc {
-namespace auth {
-namespace statistics {
-
-// Note: opcode in this array must be start with 0 and be sequential
-const int opcode_to_msgcounter[] = {
-    MSG_OPCODE_QUERY,    // Opcode =  0: Query
-    MSG_OPCODE_IQUERY,   // Opcode =  1: IQuery
-    MSG_OPCODE_STATUS,   // Opcode =  2: Status
-    MSG_OPCODE_OTHER,    // Opcode =  3: (Unassigned)
-    MSG_OPCODE_NOTIFY,   // Opcode =  4: Notify
-    MSG_OPCODE_UPDATE,   // Opcode =  5: Update
-    MSG_OPCODE_OTHER,    // Opcode =  6: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode =  7: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode =  8: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode =  9: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode = 10: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode = 11: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode = 12: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode = 13: (Unassigned)
-    MSG_OPCODE_OTHER,    // Opcode = 14: (Unassigned)
-    MSG_OPCODE_OTHER     // Opcode = 15: (Unassigned)
-};
-const size_t num_opcode_to_msgcounter =
-    sizeof(opcode_to_msgcounter) / sizeof(opcode_to_msgcounter[0]);
-
-// Note: rcode in this array must be start with 0 and be sequential
-const int rcode_to_msgcounter[] = {
-    MSG_RCODE_NOERROR,       // Rcode =  0: NoError
-    MSG_RCODE_FORMERR,       // Rcode =  1: FormErr
-    MSG_RCODE_SERVFAIL,      // Rcode =  2: ServFail
-    MSG_RCODE_NXDOMAIN,      // Rcode =  3: NXDomain
-    MSG_RCODE_NOTIMP,        // Rcode =  4: NotImp
-    MSG_RCODE_REFUSED,       // Rcode =  5: Refused
-    MSG_RCODE_YXDOMAIN,      // Rcode =  6: YXDomain
-    MSG_RCODE_YXRRSET,       // Rcode =  7: YXRRSet
-    MSG_RCODE_NXRRSET,       // Rcode =  8: NXRRSet
-    MSG_RCODE_NOTAUTH,       // Rcode =  9: NotAuth
-    MSG_RCODE_NOTZONE,       // Rcode = 10: NotZone
-    MSG_RCODE_OTHER,         // Rcode = 11: (Unassigned)
-    MSG_RCODE_OTHER,         // Rcode = 12: (Unassigned)
-    MSG_RCODE_OTHER,         // Rcode = 13: (Unassigned)
-    MSG_RCODE_OTHER,         // Rcode = 14: (Unassigned)
-    MSG_RCODE_OTHER,         // Rcode = 15: (Unassigned)
-    MSG_RCODE_BADVERS        // Rcode = 16: BADVERS
-};
-const size_t num_rcode_to_msgcounter =
-    sizeof(rcode_to_msgcounter) / sizeof(rcode_to_msgcounter[0]);
-
-Counters::Counters() :
-    server_msg_counter_(MSG_COUNTER_TYPES)
-{}
-
-void
-Counters::incRequest(const MessageAttributes& msgattrs) {
-    // protocols carrying request
-    if (msgattrs.getRequestIPVersion() == AF_INET) {
-        server_msg_counter_.inc(MSG_REQUEST_IPV4);
-    } else if (msgattrs.getRequestIPVersion() == AF_INET6) {
-        server_msg_counter_.inc(MSG_REQUEST_IPV6);
-    }
-    if (msgattrs.getRequestTransportProtocol() == IPPROTO_UDP) {
-        server_msg_counter_.inc(MSG_REQUEST_UDP);
-    } else if (msgattrs.getRequestTransportProtocol() == IPPROTO_TCP) {
-        server_msg_counter_.inc(MSG_REQUEST_TCP);
-    }
-
-    // Opcode
-    const boost::optional<isc::dns::Opcode>& opcode =
-        msgattrs.getRequestOpCode();
-    // Increment opcode counter only if the opcode exists; opcode can be empty
-    // if a short message which does not contain DNS header is received, or
-    // a response message (i.e. QR bit is set) is received.
-    if (opcode) {
-        server_msg_counter_.inc(opcode_to_msgcounter[opcode->getCode()]);
-
-        if (opcode.get() == Opcode::QUERY()) {
-            // Recursion Desired bit
-            if (msgattrs.requestHasRD()) {
-                server_msg_counter_.inc(MSG_QRYRECURSION);
-            }
-        }
-    }
-
-    // TSIG
-    if (msgattrs.requestHasTSIG()) {
-        server_msg_counter_.inc(MSG_REQUEST_TSIG);
-    }
-    if (msgattrs.requestHasBadSig()) {
-        server_msg_counter_.inc(MSG_REQUEST_BADSIG);
-        // If signature validation failed, no other request attributes (except
-        // for opcode) are reliable. Skip processing of the rest of request
-        // counters.
-        return;
-    }
-
-    // EDNS0
-    if (msgattrs.requestHasEDNS0()) {
-        server_msg_counter_.inc(MSG_REQUEST_EDNS0);
-    }
-
-    // DNSSEC OK bit
-    if (msgattrs.requestHasDO()) {
-        server_msg_counter_.inc(MSG_REQUEST_DNSSEC_OK);
-    }
-}
-
-void
-Counters::incResponse(const MessageAttributes& msgattrs,
-                      const Message& response)
-{
-    // responded
-    server_msg_counter_.inc(MSG_RESPONSE);
-
-    // response truncated
-    if (msgattrs.responseIsTruncated()) {
-        server_msg_counter_.inc(MSG_RESPONSE_TRUNCATED);
-    }
-
-    // response EDNS
-    ConstEDNSPtr response_edns = response.getEDNS();
-    if (response_edns && response_edns->getVersion() == 0) {
-        server_msg_counter_.inc(MSG_RESPONSE_EDNS0);
-    }
-
-    // response TSIG
-    if (msgattrs.responseHasTSIG()) {
-        server_msg_counter_.inc(MSG_RESPONSE_TSIG);
-    }
-
-    // response SIG(0) is currently not implemented
-
-    // RCODE
-    const unsigned int rcode = response.getRcode().getCode();
-    const unsigned int rcode_type =
-        rcode < num_rcode_to_msgcounter ?
-        rcode_to_msgcounter[rcode] : MSG_RCODE_OTHER;
-    server_msg_counter_.inc(rcode_type);
-    // Unsupported EDNS version
-    if (rcode == Rcode::BADVERS().getCode()) {
-        server_msg_counter_.inc(MSG_REQUEST_BADEDNSVER);
-    }
-
-    const boost::optional<isc::dns::Opcode>& opcode =
-        msgattrs.getRequestOpCode();
-    if (!opcode) {
-        isc_throw(isc::Unexpected, "Opcode of the request is empty while it is"
-                                   " responded");
-    }
-    if (!msgattrs.requestHasBadSig() && opcode.get() == Opcode::QUERY()) {
-        // compound attributes
-        const unsigned int answer_rrs =
-            response.getRRCount(Message::SECTION_ANSWER);
-        const bool is_aa_set =
-            response.getHeaderFlag(Message::HEADERFLAG_AA);
-
-        if (is_aa_set) {
-            // QryAuthAns
-            server_msg_counter_.inc(MSG_QRYAUTHANS);
-        } else {
-            // QryNoAuthAns
-            server_msg_counter_.inc(MSG_QRYNOAUTHANS);
-        }
-
-        if (rcode == Rcode::NOERROR_CODE) {
-            if (answer_rrs > 0) {
-                // QrySuccess
-                server_msg_counter_.inc(MSG_QRYSUCCESS);
-            } else {
-                if (is_aa_set) {
-                    // QryNxrrset
-                    server_msg_counter_.inc(MSG_QRYNXRRSET);
-                } else {
-                    // QryReferral
-                    server_msg_counter_.inc(MSG_QRYREFERRAL);
-                }
-            }
-        } else if (rcode == Rcode::REFUSED_CODE) {
-            if (!response.getHeaderFlag(Message::HEADERFLAG_RD)) {
-                // AuthRej
-                server_msg_counter_.inc(MSG_QRYREJECT);
-            }
-        }
-    }
-}
-
-void
-Counters::inc(const MessageAttributes& msgattrs, const Message& response,
-              const bool done)
-{
-    // increment request counters
-    incRequest(msgattrs);
-
-    if (done) {
-        // increment response counters if answer was sent
-        incResponse(msgattrs, response);
-    }
-}
-
-Counters::ConstItemTreePtr
-Counters::get() const {
-    using namespace isc::data;
-
-    isc::data::ElementPtr item_tree = Element::createMap();
-
-    isc::data::ElementPtr zones = Element::createMap();
-    item_tree->set("zones", zones);
-
-    isc::data::ElementPtr server = Element::createMap();
-    fillNodes(server_msg_counter_, msg_counter_tree, server);
-    zones->set("_SERVER_", server);
-
-    return (item_tree);
-}
-
-} // namespace statistics
-} // namespace auth
-} // namespace isc

+ 0 - 329
src/bin/auth/statistics.h

@@ -1,329 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef STATISTICS_H
-#define STATISTICS_H 1
-
-#include <cc/data.h>
-
-#include <dns/message.h>
-#include <dns/opcode.h>
-
-#include <statistics/counter.h>
-
-#include <boost/noncopyable.hpp>
-#include <boost/optional.hpp>
-
-#include <bitset>
-
-#include <stdint.h>
-
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netdb.h>
-
-namespace isc {
-namespace auth {
-namespace statistics {
-
-/// \brief DNS Message attributes for statistics.
-///
-/// This class holds some attributes related to a DNS message
-/// for statistics data collection.
-class MessageAttributes {
-public:
-    /// \brief IP version of DNS message.
-    enum IPVersionType {
-        IP_VERSION_UNSPEC,          // (initial value; internal use only)
-        IP_VERSION_IPV4,            ///< IPv4 message
-        IP_VERSION_IPV6             ///< IPv6 message
-    };
-
-    /// \brief Transport protocol of DNS message.
-    enum TransportProtocolType {
-        TRANSPORT_UNSPEC,           // (initial value; internal use only)
-        TRANSPORT_UDP,              ///< UDP message
-        TRANSPORT_TCP               ///< TCP message
-    };
-private:
-    // request attributes
-    int req_address_family_;        // IP version
-    int req_transport_protocol_;    // Transport layer protocol
-    boost::optional<isc::dns::Opcode> req_opcode_;  // OpCode
-    enum BitAttributes {
-        REQ_WITH_EDNS_0,            // request with EDNS ver.0
-        REQ_WITH_DNSSEC_OK,         // DNSSEC OK (DO) bit is set in request
-        REQ_WITH_RD,                // Recursion Desired (RD) bit is set in
-                                    // request
-        REQ_TSIG_SIGNED,            // request is signed with valid TSIG
-        REQ_BADSIG,                 // request is signed but bad signature
-        RES_IS_TRUNCATED,           // response is truncated
-        RES_TSIG_SIGNED,            // response is signed with TSIG
-        BIT_ATTRIBUTES_TYPES
-    };
-    std::bitset<BIT_ATTRIBUTES_TYPES> bit_attributes_;
-public:
-    /// \brief The constructor.
-    ///
-    /// \throw None
-    MessageAttributes() : req_address_family_(0), req_transport_protocol_(0)
-    {}
-
-    /// \brief Return opcode of the request.
-    ///
-    /// \return opcode of the request wrapped with boost::optional; it's
-    ///         converted to false if Opcode hasn't been set.
-    /// \throw None
-    const boost::optional<isc::dns::Opcode>& getRequestOpCode() const {
-        return (req_opcode_);
-    }
-
-    /// \brief Set opcode of the request.
-    ///
-    /// \param opcode Opcode of the request
-    /// \throw None
-    void setRequestOpCode(const isc::dns::Opcode& opcode) {
-        req_opcode_ = opcode;
-    }
-
-    /// \brief Get IP version carrying a request.
-    ///
-    /// \return IP address family carrying a request (AF_INET or AF_INET6)
-    /// \throw None
-    int getRequestIPVersion() const {
-        return (req_address_family_);
-    }
-
-    /// \brief Set IP address family carrying a request.
-    ///
-    /// \param address_family AF_INET or AF_INET6
-    /// \throw None
-    void setRequestIPVersion(const int address_family) {
-        if (address_family != AF_INET && address_family != AF_INET6) {
-            isc_throw(isc::InvalidParameter, "Unknown address family");
-        }
-        req_address_family_ = address_family;
-    }
-
-    /// \brief Get transport protocol carrying a request.
-    ///
-    /// \return Transport protocol carrying a request
-    ///         (IPPROTO_UDP or IPPROTO_TCP)
-    /// \throw None
-    int getRequestTransportProtocol() const {
-        return (req_transport_protocol_);
-    }
-
-    /// \brief Set transport protocol carrying a request.
-    ///
-    /// \param transport_protocol IPPROTO_UDP or IPPROTO_TCP
-    /// \throw None
-    void setRequestTransportProtocol(const int transport_protocol) {
-        if (transport_protocol != IPPROTO_UDP &&
-            transport_protocol != IPPROTO_TCP)
-        {
-            isc_throw(isc::InvalidParameter, "Unknown transport protocol");
-        }
-        req_transport_protocol_ = transport_protocol;
-    }
-
-    /// \brief Return whether EDNS version of the request is 0 or not.
-    ///
-    /// \return true if EDNS version of the request is 0
-    /// \throw None
-    bool requestHasEDNS0() const {
-        return (bit_attributes_[REQ_WITH_EDNS_0]);
-    }
-
-    /// \brief Set whether EDNS version of the request is 0 or not.
-    ///
-    /// \param with_edns_0 true if EDNS version of the request is 0
-    /// \throw None
-    void setRequestEDNS0(const bool with_edns_0) {
-        bit_attributes_[REQ_WITH_EDNS_0] = with_edns_0;
-    }
-
-    /// \brief Return DNSSEC OK (DO) bit of the request.
-    ///
-    /// \return true if DNSSEC OK (DO) bit of the request is set
-    /// \throw None
-    bool requestHasDO() const {
-        return (bit_attributes_[REQ_WITH_DNSSEC_OK]);
-    }
-
-    /// \brief Set DNSSEC OK (DO) bit of the request.
-    ///
-    /// \param with_dnssec_ok true if DNSSEC OK (DO) bit of the request is set
-    /// \throw None
-    void setRequestDO(const bool with_dnssec_ok) {
-        bit_attributes_[REQ_WITH_DNSSEC_OK] = with_dnssec_ok;
-    }
-
-    /// \brief Return Recursion Desired (RD) bit of the request.
-    ///
-    /// \return true if Recursion Desired (RD) bit of the request is set
-    /// \throw None
-    bool requestHasRD() const {
-        return (bit_attributes_[REQ_WITH_RD]);
-    }
-
-    /// \brief Set Recursion Desired (RD) bit of the request.
-    ///
-    /// \param with_rd true if Recursion Desired (RD)bit of the request is set
-    /// \throw None
-    void setRequestRD(const bool with_rd) {
-        bit_attributes_[REQ_WITH_RD] = with_rd;
-    }
-
-    /// \brief Return whether the request is TSIG signed or not.
-    ///
-    /// \return true if the request is TSIG signed
-    /// \throw None
-    bool requestHasTSIG() const {
-        return (bit_attributes_[REQ_TSIG_SIGNED]);
-    }
-
-    /// \brief Return whether the signature of the request is bad or not.
-    ///
-    /// \return true if the signature of the request is bad
-    /// \throw None
-    bool requestHasBadSig() const {
-        return (bit_attributes_[REQ_BADSIG]);
-    }
-
-    /// \brief Set TSIG attributes of the request.
-    ///
-    /// \param signed_tsig true if the request is signed with TSIG
-    /// \param badsig true if the signature of the request is bad; it must not
-    //                be true unless signed_tsig is true
-    /// \throw isc::InvalidParameter if badsig is true though the request is
-    ///                              not signed
-    void setRequestTSIG(const bool signed_tsig, const bool badsig) {
-        if (!signed_tsig && badsig) {
-            isc_throw(isc::InvalidParameter, "Message is not signed but badsig"
-                                             " is true");
-        }
-        bit_attributes_[REQ_TSIG_SIGNED] = signed_tsig;
-        bit_attributes_[REQ_BADSIG] = badsig;
-    }
-
-    /// \brief Return TC (truncated) bit of the response.
-    ///
-    /// \return true if the response is truncated
-    /// \throw None
-    bool responseIsTruncated() const {
-        return (bit_attributes_[RES_IS_TRUNCATED]);
-    }
-
-    /// \brief Set TC (truncated) bit of the response.
-    ///
-    /// \param is_truncated true if the response is truncated
-    /// \throw None
-    void setResponseTruncated(const bool is_truncated) {
-        bit_attributes_[RES_IS_TRUNCATED] = is_truncated;
-    }
-
-    /// \brief Return whether the response is TSIG signed or not.
-    ///
-    /// \return true if the response is signed with TSIG
-    /// \throw None
-    bool responseHasTSIG() const {
-        return (bit_attributes_[RES_TSIG_SIGNED]);
-    }
-
-    /// \brief Set whether the response is TSIG signed or not.
-    ///
-    /// \param signed_tsig true if the response is signed with TSIG
-    /// \throw None
-    void setResponseTSIG(const bool signed_tsig) {
-        bit_attributes_[RES_TSIG_SIGNED] = signed_tsig;
-    }
-};
-
-/// \brief Set of DNS message counters.
-///
-/// \c Counters is a set of DNS message counters class. It holds DNS message
-/// counters and provides an interface to increment the counter of specified
-/// type (e.g. UDP message, TCP message).
-///
-/// This class is designed to be a part of \c AuthSrv.
-/// Call \c inc() to increment a counter for the message.
-/// Call \c get() to get a set of DNS message counters.
-///
-/// We may eventually want to change the structure to hold values that are
-/// not counters (such as concurrent TCP connections), or seperate generic
-/// part to src/lib to share with the other modules.
-///
-/// This class is constructed on startup of the server, so
-/// construction overhead of this approach should be acceptable.
-///
-/// \todo Consider overhead of \c Counters::inc()
-class Counters : boost::noncopyable {
-private:
-    // counter for DNS message attributes
-    isc::statistics::Counter server_msg_counter_;
-    void incRequest(const MessageAttributes& msgattrs);
-    void incResponse(const MessageAttributes& msgattrs,
-                     const isc::dns::Message& response);
-public:
-    /// \brief A type of statistics item tree in isc::data::MapElement.
-    /// \verbatim
-    ///        {
-    ///          zone_name => {
-    ///                         item_name => item_value,
-    ///                         item_name => item_value, ...
-    ///                       },
-    ///          ...
-    ///        }
-    ///        item_name is a string seperated by '.'.
-    ///        item_value is an integer.
-    /// \endverbatim
-    typedef isc::data::ConstElementPtr ConstItemTreePtr;
-
-    /// \brief The constructor.
-    ///
-    /// This constructor is mostly exception free. But it may still throw
-    /// a standard exception if memory allocation fails inside the method.
-    Counters();
-
-    /// \brief Increment counters according to the parameters.
-    ///
-    /// \param msgattrs DNS message attributes.
-    /// \param response DNS response message.
-    /// \param done DNS response was sent to the client.
-    /// \throw isc::Unexpected Internal condition check failed.
-    void inc(const MessageAttributes& msgattrs,
-             const isc::dns::Message& response, const bool done);
-
-    /// \brief Get statistics counters.
-    ///
-    /// This method is mostly exception free. But it may still throw a
-    /// standard exception if memory allocation fails inside the method.
-    ///
-    /// \return statistics data
-    /// \throw std::bad_alloc Internal resource allocation fails
-    ConstItemTreePtr get() const;
-};
-
-} // namespace statistics
-} // namespace auth
-} // namespace isc
-
-#endif // STATISTICS_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 53
src/bin/auth/statistics_items.h.pre

@@ -1,53 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef __STATISTICS_ITEMS_H
-#define __STATISTICS_ITEMS_H 1
-
-/// This file declares a set of statistics items in Auth module for internal
-/// use. This file is intended to be included in statistics.cc and unittests.
-
-namespace isc {
-namespace auth {
-namespace statistics {
-
-struct CounterSpec {
-    /// \brief name Name of this node. This appears in the spec file.
-    const char* const name;
-    /// \brief sub_counters If this is a branch node, sub_counters points to
-    ///                     CounterSpec which contains child nodes. Otherwise,
-    ///                     for leaf nodes, sub_counters is NULL.
-    const struct CounterSpec* const sub_counters;
-    /// \brief counter_id If this is a leaf node, counter_id is an enumerator
-    ///                   of this item. Otherwise, for branch nodes, counter_id
-    ///                   is NOT_ITEM.
-    const int counter_id;
-};
-
-// ### STATISTICS ITEMS DECLARATION ###
-
-extern const int opcode_to_msgcounter[];
-extern const size_t num_opcode_to_msgcounter;
-extern const int rcode_to_msgcounter[];
-extern const size_t num_rcode_to_msgcounter;
-
-} // namespace statistics
-} // namespace auth
-} // namespace isc
-
-#endif // __STATISTICS_ITEMS_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 49
src/bin/auth/statistics_msg_items.def

@@ -1,49 +0,0 @@
-request	msg_counter_request		Request statistics	=
-	v4		MSG_REQUEST_IPV4	Number of IPv4 requests received by the b10-auth server.
-	v6		MSG_REQUEST_IPV6	Number of IPv6 requests received by the b10-auth server.
-	edns0		MSG_REQUEST_EDNS0	Number of requests with EDNS0 received by the b10-auth server.
-	badednsver	MSG_REQUEST_BADEDNSVER	Number of requests with unsupported EDNS version received by the b10-auth server.
-	tsig		MSG_REQUEST_TSIG	Number of requests with TSIG received by the b10-auth server.
-	sig0		MSG_REQUEST_SIG0	Number of requests with SIG(0) received by the b10-auth server; currently not implemented in BIND 10.
-	badsig		MSG_REQUEST_BADSIG	Number of requests with invalid TSIG or SIG(0) signature received by the b10-auth server.
-	udp		MSG_REQUEST_UDP		Number of UDP requests received by the b10-auth server.
-	tcp		MSG_REQUEST_TCP		Number of TCP requests received by the b10-auth server.
-	dnssec_ok	MSG_REQUEST_DNSSEC_OK	Number of requests with "DNSSEC OK" (DO) bit was set received by the b10-auth server.
-	;
-opcode	msg_counter_opcode		OpCode statistics	=
-	query		MSG_OPCODE_QUERY	Number of OpCode=Query requests received by the b10-auth server.
-	iquery		MSG_OPCODE_IQUERY	Number of OpCode=IQuery requests received by the b10-auth server.
-	status		MSG_OPCODE_STATUS	Number of OpCode=Status requests received by the b10-auth server.
-	notify		MSG_OPCODE_NOTIFY	Number of OpCode=Notify requests received by the b10-auth server.
-	update		MSG_OPCODE_UPDATE	Number of OpCode=Update requests received by the b10-auth server.
-	other		MSG_OPCODE_OTHER	Number of requests in other OpCode received by the b10-auth server.
-	;
-responses	MSG_RESPONSE			Number of responses sent by the b10-auth server.
-response	msg_counter_response	Response statistics	=
-	truncated	MSG_RESPONSE_TRUNCATED	Number of truncated responses sent by the b10-auth server.
-	edns0		MSG_RESPONSE_EDNS0	Number of responses with EDNS0 sent by the b10-auth server.
-	tsig		MSG_RESPONSE_TSIG	Number of responses with TSIG sent by the b10-auth server.
-	sig0		MSG_RESPONSE_SIG0	Number of responses with SIG(0) sent by the b10-auth server; currently not implemented in BIND 10.
-	;
-qrysuccess	MSG_QRYSUCCESS			Number of queries received by the b10-auth server resulted in rcode = NoError and the number of answer RR >= 1.
-qryauthans	MSG_QRYAUTHANS			Number of queries received by the b10-auth server resulted in authoritative answer.
-qrynoauthans	MSG_QRYNOAUTHANS		Number of queries received by the b10-auth server resulted in non-authoritative answer.
-qryreferral	MSG_QRYREFERRAL			Number of queries received by the b10-auth server resulted in referral answer.
-qrynxrrset	MSG_QRYNXRRSET			Number of queries received by the b10-auth server resulted in NoError and AA bit is set in the response, but the number of answer RR == 0.
-authqryrej	MSG_QRYREJECT			Number of authoritative queries rejected by the b10-auth server.
-qryrecursion	MSG_QRYRECURSION		Number of queries received by the b10-auth server with "Recursion Desired" (RD) bit was set.
-rcode		msg_counter_rcode	Rcode statistics	=
-	noerror		MSG_RCODE_NOERROR	Number of requests received by the b10-auth server resulted in RCODE = 0 (NoError).
-	formerr		MSG_RCODE_FORMERR	Number of requests received by the b10-auth server resulted in RCODE = 1 (FormErr).
-	servfail	MSG_RCODE_SERVFAIL	Number of requests received by the b10-auth server resulted in RCODE = 2 (ServFail).
-	nxdomain	MSG_RCODE_NXDOMAIN	Number of requests received by the b10-auth server resulted in RCODE = 3 (NXDomain).
-	notimp		MSG_RCODE_NOTIMP	Number of requests received by the b10-auth server resulted in RCODE = 4 (NotImp).
-	refused		MSG_RCODE_REFUSED	Number of requests received by the b10-auth server resulted in RCODE = 5 (Refused).
-	yxdomain	MSG_RCODE_YXDOMAIN	Number of requests received by the b10-auth server resulted in RCODE = 6 (YXDomain).
-	yxrrset		MSG_RCODE_YXRRSET	Number of requests received by the b10-auth server resulted in RCODE = 7 (YXRRSet).
-	nxrrset		MSG_RCODE_NXRRSET	Number of requests received by the b10-auth server resulted in RCODE = 8 (NXRRSet).
-	notauth		MSG_RCODE_NOTAUTH	Number of requests received by the b10-auth server resulted in RCODE = 9 (NotAuth).
-	notzone		MSG_RCODE_NOTZONE	Number of requests received by the b10-auth server resulted in RCODE = 10 (NotZone).
-	badvers		MSG_RCODE_BADVERS	Number of requests received by the b10-auth server resulted in RCODE = 16 (BADVERS).
-	other		MSG_RCODE_OTHER		Number of requests received by the b10-auth server resulted in other RCODEs.
-	;

+ 0 - 4
src/bin/auth/tests/.gitignore

@@ -1,4 +0,0 @@
-/run_unittests
-/example_base_inc.cc
-/example_nsec3_inc.cc
-/statistics_unittest.cc

+ 0 - 128
src/bin/auth/tests/Makefile.am

@@ -1,128 +0,0 @@
-SUBDIRS = testdata .
-
-AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
-AM_CPPFLAGS += -I$(top_builddir)/src/bin # for generated spec_config.h header
-AM_CPPFLAGS += -I$(top_builddir)/src/lib/dns -I$(top_srcdir)/src/bin
-AM_CPPFLAGS += -I$(top_builddir)/src/lib/cc
-AM_CPPFLAGS += $(BOOST_INCLUDES)
-AM_CPPFLAGS += -DAUTH_OBJ_DIR=\"$(abs_top_builddir)/src/bin/auth\"
-AM_CPPFLAGS += -DTEST_DATA_DIR=\"$(abs_top_srcdir)/src/lib/testutils/testdata\"
-AM_CPPFLAGS += -DTEST_OWN_DATA_DIR=\"$(abs_srcdir)/testdata\"
-AM_CPPFLAGS += -DTEST_OWN_DATA_BUILDDIR=\"$(abs_builddir)/testdata\"
-AM_CPPFLAGS += -DTEST_DATA_BUILDDIR=\"$(abs_top_builddir)/src/lib/testutils/testdata\"
-AM_CPPFLAGS += -DDSRC_DIR=\"$(abs_top_builddir)/src/lib/datasrc\"
-AM_CPPFLAGS += -DPLUGIN_DATA_PATH=\"$(abs_top_builddir)/src/bin/cfgmgr/plugins\"
-AM_CPPFLAGS += -DINSTALL_PROG=\"$(abs_top_srcdir)/install-sh\"
-
-AM_CXXFLAGS = $(B10_CXXFLAGS)
-
-if USE_STATIC_LINK
-AM_LDFLAGS = -static
-# Some test cases cannot work with static link.  To selectively disable such
-# tests we signal it via a definition.
-AM_CPPFLAGS += -DUSE_STATIC_LINK=1
-endif
-
-CLEANFILES = *.gcno *.gcda
-CLEANFILES += $(abs_top_builddir)/src/lib/testutils/testdata/does-not-exist.sqlite3
-
-TESTS_ENVIRONMENT = \
-        $(LIBTOOL) --mode=execute $(VALGRIND_COMMAND)
-
-EXTRA_DIST = gen-query-testdata.py
-EXTRA_DIST += gen-statisticsitems_test.py
-
-# Do not define global tests, use check-local so
-# environment can be set (needed for dynamic loading)
-TESTS =
-if HAVE_GTEST
-
-# auto-generated by statistics_items.py
-BUILT_SOURCES = statistics_unittest.cc
-
-run_unittests_SOURCES = $(top_srcdir)/src/lib/dns/tests/unittest_util.h
-run_unittests_SOURCES += $(top_srcdir)/src/lib/dns/tests/unittest_util.cc
-run_unittests_SOURCES += ../auth_srv.h ../auth_srv.cc
-run_unittests_SOURCES += ../auth_log.h ../auth_log.cc
-run_unittests_SOURCES += ../query.h ../query.cc
-run_unittests_SOURCES += ../auth_config.h ../auth_config.cc
-run_unittests_SOURCES += ../command.h ../command.cc
-run_unittests_SOURCES += ../common.h ../common.cc
-run_unittests_SOURCES += ../statistics.h ../statistics.cc ../statistics_items.h
-run_unittests_SOURCES += ../datasrc_config.h ../datasrc_config.cc
-run_unittests_SOURCES += datasrc_util.h datasrc_util.cc
-run_unittests_SOURCES += statistics_util.h statistics_util.cc
-run_unittests_SOURCES += auth_srv_unittest.cc
-run_unittests_SOURCES += config_unittest.cc
-run_unittests_SOURCES += config_syntax_unittest.cc
-run_unittests_SOURCES += command_unittest.cc
-run_unittests_SOURCES += common_unittest.cc
-run_unittests_SOURCES += query_unittest.cc
-run_unittests_SOURCES += test_datasrc_clients_mgr.h test_datasrc_clients_mgr.cc
-run_unittests_SOURCES += datasrc_clients_builder_unittest.cc
-run_unittests_SOURCES += datasrc_clients_mgr_unittest.cc
-run_unittests_SOURCES += datasrc_config_unittest.cc
-run_unittests_SOURCES += run_unittests.cc
-
-nodist_run_unittests_SOURCES = ../auth_messages.h ../auth_messages.cc
-nodist_run_unittests_SOURCES += statistics_unittest.cc
-
-run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES)
-run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
-run_unittests_LDADD = $(top_builddir)/src/lib/testutils/libb10-testutils.la
-run_unittests_LDADD +=  $(top_builddir)/src/lib/datasrc/libb10-datasrc.la
-run_unittests_LDADD +=  $(top_builddir)/src/lib/dns/libb10-dns++.la
-run_unittests_LDADD += $(top_builddir)/src/lib/util/libb10-util.la
-run_unittests_LDADD += $(top_builddir)/src/lib/asiodns/libb10-asiodns.la
-run_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
-run_unittests_LDADD += $(top_builddir)/src/lib/config/libb10-cfgclient.la
-run_unittests_LDADD += $(top_builddir)/src/lib/cc/libb10-cc.la
-run_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
-run_unittests_LDADD += $(top_builddir)/src/lib/xfr/libb10-xfr.la
-run_unittests_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
-run_unittests_LDADD += $(top_builddir)/src/lib/server_common/libb10-server-common.la
-run_unittests_LDADD += $(top_builddir)/src/lib/nsas/libb10-nsas.la
-run_unittests_LDADD += $(top_builddir)/src/lib/util/unittests/libutil_unittests.la
-run_unittests_LDADD += $(top_builddir)/src/lib/config/tests/libfake_session.la
-run_unittests_LDADD += $(top_builddir)/src/lib/util/threads/libb10-threads.la
-run_unittests_LDADD += $(GTEST_LDADD)
-run_unittests_LDADD += $(SQLITE_LIBS)
-
-# The following are definitions for auto-generating test data for query
-# tests.
-BUILT_SOURCES += example_base_inc.cc example_nsec3_inc.cc
-BUILT_SOURCES += testdata/example-base.sqlite3
-BUILT_SOURCES += testdata/example-nsec3.sqlite3
-
-CLEANFILES += example_base_inc.cc example_nsec3_inc.cc
-
-example_base_inc.cc: $(srcdir)/testdata/example-base-inc.zone
-	$(PYTHON) $(srcdir)/gen-query-testdata.py \
-		$(srcdir)/testdata/example-base-inc.zone example_base_inc.cc
-
-example_nsec3_inc.cc: $(srcdir)/testdata/example-nsec3-inc.zone
-	$(PYTHON) $(srcdir)/gen-query-testdata.py \
-		$(srcdir)/testdata/example-nsec3-inc.zone example_nsec3_inc.cc
-
-testdata/example-common-inc.zone: $(srcdir)/testdata/example-common-inc-template.zone
-	$(top_srcdir)/install-sh -c \
-		$(srcdir)/testdata/example-common-inc-template.zone \
-		testdata/example-common-inc.zone
-
-testdata/example-base.sqlite3: testdata/example-base.zone testdata/example-common-inc.zone
-	$(SHELL) $(top_builddir)/src/bin/loadzone/run_loadzone.sh \
-		-c "{\"database_file\": \"$(builddir)/testdata/example-base.sqlite3\"}" \
-		example.com testdata/example-base.zone
-
-testdata/example-nsec3.sqlite3: testdata/example-nsec3.zone testdata/example-common-inc.zone
-	$(SHELL) $(top_builddir)/src/bin/loadzone/run_loadzone.sh \
-		-c "{\"database_file\": \"$(builddir)/testdata/example-nsec3.sqlite3\"}" \
-		example.com testdata/example-nsec3.zone
-
-check-local:
-	B10_FROM_BUILD=${abs_top_builddir} ./run_unittests
-	$(PYTHON) $(srcdir)/gen-statisticsitems_test.py $(top_builddir)/src/bin/auth/b10-auth.xml
-
-noinst_PROGRAMS = run_unittests
-
-endif

Fichier diff supprimé car celui-ci est trop grand
+ 0 - 2186
src/bin/auth/tests/auth_srv_unittest.cc


+ 0 - 177
src/bin/auth/tests/command_unittest.cc

@@ -1,177 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include "datasrc_util.h"
-
-#include <auth/auth_srv.h>
-#include <auth/command.h>
-#include <auth/datasrc_config.h>
-
-#include <dns/name.h>
-#include <dns/rrclass.h>
-#include <dns/rrtype.h>
-#include <dns/rrttl.h>
-
-#include <cc/data.h>
-
-#include <config/ccsession.h>
-
-#include <asiolink/asiolink.h>
-
-#include <util/unittests/mock_socketsession.h>
-#include <testutils/mockups.h>
-
-#include <cassert>
-#include <cstdlib>
-#include <string>
-#include <stdexcept>
-
-#include <boost/bind.hpp>
-
-#include <gtest/gtest.h>
-
-#include <sys/types.h>
-#include <unistd.h>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::datasrc;
-using namespace isc::config;
-using namespace isc::util::unittests;
-using namespace isc::testutils;
-using namespace isc::auth;
-using namespace isc::auth::unittest;
-
-namespace {
-
-class AuthCommandTest : public ::testing::Test {
-protected:
-    AuthCommandTest() :
-        server_(xfrout_, ddns_forwarder_),
-        rcode_(-1),
-        expect_rcode_(0),
-        itimer_(server_.getIOService())
-    {}
-    void checkAnswer(const int expected_code, const char* name = "") {
-        SCOPED_TRACE(name);
-
-        parseAnswer(rcode_, result_);
-        EXPECT_EQ(expected_code, rcode_) << result_->str();
-    }
-    MockXfroutClient xfrout_;
-    MockSocketSessionForwarder ddns_forwarder_;
-    AuthSrv server_;
-    ConstElementPtr result_;
-    // The shutdown command parameter
-    ConstElementPtr param_;
-    int rcode_, expect_rcode_;
-    isc::asiolink::IntervalTimer itimer_;
-public:
-    void stopServer();          // need to be public for boost::bind
-    void dontStopServer();          // need to be public for boost::bind
-};
-
-TEST_F(AuthCommandTest, unknownCommand) {
-    result_ = execAuthServerCommand(server_, "no_such_command",
-                                    ConstElementPtr());
-    parseAnswer(rcode_, result_);
-    EXPECT_EQ(1, rcode_);
-}
-
-TEST_F(AuthCommandTest, DISABLED_unexpectedException) {
-    // execAuthServerCommand() won't catch standard exceptions.
-    // Skip this test for now: ModuleCCSession doesn't seem to validate
-    // commands.
-    EXPECT_THROW(execAuthServerCommand(server_, "_throw_exception",
-                                       ConstElementPtr()),
-                 runtime_error);
-}
-
-void
-AuthCommandTest::stopServer() {
-    result_ = execAuthServerCommand(server_, "shutdown", param_);
-    parseAnswer(rcode_, result_);
-    assert(rcode_ == 0); // make sure the test stops when something is wrong
-}
-
-TEST_F(AuthCommandTest, shutdown) {
-    // Param defaults to empty/null pointer on creation
-    itimer_.setup(boost::bind(&AuthCommandTest::stopServer, this), 1);
-    server_.getIOService().run();
-    EXPECT_EQ(0, rcode_);
-}
-
-TEST_F(AuthCommandTest, shutdownCorrectPID) {
-    // Put the pid parameter there
-    const pid_t pid(getpid());
-    ElementPtr param(new isc::data::MapElement());
-    param->set("pid", ConstElementPtr(new isc::data::IntElement(pid)));
-    param_ = param;
-    // With the correct PID, it should act exactly the same as in case
-    // of no parameter
-    itimer_.setup(boost::bind(&AuthCommandTest::stopServer, this), 1);
-    server_.getIOService().run();
-    EXPECT_EQ(0, rcode_);
-}
-
-// This is like stopServer, but the server should not stop after the
-// command, it should be running
-void
-AuthCommandTest::dontStopServer() {
-    result_ = execAuthServerCommand(server_, "shutdown", param_);
-    parseAnswer(rcode_, result_);
-    EXPECT_EQ(expect_rcode_, rcode_);
-    rcode_ = -1;
-    // We run the stopServer now, to really stop the server.
-    // If it had stopped already, it won't be run and the rcode -1 will
-    // be left here.
-    param_ = ConstElementPtr();
-    itimer_.cancel();
-    itimer_.setup(boost::bind(&AuthCommandTest::stopServer, this), 1);
-}
-
-// If we provide something not an int, the PID is not really specified, so
-// act as if nothing came.
-TEST_F(AuthCommandTest, shutdownNotInt) {
-    // Put the pid parameter there
-    ElementPtr param(new isc::data::MapElement());
-    param->set("pid", ConstElementPtr(new isc::data::StringElement("pid")));
-    param_ = param;
-    expect_rcode_ = 1;
-    // It should reject to stop if the PID is not an int.
-    itimer_.setup(boost::bind(&AuthCommandTest::dontStopServer, this), 1);
-    server_.getIOService().run();
-    EXPECT_EQ(0, rcode_);
-}
-
-TEST_F(AuthCommandTest, shutdownIncorrectPID) {
-    // The PID = 0 should be taken by init, so we are not init and the
-    // PID should be different
-    param_ = Element::fromJSON("{\"pid\": 0}");
-    itimer_.setup(boost::bind(&AuthCommandTest::dontStopServer, this), 1);
-    server_.getIOService().run();
-    EXPECT_EQ(0, rcode_);
-}
-
-TEST_F(AuthCommandTest, getStats) {
-    result_ = execAuthServerCommand(server_, "getstats", ConstElementPtr());
-    parseAnswer(rcode_, result_);
-    // Just check the command execution succeeded.  Detailed tests specific to
-    // statistics are done in its own tests.
-    EXPECT_EQ(0, rcode_);
-}
-}

+ 0 - 122
src/bin/auth/tests/common_unittest.cc

@@ -1,122 +0,0 @@
-// Copyright (C) 2011  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <gtest/gtest.h>
-#include <auth/common.h>
-#include <auth/spec_config.h>
-#include <vector>
-#include <string>
-#include <cstdio>
-#include <boost/foreach.hpp>
-
-using std::pair;
-using std::vector;
-using std::string;
-
-namespace {
-
-class Paths : public ::testing::Test {
-private:
-    typedef pair<string, string*> Environ;
-    vector<Environ> restoreEnviron;
-public:
-    void TearDown() {
-        // Restore the original environment
-        BOOST_FOREACH(const Environ &env, restoreEnviron) {
-            if (env.second == NULL) {
-                EXPECT_EQ(0, unsetenv(env.first.c_str())) <<
-                    "Couldn't restore environment, results of other tests "
-                    "are uncertain";
-            } else {
-                EXPECT_EQ(0, setenv(env.first.c_str(), env.second->c_str(),
-                                    1)) << "Couldn't restore environment, "
-                    "results of other tests are uncertain";
-            }
-        }
-    }
-protected:
-    // Sets a temporary value into environment. If value is empty, it deletes
-    // the variable from environment (just for simplicity).
-    void setEnv(const string& name, const string& value) {
-        // Backup the original environment
-        char* env(getenv(name.c_str()));
-        restoreEnviron.push_back(Environ(name, env == NULL ? NULL :
-                                         new string(env)));
-        // Set the new value
-        if (value.empty()) {
-            EXPECT_EQ(0, unsetenv(name.c_str()));
-        } else {
-            EXPECT_EQ(0, setenv(name.c_str(), value.c_str(), 1));
-        }
-    }
-    // Test getter functions for a socket file path under given environment
-    void testSocketPath(const string& fromBuild, const string& localStateDir,
-                        const string& socketFile, const string& env_name,
-                        const string& expected, string (*actual_fn)())
-    {
-        setEnv("B10_FROM_BUILD", fromBuild);
-        setEnv("B10_FROM_SOURCE_LOCALSTATEDIR", localStateDir);
-        setEnv(env_name, socketFile);
-        EXPECT_EQ(expected, actual_fn());
-    }
-};
-
-// Test that when we have no special environment, we get the default from prefix
-TEST_F(Paths, xfroutNoEnv) {
-    testSocketPath("", "", "", "BIND10_XFROUT_SOCKET_FILE",
-                   UNIX_XFROUT_SOCKET_FILE, getXfroutSocketPath);
-}
-
-TEST_F(Paths, ddnsNoEnv) {
-    testSocketPath("", "", "", "BIND10_DDNS_SOCKET_FILE",
-                   UNIX_DDNS_SOCKET_FILE, getDDNSSocketPath);
-}
-
-// Override by B10_FROM_BUILD
-TEST_F(Paths, xfroutFromBuild) {
-    testSocketPath("/from/build", "", "/wrong/path",
-                   "BIND10_XFROUT_SOCKET_FILE", "/from/build/auth_xfrout_conn",
-                   getXfroutSocketPath);
-}
-
-TEST_F(Paths, ddnsFromBuild) {
-    testSocketPath("/from/build", "", "/wrong/path", "BIND10_DDNS_SOCKET_FILE",
-                   "/from/build/ddns_socket", getDDNSSocketPath);
-}
-
-// Override by B10_FROM_SOURCE_LOCALSTATEDIR
-TEST_F(Paths, xfroutLocalStatedir) {
-    testSocketPath("/wrong/path", "/state/dir", "/wrong/path",
-                   "BIND10_XFROUT_SOCKET_FILE", "/state/dir/auth_xfrout_conn",
-                   getXfroutSocketPath);
-}
-
-TEST_F(Paths, ddnsLocalStatedir) {
-    testSocketPath("/wrong/path", "/state/dir", "/wrong/path",
-                   "BIND10_DDNS_SOCKET_FILE", "/state/dir/ddns_socket",
-                   getDDNSSocketPath);
-}
-
-// Override by BIND10_xxx_SOCKET_FILE explicitly
-TEST_F(Paths, xfroutFromEnv) {
-    testSocketPath("", "", "/the/path/to/file", "BIND10_XFROUT_SOCKET_FILE",
-                   "/the/path/to/file", getXfroutSocketPath);
-}
-
-TEST_F(Paths, ddnsFromEnv) {
-    testSocketPath("", "", "/the/path/to/file", "BIND10_DDNS_SOCKET_FILE",
-                   "/the/path/to/file", getDDNSSocketPath);
-}
-
-}

+ 0 - 89
src/bin/auth/tests/config_syntax_unittest.cc

@@ -1,89 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <cc/data.h>
-#include <config/module_spec.h>
-
-#include <gtest/gtest.h>
-
-using namespace isc::data;
-using namespace isc::config;
-
-namespace {
-
-const char* const SPEC_FILE = AUTH_OBJ_DIR "/auth.spec";
-
-class AuthConfigSyntaxTest : public ::testing::Test {
-protected:
-    AuthConfigSyntaxTest() : mspec_(moduleSpecFromFile(SPEC_FILE))
-    {}
-    ModuleSpec mspec_;
-};
-
-TEST_F(AuthConfigSyntaxTest, inmemoryDefaultFileType) {
-    // filetype is optional
-    EXPECT_TRUE(
-        mspec_.validateConfig(
-            Element::fromJSON(
-                "{\"tcp_recv_timeout\": 1000,"
-                " \"listen_on\": [], \"datasources\": "
-                "  [{\"type\": \"memory\", \"class\": \"IN\", "
-                "    \"zones\": [{\"origin\": \"example.com\","
-                "                 \"file\": \""
-                TEST_DATA_DIR "/example.zone\"}]}]}"), true));
-}
-
-TEST_F(AuthConfigSyntaxTest, inmemorySQLite3Backend) {
-    // Specifying non-default in-memory filetype
-    EXPECT_TRUE(
-        mspec_.validateConfig(
-            Element::fromJSON(
-                "{\"tcp_recv_timeout\": 1000,"
-                " \"datasources\": "
-                "  [{\"type\": \"memory\","
-                "    \"zones\": [{\"origin\": \"example.com\","
-                "                 \"file\": \""
-                TEST_DATA_DIR "/example.zone\","
-                "                 \"filetype\": \"sqlite3\"}]}]}"), false));
-}
-
-TEST_F(AuthConfigSyntaxTest, badInmemoryFileType) {
-    // filetype must be a string
-    ASSERT_FALSE(
-        mspec_.validateConfig(
-            Element::fromJSON(
-                "{\"tcp_recv_timeout\": 1000,"
-                " \"datasources\": "
-                "  [{\"type\": \"memory\","
-                "    \"zones\": [{\"origin\": \"example.com\","
-                "                 \"file\": \""
-                TEST_DATA_DIR "/example.zone\","
-                "                 \"filetype\": 42}]}]}"), false));
-}
-
-TEST_F(AuthConfigSyntaxTest, badTCPRecvTimeout) {
-    // tcp_recv_timeout must be int
-    EXPECT_FALSE(
-        mspec_.validateConfig(
-            Element::fromJSON(
-                "{\"tcp_recv_timeout\": \"foo\","
-                " \"datasources\": "
-                "  [{\"type\": \"memory\","
-                "    \"zones\": [{\"origin\": \"example.com\","
-                "                 \"file\": \""
-                TEST_DATA_DIR "/example.zone\","
-                "                 \"filetype\": \"sqlite3\"}]}]}"), false));
-}
-
-}

+ 0 - 158
src/bin/auth/tests/config_unittest.cc

@@ -1,158 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <gtest/gtest.h>
-
-#include <exceptions/exceptions.h>
-
-#include <dns/rrclass.h>
-#include <dns/masterload.h>
-
-#include <cc/data.h>
-
-#include <datasrc/exceptions.h>
-
-#include <xfr/xfrout_client.h>
-
-#include <auth/auth_srv.h>
-#include <auth/auth_config.h>
-#include <auth/common.h>
-
-#include "datasrc_util.h"
-
-#include <util/unittests/mock_socketsession.h>
-#include <testutils/mockups.h>
-#include <testutils/portconfig.h>
-#include <testutils/socket_request.h>
-
-#include <sstream>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::datasrc;
-using namespace isc::asiodns;
-using namespace isc::auth::unittest;
-using namespace isc::util::unittests;
-using namespace isc::testutils;
-
-namespace {
-class AuthConfigTest : public ::testing::Test {
-protected:
-    AuthConfigTest() :
-        dnss_(),
-        rrclass(RRClass::IN()),
-        server(xfrout, ddns_forwarder),
-        // The empty string is expected value of the parameter of
-        // requestSocket, not the app_name (there's no fallback, it checks
-        // the empty string is passed).
-        sock_requestor_(dnss_, address_store_, 53210, "")
-    {
-        server.setDNSService(dnss_);
-    }
-    MockDNSService dnss_;
-    const RRClass rrclass;
-    MockXfroutClient xfrout;
-    MockSocketSessionForwarder ddns_forwarder;
-    AuthSrv server;
-    isc::server_common::portconfig::AddressList address_store_;
-private:
-    isc::testutils::TestSocketRequestor sock_requestor_;
-};
-
-TEST_F(AuthConfigTest, versionConfig) {
-    // make sure it does not throw on 'version'
-    EXPECT_NO_THROW(configureAuthServer(
-                        server,
-                        Element::fromJSON("{\"version\": 0}")));
-}
-
-TEST_F(AuthConfigTest, exceptionGuarantee) {
-    using namespace isc::server_common::portconfig;
-    AddressList a;
-    a.push_back(AddressPair("127.0.0.1", 53210));
-    server.setListenAddresses(a);
-    const AddressList b = server.getListenAddresses();
-    EXPECT_EQ(a.size(), b.size());
-    EXPECT_EQ(a.at(0).first, b.at(0).first);
-    EXPECT_EQ(a.at(0).second, b.at(0).second);
-    // The test socket request will reject the second address (192.0.2.2)
-    // with an exception
-    EXPECT_THROW(configureAuthServer(
-                     server,
-                     Element::fromJSON(
-                         "{ \"listen_on\": ["
-                           "{\"address\": \"::1\", \"port\": 53210},"
-                           "{\"address\": \"192.0.2.2\", \"port\": 53210}"
-                         "]}")),
-                 AuthConfigError);
-    // The server state shouldn't change
-    const AddressList c = server.getListenAddresses();
-    EXPECT_EQ(a.size(), c.size());
-    EXPECT_EQ(a.at(0).first, c.at(0).first);
-    EXPECT_EQ(a.at(0).second, c.at(0).second);
-}
-
-TEST_F(AuthConfigTest, badConfig) {
-    // These should normally not happen, but should be handled to avoid
-    // an unexpected crash due to a bug of the caller.
-    EXPECT_THROW(configureAuthServer(server, ElementPtr()), AuthConfigError);
-    EXPECT_THROW(configureAuthServer(server, Element::fromJSON("[]")),
-                                     AuthConfigError);
-}
-
-TEST_F(AuthConfigTest, unknownConfigVar) {
-    EXPECT_THROW(createAuthConfigParser(server, "no_such_config_var"),
-                 AuthConfigError);
-}
-
-TEST_F(AuthConfigTest, exceptionFromCommit) {
-    EXPECT_THROW(configureAuthServer(server, Element::fromJSON(
-                                         "{\"_commit_throw\": 10}")),
-                 FatalError);
-}
-
-// Test invalid address configs are rejected
-TEST_F(AuthConfigTest, invalidListenAddressConfig) {
-    // This currently passes simply because the config doesn't know listen_on
-    isc::testutils::portconfig::invalidListenAddressConfig(server);
-}
-
-// Try setting addresses through config
-TEST_F(AuthConfigTest, listenAddressConfig) {
-    isc::testutils::portconfig::listenAddressConfig(server);
-
-    // listenAddressConfig should have attempted to create 4 DNS server
-    // objects: two IP addresses, TCP and UDP for each.  For UDP, the "SYNC_OK"
-    // option should have been specified.
-    EXPECT_EQ(2, dnss_.getTCPFdParams().size());
-    EXPECT_EQ(2, dnss_.getUDPFdParams().size());
-    EXPECT_EQ(DNSService::SERVER_SYNC_OK, dnss_.getUDPFdParams().at(0).options);
-    EXPECT_EQ(DNSService::SERVER_SYNC_OK, dnss_.getUDPFdParams().at(1).options);
-}
-
-// Try setting tcp receive timeout through config
-TEST_F(AuthConfigTest, tcpRecvTimeoutConfig) {
-    configureAuthServer(server, Element::fromJSON(
-    "{ \"tcp_recv_timeout\": 123 }"));
-    EXPECT_EQ(123, dnss_.getTCPRecvTimeout());
-    configureAuthServer(server, Element::fromJSON(
-    "{ \"tcp_recv_timeout\": 2000 }"));
-    EXPECT_EQ(2000, dnss_.getTCPRecvTimeout());
-    EXPECT_THROW(configureAuthServer(server, Element::fromJSON(
-                    "{ \"tcp_recv_timeout\": -123 }")),
-                 AuthConfigError);
-}
-
-}

+ 0 - 759
src/bin/auth/tests/datasrc_clients_builder_unittest.cc

@@ -1,759 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include <util/unittests/check_valgrind.h>
-
-#include <dns/name.h>
-#include <dns/rrclass.h>
-
-#include <cc/data.h>
-
-#include <datasrc/client.h>
-#include <datasrc/factory.h>
-
-#include <auth/datasrc_clients_mgr.h>
-#include <auth/datasrc_config.h>
-
-#include <testutils/dnsmessage_test.h>
-
-#include "test_datasrc_clients_mgr.h"
-#include "datasrc_util.h"
-
-#include <gtest/gtest.h>
-
-#include <boost/function.hpp>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-
-#include <cstdlib>
-#include <string>
-#include <sstream>
-#include <cerrno>
-#include <unistd.h>
-
-using isc::data::ConstElementPtr;
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::datasrc;
-using namespace isc::auth::datasrc_clientmgr_internal;
-using namespace isc::auth::unittest;
-using namespace isc::testutils;
-
-namespace {
-class DataSrcClientsBuilderTest : public ::testing::Test {
-protected:
-    DataSrcClientsBuilderTest() :
-        clients_map(new std::map<RRClass,
-                    boost::shared_ptr<ConfigurableClientList> >),
-        write_end(-1), read_end(-1),
-        builder(&command_queue, &callback_queue, &cond, &queue_mutex,
-                &clients_map, &map_mutex, generateSockets()),
-        cond(command_queue, delayed_command_queue), rrclass(RRClass::IN()),
-        shutdown_cmd(SHUTDOWN, ConstElementPtr(), FinishedCallback()),
-        noop_cmd(NOOP, ConstElementPtr(), FinishedCallback())
-    {}
-    ~ DataSrcClientsBuilderTest() {
-
-    }
-
-    void TearDown() {
-        // Some tests create this file. Delete it if it exists.
-        unlink(TEST_DATA_BUILDDIR "/test1.zone.image");
-    }
-
-    void configureZones();      // used for loadzone related tests
-
-    ClientListMapPtr clients_map; // configured clients
-    std::list<Command> command_queue; // test command queue
-    std::list<Command> delayed_command_queue; // commands available after wait
-    std::list<FinishedCallback> callback_queue; // Callbacks from commands
-    int write_end, read_end;
-    TestDataSrcClientsBuilder builder;
-    TestCondVar cond;
-    TestMutex queue_mutex;
-    TestMutex map_mutex;
-    const RRClass rrclass;
-    const Command shutdown_cmd;
-    const Command noop_cmd;
-private:
-    int generateSockets() {
-        int pair[2];
-        int result = socketpair(AF_UNIX, SOCK_STREAM, 0, pair);
-        assert(result == 0);
-        write_end = pair[0];
-        read_end = pair[1];
-        return write_end;
-    }
-};
-
-TEST_F(DataSrcClientsBuilderTest, runSingleCommand) {
-    // A simplest case, just to check the basic behavior.
-    command_queue.push_back(shutdown_cmd);
-    builder.run();
-    EXPECT_TRUE(command_queue.empty());
-    EXPECT_EQ(0, cond.wait_count); // no wait because command queue is not empty
-    EXPECT_EQ(1, queue_mutex.lock_count);
-    EXPECT_EQ(1, queue_mutex.unlock_count);
-    // No callback scheduled, none called.
-    EXPECT_TRUE(callback_queue.empty());
-    // Not woken up.
-    char c;
-    int result = recv(read_end, &c, 1, MSG_DONTWAIT);
-    EXPECT_EQ(-1, result);
-    EXPECT_TRUE(errno == EAGAIN || errno == EWOULDBLOCK);
-}
-
-// Just to have a valid function callback to pass
-void emptyCallsback() {}
-
-// Check a command finished callback is passed
-TEST_F(DataSrcClientsBuilderTest, commandFinished) {
-    command_queue.push_back(Command(SHUTDOWN, ConstElementPtr(),
-                                    emptyCallsback));
-    builder.run();
-    EXPECT_EQ(0, cond.wait_count); // no wait because command queue is not empty
-    // Once for picking up data, once for putting the callback there
-    EXPECT_EQ(2, queue_mutex.lock_count);
-    EXPECT_EQ(2, queue_mutex.unlock_count);
-    // There's one callback in the queue
-    ASSERT_EQ(1, callback_queue.size());
-    // Not using EXPECT_EQ, as that produces warning in printing out the result
-    EXPECT_TRUE(emptyCallsback == callback_queue.front());
-    // And we are woken up.
-    char c;
-    int result = recv(read_end, &c, 1, MSG_DONTWAIT);
-    EXPECT_EQ(1, result);
-}
-
-// Test that low-level errors with the synchronization socket
-// (an unexpected condition) is detected and program aborted.
-TEST_F(DataSrcClientsBuilderTest, finishedCrash) {
-    command_queue.push_back(Command(SHUTDOWN, ConstElementPtr(),
-                                    emptyCallsback));
-    // Break the socket
-    close(write_end);
-    EXPECT_DEATH_IF_SUPPORTED({builder.run();}, "");
-}
-
-TEST_F(DataSrcClientsBuilderTest, runMultiCommands) {
-    // Two NOOP commands followed by SHUTDOWN.  We should see two doNoop()
-    // calls.
-    command_queue.push_back(noop_cmd);
-    command_queue.push_back(noop_cmd);
-    command_queue.push_back(shutdown_cmd);
-    builder.run();
-    EXPECT_TRUE(command_queue.empty());
-    EXPECT_EQ(1, queue_mutex.lock_count);
-    EXPECT_EQ(1, queue_mutex.unlock_count);
-    EXPECT_EQ(2, queue_mutex.noop_count);
-}
-
-TEST_F(DataSrcClientsBuilderTest, exception) {
-    // Let the noop command handler throw exceptions and see if we can see
-    // them.  Right now, we simply abort to prevent the system from running
-    // with half-broken state.  Eventually we should introduce a better
-    // error handling.
-    if (!isc::util::unittests::runningOnValgrind()) {
-        command_queue.push_back(noop_cmd);
-        queue_mutex.throw_from_noop = TestMutex::EXCLASS;
-        EXPECT_DEATH_IF_SUPPORTED({builder.run();}, "");
-
-        command_queue.push_back(noop_cmd);
-        queue_mutex.throw_from_noop = TestMutex::INTEGER;
-        EXPECT_DEATH_IF_SUPPORTED({builder.run();}, "");
-    }
-
-    command_queue.push_back(noop_cmd);
-    command_queue.push_back(shutdown_cmd); // we need to stop the loop
-    queue_mutex.throw_from_noop = TestMutex::INTERNAL;
-    builder.run();
-}
-
-TEST_F(DataSrcClientsBuilderTest, condWait) {
-    // command_queue is originally empty, so it will require waiting on
-    // condvar.  specialized wait() will make the delayed command available.
-    delayed_command_queue.push_back(shutdown_cmd);
-    builder.run();
-
-    // There should be one call to wait()
-    EXPECT_EQ(1, cond.wait_count);
-    // wait() effectively involves one more set of lock/unlock, so we have
-    // two in total
-    EXPECT_EQ(2, queue_mutex.lock_count);
-    EXPECT_EQ(2, queue_mutex.unlock_count);
-}
-
-TEST_F(DataSrcClientsBuilderTest, reconfigure) {
-    // Full testing of different configurations is not here, but we
-    // do check a few cases of correct and erroneous input, to verify
-    // the error handling
-
-    // A command structure we'll modify to send different commands
-    Command reconfig_cmd(RECONFIGURE, ConstElementPtr(), FinishedCallback());
-
-    // Initially, no clients should be there
-    EXPECT_TRUE(clients_map->empty());
-
-    // A config that doesn't do much except be accepted
-    ConstElementPtr good_config = Element::fromJSON(
-        "{"
-        "\"IN\": [{"
-        "   \"type\": \"MasterFiles\","
-        "   \"params\": {},"
-        "   \"cache-enable\": true"
-        "}]"
-        "}"
-    );
-
-    // A configuration that is 'correct' in the top-level, but contains
-    // bad data for the type it specifies
-    ConstElementPtr bad_config = Element::fromJSON(
-        "{"
-        "\"IN\": [{"
-        "   \"type\": \"MasterFiles\","
-        "   \"params\": { \"foo\": [ 1, 2, 3, 4  ]},"
-        "   \"cache-enable\": true"
-        "}]"
-        "}"
-    );
-
-    reconfig_cmd.params = good_config;
-    EXPECT_TRUE(builder.handleCommand(reconfig_cmd));
-    EXPECT_EQ(1, clients_map->size());
-    EXPECT_EQ(1, map_mutex.lock_count);
-
-    // Store the nonempty clients map we now have
-    ClientListMapPtr working_config_clients(clients_map);
-
-    // If a 'bad' command argument got here, the config validation should
-    // have failed already, but still, the handler should return true,
-    // and the clients_map should not be updated.
-    reconfig_cmd.params = Element::create("{ \"foo\": \"bar\" }");
-    EXPECT_TRUE(builder.handleCommand(reconfig_cmd));
-    EXPECT_EQ(working_config_clients, clients_map);
-    // Building failed, so map mutex should not have been locked again
-    EXPECT_EQ(1, map_mutex.lock_count);
-
-    // The same for a configuration that has bad data for the type it
-    // specifies
-    reconfig_cmd.params = bad_config;
-    builder.handleCommand(reconfig_cmd);
-    EXPECT_TRUE(builder.handleCommand(reconfig_cmd));
-    EXPECT_EQ(working_config_clients, clients_map);
-    // Building failed, so map mutex should not have been locked again
-    EXPECT_EQ(1, map_mutex.lock_count);
-
-    // The same goes for an empty parameter (it should at least be
-    // an empty map)
-    reconfig_cmd.params = ConstElementPtr();
-    EXPECT_TRUE(builder.handleCommand(reconfig_cmd));
-    EXPECT_EQ(working_config_clients, clients_map);
-    EXPECT_EQ(1, map_mutex.lock_count);
-
-    // Reconfigure again with the same good clients, the result should
-    // be a different map than the original, but not an empty one.
-    reconfig_cmd.params = good_config;
-    EXPECT_TRUE(builder.handleCommand(reconfig_cmd));
-    EXPECT_NE(working_config_clients, clients_map);
-    EXPECT_EQ(1, clients_map->size());
-    EXPECT_EQ(2, map_mutex.lock_count);
-
-    // And finally, try an empty config to disable all datasource clients
-    reconfig_cmd.params = Element::createMap();
-    EXPECT_TRUE(builder.handleCommand(reconfig_cmd));
-    EXPECT_EQ(0, clients_map->size());
-    EXPECT_EQ(3, map_mutex.lock_count);
-
-    // Also check if it has been cleanly unlocked every time
-    EXPECT_EQ(3, map_mutex.unlock_count);
-}
-
-TEST_F(DataSrcClientsBuilderTest, shutdown) {
-    EXPECT_FALSE(builder.handleCommand(shutdown_cmd));
-}
-
-TEST_F(DataSrcClientsBuilderTest, badCommand) {
-    // out-of-range command ID
-    EXPECT_THROW(builder.handleCommand(Command(NUM_COMMANDS,
-                                               ConstElementPtr(),
-                                               FinishedCallback())),
-                 isc::Unexpected);
-}
-
-// A helper function commonly used for the "loadzone" command tests.
-// It configures the given data source client lists with a memory data source
-// containing two zones, and checks the zones are correctly loaded.
-void
-zoneChecks(ClientListMapPtr clients_map, RRClass rrclass) {
-    EXPECT_EQ(ZoneFinder::SUCCESS, clients_map->find(rrclass)->second->
-              find(Name("ns.test1.example")).finder_->
-              find(Name("ns.test1.example"), RRType::A())->code);
-    EXPECT_EQ(ZoneFinder::NXRRSET, clients_map->find(rrclass)->second->
-              find(Name("ns.test1.example")).finder_->
-              find(Name("ns.test1.example"), RRType::AAAA())->code);
-    EXPECT_EQ(ZoneFinder::SUCCESS, clients_map->find(rrclass)->second->
-              find(Name("ns.test2.example")).finder_->
-              find(Name("ns.test2.example"), RRType::A())->code);
-    EXPECT_EQ(ZoneFinder::NXRRSET, clients_map->find(rrclass)->second->
-              find(Name("ns.test2.example")).finder_->
-              find(Name("ns.test2.example"), RRType::AAAA())->code);
-}
-
-// Another helper that checks after completing loadzone command.
-void
-newZoneChecks(ClientListMapPtr clients_map, RRClass rrclass) {
-    EXPECT_EQ(ZoneFinder::SUCCESS, clients_map->find(rrclass)->second->
-              find(Name("ns.test1.example")).finder_->
-              find(Name("ns.test1.example"), RRType::A())->code);
-    // now test1.example should have ns/AAAA
-    EXPECT_EQ(ZoneFinder::SUCCESS, clients_map->find(rrclass)->second->
-              find(Name("ns.test1.example")).finder_->
-              find(Name("ns.test1.example"), RRType::AAAA())->code);
-
-    // test2.example shouldn't change
-    EXPECT_EQ(ZoneFinder::SUCCESS, clients_map->find(rrclass)->second->
-              find(Name("ns.test2.example")).finder_->
-              find(Name("ns.test2.example"), RRType::A())->code);
-    EXPECT_EQ(ZoneFinder::NXRRSET,
-              clients_map->find(rrclass)->second->
-              find(Name("ns.test2.example")).finder_->
-              find(Name("ns.test2.example"), RRType::AAAA())->code);
-}
-
-void
-DataSrcClientsBuilderTest::configureZones() {
-    ASSERT_EQ(0, std::system(INSTALL_PROG " -c " TEST_DATA_DIR "/test1.zone.in "
-                             TEST_DATA_BUILDDIR "/test1.zone.copied"));
-    ASSERT_EQ(0, std::system(INSTALL_PROG " -c " TEST_DATA_DIR "/test2.zone.in "
-                             TEST_DATA_BUILDDIR "/test2.zone.copied"));
-
-    const ConstElementPtr config(
-        Element::fromJSON(
-            "{"
-            "\"IN\": [{"
-            "   \"type\": \"MasterFiles\","
-            "   \"params\": {"
-            "       \"test1.example\": \"" +
-            std::string(TEST_DATA_BUILDDIR "/test1.zone.copied") + "\","
-            "       \"test2.example\": \"" +
-            std::string(TEST_DATA_BUILDDIR "/test2.zone.copied") + "\""
-            "   },"
-            "   \"cache-enable\": true"
-            "}]}"));
-    clients_map = configureDataSource(config);
-    zoneChecks(clients_map, rrclass);
-}
-
-TEST_F(DataSrcClientsBuilderTest, loadZone) {
-    // pre test condition checks
-    EXPECT_EQ(0, map_mutex.lock_count);
-    EXPECT_EQ(0, map_mutex.unlock_count);
-
-    configureZones();
-
-    EXPECT_EQ(0, system(INSTALL_PROG " -c " TEST_DATA_DIR
-                        "/test1-new.zone.in "
-                        TEST_DATA_BUILDDIR "/test1.zone.copied"));
-    EXPECT_EQ(0, system(INSTALL_PROG " -c " TEST_DATA_DIR
-                        "/test2-new.zone.in "
-                        TEST_DATA_BUILDDIR "/test2.zone.copied"));
-
-    const Command loadzone_cmd(LOADZONE, Element::fromJSON(
-                                   "{\"class\": \"IN\","
-                                   " \"origin\": \"test1.example\"}"),
-                               FinishedCallback());
-    EXPECT_TRUE(builder.handleCommand(loadzone_cmd));
-
-    // loadZone involves two critical sections: one for getting the zone
-    // writer, and one for actually updating the zone data.  So the lock/unlock
-    // count should be incremented by 2.
-    EXPECT_EQ(2, map_mutex.lock_count);
-    EXPECT_EQ(2, map_mutex.unlock_count);
-
-    newZoneChecks(clients_map, rrclass);
-}
-
-TEST_F(DataSrcClientsBuilderTest,
-#ifdef USE_STATIC_LINK
-       DISABLED_loadZoneSQLite3
-#else
-       loadZoneSQLite3
-#endif
-    )
-{
-    // Prepare the database first
-    const std::string test_db = TEST_DATA_BUILDDIR "/auth_test.sqlite3.copied";
-    std::stringstream ss("example.org. 3600 IN SOA . . 0 0 0 0 0\n"
-                         "example.org. 3600 IN NS ns1.example.org.\n");
-    createSQLite3DB(rrclass, Name("example.org"), test_db.c_str(), ss);
-    // This describes the data source in the configuration
-    const ConstElementPtr config(Element::fromJSON("{"
-        "\"IN\": [{"
-        "    \"type\": \"sqlite3\","
-        "    \"params\": {\"database_file\": \"" + test_db + "\"},"
-        "    \"cache-enable\": true,"
-        "    \"cache-zones\": [\"example.org\"]"
-        "}]}"));
-    clients_map = configureDataSource(config);
-
-    // Check that the A record at www.example.org does not exist
-    EXPECT_EQ(ZoneFinder::NXDOMAIN,
-              clients_map->find(rrclass)->second->
-              find(Name("example.org")).finder_->
-              find(Name("www.example.org"), RRType::A())->code);
-
-    // Add the record to the underlying sqlite database, by loading
-    // it as a separate datasource, and updating it
-    ConstElementPtr sql_cfg = Element::fromJSON("{ \"type\": \"sqlite3\","
-                                                "\"database_file\": \""
-                                                + test_db + "\"}");
-    DataSourceClientContainer sql_ds("sqlite3", sql_cfg);
-    ZoneUpdaterPtr sql_updater =
-        sql_ds.getInstance().getUpdater(Name("example.org"), false);
-    sql_updater->addRRset(
-        *textToRRset("www.example.org. 60 IN A 192.0.2.1"));
-    sql_updater->commit();
-
-    EXPECT_EQ(ZoneFinder::NXDOMAIN,
-              clients_map->find(rrclass)->second->
-              find(Name("example.org")).finder_->
-              find(Name("www.example.org"), RRType::A())->code);
-
-    // Now send the command to reload it
-    const Command loadzone_cmd(LOADZONE, Element::fromJSON(
-                                   "{\"class\": \"IN\","
-                                   " \"origin\": \"example.org\"}"),
-                               FinishedCallback());
-    EXPECT_TRUE(builder.handleCommand(loadzone_cmd));
-    // And now it should be present too.
-    EXPECT_EQ(ZoneFinder::SUCCESS,
-              clients_map->find(rrclass)->second->
-              find(Name("example.org")).finder_->
-              find(Name("www.example.org"), RRType::A())->code);
-
-    // An error case: the zone has no configuration. (note .com here)
-    const Command nozone_cmd(LOADZONE, Element::fromJSON(
-                                 "{\"class\": \"IN\","
-                                 " \"origin\": \"example.com\"}"),
-                             FinishedCallback());
-    EXPECT_THROW(builder.handleCommand(nozone_cmd),
-                 TestDataSrcClientsBuilder::InternalCommandError);
-    // The previous zone is not hurt in any way
-    EXPECT_EQ(ZoneFinder::SUCCESS, clients_map->find(rrclass)->second->
-              find(Name("example.org")).finder_->
-              find(Name("example.org"), RRType::SOA())->code);
-
-    // attempt of reloading a zone but in-memory cache is disabled.  In this
-    // case the command is simply ignored.
-    const size_t orig_lock_count = map_mutex.lock_count;
-    const size_t orig_unlock_count = map_mutex.unlock_count;
-    const ConstElementPtr config2(Element::fromJSON("{"
-        "\"IN\": [{"
-        "    \"type\": \"sqlite3\","
-        "    \"params\": {\"database_file\": \"" + test_db + "\"},"
-        "    \"cache-enable\": false,"
-        "    \"cache-zones\": [\"example.org\"]"
-        "}]}"));
-    clients_map = configureDataSource(config2);
-    builder.handleCommand(
-                     Command(LOADZONE, Element::fromJSON(
-                                 "{\"class\": \"IN\","
-                                 " \"origin\": \"example.org\"}"),
-                             FinishedCallback()));
-    // Only one mutex was needed because there was no actual reload.
-    EXPECT_EQ(orig_lock_count + 1, map_mutex.lock_count);
-    EXPECT_EQ(orig_unlock_count + 1, map_mutex.unlock_count);
-
-    // zone doesn't exist in the data source
-    const ConstElementPtr config_nozone(Element::fromJSON("{"
-        "\"IN\": [{"
-        "    \"type\": \"sqlite3\","
-        "    \"params\": {\"database_file\": \"" + test_db + "\"},"
-        "    \"cache-enable\": true,"
-        "    \"cache-zones\": [\"nosuchzone.example\"]"
-        "}]}"));
-    clients_map = configureDataSource(config_nozone);
-    EXPECT_THROW(
-        builder.handleCommand(
-            Command(LOADZONE, Element::fromJSON(
-                        "{\"class\": \"IN\","
-                        " \"origin\": \"nosuchzone.example\"}"),
-                    FinishedCallback())),
-        TestDataSrcClientsBuilder::InternalCommandError);
-
-    // basically impossible case: in-memory cache is completely disabled.
-    // In this implementation of manager-builder, this should never happen,
-    // but it catches it like other configuration error and keeps going.
-    clients_map->clear();
-    boost::shared_ptr<ConfigurableClientList> nocache_list(
-        new ConfigurableClientList(rrclass));
-    nocache_list->configure(
-        Element::fromJSON(
-            "[{\"type\": \"sqlite3\","
-            "  \"params\": {\"database_file\": \"" + test_db + "\"},"
-            "  \"cache-enable\": true,"
-            "  \"cache-zones\": [\"example.org\"]"
-            "}]"), false);           // false = disable cache
-    (*clients_map)[rrclass] = nocache_list;
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE, Element::fromJSON(
-                                 "{\"class\": \"IN\","
-                                 " \"origin\": \"example.org\"}"),
-                             FinishedCallback())),
-                 TestDataSrcClientsBuilder::InternalCommandError);
-}
-
-TEST_F(DataSrcClientsBuilderTest, loadBrokenZone) {
-    configureZones();
-
-    ASSERT_EQ(0, std::system(INSTALL_PROG " -c " TEST_DATA_DIR
-                             "/test1-broken.zone.in "
-                             TEST_DATA_BUILDDIR "/test1.zone.copied"));
-    // there's an error in the new zone file.  reload will be rejected.
-    const Command loadzone_cmd(LOADZONE, Element::fromJSON(
-                                   "{\"class\": \"IN\","
-                                   " \"origin\": \"test1.example\"}"),
-                               FinishedCallback());
-    EXPECT_THROW(builder.handleCommand(loadzone_cmd),
-                 TestDataSrcClientsBuilder::InternalCommandError);
-    zoneChecks(clients_map, rrclass);     // zone shouldn't be replaced
-}
-
-TEST_F(DataSrcClientsBuilderTest, loadUnreadableZone) {
-    // If the test is run as the root user, it will fail as insufficient
-    // permissions will not stop the root user from using a file.
-    if (getuid() == 0) {
-        std::cerr << "Skipping test as it's run as the root user" << std::endl;
-        return;
-    }
-
-    configureZones();
-
-    // install the zone file as unreadable
-    ASSERT_EQ(0, std::system(INSTALL_PROG " -c -m 000 " TEST_DATA_DIR
-                             "/test1.zone.in "
-                             TEST_DATA_BUILDDIR "/test1.zone.copied"));
-    const Command loadzone_cmd(LOADZONE, Element::fromJSON(
-                                   "{\"class\": \"IN\","
-                                   " \"origin\": \"test1.example\"}"),
-                               FinishedCallback());
-    EXPECT_THROW(builder.handleCommand(loadzone_cmd),
-                 TestDataSrcClientsBuilder::InternalCommandError);
-    zoneChecks(clients_map, rrclass);     // zone shouldn't be replaced
-}
-
-TEST_F(DataSrcClientsBuilderTest, loadZoneWithoutDataSrc) {
-    // try to execute load command without configuring the zone beforehand.
-    // it should fail.
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE,
-                             Element::fromJSON(
-                                 "{\"class\": \"IN\", "
-                                 " \"origin\": \"test1.example\"}"),
-                             FinishedCallback())),
-                 TestDataSrcClientsBuilder::InternalCommandError);
-}
-
-TEST_F(DataSrcClientsBuilderTest, loadZoneInvalidParams) {
-    configureZones();
-
-    if (!isc::util::unittests::runningOnValgrind()) {
-        // null arg: this causes assertion failure
-        EXPECT_DEATH_IF_SUPPORTED({
-                builder.handleCommand(Command(LOADZONE, ElementPtr(),
-                                              FinishedCallback()));
-            }, "");
-    }
-
-    // zone class is bogus (note that this shouldn't happen except in tests)
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE,
-                             Element::fromJSON(
-                                 "{\"origin\": \"test1.example\","
-                                 " \"class\": \"no_such_class\"}"),
-                             FinishedCallback())),
-                 InvalidRRClass);
-
-    // not a string
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE,
-                             Element::fromJSON(
-                                 "{\"origin\": \"test1.example\","
-                                 " \"class\": 1}"),
-                             FinishedCallback())),
-                 isc::data::TypeError);
-
-    // class or origin is missing: result in assertion failure
-    if (!isc::util::unittests::runningOnValgrind()) {
-        EXPECT_DEATH_IF_SUPPORTED({
-                builder.handleCommand(Command(LOADZONE,
-                                              Element::fromJSON(
-                                                  "{\"class\": \"IN\"}"),
-                                              FinishedCallback()));
-            }, "");
-    }
-
-    // origin is bogus
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE,
-                             Element::fromJSON(
-                                 "{\"class\": \"IN\", \"origin\": \"...\"}"),
-                             FinishedCallback())),
-                 EmptyLabel);
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE,
-                             Element::fromJSON(
-                                 "{\"origin\": 10, \"class\": 1}"),
-                             FinishedCallback())),
-                 isc::data::TypeError);
-}
-
-// This works only if mapped memory segment is compiled.
-// Note also that this test case may fail as we make b10-auth more aware
-// of shared-memory cache.
-TEST_F(DataSrcClientsBuilderTest,
-#ifdef USE_SHARED_MEMORY
-       loadInNonWritableCache
-#else
-       DISABLED_loadInNonWritableCache
-#endif
-    )
-{
-    const ConstElementPtr config = Element::fromJSON(
-        "{"
-        "\"IN\": [{"
-        "   \"type\": \"MasterFiles\","
-        "   \"params\": {"
-        "       \"test1.example\": \"" +
-        std::string(TEST_DATA_BUILDDIR "/test1.zone.copied") + "\"},"
-        "   \"cache-enable\": true,"
-        "   \"cache-type\": \"mapped\""
-        "}]}");
-    clients_map = configureDataSource(config);
-
-    EXPECT_THROW(builder.handleCommand(
-                     Command(LOADZONE,
-                             Element::fromJSON(
-                                 "{\"origin\": \"test1.example\","
-                                 " \"class\": \"IN\"}"),
-                             FinishedCallback())),
-                 TestDataSrcClientsBuilder::InternalCommandError);
-}
-
-// Test the SEGMENT_INFO_UPDATE command. This test is little bit
-// indirect. It doesn't seem possible to fake the client list inside
-// easily. So we create a real image to load and load it. Then we check
-// the segment is used.
-TEST_F(DataSrcClientsBuilderTest,
-#ifdef USE_SHARED_MEMORY
-       segmentInfoUpdate
-#else
-       DISABLED_segmentInfoUpdate
-#endif
-      )
-{
-    // First, prepare the file image to be mapped
-    const ConstElementPtr config = Element::fromJSON(
-        "{"
-        "\"IN\": [{"
-        "   \"type\": \"MasterFiles\","
-        "   \"params\": {"
-        "       \"test1.example\": \""
-        TEST_DATA_BUILDDIR "/test1.zone.copied\"},"
-        "   \"cache-enable\": true,"
-        "   \"cache-type\": \"mapped\""
-        "}]}");
-    const ConstElementPtr segment_config = Element::fromJSON(
-        "{"
-        "  \"mapped-file\": \""
-        TEST_DATA_BUILDDIR "/test1.zone.image" "\"}");
-    clients_map = configureDataSource(config);
-    {
-        const boost::shared_ptr<ConfigurableClientList> list =
-            (*clients_map)[RRClass::IN()];
-        list->resetMemorySegment("MasterFiles",
-                                 memory::ZoneTableSegment::CREATE,
-                                 segment_config);
-        const ConfigurableClientList::ZoneWriterPair result =
-            list->getCachedZoneWriter(isc::dns::Name("test1.example"), false,
-                                      "MasterFiles");
-        ASSERT_EQ(ConfigurableClientList::ZONE_SUCCESS, result.first);
-        result.second->load();
-        result.second->install();
-        // not absolutely necessary, but just in case
-        result.second->cleanup();
-    } // Release this list. That will release the file with the image too,
-      // so we can map it read only from somewhere else.
-
-    // Create a new map, with the same configuration, but without the segments
-    // set
-    clients_map = configureDataSource(config);
-    const boost::shared_ptr<ConfigurableClientList> list =
-        (*clients_map)[RRClass::IN()];
-    EXPECT_EQ(SEGMENT_WAITING, list->getStatus()[0].getSegmentState());
-    // Send the command
-    const ElementPtr command_args = Element::fromJSON(
-        "{"
-        "  \"data-source-name\": \"MasterFiles\","
-        "  \"data-source-class\": \"IN\""
-        "}");
-    command_args->set("segment-params", segment_config);
-    builder.handleCommand(Command(SEGMENT_INFO_UPDATE, command_args,
-                                  FinishedCallback()));
-    // The segment is now used.
-    EXPECT_EQ(SEGMENT_INUSE, list->getStatus()[0].getSegmentState());
-
-    // Some invalid inputs (wrong class, different name of data source, etc).
-
-    // Copy the confing and modify
-    const ElementPtr bad_name = Element::fromJSON(command_args->toWire());
-    // Set bad name
-    bad_name->set("data-source-name", Element::create("bad"));
-    EXPECT_DEATH_IF_SUPPORTED({
-        builder.handleCommand(Command(SEGMENT_INFO_UPDATE, bad_name,
-                                      FinishedCallback()));
-    }, "");
-
-    // Another copy with wrong class
-    const ElementPtr bad_class = Element::fromJSON(command_args->toWire());
-    // Set bad class
-    bad_class->set("data-source-class", Element::create("bad"));
-    // Aborts (we are out of sync somehow).
-    EXPECT_DEATH_IF_SUPPORTED({
-        builder.handleCommand(Command(SEGMENT_INFO_UPDATE, bad_class,
-                                      FinishedCallback()));
-    }, "");
-
-    // Class CH is valid, but not present.
-    bad_class->set("data-source-class", Element::create("CH"));
-    EXPECT_DEATH_IF_SUPPORTED({
-        builder.handleCommand(Command(SEGMENT_INFO_UPDATE, bad_class,
-                                      FinishedCallback()));
-    }, "");
-
-    // And break the segment params
-    const ElementPtr bad_params = Element::fromJSON(command_args->toWire());
-    bad_params->set("segment-params",
-                    Element::fromJSON("{\"mapped-file\": \"/bad/file\"}"));
-
-    EXPECT_DEATH_IF_SUPPORTED({
-        builder.handleCommand(Command(SEGMENT_INFO_UPDATE, bad_class,
-                                      FinishedCallback()));
-    }, "");
-}
-
-} // unnamed namespace

+ 0 - 323
src/bin/auth/tests/datasrc_clients_mgr_unittest.cc

@@ -1,323 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <exceptions/exceptions.h>
-
-#include <dns/rrclass.h>
-
-#include <cc/data.h>
-
-#include <datasrc/client_list.h>
-
-#include <auth/datasrc_clients_mgr.h>
-#include "test_datasrc_clients_mgr.h"
-
-#include <gtest/gtest.h>
-
-#include <boost/function.hpp>
-
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::datasrc;
-using namespace isc::auth;
-using namespace isc::auth::datasrc_clientmgr_internal;
-
-namespace {
-void
-shutdownCheck() {
-    // Check for common points on shutdown.  The manager should have acquired
-    // the lock, put a SHUTDOWN command to the queue, and should have signaled
-    // the builder. It should check again for the callback queue, with the lock
-    EXPECT_EQ(2, FakeDataSrcClientsBuilder::queue_mutex->lock_count);
-    EXPECT_EQ(1, FakeDataSrcClientsBuilder::cond->signal_count);
-    EXPECT_EQ(1, FakeDataSrcClientsBuilder::command_queue->size());
-    const Command& cmd = FakeDataSrcClientsBuilder::command_queue->front();
-    EXPECT_EQ(SHUTDOWN, cmd.id);
-    EXPECT_FALSE(cmd.params);   // no argument
-
-    // Finally, the manager should wait for the thread to terminate.
-    EXPECT_TRUE(FakeDataSrcClientsBuilder::thread_waited);
-}
-
-// Commonly used pattern of checking member variables shared between the
-// manager and builder.
-void
-checkSharedMembers(size_t expected_queue_lock_count,
-                   size_t expected_queue_unlock_count,
-                   size_t expected_map_lock_count,
-                   size_t expected_map_unlock_count,
-                   size_t expected_cond_signal_count,
-                   size_t expected_command_queue_size)
-{
-    EXPECT_EQ(expected_queue_lock_count,
-              FakeDataSrcClientsBuilder::queue_mutex->lock_count);
-    EXPECT_EQ(expected_queue_unlock_count,
-              FakeDataSrcClientsBuilder::queue_mutex->unlock_count);
-    EXPECT_EQ(expected_map_lock_count,
-              FakeDataSrcClientsBuilder::map_mutex->lock_count);
-    EXPECT_EQ(expected_map_unlock_count,
-              FakeDataSrcClientsBuilder::map_mutex->unlock_count);
-    EXPECT_EQ(expected_cond_signal_count,
-              FakeDataSrcClientsBuilder::cond->signal_count);
-    EXPECT_EQ(expected_command_queue_size,
-              FakeDataSrcClientsBuilder::command_queue->size());
-}
-
-TEST(DataSrcClientsMgrTest, start) {
-    // When we create a manager, builder's run() method should be called.
-    FakeDataSrcClientsBuilder::started = false;
-    {
-        TestDataSrcClientsMgr mgr;
-        EXPECT_TRUE(FakeDataSrcClientsBuilder::started);
-        EXPECT_TRUE(FakeDataSrcClientsBuilder::command_queue->empty());
-
-        // Check pre-destroy conditions
-        EXPECT_EQ(0, FakeDataSrcClientsBuilder::cond->signal_count);
-        EXPECT_FALSE(FakeDataSrcClientsBuilder::thread_waited);
-    } // mgr and builder have been destroyed by this point.
-
-    // We stopped the manager implicitly (without shutdown()).  The manager
-    // will internally notify it
-    shutdownCheck();
-}
-
-TEST(DataSrcClientsMgrTest, shutdownWithUncaughtException) {
-    // Emulating the case when the builder exists on exception.  shutdown()
-    // will encounter UncaughtException exception and catch it.
-    EXPECT_NO_THROW({
-            TestDataSrcClientsMgr mgr;
-            FakeDataSrcClientsBuilder::thread_throw_on_wait =
-                FakeDataSrcClientsBuilder::THROW_UNCAUGHT_EX;
-        });
-}
-
-TEST(DataSrcClientsMgrTest, shutdownWithException) {
-    EXPECT_NO_THROW({
-            TestDataSrcClientsMgr mgr;
-            FakeDataSrcClientsBuilder::thread_throw_on_wait =
-                FakeDataSrcClientsBuilder::THROW_OTHER;
-        });
-}
-
-TEST(DataSrcClientsMgrTest, reconfigure) {
-    TestDataSrcClientsMgr mgr;
-
-    // Check pre-command condition
-    checkSharedMembers(0, 0, 0, 0, 0, 0);
-
-    // A valid reconfigure argument
-    ConstElementPtr reconfigure_arg = Element::fromJSON(
-        "{""\"IN\": [{\"type\": \"MasterFiles\", \"params\": {},"
-        "             \"cache-enable\": true}]}");
-
-    // On reconfigure(), it just send the RECONFIGURE command to the builder
-    // thread with the given argument intact.
-    mgr.reconfigure(reconfigure_arg);
-
-    // The manager should have acquired the queue lock, send RECONFIGURE
-    // command with the arg, wake up the builder thread by signal.  It doesn't
-    // touch or refer to the map, so it shouldn't acquire the map lock.
-    checkSharedMembers(1, 1, 0, 0, 1, 1);
-    const Command& cmd1 = FakeDataSrcClientsBuilder::command_queue->front();
-    EXPECT_EQ(RECONFIGURE, cmd1.id);
-    EXPECT_EQ(reconfigure_arg, cmd1.params);
-
-    // Non-null, but semantically invalid argument.  The manager doesn't do
-    // this check, so it should result in the same effect.
-    FakeDataSrcClientsBuilder::command_queue->clear();
-    reconfigure_arg = isc::data::Element::create("{ \"foo\": \"bar\" }");
-    mgr.reconfigure(reconfigure_arg);
-    checkSharedMembers(2, 2, 0, 0, 2, 1);
-    const Command& cmd2 = FakeDataSrcClientsBuilder::command_queue->front();
-    EXPECT_EQ(RECONFIGURE, cmd2.id);
-    EXPECT_EQ(reconfigure_arg, cmd2.params);
-
-    // Passing NULL argument is immediately rejected
-    EXPECT_THROW(mgr.reconfigure(ConstElementPtr()), isc::InvalidParameter);
-    checkSharedMembers(2, 2, 0, 0, 2, 1); // no state change
-}
-
-TEST(DataSrcClientsMgrTest, holder) {
-    TestDataSrcClientsMgr mgr;
-
-    {
-        // Initially it's empty, so findClientList() will always return NULL
-        TestDataSrcClientsMgr::Holder holder(mgr);
-        EXPECT_FALSE(holder.findClientList(RRClass::IN()));
-        EXPECT_FALSE(holder.findClientList(RRClass::CH()));
-        EXPECT_TRUE(holder.getClasses().empty());
-        // map should be protected here
-        EXPECT_EQ(1, FakeDataSrcClientsBuilder::map_mutex->lock_count);
-        EXPECT_EQ(0, FakeDataSrcClientsBuilder::map_mutex->unlock_count);
-    }
-    // map lock has been released
-    EXPECT_EQ(1, FakeDataSrcClientsBuilder::map_mutex->unlock_count);
-
-    // Put something in, that should become visible.
-    ConstElementPtr reconfigure_arg = Element::fromJSON(
-        "{\"IN\": [{\"type\": \"MasterFiles\", \"params\": {},"
-        "           \"cache-enable\": true}],"
-        " \"CH\": [{\"type\": \"MasterFiles\", \"params\": {},"
-        "           \"cache-enable\": true}]}");
-    mgr.reconfigure(reconfigure_arg);
-    {
-        TestDataSrcClientsMgr::Holder holder(mgr);
-        EXPECT_TRUE(holder.findClientList(RRClass::IN()));
-        EXPECT_TRUE(holder.findClientList(RRClass::CH()));
-        EXPECT_EQ(2, holder.getClasses().size());
-    }
-    // We need to clear command queue by hand
-    FakeDataSrcClientsBuilder::command_queue->clear();
-
-    // Replace the lists with new lists containing only one list.
-    // The CH will disappear again.
-    reconfigure_arg = Element::fromJSON(
-        "{\"IN\": [{\"type\": \"MasterFiles\", \"params\": {},"
-        "           \"cache-enable\": true}]}");
-    mgr.reconfigure(reconfigure_arg);
-    {
-        TestDataSrcClientsMgr::Holder holder(mgr);
-        EXPECT_TRUE(holder.findClientList(RRClass::IN()));
-        EXPECT_FALSE(holder.findClientList(RRClass::CH()));
-        EXPECT_EQ(RRClass::IN(), holder.getClasses()[0]);
-    }
-
-    // Duplicate lock acquisition is prohibited (only test mgr can detect
-    // this reliably, so this test may not be that useful)
-    TestDataSrcClientsMgr::Holder holder1(mgr);
-    EXPECT_THROW(TestDataSrcClientsMgr::Holder holder2(mgr), isc::Unexpected);
-}
-
-TEST(DataSrcClientsMgrTest, reload) {
-    TestDataSrcClientsMgr mgr;
-    EXPECT_TRUE(FakeDataSrcClientsBuilder::started);
-    EXPECT_TRUE(FakeDataSrcClientsBuilder::command_queue->empty());
-
-    isc::data::ElementPtr args =
-        isc::data::Element::fromJSON("{ \"class\": \"IN\","
-                                     "  \"origin\": \"example.com\" }");
-    mgr.loadZone(args);
-    EXPECT_EQ(1, FakeDataSrcClientsBuilder::command_queue->size());
-    mgr.loadZone(args);
-    EXPECT_EQ(2, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // Should fail with non-string 'class' value
-    args->set("class", Element::create(1));
-    EXPECT_THROW(mgr.loadZone(args), CommandError);
-    EXPECT_EQ(2, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // And with badclass
-    args->set("class", Element::create("BADCLASS"));
-    EXPECT_THROW(mgr.loadZone(args), CommandError);
-    EXPECT_EQ(2, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // Should succeed without 'class'
-    args->remove("class");
-    mgr.loadZone(args);
-    EXPECT_EQ(3, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // but fail without origin, without sending new commands
-    args->remove("origin");
-    EXPECT_THROW(mgr.loadZone(args), CommandError);
-    EXPECT_EQ(3, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // And for 'origin' that is not a string
-    args->set("origin", Element::create(1));
-    EXPECT_THROW(mgr.loadZone(args), CommandError);
-    EXPECT_EQ(3, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // And origin that is not a correct name
-    args->set("origin", Element::create(".."));
-    EXPECT_THROW(mgr.loadZone(args), CommandError);
-    EXPECT_EQ(3, FakeDataSrcClientsBuilder::command_queue->size());
-
-    // same for empty data and data that is not a map
-    EXPECT_THROW(mgr.loadZone(isc::data::ConstElementPtr()), CommandError);
-    EXPECT_THROW(mgr.loadZone(isc::data::Element::createList()), CommandError);
-    EXPECT_EQ(3, FakeDataSrcClientsBuilder::command_queue->size());
-}
-
-TEST(DataSrcClientsMgrTest, segmentUpdate) {
-    TestDataSrcClientsMgr mgr;
-    EXPECT_TRUE(FakeDataSrcClientsBuilder::started);
-    EXPECT_TRUE(FakeDataSrcClientsBuilder::command_queue->empty());
-
-    isc::data::ElementPtr args =
-        isc::data::Element::fromJSON("{\"data-source-class\": \"IN\","
-                                     " \"data-source-name\": \"sqlite3\","
-                                     " \"segment-params\": {}}");
-    mgr.segmentInfoUpdate(args);
-    EXPECT_EQ(1, FakeDataSrcClientsBuilder::command_queue->size());
-    // Some invalid inputs
-    EXPECT_THROW(mgr.segmentInfoUpdate(isc::data::Element::fromJSON(
-        "{\"data-source-class\": \"IN\","
-        " \"data-source-name\": \"sqlite3\"}")), CommandError);
-    EXPECT_THROW(mgr.segmentInfoUpdate(isc::data::Element::fromJSON(
-        "{\"data-source-name\": \"sqlite3\","
-        " \"segment-params\": {}}")), CommandError);
-    EXPECT_THROW(mgr.segmentInfoUpdate(isc::data::Element::fromJSON(
-        "{\"data-source-class\": \"IN\","
-        " \"segment-params\": {}}")), CommandError);
-    EXPECT_EQ(1, FakeDataSrcClientsBuilder::command_queue->size());
-}
-
-void
-callback(bool* called, int *tag_target, int tag_value) {
-    *called = true;
-    *tag_target = tag_value;
-}
-
-// Test we can wake up the main thread by writing to the file descriptor and
-// that the callbacks are executed and removed when woken up.
-TEST(DataSrcClientsMgrTest, wakeup) {
-    bool called = false;
-    int tag;
-    {
-        TestDataSrcClientsMgr mgr;
-        // There's some real file descriptor (or something that looks so)
-        ASSERT_GT(FakeDataSrcClientsBuilder::wakeup_fd, 0);
-        // Push a callback in and wake the manager
-        FakeDataSrcClientsBuilder::callback_queue->
-            push_back(boost::bind(callback, &called, &tag, 1));
-        EXPECT_EQ(1, write(FakeDataSrcClientsBuilder::wakeup_fd, "w", 1));
-        mgr.run_one();
-        EXPECT_TRUE(called);
-        EXPECT_EQ(1, tag);
-        EXPECT_TRUE(FakeDataSrcClientsBuilder::callback_queue->empty());
-
-        called = false;
-        // If we wake up and don't push anything, it doesn't break.
-        EXPECT_EQ(1, write(FakeDataSrcClientsBuilder::wakeup_fd, "w", 1));
-        mgr.run_one();
-        EXPECT_FALSE(called);
-
-        // When we terminate, it should process whatever is left
-        // of the callbacks. So push and terminate (and don't directly
-        // wake).
-        FakeDataSrcClientsBuilder::callback_queue->
-            push_back(boost::bind(callback, &called, &tag, 2));
-    }
-    EXPECT_TRUE(called);
-    EXPECT_EQ(2, tag);
-    EXPECT_TRUE(FakeDataSrcClientsBuilder::callback_queue->empty());
-}
-
-TEST(DataSrcClientsMgrTest, realThread) {
-    // Using the non-test definition with a real thread.  Just checking
-    // no disruption happens.
-    isc::asiolink::IOService service;
-    DataSrcClientsMgr mgr(service);
-}
-
-} // unnamed namespace

+ 0 - 298
src/bin/auth/tests/datasrc_config_unittest.cc

@@ -1,298 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <auth/datasrc_config.h>
-
-#include <config/tests/fake_session.h>
-#include <config/ccsession.h>
-
-#include <gtest/gtest.h>
-
-#include <boost/bind.hpp>
-#include <boost/shared_ptr.hpp>
-
-#include <memory>
-
-using namespace isc;
-using namespace isc::cc;
-using namespace isc::config;
-using namespace isc::data;
-using namespace isc::dns;
-using namespace std;
-
-namespace {
-
-class DatasrcConfigTest;
-
-class FakeList {
-public:
-    FakeList(const RRClass&) :
-        configuration_(new ListElement)
-    {}
-    void configure(const ConstElementPtr& configuration, bool allow_cache) {
-        EXPECT_TRUE(allow_cache);
-        conf_ = configuration->get(0)->get("type")->stringValue();
-        configuration_ = configuration;
-    }
-    const string& getConf() const {
-        return (conf_);
-    }
-    ConstElementPtr getConfiguration() const {
-        return (configuration_);
-    }
-private:
-    string conf_;
-    ConstElementPtr configuration_;
-};
-
-typedef boost::shared_ptr<FakeList> ListPtr;
-
-// Forward declaration.  We need precise definition of DatasrcConfigTest
-// to complete this function.
-void
-testConfigureDataSource(DatasrcConfigTest& test,
-                        const isc::data::ConstElementPtr& config);
-
-void
-datasrcConfigHandler(DatasrcConfigTest* fake_server, const std::string&,
-                     isc::data::ConstElementPtr config,
-                     const isc::config::ConfigData&)
-{
-    if (config->contains("classes")) {
-        testConfigureDataSource(*fake_server, config->get("classes"));
-    }
-}
-
-class DatasrcConfigTest : public ::testing::Test {
-public:
-    void setDataSrcClientLists(boost::shared_ptr<std::map<dns::RRClass,
-                               ListPtr> > new_lists)
-    {
-        lists_.clear();         // first empty it
-
-        // Record the operation and results.  Note that map elements are
-        // sorted by RRClass, so the ordering should be predictable.
-        for (std::map<dns::RRClass, ListPtr>::const_iterator it =
-                 new_lists->begin();
-             it != new_lists->end();
-             ++it)
-        {
-            const RRClass rrclass = it->first;
-            ListPtr list = it->second;
-            log_ += "set " + rrclass.toText() + " " +
-                (list ? list->getConf() : "") + "\n";
-            lists_[rrclass] = list;
-        }
-    }
-
-protected:
-    DatasrcConfigTest() :
-        session(ElementPtr(new ListElement), ElementPtr(new ListElement),
-                ElementPtr(new ListElement)),
-        specfile(string(TEST_OWN_DATA_DIR) + "/spec.spec")
-    {
-        initSession();
-    }
-    void initSession() {
-        session.getMessages()->add(createAnswer());
-        mccs.reset(new ModuleCCSession(specfile, session, NULL, NULL, false,
-                                       false));
-    }
-    void TearDown() {
-        // Make sure no matter what we did, it is cleaned up.  Also check
-        // we really have subscribed to the configuration, and after removing
-        // it we actually cancel it.
-        EXPECT_TRUE(session.haveSubscription("data_sources", "*"));
-        mccs->removeRemoteConfig("data_sources");
-        EXPECT_FALSE(session.haveSubscription("data_sources", "*"));
-    }
-    void SetUp() {
-        session.getMessages()->
-            add(createAnswer(0,
-                             moduleSpecFromFile(string(PLUGIN_DATA_PATH) +
-                                                "/datasrc.spec").
-                             getFullSpec()));
-        session.getMessages()->add(createAnswer(0,
-                                                ElementPtr(new MapElement)));
-        mccs->addRemoteConfig("data_sources",
-                              boost::bind(datasrcConfigHandler,
-                                          this, _1, _2, _3), false);
-    }
-    ElementPtr buildConfig(const string& config) const {
-        const ElementPtr internal(Element::fromJSON(config));
-        const ElementPtr external(Element::fromJSON("{\"version\": 1}"));
-        external->set("classes", internal);
-        return (external);
-    }
-    void initializeINList() {
-        const ConstElementPtr
-            config(buildConfig("{\"IN\": [{\"type\": \"xxx\"}]}"));
-        session.addMessage(createCommand("config_update", config),
-                           "data_sources", "*");
-        mccs->checkCommand();
-        // Check that the passed config is stored.
-        EXPECT_EQ("set IN xxx\n", log_);
-        EXPECT_EQ(1, lists_.size());
-    }
-    FakeSession session;
-    auto_ptr<ModuleCCSession> mccs;
-    const string specfile;
-    std::map<RRClass, ListPtr> lists_;
-    string log_;
-};
-
-void
-testConfigureDataSource(DatasrcConfigTest& test,
-                        const isc::data::ConstElementPtr& config)
-{
-    // We use customized (faked lists) for the List type.  This makes it
-    // possible to easily look that they were called.
-    boost::shared_ptr<std::map<dns::RRClass, ListPtr> > lists =
-        configureDataSourceGeneric<FakeList>(config);
-    test.setDataSrcClientLists(lists);
-}
-
-// Push there a configuration with a single list.
-TEST_F(DatasrcConfigTest, createList) {
-    initializeINList();
-}
-
-TEST_F(DatasrcConfigTest, modifyList) {
-    // First, initialize the list, and confirm the current config
-    initializeINList();
-    EXPECT_EQ("xxx", lists_[RRClass::IN()]->getConf());
-
-    // And now change the configuration of the list
-    const ElementPtr
-        config(buildConfig("{\"IN\": [{\"type\": \"yyy\"}]}"));
-    session.addMessage(createCommand("config_update", config), "data_sources",
-                       "*");
-    log_ = "";
-    mccs->checkCommand();
-    // Now the new one should be installed.
-    EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
-    EXPECT_EQ(1, lists_.size());
-}
-
-// Check we can have multiple lists at once
-TEST_F(DatasrcConfigTest, multiple) {
-    const ElementPtr
-        config(buildConfig("{\"IN\": [{\"type\": \"yyy\"}], "
-                                 "\"CH\": [{\"type\": \"xxx\"}]}"));
-    session.addMessage(createCommand("config_update", config), "data_sources",
-                       "*");
-    mccs->checkCommand();
-    // We have set commands for both classes.
-    EXPECT_EQ("set IN yyy\nset CH xxx\n", log_);
-    // We should have both there
-    EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
-    EXPECT_EQ("xxx", lists_[RRClass::CH()]->getConf());
-    EXPECT_EQ(2, lists_.size());
-}
-
-// Check we can add another one later and the old one does not get
-// overwritten.
-//
-// It's almost like above, but we initialize first with single-list
-// config.
-TEST_F(DatasrcConfigTest, updateAdd) {
-    initializeINList();
-    const ElementPtr
-        config(buildConfig("{\"IN\": [{\"type\": \"yyy\"}], "
-                           "\"CH\": [{\"type\": \"xxx\"}]}"));
-    session.addMessage(createCommand("config_update", config), "data_sources",
-                       "*");
-    log_ = "";
-    mccs->checkCommand();
-    EXPECT_EQ("set IN yyy\nset CH xxx\n", log_);
-    EXPECT_EQ("xxx", lists_[RRClass::CH()]->getConf());
-    EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
-    EXPECT_EQ(2, lists_.size());
-}
-
-// We delete a class list in this test.
-TEST_F(DatasrcConfigTest, updateDelete) {
-    initializeINList();
-    const ElementPtr
-        config(buildConfig("{}"));
-    session.addMessage(createCommand("config_update", config), "data_sources",
-                       "*");
-    log_ = "";
-    mccs->checkCommand();
-
-    // No operation takes place in the configuration, and the old one is
-    // just dropped
-    EXPECT_EQ("", log_);
-    EXPECT_TRUE(lists_.empty());
-}
-
-// Check that broken new configuration doesn't break the running configuration.
-TEST_F(DatasrcConfigTest, brokenConfigForAdd) {
-    initializeINList();
-    // The configuration is wrong. However, the CH one will be handled
-    // without an error first.
-    const ElementPtr
-        config(buildConfig("{\"IN\": [{\"type\": 13}], "
-                           "\"CH\": [{\"type\": \"xxx\"}]}"));
-    session.addMessage(createCommand("config_update", config), "data_sources",
-                       "*");
-    log_ = "";
-    // It does not throw, as it is handled in the ModuleCCSession.
-    // Throwing from the reconfigure is checked in other tests.
-    EXPECT_NO_THROW(mccs->checkCommand());
-    // Anyway, the result should not contain CH now and the original IN should
-    // be there.
-    EXPECT_EQ("xxx", lists_[RRClass::IN()]->getConf());
-    EXPECT_FALSE(lists_[RRClass::CH()]);
-}
-
-// Similar to the previous one, but the broken config would delete part of
-// the running config.
-TEST_F(DatasrcConfigTest, brokenConfigForDelete) {
-    initializeINList();
-    // Put the CH there
-    const ElementPtr
-        config1(Element::fromJSON("{\"IN\": [{\"type\": \"yyy\"}], "
-                                  "\"CH\": [{\"type\": \"xxx\"}]}"));
-    testConfigureDataSource(*this, config1);
-    const ElementPtr
-        config2(Element::fromJSON("{\"IN\": [{\"type\": 13}]}"));
-    // This would delete CH. However, the new config is broken, so it won't
-    // actually apply.
-    EXPECT_THROW(testConfigureDataSource(*this, config2), TypeError);
-    EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
-    EXPECT_EQ("xxx", lists_[RRClass::CH()]->getConf());
-}
-
-// Similar to the previous cases, but the broken config would modify the
-// running config of one of the classes.
-TEST_F(DatasrcConfigTest, brokenConfigForModify) {
-    initializeINList();
-    // Put the CH there
-    const ElementPtr
-        config1(Element::fromJSON("{\"IN\": [{\"type\": \"yyy\"}], "
-                                  "\"CH\": [{\"type\": \"xxx\"}]}"));
-    testConfigureDataSource(*this, config1);
-    // Now, the CH change will be handled first without an error, then
-    // the change to the IN class will fail, and the none of the changes
-    // will apply.
-    const ElementPtr
-        config2(Element::fromJSON("{\"IN\": [{\"type\": 13}], "
-                                  "\"CH\": [{\"type\": \"yyy\"}]}"));
-    EXPECT_THROW(testConfigureDataSource(*this, config2), TypeError);
-    EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
-    EXPECT_EQ("xxx", lists_[RRClass::CH()]->getConf());
-}
-
-}

+ 0 - 77
src/bin/auth/tests/datasrc_util.cc

@@ -1,77 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <exceptions/exceptions.h>
-
-#include <dns/masterload.h>
-#include <dns/name.h>
-#include <dns/rrclass.h>
-
-#include <cc/data.h>
-
-#include <datasrc/client.h>
-#include <datasrc/zone.h>
-#include <datasrc/factory.h>
-
-#include "datasrc_util.h"
-
-#include <boost/bind.hpp>
-
-#include <istream>
-
-#include <cstdlib>
-
-using namespace std;
-
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::datasrc;
-
-namespace isc {
-namespace auth {
-namespace unittest {
-
-namespace {
-void
-addRRset(ZoneUpdaterPtr updater, ConstRRsetPtr rrset) {
-    updater->addRRset(*rrset);
-}
-}
-
-void
-createSQLite3DB(RRClass zclass, const Name& zname,
-                const char* const db_file, istream& rr_stream)
-{
-    // We always begin with an empty template SQLite3 DB file and install
-    // the zone data from the zone file.
-    const char* const install_cmd_prefix = INSTALL_PROG " -c " TEST_DATA_DIR
-        "/rwtest.sqlite3 ";
-    const string install_cmd = string(install_cmd_prefix) + db_file;
-    if (system(install_cmd.c_str()) != 0) {
-        isc_throw(isc::Unexpected,
-                  "Error setting up; command failed: " << install_cmd);
-    }
-
-    DataSourceClientContainer container("sqlite3",
-                                        Element::fromJSON(
-                                            "{\"database_file\": \"" +
-                                            string(db_file) + "\"}"));
-    ZoneUpdaterPtr updater = container.getInstance().getUpdater(zname, true);
-    masterLoad(rr_stream, zname, zclass, boost::bind(addRRset, updater, _1));
-    updater->commit();
-}
-
-} // end of unittest
-} // end of auth
-} // end of isc

+ 0 - 58
src/bin/auth/tests/datasrc_util.h

@@ -1,58 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef AUTH_DATA_SOURCE_UTIL_H
-#define AUTH_DATA_SOURCE_UTIL_H 1
-
-#include <dns/name.h>
-#include <dns/rrclass.h>
-
-#include <istream>
-
-namespace isc {
-namespace auth {
-namespace unittest {
-
-/// \brief Create an SQLite3 database file for a given zone from a stream.
-///
-/// This function creates an SQLite3 DB file for the specified zone
-/// with specified content.  The zone will be created in the given
-/// SQLite3 database file.  The database file does not have to exist;
-/// this function will automatically create a new file for the test
-/// based on a template that only contains the necessary schema. If
-/// the given file already exists this function overrides the content
-/// (so basically the file must be an ephemeral one only for that test
-/// case).
-///
-/// The input stream must produce strings as the corresponding
-/// \c dns::masterLoad() function expects.
-///
-/// \param zclass The RR class of the zone
-/// \param zname The origin name of the zone
-/// \param db_file The SQLite3 data base file in which the zone data should be
-/// installed.
-/// \param rr_stream An input stream that produces zone data.
-void
-createSQLite3DB(dns::RRClass zclass, const dns::Name& zname,
-                const char* const db_file, std::istream& rr_stream);
-
-} // end of unittest
-} // end of auth
-} // end of isc
-
-#endif  // AUTH_DATA_SOURCE_UTIL_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 98
src/bin/auth/tests/gen-query-testdata.py

@@ -1,98 +0,0 @@
-#!/usr/bin/env python3
-
-# Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-#
-# Permission to use, copy, modify, and/or distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-# PERFORMANCE OF THIS SOFTWARE.
-
-"""\
-This is a supplemental script to auto generate test data in the form of
-C++ source code from a DNS zone file.
-
-Usage: python gen-query-testdata.py source_file output-cc-file
-
-The usage doesn't matter much, though, because it's expected to be invoked
-from Makefile, and that would be only use case of this script.
-"""
-
-import sys
-import re
-
-# Markup for variable definition
-re_start_rr = re.compile('^;var=(.*)')
-
-# Skip lines starting with ';' (comments) or empty lines.  re_start_rr
-# will also match this expression, so it should be checked first.
-re_skip = re.compile('(^;)|(^\s*$)')
-
-def parse_input(input_file):
-    '''Build an internal list of RR data from the input source file.
-
-    It generates a list of (variable_name, list of RR) tuples, where
-    variable_name is the expected C++ variable name for the subsequent RRs
-    if they are expected to be named.  It can be an empty string if the RRs
-    are only expected to appear in the zone file.
-    The second element of the tuple is a list of strings, each of which
-    represents a single RR, e.g., "example.com 3600 IN A 192.0.2.1".
-
-    '''
-    result = []
-    rrs = None
-    with open(input_file) as f:
-        for line in f:
-            m = re_start_rr.match(line)
-            if m:
-                if rrs is not None:
-                    result.append((rr_varname, rrs))
-                rrs = []
-                rr_varname = m.group(1)
-            elif re_skip.match(line):
-                continue
-            else:
-                rrs.append(line.rstrip('\n'))
-
-        # if needed, store the last RRs (they are not followed by 'var=' mark)
-        if rrs is not None:
-            result.append((rr_varname, rrs))
-
-    return result
-
-def generate_variables(out_file, rrsets_data):
-    '''Generate a C++ source file containing a C-string variables for RRs.
-
-    This produces a definition of C-string for each RRset that is expected
-    to be named as follows:
-    const char* const var_name =
-        "example.com. 3600 IN A 192.0.2.1\n"
-        "example.com. 3600 IN A 192.0.2.2\n";
-
-    Escape character '\' in the string will be further escaped so it will
-    compile.
-
-    '''
-    with open(out_file, 'w') as out:
-        for (var_name, rrs) in rrsets_data:
-            if len(var_name) > 0:
-                out.write('const char* const ' + var_name + ' =\n')
-                # Combine all RRs, escaping '\' as a C-string
-                out.write('\n'.join(['    \"%s\\n\"' %
-                                     (rr.replace('\\', '\\\\'))
-                                     for rr in rrs]))
-                out.write(';\n')
-
-if __name__ == "__main__":
-    if len(sys.argv) < 3:
-        sys.stderr.write('gen-query-testdata.py require 2 args\n')
-        sys.exit(1)
-    rrsets_data = parse_input(sys.argv[1])
-    generate_variables(sys.argv[2], rrsets_data)
-

+ 0 - 90
src/bin/auth/tests/gen-statisticsitems_test.py

@@ -1,90 +0,0 @@
-# Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-#
-# Permission to use, copy, modify, and/or distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-# PERFORMANCE OF THIS SOFTWARE.
-
-"""\
-This script checks output of gen-statisticsitems.py.
-
-This script checks XML file. Spec file, C++ code and header files syntax is
-checked in the other unittests or system tests.
-"""
-
-import os
-import sys
-from xml.etree import ElementTree
-
-"""\
-User-defined exception for parse error. It is thrown if a file is not
-formatted as expected.
-"""
-class ParseError(Exception):
-    pass
-
-"""\
-Test XML file.
-
-It should have <refsect1> which has <title>STATISTICS DATA</title>.
-Inside the section, it should have one or more <varlistentry> of each item
-inside <variablelist>.
-Each <varlistentry> should have <term> for item name and <simpara> inside
-<listitem> for item description.
-
-Example:
-    <refsect1>
-        <title>STATISTICS DATA</title>
-        <variablelist>
-        <varlistentry>
-          <term>item1</term>
-          <listitem><simpara>statistics item</simpara></listitem>
-        </varlistentry>
-        <varlistentry>
-          <term>item2</term>
-          <listitem><simpara>another statistics item</simpara></listitem>
-        </varlistentry>
-        </variablelist>
-    </refsect1>
-"""
-def test_xml_file(xmlfilepath):
-    xmltree = ElementTree.parse(xmlfilepath)
-    root = xmltree.getroot()
-    # find <refsect1> which has <title> of 'STATISTICS DATA'
-    stats_node = [t for t in root.findall('./refsect1')
-            if t.find('./title').text == 'STATISTICS DATA']
-    if not stats_node:
-        raise ParseError('Statistics data section does not exist')
-    # find all <varlistentry> inside <variablelist>
-    entries = stats_node[0].find('./variablelist').findall('./varlistentry')
-    if not entries:
-        raise ParseError('<varlistentry> does not exist inside section')
-    for entry in entries:
-        # find <term> for item name
-        name = entry.find('./term')
-        if name is None or name.text == '':
-            raise ParseError('<term> for item name does not exist')
-        # find <simpara> inside <listitem> for item description
-        description = entry.find('./listitem/simpara')
-        if description is None or description.text == '':
-            raise ParseError('<listitem> nor <simpara> for item description'
-                             ' does not exist')
-    return
-
-if __name__ == "__main__":
-    xmlfilepath = sys.argv[1]
-    try:
-        test_xml_file(xmlfilepath)
-    except ImportError:
-        # pyexpat library is required for ElementTree.parse() but it is
-        # missing in some environment. Just skip this test.
-        print ("Required library is missing, skipping this test.")
-        print ("Detailed information:")
-        print (sys.exc_info()[1])

Fichier diff supprimé car celui-ci est trop grand
+ 0 - 2863
src/bin/auth/tests/query_unittest.cc


+ 0 - 29
src/bin/auth/tests/run_unittests.cc

@@ -1,29 +0,0 @@
-// Copyright (C) 2009  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <gtest/gtest.h>
-#include <log/logger_support.h>
-#include <util/unittests/run_all.h>
-
-#include <dns/tests/unittest_util.h>
-
-int
-main(int argc, char* argv[]) {
-    ::testing::InitGoogleTest(&argc, argv);
-    isc::UnitTestUtil::addDataPath(TEST_DATA_DIR);
-    isc::UnitTestUtil::addDataPath(TEST_DATA_BUILDDIR);
-    isc::log::initLogger();
-
-    return (isc::util::unittests::run_all());
-}

+ 0 - 772
src/bin/auth/tests/statistics_unittest.cc.pre

@@ -1,772 +0,0 @@
-// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <config.h>
-
-#include <gtest/gtest.h>
-
-#include <boost/bind.hpp>
-
-#include <dns/opcode.h>
-#include <dns/rcode.h>
-#include <dns/rrttl.h>
-
-#include <cc/data.h>
-
-#include <auth/statistics.h>
-#include <auth/statistics_items.h>
-
-#include <dns/tests/unittest_util.h>
-
-#include "statistics_util.h"
-
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netdb.h>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::data;
-using namespace isc::auth::statistics;
-using namespace isc::auth::unittest;
-
-namespace {
-
-// ### STATISTICS ITEMS DEFINITION ###
-
-class CountersTest : public ::testing::Test {
-protected:
-    CountersTest() : counters() {}
-    ~CountersTest() {}
-    Counters counters;
-};
-
-void
-buildSkeletonMessage(MessageAttributes& msgattrs) {
-    msgattrs.setRequestIPVersion(AF_INET);
-    msgattrs.setRequestTransportProtocol(IPPROTO_UDP);
-    msgattrs.setRequestOpCode(Opcode::QUERY());
-    msgattrs.setRequestEDNS0(true);
-    msgattrs.setRequestDO(true);
-}
-
-TEST_F(CountersTest, invalidParameterForSetRequestIPVersion) {
-    MessageAttributes msgattrs;
-
-    // It should not throw if the parameter is AF_INET or AF_INET6.
-    EXPECT_NO_THROW(msgattrs.setRequestIPVersion(AF_INET));
-    EXPECT_NO_THROW(msgattrs.setRequestIPVersion(AF_INET6));
-
-    // It should throw isc::InvalidParameter if the parameter is not AF_INET
-    // nor AF_INET6.
-    EXPECT_THROW(msgattrs.setRequestIPVersion(AF_UNIX), isc::InvalidParameter);
-}
-
-TEST_F(CountersTest, invalidParameterForSetRequestTransportProtocol) {
-    MessageAttributes msgattrs;
-
-    // It should not throw if the parameter is IPPROTO_UDP or IPPROTO_TCP.
-    EXPECT_NO_THROW(msgattrs.setRequestTransportProtocol(IPPROTO_UDP));
-    EXPECT_NO_THROW(msgattrs.setRequestTransportProtocol(IPPROTO_TCP));
-
-    // It should throw isc::InvalidParameter if the parameter is not
-    // IPPROTO_UDP nor IPPROTO_TCP.
-    EXPECT_THROW(msgattrs.setRequestTransportProtocol(IPPROTO_IP),
-                 isc::InvalidParameter);
-}
-
-TEST_F(CountersTest, invalidOperationForGetRequestOpCode) {
-    MessageAttributes msgattrs;
-
-    // getRequestOpCode() should return boost::none when called before
-    // opcode is set with setRequestOpCode().
-    EXPECT_FALSE(msgattrs.getRequestOpCode());
-
-    msgattrs.setRequestOpCode(Opcode::QUERY());
-    // getRequestOpCode() should be Opcode::QUERY.
-    EXPECT_EQ(Opcode::QUERY(), msgattrs.getRequestOpCode().get());
-}
-
-TEST_F(CountersTest, invalidParameterForSetRequestTSIG) {
-    MessageAttributes msgattrs;
-
-    // These patterns should not throw:
-    //      request signature  badsig
-    //     --------------------------
-    //      (none)             false
-    //      TSIG               false
-    //      TSIG               true
-    EXPECT_NO_THROW(msgattrs.setRequestTSIG(false, false));
-    EXPECT_NO_THROW(msgattrs.setRequestTSIG(true, false));
-    EXPECT_NO_THROW(msgattrs.setRequestTSIG(true, true));
-
-    // It should throw isc::InvalidParameter if a message is not signed but
-    // badsig is true
-    EXPECT_THROW(msgattrs.setRequestTSIG(false, true), isc::InvalidParameter);
-}
-
-TEST_F(CountersTest, incrementResponse) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test response counters are incremented only if responded == true.
-    for (int i = 0; i < 2; ++i) {
-        const bool responded = i & 1;
-
-        buildSkeletonMessage(msgattrs);
-
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        counters.inc(msgattrs, response, responded);
-
-        expect.clear();
-        expect["opcode.query"] = i+1;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = i+1;
-        expect["request.badednsver"] = 0;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = responded ? 1 : 0;
-        expect["qrynoauthans"] = responded ? 1 : 0;
-        expect["rcode.refused"] = responded ? 1 : 0;
-        expect["authqryrej"] = responded ? 1 : 0;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementProtocolType) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test these patterns:
-    //      af     proto
-    //     -----------------
-    //      ipv6   tcp
-    //      ipv4   tcp
-    //      ipv6   udp
-    //      ipv4   udp
-    int count_v4 = 0, count_v6 = 0, count_udp = 0, count_tcp = 0;
-    for (int i = 0; i < 4; ++i) {
-        const int af = i & 1 ? AF_INET : AF_INET6;
-        const int proto = i & 2 ? IPPROTO_UDP : IPPROTO_TCP;
-
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestIPVersion(af);
-        msgattrs.setRequestTransportProtocol(proto);
-
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        counters.inc(msgattrs, response, true);
-
-        if (af == AF_INET) {
-            ++count_v4;
-        } else {
-            ++count_v6;
-        }
-        if (proto == IPPROTO_UDP) {
-            ++count_udp;
-        } else {
-            ++count_tcp;
-        }
-
-        expect.clear();
-        expect["opcode.query"] = i+1;
-        expect["request.v4"] = count_v4;
-        expect["request.v6"] = count_v6;
-        expect["request.udp"] = count_udp;
-        expect["request.tcp"] = count_tcp;
-        expect["request.edns0"] = i+1;
-        expect["request.badednsver"] = 0;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = i+1;
-        expect["qrynoauthans"] = i+1;
-        expect["rcode.refused"] = i+1;
-        expect["authqryrej"] = i+1;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementDO) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test these patterns:
-    //     DNSSEC OK
-    //    -----------
-    //     false
-    //     true
-    for (int i = 0; i < 2; ++i) {
-        const bool is_dnssec_ok = i & 1;
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestDO(is_dnssec_ok);
-
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        counters.inc(msgattrs, response, true);
-
-        expect.clear();
-        expect["opcode.query"] = i+1;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = i+1;
-        expect["request.badednsver"] = 0;
-        expect["request.dnssec_ok"] = i & 1;
-        expect["responses"] = i+1;
-        expect["qrynoauthans"] = i+1;
-        expect["rcode.refused"] = i+1;
-        expect["authqryrej"] = i+1;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementEDNS) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test these patterns:
-    //     request edns0   response edns0
-    //    --------------------------------
-    //     false           true
-    //     true            false
-    //
-    // They can't be both true since edns0 and badednsver are exclusive.
-    int count_req_edns0 = 0, count_res_edns0 = 0;
-    for (int i = 0; i < 2; ++i) {
-        const bool is_edns0 = i & 1;
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestEDNS0(is_edns0);
-
-        if (!is_edns0) {
-            ConstEDNSPtr edns = EDNSPtr(new EDNS(0));
-            response.setEDNS(edns);
-        } else {
-            response.setEDNS(EDNSPtr());
-        }
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        counters.inc(msgattrs, response, true);
-
-        if (is_edns0) {
-            ++count_req_edns0;
-        } else {
-            ++count_res_edns0;
-        }
-
-        expect.clear();
-        expect["opcode.query"] = i+1;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = count_req_edns0;
-        expect["response.edns0"] = count_res_edns0;
-        expect["request.badednsver"] = 0;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = i+1;
-        expect["qrynoauthans"] = i+1;
-        expect["rcode.refused"] = i+1;
-        expect["authqryrej"] = i+1;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementTSIG) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test these patterns:
-    //      request signature  badsig   response signature
-    //     -----------------------------------------------
-    //      (none)             false    (none)
-    //      TSIG               false    TSIG
-    //      TSIG               true     (none)
-    //
-    // badsig can't be true if the message does not have signature.
-    int count_req_tsig = 0, count_res_tsig = 0, count_badsig = 0;
-    for (int i = 0; i < 3; ++i) {
-        const bool is_req_tsig = (i == 2) ? true : (i & 1) != 0;
-        const bool is_res_tsig = (i & 1) != 0;
-        const bool is_badsig = (i & 2) != 0;
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestTSIG(is_req_tsig, is_badsig);
-        msgattrs.setResponseTSIG(is_res_tsig);
-
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        // don't increment response counters if signature is bad
-        counters.inc(msgattrs, response, !is_badsig);
-
-        if (is_req_tsig) {
-            ++count_req_tsig;
-        }
-        if (is_res_tsig) {
-            ++count_res_tsig;
-        }
-        if (is_badsig) {
-            ++count_badsig;
-        }
-
-        expect.clear();
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["opcode.query"] = i+1;
-        expect["request.edns0"] = i+1 - count_badsig;
-        expect["request.badednsver"] = 0;
-        expect["request.dnssec_ok"] = i+1 - count_badsig;
-        expect["request.tsig"] = count_req_tsig;
-        expect["response.tsig"] = count_res_tsig;
-        expect["request.sig0"] = 0;
-        expect["request.badsig"] = count_badsig;
-        expect["responses"] = i+1 - count_badsig;
-        expect["qrynoauthans"] = i+1 - count_badsig;
-        expect["rcode.refused"] = i+1 - count_badsig;
-        expect["authqryrej"] = i+1 - count_badsig;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementRD) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test these patterns:
-    //     OpCode         Recursion Desired
-    //    ---------------------------
-    //     0 (Query)      false
-    //     0 (Query)      true
-    //     2 (Status)     false
-    //     2 (Status)     true
-    //  Make sure the counter will be incremented only for the requests with
-    //  OpCode=Query and Recursion Desired (RD) bit=1.
-    int count_opcode_query = 0;
-    int count_opcode_status = 0;
-    for (int i = 0; i < 4; ++i) {
-        const bool is_recursion_desired = i & 1;
-        const uint8_t opcode_code = i & 0x2;
-        const Opcode opcode(opcode_code);
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestRD(is_recursion_desired);
-        msgattrs.setRequestOpCode(opcode);
-
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        counters.inc(msgattrs, response, true);
-
-        if (opcode == Opcode::QUERY()) {
-            ++count_opcode_query;
-        } else {
-            ++count_opcode_status;
-        }
-
-        expect.clear();
-        expect["opcode.query"] = count_opcode_query;
-        expect["opcode.status"] = count_opcode_status;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = i+1;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = i+1;
-        // qryrecursion will (only) be incremented if i == 1: OpCode=Query and
-        // RD bit=1
-        expect["qryrecursion"] = (i == 0) ? 0 : 1;
-        expect["rcode.refused"] = i+1;
-        // these counters are for queries; the value will be equal to the
-        // number of requests with OpCode=Query
-        expect["qrynoauthans"] = count_opcode_query;
-        expect["authqryrej"] = count_opcode_query;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementOpcode) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test all opcodes (QUERY..RESERVED15)
-    int count_all = 0, count_opcode_other = 0;
-    for (uint8_t i = Opcode::QUERY().getCode(),
-                 e = Opcode::RESERVED15().getCode();
-         i <= e;
-         ++i)
-    {
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestOpCode(Opcode(i));
-        msgattrs.setRequestTSIG(false, false);
-
-        response.setRcode(Rcode::REFUSED());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        for (uint8_t j = 0; j < i; ++j) {
-            // count up i times for i-th opcode to identify counters
-            counters.inc(msgattrs, response, true);
-            ++count_all;
-        }
-
-        expect.clear();
-        expect["request.v4"] = count_all;
-        expect["request.udp"] = count_all;
-        expect["request.edns0"] = count_all;
-        expect["request.badednsver"] = 0;
-        expect["request.dnssec_ok"] = count_all;
-        expect["request.tsig"] = 0;
-        expect["request.sig0"] = 0;
-        expect["request.badsig"] = 0;
-        expect["responses"] = count_all;
-        expect["rcode.refused"] = count_all;
-        if (opcode_to_msgcounter[i] == MSG_OPCODE_OTHER) {
-            count_opcode_other += i;
-        }
-        for (uint8_t j = 0; j <= i; ++j) {
-            if (opcode_to_msgcounter[j] == MSG_OPCODE_OTHER) {
-                expect["opcode.other"] = count_opcode_other;
-            } else {
-                std::string code_text = Opcode(j).toText();
-                std::transform(code_text.begin(), code_text.end(),
-                               code_text.begin(), ::tolower);
-                expect["opcode."+code_text] = j;
-            }
-        }
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementRcode) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test all rcodes (NOERROR..BADVERS)
-    int count_all = 0, count_rcode_other = 0, count_ednsbadver = 0;
-    for (uint16_t i = Rcode::NOERROR().getCode(),
-                  e = Rcode::BADVERS().getCode();
-         i <= e;
-         ++i)
-    {
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestOpCode(Opcode::IQUERY());
-        msgattrs.setRequestTSIG(false, false);
-
-        response.setRcode(Rcode(i));
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::AAAA()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        for (uint16_t j = 0; j < i; ++j) {
-            // count up i times for i-th rcode to identify counters
-            counters.inc(msgattrs, response, true);
-            ++count_all;
-        }
-
-        expect.clear();
-        expect["opcode.iquery"] = count_all;
-        expect["request.v4"] = count_all;
-        expect["request.udp"] = count_all;
-        expect["request.edns0"] = count_all;
-        expect["request.dnssec_ok"] = count_all;
-        expect["request.tsig"] = 0;
-        expect["request.sig0"] = 0;
-        expect["request.badsig"] = 0;
-        expect["responses"] = count_all;
-        if (rcode_to_msgcounter[i] == MSG_RCODE_OTHER) {
-            count_rcode_other += i;
-        }
-        // "request.badednsver" counts for Rcode == BADVERS
-        if (rcode_to_msgcounter[i] == MSG_RCODE_BADVERS) {
-            count_ednsbadver += i;
-        }
-        expect["request.badednsver"] = count_ednsbadver;
-        for (uint16_t j = 0; j <= i; ++j) {
-            if (rcode_to_msgcounter[j] == MSG_RCODE_OTHER) {
-                expect["rcode.other"] = count_rcode_other;
-            } else {
-                std::string code_text = Rcode(j).toText();
-                std::transform(code_text.begin(), code_text.end(),
-                               code_text.begin(), ::tolower);
-                expect["rcode."+code_text] = j;
-            }
-        }
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementTruncated) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Test these patterns:
-    //      truncated
-    //     -----------
-    //      false
-    //      true
-    int count_truncated = 0;
-    for (int i = 0; i < 2; ++i) {
-        const bool is_truncated = i & 1;
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestOpCode(Opcode::IQUERY());
-        msgattrs.setRequestTSIG(false, false);
-        msgattrs.setResponseTruncated(is_truncated);
-
-        response.setRcode(Rcode::SERVFAIL());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::TXT()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-        counters.inc(msgattrs, response, true);
-
-        if (is_truncated) {
-            ++count_truncated;
-        }
-
-        expect.clear();
-        expect["opcode.iquery"] = i+1;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = i+1;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = i+1;
-        expect["rcode.servfail"] = i+1;
-        expect["response.truncated"] = count_truncated;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementQryAuthAnsAndNoAuthAns) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Opcode = QUERY, ANCOUNT = 0 (don't care), Rcode = SERVFAIL (don't care)
-    // Test these patterns:
-    //      AA flag
-    //     -----------------------
-    //      false -> QryNoAuthAns
-    //      true  -> QryAuthAns
-    int count_authans = 0, count_noauthans = 0;
-    for (int i = 0; i < 2; ++i) {
-        const bool is_aa_set = i & 1;
-        buildSkeletonMessage(msgattrs);
-        msgattrs.setRequestTSIG(false, false);
-
-        response.setRcode(Rcode::SERVFAIL());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::TXT()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-        if (is_aa_set) {
-            response.setHeaderFlag(Message::HEADERFLAG_AA);
-            ++count_authans;
-        } else {
-            ++count_noauthans;
-        }
-
-        counters.inc(msgattrs, response, true);
-
-        expect.clear();
-        expect["opcode.query"] = i+1;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = i+1;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = i+1;
-        expect["rcode.servfail"] = i+1;
-        expect["qryauthans"] = count_authans;
-        expect["qrynoauthans"] = count_noauthans;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementQrySuccess) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Opcode = QUERY, Rcode = NOERROR, ANCOUNT > 0
-    msgattrs.setRequestIPVersion(AF_INET);
-    msgattrs.setRequestTransportProtocol(IPPROTO_UDP);
-    msgattrs.setRequestOpCode(Opcode::QUERY());
-    msgattrs.setRequestEDNS0(true);
-    msgattrs.setRequestDO(true);
-    msgattrs.setRequestTSIG(false, false);
-
-    response.setRcode(Rcode::NOERROR());
-    response.addQuestion(Question(Name("example.com"),
-                                  RRClass::IN(), RRType::TXT()));
-    RRsetPtr answer_rrset(new RRset(Name("example.com"),
-                                    RRClass::IN(), RRType::TXT(),
-                                    RRTTL(3600)));
-    answer_rrset->addRdata(rdata::createRdata(RRType::TXT(),
-                                              RRClass::IN(),
-                                              "Answer"));
-    response.addRRset(Message::SECTION_ANSWER, answer_rrset);
-    response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-    counters.inc(msgattrs, response, true);
-
-    expect.clear();
-    expect["opcode.query"] = 1;
-    expect["request.v4"] = 1;
-    expect["request.udp"] = 1;
-    expect["request.edns0"] = 1;
-    expect["request.dnssec_ok"] = 1;
-    expect["responses"] = 1;
-    expect["rcode.noerror"] = 1;
-    expect["qrysuccess"] = 1;
-    // noauthans is also incremented
-    expect["qrynoauthans"] = 1;
-    checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                            expect);
-}
-
-TEST_F(CountersTest, incrementQryReferralAndNxrrset) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Opcode = QUERY, Rcode = NOERROR, ANCOUNT = 0
-    // Test these patterns:
-    //      AA flag
-    //     ----------------------
-    //      false -> QryReferral
-    //      true  -> QryNxrrset
-    int count_referral = 0, count_nxrrset = 0;
-    for (int i = 0; i < 2; ++i) {
-        const bool is_aa_set = i & 1;
-        msgattrs.setRequestIPVersion(AF_INET);
-        msgattrs.setRequestTransportProtocol(IPPROTO_UDP);
-        msgattrs.setRequestOpCode(Opcode::QUERY());
-        msgattrs.setRequestEDNS0(true);
-        msgattrs.setRequestDO(true);
-        msgattrs.setRequestTSIG(false, false);
-
-        response.setRcode(Rcode::NOERROR());
-        response.addQuestion(Question(Name("example.com"),
-                                      RRClass::IN(), RRType::TXT()));
-        response.setHeaderFlag(Message::HEADERFLAG_QR);
-        if (is_aa_set) {
-            response.setHeaderFlag(Message::HEADERFLAG_AA);
-            ++count_nxrrset;
-        } else {
-            ++count_referral;
-        }
-
-        counters.inc(msgattrs, response, true);
-
-        expect.clear();
-        expect["opcode.query"] = i+1;
-        expect["request.v4"] = i+1;
-        expect["request.udp"] = i+1;
-        expect["request.edns0"] = i+1;
-        expect["request.dnssec_ok"] = i+1;
-        expect["responses"] = i+1;
-        expect["rcode.noerror"] = i+1;
-        expect["qrynxrrset"] = count_nxrrset;
-        expect["qryreferral"] = count_referral;
-        // qryauthans or qrynoauthans is also incremented
-        expect["qryauthans"] = count_nxrrset;
-        expect["qrynoauthans"] = count_referral;
-        checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                                expect);
-    }
-}
-
-TEST_F(CountersTest, incrementAuthQryRej) {
-    Message response(Message::RENDER);
-    MessageAttributes msgattrs;
-    std::map<std::string, int> expect;
-
-    // Opcode = QUERY, Rcode = REFUSED, ANCOUNT = 0 (don't care)
-    msgattrs.setRequestIPVersion(AF_INET);
-    msgattrs.setRequestTransportProtocol(IPPROTO_UDP);
-    msgattrs.setRequestOpCode(Opcode::QUERY());
-    msgattrs.setRequestEDNS0(true);
-    msgattrs.setRequestDO(true);
-    msgattrs.setRequestTSIG(false, false);
-
-    response.setRcode(Rcode::REFUSED());
-    response.addQuestion(Question(Name("example.com"),
-                                  RRClass::IN(), RRType::TXT()));
-    response.setHeaderFlag(Message::HEADERFLAG_QR);
-
-    counters.inc(msgattrs, response, true);
-
-    expect.clear();
-    expect["opcode.query"] = 1;
-    expect["request.v4"] = 1;
-    expect["request.udp"] = 1;
-    expect["request.edns0"] = 1;
-    expect["request.dnssec_ok"] = 1;
-    expect["responses"] = 1;
-    expect["rcode.refused"] = 1;
-    expect["authqryrej"] = 1;
-    // noauthans is also incremented since AA bit is not set
-    expect["qrynoauthans"] = 1;
-    checkStatisticsCounters(counters.get()->get("zones")->get("_SERVER_"),
-                            expect);
-}
-
-int
-countTreeElements(const struct CounterSpec* tree) {
-    int count = 0;
-    for (int i = 0; tree[i].name != NULL; ++i) {
-        if (tree[i].sub_counters == NULL) {
-            ++count;
-        } else {
-            count += countTreeElements(tree[i].sub_counters);
-        }
-    }
-    return (count);
-}
-
-TEST(StatisticsItemsTest, MSGItemNamesCheck) {
-    EXPECT_EQ(MSG_COUNTER_TYPES, countTreeElements(msg_counter_tree));
-}
-
-}

+ 0 - 75
src/bin/auth/tests/statistics_util.cc

@@ -1,75 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include "statistics_util.h"
-
-#include <gtest/gtest.h>
-
-#include <string>
-#include <map>
-
-namespace {
-void
-flatten(std::map<std::string, int>& flat_map, const std::string& prefix,
-        const isc::data::ConstElementPtr map_element)
-{
-    std::map<std::string, isc::data::ConstElementPtr> map =
-        map_element->mapValue();
-    for (std::map<std::string, isc::data::ConstElementPtr>::const_iterator
-             i = map.begin(), e = map.end();
-         i != e;
-         ++i)
-    {
-        switch (i->second->getType()) {
-            case isc::data::Element::map:
-                flatten(flat_map, i->first + ".", i->second);
-                break;
-            case isc::data::Element::integer:
-                flat_map[prefix + i->first] = i->second->intValue();
-                break;
-            default:
-                FAIL() << "Element Parse Error";
-        }
-    }
-}
-}
-
-namespace isc {
-namespace auth {
-namespace unittest {
-
-void
-checkStatisticsCounters(const isc::data::ConstElementPtr counters,
-                        const std::map<std::string, int>& expect)
-{
-    std::map<std::string, int> stats_map;
-    flatten(stats_map, "", counters);
-
-    for (std::map<std::string, int>::const_iterator
-            i = stats_map.begin(), e = stats_map.end();
-            i != e;
-            ++i)
-    {
-        const int value =
-            expect.find(i->first) == expect.end() ?
-                0 : expect.find(i->first)->second;
-        EXPECT_EQ(value, i->second) << "Expected counter "
-            << i->first << " = " << value << ", actual: "
-            << i->second;
-    }
-}
-
-} // end of unittest
-} // end of auth
-} // end of isc

+ 0 - 38
src/bin/auth/tests/statistics_util.h

@@ -1,38 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef __AUTH_STATISTICS_UTIL_H
-#define __AUTH_STATISTICS_UTIL_H 1
-
-#include <cc/data.h>
-
-namespace isc {
-namespace auth {
-namespace unittest {
-
-// Test if the counters has expected values specified in expect and the others
-// are zero.
-void
-checkStatisticsCounters(const isc::data::ConstElementPtr counters,
-                        const std::map<std::string, int>& expect);
-
-} // end of unittest
-} // end of auth
-} // end of isc
-
-#endif  // __AUTH_STATISTICS_UTIL_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 102
src/bin/auth/tests/test_datasrc_clients_mgr.cc

@@ -1,102 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#include <exceptions/exceptions.h>
-#include <auth/datasrc_config.h>
-
-#include "test_datasrc_clients_mgr.h"
-
-#include <cassert>
-
-namespace isc {
-namespace auth {
-namespace datasrc_clientmgr_internal {
-
-// Define static DataSrcClientsBuilder member variables.
-bool FakeDataSrcClientsBuilder::started = false;
-std::list<Command>* FakeDataSrcClientsBuilder::command_queue = NULL;
-std::list<FinishedCallback>* FakeDataSrcClientsBuilder::callback_queue = NULL;
-std::list<Command> FakeDataSrcClientsBuilder::command_queue_copy;
-std::list<FinishedCallback> FakeDataSrcClientsBuilder::callback_queue_copy;
-TestCondVar* FakeDataSrcClientsBuilder::cond = NULL;
-TestCondVar FakeDataSrcClientsBuilder::cond_copy;
-TestMutex* FakeDataSrcClientsBuilder::queue_mutex = NULL;
-isc::datasrc::ClientListMapPtr*
-    FakeDataSrcClientsBuilder::clients_map = NULL;
-TestMutex* FakeDataSrcClientsBuilder::map_mutex = NULL;
-TestMutex FakeDataSrcClientsBuilder::queue_mutex_copy;
-bool FakeDataSrcClientsBuilder::thread_waited = false;
-FakeDataSrcClientsBuilder::ExceptionFromWait
-FakeDataSrcClientsBuilder::thread_throw_on_wait =
-    FakeDataSrcClientsBuilder::NOTHROW;
-int FakeDataSrcClientsBuilder::wakeup_fd = -1;
-
-template<>
-void
-TestDataSrcClientsBuilder::doNoop() {
-    ++queue_mutex_->noop_count;
-    switch (queue_mutex_->throw_from_noop) {
-    case TestMutex::NONE:
-        break;                  // no throw
-    case TestMutex::EXCLASS:
-        isc_throw(Exception, "test exception");
-    case TestMutex::INTEGER:
-        throw 42;
-    case TestMutex::INTERNAL:
-        isc_throw(InternalCommandError, "internal error, should be ignored");
-    }
-}
-} // namespace datasrc_clientmgr_internal
-
-template<>
-void
-TestDataSrcClientsMgrBase::cleanup() {
-    using namespace datasrc_clientmgr_internal;
-    // Make copy of some of the manager's member variables and reset the
-    // corresponding pointers.  The currently pointed objects are in the
-    // manager object, which are going to be invalidated.
-
-    FakeDataSrcClientsBuilder::command_queue_copy = command_queue_;
-    FakeDataSrcClientsBuilder::command_queue =
-        &FakeDataSrcClientsBuilder::command_queue_copy;
-    FakeDataSrcClientsBuilder::queue_mutex_copy = queue_mutex_;
-    FakeDataSrcClientsBuilder::queue_mutex =
-        &FakeDataSrcClientsBuilder::queue_mutex_copy;
-    FakeDataSrcClientsBuilder::cond_copy = cond_;
-    FakeDataSrcClientsBuilder::cond =
-        &FakeDataSrcClientsBuilder::cond_copy;
-    FakeDataSrcClientsBuilder::callback_queue_copy =
-        *FakeDataSrcClientsBuilder::callback_queue;
-    FakeDataSrcClientsBuilder::callback_queue =
-        &FakeDataSrcClientsBuilder::callback_queue_copy;
-}
-
-template<>
-void
-TestDataSrcClientsMgrBase::reconfigureHook() {
-    using namespace datasrc_clientmgr_internal;
-
-    // Simply replace the local map, ignoring bogus config value.
-    assert(command_queue_.front().id == RECONFIGURE);
-    try {
-        clients_map_ = configureDataSource(command_queue_.front().params);
-    } catch (...) {}
-}
-
-} // namespace auth
-} // namespace isc
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 243
src/bin/auth/tests/test_datasrc_clients_mgr.h

@@ -1,243 +0,0 @@
-// Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-//
-// Permission to use, copy, modify, and/or distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-// PERFORMANCE OF THIS SOFTWARE.
-
-#ifndef TEST_DATASRC_CLIENTS_MGR_H
-#define TEST_DATASRC_CLIENTS_MGR_H 1
-
-#include <exceptions/exceptions.h>
-
-#include <auth/datasrc_clients_mgr.h>
-#include <datasrc/datasrc_config.h>
-
-#include <asiolink/io_service.h>
-
-#include <boost/function.hpp>
-
-#include <list>
-
-// In this file we provide specialization of thread, mutex, condition variable,
-// and DataSrcClientsBuilder for convenience of tests.  They don't use
-// actual threads or mutex, and allow tests to inspect some internal states
-// of the corresponding objects.
-//
-// In many cases, tests can use TestDataSrcClientsMgr (defined below) where
-// DataSrcClientsMgr is needed.
-
-// Below we extend the isc::auth::datasrc_clientmgr_internal namespace to
-// specialize the doNoop() method.
-namespace isc {
-namespace auth {
-namespace datasrc_clientmgr_internal {
-class TestMutex {
-public:
-    // for throw_from_noop.
-    // None: no throw from specialized doNoop()
-    // EXCLASS: throw some exception class object
-    // INTEGER: throw an integer
-    // INTERNAL: internal error (shouldn't terminate the thread)
-    enum ExceptionFromNoop { NONE, EXCLASS, INTEGER, INTERNAL };
-
-    TestMutex() : lock_count(0), unlock_count(0), noop_count(0),
-                  throw_from_noop(NONE)
-    {}
-    class Locker {
-    public:
-        Locker(TestMutex& mutex) : mutex_(mutex) {
-            if (mutex.lock_count != mutex.unlock_count) {
-                isc_throw(Unexpected,
-                          "attempt of duplicate lock acquisition");
-            }
-
-            ++mutex.lock_count;
-            if (mutex.lock_count > 100) { // 100 is an arbitrary choice
-                isc_throw(Unexpected,
-                          "too many test mutex count, likely a bug in test");
-            }
-        }
-        ~Locker() {
-            ++mutex_.unlock_count;
-        }
-    private:
-        TestMutex& mutex_;
-    };
-    size_t lock_count; // number of lock acquisitions; tests can check this
-    size_t unlock_count; // number of lock releases; tests can check this
-    size_t noop_count;          // allow doNoop() to modify this
-    ExceptionFromNoop throw_from_noop; // tests can set this to control doNoop
-};
-
-class TestCondVar {
-public:
-    TestCondVar() : wait_count(0), signal_count(0), command_queue_(NULL),
-                    delayed_command_queue_(NULL)
-    {}
-    TestCondVar(std::list<Command>& command_queue,
-                std::list<Command>& delayed_command_queue) :
-        wait_count(0),
-        signal_count(0),
-        command_queue_(&command_queue),
-        delayed_command_queue_(&delayed_command_queue)
-    {
-    }
-    void wait(TestMutex& mutex) {
-        // bookkeeping
-        ++mutex.unlock_count;
-        ++wait_count;
-        ++mutex.lock_count;
-
-        if (wait_count > 100) { // 100 is an arbitrary choice
-            isc_throw(Unexpected,
-                      "too many cond wait count, likely a bug in test");
-        }
-
-        // make the delayed commands available
-        command_queue_->splice(command_queue_->end(), *delayed_command_queue_);
-    }
-    void signal() {
-        ++signal_count;
-    }
-    size_t wait_count; // number of calls to wait(); tests can check this
-    size_t signal_count; // number of calls to signal(); tests can check this
-private:
-    std::list<Command>* command_queue_;
-    std::list<Command>* delayed_command_queue_;
-};
-
-// Convenient shortcut
-typedef DataSrcClientsBuilderBase<TestMutex, TestCondVar>
-TestDataSrcClientsBuilder;
-
-// We specialize this command handler for the convenience of tests.
-// It abuses our specialized Mutex to count the number of calls of this method.
-template<>
-void
-TestDataSrcClientsBuilder::doNoop();
-
-// A specialization of DataSrcClientsBuilder that allows tests to inspect
-// its internal states via static class variables.  Using static is suboptimal,
-// but DataSrcClientsMgr is highly encapsulated, this seems to be the best
-// possible compromise.
-class FakeDataSrcClientsBuilder {
-public:
-    // true iff a builder has started.
-    static bool started;
-
-    // These five correspond to the resource shared with the manager.
-    // xxx_copy will be set in the manager's destructor to record the
-    // final state of the manager.
-    static std::list<Command>* command_queue;
-    static std::list<FinishedCallback>* callback_queue;
-    static TestCondVar* cond;
-    static TestMutex* queue_mutex;
-    static int wakeup_fd;
-    static isc::datasrc::ClientListMapPtr* clients_map;
-    static TestMutex* map_mutex;
-    static std::list<Command> command_queue_copy;
-    static std::list<FinishedCallback> callback_queue_copy;
-    static TestCondVar cond_copy;
-    static TestMutex queue_mutex_copy;
-
-    // true iff the manager waited on the thread running the builder.
-    static bool thread_waited;
-
-    // If set to true by a test, TestThread::wait() throws an exception
-    // exception.
-    enum ExceptionFromWait { NOTHROW, THROW_UNCAUGHT_EX, THROW_OTHER };
-    static ExceptionFromWait thread_throw_on_wait;
-
-    FakeDataSrcClientsBuilder(
-        std::list<Command>* command_queue,
-        std::list<FinishedCallback>* callback_queue,
-        TestCondVar* cond,
-        TestMutex* queue_mutex,
-        isc::datasrc::ClientListMapPtr* clients_map,
-        TestMutex* map_mutex, int wakeup_fd)
-    {
-        FakeDataSrcClientsBuilder::started = false;
-        FakeDataSrcClientsBuilder::command_queue = command_queue;
-        FakeDataSrcClientsBuilder::callback_queue = callback_queue;
-        FakeDataSrcClientsBuilder::cond = cond;
-        FakeDataSrcClientsBuilder::queue_mutex = queue_mutex;
-        FakeDataSrcClientsBuilder::wakeup_fd = wakeup_fd;
-        FakeDataSrcClientsBuilder::clients_map = clients_map;
-        FakeDataSrcClientsBuilder::map_mutex = map_mutex;
-        FakeDataSrcClientsBuilder::thread_waited = false;
-        FakeDataSrcClientsBuilder::thread_throw_on_wait = NOTHROW;
-    }
-    void run() {
-        FakeDataSrcClientsBuilder::started = true;
-    }
-};
-
-// A fake thread class that doesn't really invoke thread but simply calls
-// the given main function (synchronously).  Tests can tweak the wait()
-// behavior via some static variables so it will throw some exceptions.
-class TestThread {
-public:
-    TestThread(const boost::function<void()>& main) {
-        main();
-    }
-    void wait() {
-        FakeDataSrcClientsBuilder::thread_waited = true;
-        switch (FakeDataSrcClientsBuilder::thread_throw_on_wait) {
-        case FakeDataSrcClientsBuilder::NOTHROW:
-            break;
-        case FakeDataSrcClientsBuilder::THROW_UNCAUGHT_EX:
-            isc_throw(util::thread::Thread::UncaughtException,
-                      "TestThread wait() saw an exception");
-        case FakeDataSrcClientsBuilder::THROW_OTHER:
-            isc_throw(Unexpected,
-                      "General emulated failure in TestThread wait()");
-        }
-    }
-};
-} // namespace datasrc_clientmgr_internal
-
-// Convenient shortcut
-typedef DataSrcClientsMgrBase<
-    datasrc_clientmgr_internal::TestThread,
-    datasrc_clientmgr_internal::FakeDataSrcClientsBuilder,
-    datasrc_clientmgr_internal::TestMutex,
-    datasrc_clientmgr_internal::TestCondVar> TestDataSrcClientsMgrBase;
-
-// A specialization of manager's "cleanup" called at the end of the
-// destructor.  We use this to record the final values of some of the class
-// member variables.
-template<>
-void
-TestDataSrcClientsMgrBase::cleanup();
-
-template<>
-void
-TestDataSrcClientsMgrBase::reconfigureHook();
-
-// A (hackish) trick how to not require the IOService to be passed from the
-// tests. We can't create the io service as a member, because it would
-// get initialized too late.
-class TestDataSrcClientsMgr :
-    public asiolink::IOService,
-    public TestDataSrcClientsMgrBase {
-public:
-    TestDataSrcClientsMgr() :
-        TestDataSrcClientsMgrBase(*static_cast<asiolink::IOService*>(this))
-    {}
-};
-} // namespace auth
-} // namespace isc
-
-#endif  // TEST_DATASRC_CLIENTS_MGR_H
-
-// Local Variables:
-// mode: c++
-// End:

+ 0 - 18
src/bin/auth/tests/testdata/.gitignore

@@ -1,18 +0,0 @@
-/badExampleQuery_fromWire.wire
-/examplequery_fromWire.wire
-/iqueryresponse_fromWire.wire
-/multiquestion_fromWire.wire
-/queryBadEDNS_fromWire.wire
-/shortanswer_fromWire.wire
-/simplequery_fromWire.wire
-/simpleresponse_fromWire.wire
-/example-base.sqlite3
-/example-base.sqlite3.copied
-/example-base.zone
-/example-base.zone
-/example-common-inc.zone
-/example-nsec3-inc.zone
-/example-nsec3.sqlite3
-/example-nsec3.sqlite3.copied
-/example-nsec3.zone
-/example.zone

+ 0 - 32
src/bin/auth/tests/testdata/Makefile.am

@@ -1,32 +0,0 @@
-CLEANFILES = *.wire *.copied
-CLEANFILES += example-base.sqlite3 example-nsec3.sqlite3
-CLEANFILES += example-common-inc.zone
-
-BUILT_SOURCES = badExampleQuery_fromWire.wire examplequery_fromWire.wire
-BUILT_SOURCES += iqueryresponse_fromWire.wire multiquestion_fromWire.wire
-BUILT_SOURCES += queryBadEDNS_fromWire.wire shortanswer_fromWire.wire
-BUILT_SOURCES += simplequery_fromWire.wire simpleresponse_fromWire.wire
-
-# NOTE: keep this in sync with real file listing
-# so is included in tarball
-EXTRA_DIST = badExampleQuery_fromWire.spec
-EXTRA_DIST += examplequery_fromWire.spec
-EXTRA_DIST += iqueryresponse_fromWire.spec
-EXTRA_DIST += multiquestion_fromWire.spec
-EXTRA_DIST += queryBadEDNS_fromWire.spec
-EXTRA_DIST += shortanswer_fromWire.spec
-EXTRA_DIST += shortmessage_fromWire
-EXTRA_DIST += shortquestion_fromWire
-EXTRA_DIST += shortresponse_fromWire
-EXTRA_DIST += simplequery_fromWire.spec
-EXTRA_DIST += simpleresponse_fromWire.spec
-EXTRA_DIST += spec.spec
-
-EXTRA_DIST += example.com
-EXTRA_DIST += example.sqlite3
-
-EXTRA_DIST += example-base-inc.zone example-nsec3-inc.zone
-EXTRA_DIST += example-common-inc-template.zone
-
-.spec.wire:
-	$(PYTHON) $(top_builddir)/src/lib/util/python/gen_wiredata.py -o $@ $<

+ 0 - 10
src/bin/auth/tests/testdata/badExampleQuery_fromWire.spec

@@ -1,10 +0,0 @@
-#
-# A simple QUERY message for the example.com zone that would hit a broken
-# record of the data source.
-#
-
-[header]
-# use default
-[question]
-name: broken.example.com
-rrtype: AAAA

+ 0 - 241
src/bin/auth/tests/testdata/example-base-inc.zone

@@ -1,241 +0,0 @@
-;; This file defines a set of RRs commonly used in query tests in the
-;; form of standard master zone file.
-;;
-;; It's a sequence of the following pattern:
-;; ;var=<var_name>
-;; RR_1
-;; RR_2
-;; ..
-;; RR_n
-;;
-;; where var_name is a string that can be used as a variable name in a
-;; C/C++ source file or an empty string.  RR_x is a single-line
-;; textual representation of an arbitrary DNS RR.
-;;
-;; If var_name is non empty, the generator script will define a C
-;; variable of C-string type for that set of RRs so that it can be referred
-;; to in the test source file.
-;;
-;; Note that lines beginning ';var=' is no different from other
-;; comment lines as a zone file.  It has special meaning only for the
-;; generator script.  Obviously, real comment lines cannot begin with
-;; ';var=' (which should be less likely to happen in practice though).
-;;
-;; These RRs will be loaded into in-memory data source in that order.
-;; Note that it may impose stricter restriction on the order of RRs.
-;; In general, each RRset of the same name and type and its RRSIG (if
-;; any) is expected to be grouped.
-
-;var=soa_txt
-example.com. 3600 IN SOA . . 1 0 0 0 0
-;var=zone_ns_txt
-example.com. 3600 IN NS glue.delegation.example.com.
-example.com. 3600 IN NS noglue.example.com.
-example.com. 3600 IN NS example.net.
-
-;var=
-example.com. 3600 IN RRSIG SOA 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-example.com. 3600 IN RRSIG NS 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; Note: the position of the next RR is tricky.  It's placed here to
-;; be grouped with the subsequent A RR of the name.  But we also want
-;; to group the A RR with other RRs of a different owner name, so the RRSIG
-;; cannot be placed after the A RR.  The empty 'var=' specification is
-;; not necessary here, but in case we want to reorganize the ordering
-;; (in which case it's more likely to be needed), we keep it here.
-;var=
-noglue.example.com. 3600 IN RRSIG A 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;var=ns_addrs_txt
-noglue.example.com. 3600 IN A 192.0.2.53
-glue.delegation.example.com. 3600 IN A 192.0.2.153
-glue.delegation.example.com. 3600 IN AAAA 2001:db8::53
-
-;var=
-glue.delegation.example.com. 3600 IN RRSIG A 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-glue.delegation.example.com. 3600 IN RRSIG AAAA 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;var=delegation_txt
-delegation.example.com. 3600 IN NS glue.delegation.example.com.
-delegation.example.com. 3600 IN NS noglue.example.com.
-delegation.example.com. 3600 IN NS cname.example.com.
-delegation.example.com. 3600 IN NS example.org.
-
-;var=
-delegation.example.com. 3600 IN RRSIG DS 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; Borrowed from the RFC4035
-;var=delegation_ds_txt
-delegation.example.com. 3600 IN DS 57855 5 1 B6DCD485719ADCA18E5F3D48A2331627FDD3 636B
-;var=mx_txt
-mx.example.com. 3600 IN MX 10 www.example.com.
-mx.example.com. 3600 IN MX 20 mailer.example.org.
-mx.example.com. 3600 IN MX 30 mx.delegation.example.com.
-;var=www_a_txt
-www.example.com. 3600 IN A 192.0.2.80
-
-;var=
-www.example.com. 3600 IN RRSIG A 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;var=cname_txt
-cname.example.com. 3600 IN CNAME www.example.com.
-;var=cname_nxdom_txt
-cnamenxdom.example.com. 3600 IN CNAME nxdomain.example.com.
-;; CNAME Leading out of zone
-;var=cname_out_txt
-cnameout.example.com. 3600 IN CNAME www.example.org.
-;; The DNAME to do tests against
-;var=dname_txt
-dname.example.com. 3600 IN DNAME somethinglong.dnametarget.example.com.
-;; Some data at the dname node (allowed by RFC 2672)
-;var=dname_a_txt
-dname.example.com. 3600 IN A 192.0.2.5
-;; This is not inside the zone, this is created at runtime
-;; www.dname.example.com. 3600 IN CNAME www.somethinglong.dnametarget.example.com.
-;; The rest of data won't be referenced from the test cases.
-;var=other_zone_rrs
-cnamemailer.example.com. 3600 IN CNAME www.example.com.
-cnamemx.example.com. 3600 IN MX 10 cnamemailer.example.com.
-mx.delegation.example.com. 3600 IN A 192.0.2.100
-;; Wildcards
-;var=wild_txt
-*.wild.example.com. 3600 IN A 192.0.2.7
-;var=nsec_wild_txt
-*.wild.example.com. 3600 IN NSEC www.example.com. A NSEC RRSIG
-
-;var=
-*.wild.example.com. 3600 IN RRSIG A 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-*.wild.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;var=cnamewild_txt
-*.cnamewild.example.com. 3600 IN CNAME www.example.org.
-;var=nsec_cnamewild_txt
-*.cnamewild.example.com. 3600 IN NSEC delegation.example.com. CNAME NSEC RRSIG
-
-;var=
-*.cnamewild.example.com. 3600 IN RRSIG CNAME 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-*.cnamewild.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; Wildcard_nxrrset
-;var=wild_txt_nxrrset
-*.uwild.example.com. 3600 IN A 192.0.2.9
-;var=nsec_wild_txt_nxrrset
-*.uwild.example.com. 3600 IN NSEC www.uwild.example.com. A NSEC RRSIG
-;var=
-*.uwild.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-;var=wild_txt_next
-www.uwild.example.com. 3600 IN A 192.0.2.11
-;var=
-www.uwild.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-;var=nsec_wild_txt_next
-www.uwild.example.com. 3600 IN NSEC *.wild.example.com. A NSEC RRSIG
-;; Wildcard empty
-;var=empty_txt
-b.*.t.example.com. 3600 IN A 192.0.2.13
-;var=nsec_empty_txt
-b.*.t.example.com. 3600 IN NSEC *.uwild.example.com. A NSEC RRSIG
-
-;var=
-b.*.t.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;var=empty_prev_txt
-t.example.com. 3600 IN A 192.0.2.15
-;var=nsec_empty_prev_txt
-t.example.com. 3600 IN NSEC b.*.t.example.com. A NSEC RRSIG
-
-;var=
-t.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; Used in NXDOMAIN proof test.  We are going to test some unusual case where
-;; the best possible wildcard is below the "next domain" of the NSEC RR that
-;; proves the NXDOMAIN, i.e.,
-;; mx.example.com. (exist)
-;; !.no.example.com. (qname, NXDOMAIN)
-;; &.no.example.com. (exist)
-;; *.no.example.com. (best possible wildcard, not exist)
-;var=no_txt
-&.no.example.com. 3600 IN AAAA 2001:db8::53
-;; NSEC records.
-;var=nsec_apex_txt
-example.com. 3600 IN NSEC cname.example.com. NS SOA NSEC RRSIG
-;var=
-example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-;var=nsec_mx_txt
-mx.example.com. 3600 IN NSEC &.no.example.com. MX NSEC RRSIG
-
-;var=
-mx.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;var=nsec_no_txt
-&.no.example.com. 3600 IN NSEC nz.no.example.com. AAAA NSEC RRSIG
-
-;var=
-&.no.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; We'll also test the case where a single NSEC proves both NXDOMAIN and the
-;; non existence of wildcard.  The following records will be used for that
-;; test.
-;; &.no.example.com. (exist, whose NSEC proves everything)
-;; *.no.example.com. (best possible wildcard, not exist)
-;; nx.no.example.com. (NXDOMAIN)
-;; nz.no.example.com. (exist)
-;var=nz_txt
-nz.no.example.com. 3600 IN AAAA 2001:db8::5300
-;var=nsec_nz_txt
-nz.no.example.com. 3600 IN NSEC noglue.example.com. AAAA NSEC RRSIG
-;var=nsec_nxdomain_txt
-noglue.example.com. 3600 IN NSEC nonsec.example.com. A
-
-;var=
-noglue.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; NSEC for the normal NXRRSET case
-;var=nsec_www_txt
-www.example.com. 3600 IN NSEC example.com. A NSEC RRSIG
-
-;var=
-www.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; Authoritative data without NSEC
-;var=nonsec_a_txt
-nonsec.example.com. 3600 IN A 192.0.2.0
-
-;; (Secure) delegation data; Delegation with DS record
-;var=signed_delegation_txt
-signed-delegation.example.com. 3600 IN NS ns.example.net.
-;var=signed_delegation_ds_txt
-signed-delegation.example.com. 3600 IN DS 12345 8 2 764501411DE58E8618945054A3F620B36202E115D015A7773F4B78E0F952CECA
-
-;var=
-signed-delegation.example.com. 3600 IN RRSIG DS 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; (Secure) delegation data; Delegation without DS record (and both NSEC
-;; and NSEC3 denying its existence)
-;var=unsigned_delegation_txt
-unsigned-delegation.example.com. 3600 IN NS ns.example.net.
-;var=unsigned_delegation_nsec_txt
-unsigned-delegation.example.com. 3600 IN NSEC unsigned-delegation-optout.example.com. NS RRSIG NSEC
-
-;var=
-unsigned-delegation.example.com. 3600 IN RRSIG NSEC 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-
-;; Delegation without DS record, and no direct matching NSEC3 record
-;var=unsigned_delegation_optout_txt
-unsigned-delegation-optout.example.com. 3600 IN NS ns.example.net.
-;var=unsigned_delegation_optout_nsec_txt
-unsigned-delegation-optout.example.com. 3600 IN NSEC *.uwild.example.com. NS RRSIG NSEC
-
-;; (Secure) delegation data; Delegation where the DS lookup will raise an
-;; exception.
-;var=bad_delegation_txt
-bad-delegation.example.com. 3600 IN NS ns.example.net.
-
-;; Delegation from an unsigned parent.  There's no DS, and there's no NSEC
-;; or NSEC3 that proves it.
-;var=nosec_delegation_txt
-nosec-delegation.example.com. 3600 IN NS ns.nosec.example.net.
-
-;; Setup for emulating insecure delegation that contain an empty name.
-;; the delegation itself isn't expected to be used directly in tests.
-;var=
-delegation.empty.example.com. 3600 IN NS ns.delegation.empty.example

+ 0 - 7
src/bin/auth/tests/testdata/example-base.zone.in

@@ -1,7 +0,0 @@
-;;
-;; This is a complete (but crafted and somewhat broken) zone file used
-;; in query tests.
-;;
-
-$INCLUDE @abs_srcdir@/example-base-inc.zone
-$INCLUDE @abs_builddir@/example-common-inc.zone

+ 0 - 5
src/bin/auth/tests/testdata/example-common-inc-template.zone

@@ -1,5 +0,0 @@
-;;
-;; This is an initial template of part of test zone file used in query test
-;; and expected to be included from other zone files.  This is
-;; intentionally kept empty.
-;;

+ 0 - 16
src/bin/auth/tests/testdata/example-nsec3-inc.zone

@@ -1,16 +0,0 @@
-;; See example-base-inc.zone for general notes.
-
-;; NSEC3PARAM.  This is needed for database-based data source to
-;; signal the zone is NSEC3-signed
-;var=
-example.com. 3600 IN NSEC3PARAM 1 1 12 aabbccdd
-
-;; NSEC3 RRs.  You may also need to add mapping to MockZoneFinder::hash_map_.
-;var=nsec3_apex_txt
-0p9mhaveqvm6t7vbl5lop2u3t2rp3tom.example.com. 3600 IN NSEC3 1 1 12 aabbccdd 2t7b4g4vsa5smi47k61mv5bv1a22bojr NS SOA NSEC3PARAM RRSIG
-;var=nsec3_apex_rrsig_txt
-0p9mhaveqvm6t7vbl5lop2u3t2rp3tom.example.com. 3600 IN RRSIG NSEC3 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE
-;var=nsec3_www_txt
-q04jkcevqvmu85r014c7dkba38o0ji5r.example.com. 3600 IN NSEC3 1 1 12 aabbccdd r53bq7cc2uvmubfu5ocmm6pers9tk9en A RRSIG
-;var=nsec3_www_rrsig_txt
-q04jkcevqvmu85r014c7dkba38o0ji5r.example.com. 3600 IN RRSIG NSEC3 5 3 3600 20000101000000 20000201000000 12345 example.com. FAKEFAKEFAKE

+ 0 - 8
src/bin/auth/tests/testdata/example-nsec3.zone.in

@@ -1,8 +0,0 @@
-;;
-;; This is a complete (but crafted and somewhat broken) zone file used
-;; in query tests including NSEC3 records, making the zone is "NSEC3 signed".
-;;
-
-$INCLUDE @abs_srcdir@/example-base-inc.zone
-$INCLUDE @abs_srcdir@/example-nsec3-inc.zone
-$INCLUDE @abs_builddir@/example-common-inc.zone

+ 0 - 8
src/bin/auth/tests/testdata/example.com

@@ -1,8 +0,0 @@
-$TTL 3600
-@    SOA ns.example.com. admin.example.com. 1234 3600 1800 2419200 7200
-        	NS ns.example.com.
-ns.example.com.	A 192.0.2.1
-
-;; bogus RDATA for CNAME RR, but the loadzone tool accepts it.  looking up this
-;; record will trigger an exception.
-broken.example.com. CNAME 0123456789012345678901234567890123456789012345678901234567890123456789.example.com.

BIN
src/bin/auth/tests/testdata/example.sqlite3


+ 0 - 6
src/bin/auth/tests/testdata/example.zone.in

@@ -1,6 +0,0 @@
-;;
-;; This is a complete (but crafted and somewhat broken) zone file used
-;; in query tests, excluding NSEC3 records.
-;;
-
-$INCLUDE @abs_builddir@/example-base.zone

+ 0 - 9
src/bin/auth/tests/testdata/examplequery_fromWire.spec

@@ -1,9 +0,0 @@
-#
-# A simple QUERY message for the example.com zone
-#
-
-[header]
-# use default
-[question]
-# use default
-name: ns.example.com

+ 0 - 9
src/bin/auth/tests/testdata/iqueryresponse_fromWire.spec

@@ -1,9 +0,0 @@
-#
-# A response to an IQUERY request.
-#
-
-[header]
-qr: response
-opcode: iquery
-[question]
-# use default

+ 0 - 12
src/bin/auth/tests/testdata/multiquestion_fromWire.spec

@@ -1,12 +0,0 @@
-#
-# A QUERY message with multiple questions.
-#
-
-[custom]
-sections: header:question/0:question/1
-[header]
-qdcount: 2
-[question/0]
-# use default
-[question/1]
-rrtype: AAAA 

+ 0 - 12
src/bin/auth/tests/testdata/queryBadEDNS_fromWire.spec

@@ -1,12 +0,0 @@
-#
-# A QUERY message with unsupported version of EDNS.
-#
-
-[header]
-arcount: 1
-# use default
-[question]
-# use default
-[edns]
-version: 1
-do: 1

+ 0 - 10
src/bin/auth/tests/testdata/shortanswer_fromWire.spec

@@ -1,10 +0,0 @@
-#
-# A QUERY message with a broken answer section (ancount > 0 but the section
-# is empty)
-#
-
-[header]
-# use default
-arcount: 1
-[question]
-# use default

+ 0 - 9
src/bin/auth/tests/testdata/shortmessage_fromWire

@@ -1,9 +0,0 @@
-###
-### DNS message-like data but doesn't contain sufficient length of data.
-###
-
-# Header Section
-# ID=4149 QR=Query Opcode=QUERY(0) Rcode=NOERROR(0)
-1035 0000
-# QDCNT=1, ANCNT=0, NSCNT=0, (ARCNT is missing)
-0001 0000 0000

+ 0 - 13
src/bin/auth/tests/testdata/shortquestion_fromWire

@@ -1,13 +0,0 @@
-###
-### A query-like data, but missing QCLASS field in the Question section.
-###
-
-# Header Section
-# ID=4149 QR=Query Opcode=QUERY(0) Rcode=NOERROR(0)
-1035 0000
-# QDCNT=1, ANCNT=0, NSCNT=0, ARCNT=0
-0001 0000 0000 0000
-
-# Question Section
-# QNAME=example.com. QTYPE=A(1) (QCLASS missing)
-076578616d706c6503636f6d00 0001

+ 0 - 13
src/bin/auth/tests/testdata/shortresponse_fromWire

@@ -1,13 +0,0 @@
-###
-### A response-like data, but missing QCLASS field in the Question section.
-###
-
-# Header Section
-# ID=4149 QR=Response Opcode=QUERY(0) Rcode=NOERROR(0)
-1035 8000
-# QDCNT=1, ANCNT=0, NSCNT=0, ARCNT=0
-0001 0000 0000 0000
-
-# Question Section
-# QNAME=example.com. QTYPE=A(1) (QCLASS is missing)
-076578616d706c6503636f6d00 0001

+ 0 - 8
src/bin/auth/tests/testdata/simplequery_fromWire.spec

@@ -1,8 +0,0 @@
-#
-# A simple QUERY message.
-#
-
-[header]
-# use default
-[question]
-# use default

+ 0 - 8
src/bin/auth/tests/testdata/simpleresponse_fromWire.spec

@@ -1,8 +0,0 @@
-#
-# A simple response message.
-#
-
-[header]
-qr: response
-[question]
-# use default

+ 0 - 5
src/bin/auth/tests/testdata/spec.spec

@@ -1,5 +0,0 @@
-{
-    "module_spec": {
-        "module_name": "test"
-    }
-}

+ 0 - 7
src/bin/cfgmgr/plugins/Makefile.am

@@ -14,12 +14,5 @@ pythondir = $(config_plugindir)
 CLEANFILES = b10logging.pyc tsig_keys.pyc datasrc.spec
 CLEANDIRS = __pycache__
 
-if WANT_DNS
-
-config_plugin_DATA += datasrc.spec
-python_PYTHON += datasrc_config_plugin.py
-
-endif
-
 clean-local:
 	rm -rf $(CLEANDIRS)

+ 0 - 8
src/bin/cfgmgr/plugins/tests/Makefile.am

@@ -1,14 +1,6 @@
 PYCOVERAGE_RUN = @PYCOVERAGE_RUN@
 PYTESTS = tsig_keys_test.py logging_test.py
 
-if WANT_DNS
-
-PYTESTS += datasrc_test.py
-
-endif
-
-
-
 EXTRA_DIST = $(PYTESTS)
 
 # If necessary (rare cases), explicitly specify paths to dynamic libraries

+ 0 - 4
src/bin/dbutil/.gitignore

@@ -1,4 +0,0 @@
-/b10-dbutil
-/dbutil.py
-/run_dbutil.sh
-/b10-dbutil.8

+ 0 - 46
src/bin/dbutil/Makefile.am

@@ -1,46 +0,0 @@
-SUBDIRS = . tests
-
-bin_SCRIPTS = b10-dbutil
-man_MANS = b10-dbutil.8
-
-nodist_pylogmessage_PYTHON = $(PYTHON_LOGMSGPKG_DIR)/work/dbutil_messages.py
-pylogmessagedir = $(pyexecdir)/isc/log_messages/
-
-EXTRA_DIST = $(man_MANS) b10-dbutil.xml dbutil_messages.mes
-
-noinst_SCRIPTS = run_dbutil.sh
-
-CLEANFILES = b10-dbutil b10-dbutil.pyc
-CLEANFILES += $(PYTHON_LOGMSGPKG_DIR)/work/dbutil_messages.py
-CLEANFILES += $(PYTHON_LOGMSGPKG_DIR)/work/dbutil_messages.pyc
-CLEANFILES += $(PYTHON_LOGMSGPKG_DIR)/work/dbutil_messages.pyo
-DISTCLEANFILES = $(man_MANS)
-
-if GENERATE_DOCS
-
-b10-dbutil.8: b10-dbutil.xml
-	@XSLTPROC@ --novalid --xinclude --nonet -o $@ http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl $(srcdir)/b10-dbutil.xml
-
-else
-
-$(man_MANS):
-	@echo Man generation disabled.  Creating dummy $@.  Configure with --enable-generate-docs to enable it.
-	@echo Man generation disabled.  Remove this file, configure with --enable-generate-docs, and rebuild BIND 10 > $@
-
-endif
-
-# Define rule to build logging source files from message file
-$(PYTHON_LOGMSGPKG_DIR)/work/dbutil_messages.py : dbutil_messages.mes
-	$(top_builddir)/src/lib/log/compiler/message \
-	-d $(PYTHON_LOGMSGPKG_DIR)/work -p $(srcdir)/dbutil_messages.mes
-
-b10-dbutil: dbutil.py $(PYTHON_LOGMSGPKG_DIR)/work/dbutil_messages.py
-	$(SED) -e "s|@@PYTHONPATH@@|@pyexecdir@|" \
-	       -e "s|@@SYSCONFDIR@@|@sysconfdir@|" \
-	       -e "s|@@LIBEXECDIR@@|$(pkglibexecdir)|" dbutil.py >$@
-	chmod a+x $@
-
-CLEANDIRS = __pycache__
-
-clean-local:
-	rm -rf $(CLEANDIRS)

+ 0 - 196
src/bin/dbutil/b10-dbutil.xml

@@ -1,196 +0,0 @@
-<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
-               "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
-	       [<!ENTITY mdash "&#8212;">]>
-<!--
- - Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
- -
- - Permission to use, copy, modify, and/or distribute this software for any
- - purpose with or without fee is hereby granted, provided that the above
- - copyright notice and this permission notice appear in all copies.
- -
- - THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
- - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- - AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
- - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
- - OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- - PERFORMANCE OF THIS SOFTWARE.
--->
-
-<refentry>
-
-  <refentryinfo>
-    <date>June 20, 2012</date>
-  </refentryinfo>
-
-  <refmeta>
-    <refentrytitle>b10-dbutil</refentrytitle>
-    <manvolnum>8</manvolnum>
-    <refmiscinfo>BIND10</refmiscinfo>
-  </refmeta>
-
-  <refnamediv>
-    <refname>b10-dbutil</refname>
-    <refpurpose>Zone Database Maintenance Utility</refpurpose>
-  </refnamediv>
-
-  <docinfo>
-    <copyright>
-      <year>2012</year>
-      <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
-    </copyright>
-  </docinfo>
-
-  <refsynopsisdiv>
-    <cmdsynopsis>
-      <command>b10-dbutil --check</command>
-        <arg>--verbose</arg>
-        <arg>--quiet</arg>
-        <arg><replaceable choice='req'>dbfile</replaceable></arg>
-    </cmdsynopsis>
-    <cmdsynopsis>
-      <command>b10-dbutil --upgrade</command>
-        <arg>--noconfirm</arg>
-        <arg>--verbose</arg>
-        <arg>--quiet</arg>
-        <arg><replaceable choice='req'>dbfile</replaceable></arg>
-    </cmdsynopsis>
-  </refsynopsisdiv>
-
-  <refsect1>
-    <title>DESCRIPTION</title>
-    <para>
-      The <command>b10-dbutil</command> utility is a general
-      administration utility for SQL databases for BIND 10. (Currently
-      only SQLite is supported by BIND 10.)  It can report the
-      current verion of the schema, and upgrade an existing database
-      to the latest version of the schema.
-    </para>
-
-    <para>
-      <command>b10-dbutil</command> operates in one of two modes: check mode
-      or upgrade mode.
-    </para>
-
-    <para>
-      In check mode (<command>b10-dbutil --check</command>), the
-      utility reads the version of the database schema from the database
-      and prints it.  It will tell you whether the schema is at the latest
-      version supported by BIND 10. Exit status is 0 if the schema is at
-      the correct version, 1 if the schema is at an older version, or 2 if
-      the schema is at a version not yet supported by this version of
-      <command>b10-dbutil</command>.
-      Any higher value indicates an error during command-line
-      parsing or execution.
-    </para>
-
-    <para>
-      When the upgrade function is selected
-      (<command>b10-dbutil --upgrade</command>), the
-      utility takes a copy of the database, then upgrades it to the latest
-      version of the schema.  The contents of the database remain intact.
-      (The backup file is a file in the same directory as the database
-      file.  It has the same name, with ".backup" appended to it.  If a
-      file of that name already exists, the file will have the suffix
-      ".backup-1".  If that exists, the file will be suffixed ".backup-2",
-      and so on). Exit status is 0 if the upgrade is either successful or
-      aborted by the user, and non-zero if there is an error.
-    </para>
-
-    <para>
-    When upgrading the database, it is <emphasis>strongly</emphasis>
-    recommended that BIND 10 not be running while the upgrade is in
-    progress.
-    </para>
-
-  </refsect1>
-
-  <refsect1>
-    <title>ARGUMENTS</title>
-
-    <para>The arguments are as follows:</para>
-
-    <variablelist>
-      <varlistentry>
-        <term>
-         <option>--check</option>
-        </term>
-        <listitem>
-          <para>Selects the version check function, which reports the
-          current version of the database.  This is mutually exclusive
-          with the <option>--upgrade</option> option.
-          </para>
-        </listitem>
-      </varlistentry>
-
-      <varlistentry>
-        <term>
-         <option>--noconfirm</option>
-        </term>
-        <listitem>
-          <para>Only valid with <option>--upgrade</option>, this disables
-          the prompt.
-          Normally the utility will print a warning that an upgrade is
-          about to take place and request that you type "Yes" to continue.
-          If this switch is given on the command line, no prompt will
-          be issued and the utility will just perform the upgrade.
-          </para>
-        </listitem>
-      </varlistentry>
-
-      <varlistentry>
-        <term>
-         <option>--upgrade</option>
-        </term>
-        <listitem>
-          <para>Selects the upgrade function, which upgrades the database
-          to the latest version of the schema.  This is mutually exclusive
-          with the <option>--check</option> option.
-          </para>
-          <para>
-          The upgrade function will upgrade a BIND 10 database &mdash;
-          no matter how old the schema &mdash; preserving all data.
-	  A backup file is created before the upgrade (with the
-	  same name as the database, but with ".backup" suffixed
-	  to it).  If the upgrade fails, this file can be copied
-	  back to restore the original database.
-          </para>
-        </listitem>
-      </varlistentry>
-
-      <varlistentry>
-        <term>
-         <option>--verbose</option>
-        </term>
-        <listitem>
-          <para>Enable verbose mode.  Each SQL command issued by the
-          utility will be printed to STDERR before it is executed.</para>
-        </listitem>
-      </varlistentry>
-
-      <varlistentry>
-        <term>
-         <option>--quiet</option>
-        </term>
-        <listitem>
-          <para>Enable quiet mode. No output is printed, except errors during
-            command-line argument parsing, or the user confirmation dialog.
-          </para>
-        </listitem>
-      </varlistentry>
-
-      <varlistentry>
-        <term>
-        <option><replaceable choice='req'>dbfile</replaceable></option>
-        </term>
-        <listitem>
-          <para>
-          Name of the database file to check or upgrade.
-          </para>
-        </listitem>
-      </varlistentry>
-
-
-    </variablelist>
-  </refsect1>
-</refentry>

+ 0 - 627
src/bin/dbutil/dbutil.py.in

@@ -1,627 +0,0 @@
-#!@PYTHON@
-
-# Copyright (C) 2012  Internet Systems Consortium.
-#
-# Permission to use, copy, modify, and distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
-# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
-# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
-# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
-# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-"""
-@file Database Utilities
-
-This file holds the "dbutil" program, a general utility program for doing
-management of the BIND 10 database.  There are two modes of operation:
-
-      b10-dbutil --check [--verbose] database
-      b10-dbutil --upgrade [--noconfirm] [--verbose] database
-
-The first form checks the version of the given database.  The second form
-upgrades the database to the latest version of the schema, omitting the
-warning prompt if --noconfirm is given.
-
-For maximum safety, prior to the upgrade a backup database is created.
-The is the database name with ".backup" appended to it (or ".backup-n" if
-".backup" already exists).  This is used to restore the database if the
-upgrade fails.
-"""
-
-# Exit codes
-# These are defined here because one of them is already used before most
-# of the import statements.
-EXIT_SUCCESS = 0
-EXIT_NEED_UPDATE = 1
-EXIT_VERSION_TOO_HIGH = 2
-EXIT_COMMAND_ERROR = 3
-EXIT_READ_ERROR = 4
-EXIT_UPGRADE_ERROR = 5
-EXIT_UNCAUGHT_EXCEPTION = 6
-
-import sys; sys.path.append("@@PYTHONPATH@@")
-
-# Normally, python exits with a status code of 1 on uncaught exceptions
-# Since we reserve exit status 1 for 'database needs upgrade', we
-# override the excepthook to exit with a different status
-def my_except_hook(a, b, c):
-    sys.__excepthook__(a,b,c)
-    sys.exit(EXIT_UNCAUGHT_EXCEPTION)
-sys.excepthook = my_except_hook
-
-import os, sqlite3, shutil
-from optparse import OptionParser
-import isc.util.process
-import isc.util.traceback_handler
-import isc.log
-from isc.log_messages.dbutil_messages import *
-
-isc.log.init("b10-dbutil")
-logger = isc.log.Logger("dbutil")
-isc.util.process.rename()
-
-TRACE_BASIC = logger.DBGLVL_TRACE_BASIC
-
-
-# @brief Version String
-# This is the version displayed to the user.  It comprises the module name,
-# the module version number, and the overall BIND 10 version number (set in
-# configure.ac)
-VERSION = "b10-dbutil 20120319 (BIND 10 @PACKAGE_VERSION@)"
-
-# @brief Statements to Update the Database
-# These are in the form of a list of dictionaries, each of which contains the
-# information to perform an incremental upgrade from one version of the
-# database to the next.  The information is:
-#
-# a) from: (major, minor) version that the database is expected to be at
-#    to perform this upgrade.
-# b) to: (major, minor) version of the database to which this set of statements
-#    upgrades the database to.  (This is used for documentation purposes,
-#    and to update the schema_version table when the upgrade is complete.)
-# c) statements: List of SQL statments to perform the upgrade.
-#
-# The incremental upgrades are performed one after the other.  If the version
-# of the database does not exactly match that required for the incremental
-# upgrade, the upgrade is skipped.  For this reason, the list must be in
-# ascending order (e.g. upgrade 1.0 to 2.0, 2.0 to 2.1, 2.1 to 2.2 etc.).
-#
-# Note that apart from the 1.0 to 2.0 upgrade, no upgrade need alter the
-# schema_version table: that is done by the upgrade process using the
-# information in the "to" field.
-UPGRADES = [
-    {'from': (1, 0), 'to': (2, 0),
-        'statements': [
-
-            # Move to the latest "V1" state of the database if not there
-            # already.
-            "CREATE TABLE IF NOT EXISTS diffs (" +
-                "id INTEGER PRIMARY KEY, " +
-                "zone_id INTEGER NOT NULL," +
-                "version INTEGER NOT NULL, " +
-                "operation INTEGER NOT NULL, " +
-                "name STRING NOT NULL COLLATE NOCASE, " +
-                "rrtype STRING NOT NULL COLLATE NOCASE, " +
-                "ttl INTEGER NOT NULL, " +
-                "rdata STRING NOT NULL)",
-
-            # Within SQLite with can only rename tables and add columns; we
-            # can't drop columns nor can we alter column characteristics.
-            # So the strategy is to rename the table, create the new table,
-            # then copy all data across.  This means creating new indexes
-            # as well; these are created after the data has been copied.
-
-            # zones table
-            "DROP INDEX zones_byname",
-            "ALTER TABLE zones RENAME TO old_zones",
-            "CREATE TABLE zones (" +
-                "id INTEGER PRIMARY KEY, " +
-                "name TEXT NOT NULL COLLATE NOCASE, " +
-                "rdclass TEXT NOT NULL COLLATE NOCASE DEFAULT 'IN', " +
-                "dnssec BOOLEAN NOT NULL DEFAULT 0)",
-            "INSERT INTO ZONES " +
-                "SELECT id, name, rdclass, dnssec FROM old_zones",
-            "CREATE INDEX zones_byname ON zones (name)",
-            "DROP TABLE old_zones",
-
-            # records table
-            "DROP INDEX records_byname",
-            "DROP INDEX records_byrname",
-            "ALTER TABLE records RENAME TO old_records",
-            "CREATE TABLE records (" +
-                "id INTEGER PRIMARY KEY, " +
-                "zone_id INTEGER NOT NULL, " +
-                "name TEXT NOT NULL COLLATE NOCASE, " +
-                "rname TEXT NOT NULL COLLATE NOCASE, " +
-                "ttl INTEGER NOT NULL, " +
-                "rdtype TEXT NOT NULL COLLATE NOCASE, " +
-                "sigtype TEXT COLLATE NOCASE, " +
-                "rdata TEXT NOT NULL)",
-            "INSERT INTO records " +
-                "SELECT id, zone_id, name, rname, ttl, rdtype, sigtype, " +
-                    "rdata FROM old_records",
-            "CREATE INDEX records_byname ON records (name)",
-            "CREATE INDEX records_byrname ON records (rname)",
-            "CREATE INDEX records_bytype_and_rname ON records (rdtype, rname)",
-            "DROP TABLE old_records",
-
-            # nsec3 table
-            "DROP INDEX nsec3_byhash",
-            "ALTER TABLE nsec3 RENAME TO old_nsec3",
-            "CREATE TABLE nsec3 (" +
-                "id INTEGER PRIMARY KEY, " +
-                "zone_id INTEGER NOT NULL, " +
-                "hash TEXT NOT NULL COLLATE NOCASE, " +
-                "owner TEXT NOT NULL COLLATE NOCASE, " +
-                "ttl INTEGER NOT NULL, " +
-                "rdtype TEXT NOT NULL COLLATE NOCASE, " +
-                "rdata TEXT NOT NULL)",
-            "INSERT INTO nsec3 " +
-                "SELECT id, zone_id, hash, owner, ttl, rdtype, rdata " +
-                    "FROM old_nsec3",
-            "CREATE INDEX nsec3_byhash ON nsec3 (hash)",
-            "DROP TABLE old_nsec3",
-
-            # diffs table
-            "ALTER TABLE diffs RENAME TO old_diffs",
-            "CREATE TABLE diffs (" +
-                "id INTEGER PRIMARY KEY, " +
-                "zone_id INTEGER NOT NULL, " +
-                "version INTEGER NOT NULL, " +
-                "operation INTEGER NOT NULL, " +
-                "name TEXT NOT NULL COLLATE NOCASE, " +
-                "rrtype TEXT NOT NULL COLLATE NOCASE, " +
-                "ttl INTEGER NOT NULL, " +
-                "rdata TEXT NOT NULL)",
-            "INSERT INTO diffs " +
-                "SELECT id, zone_id, version, operation, name, rrtype, " +
-                    "ttl, rdata FROM old_diffs",
-            "DROP TABLE old_diffs",
-
-            # Schema table.  This is updated to include a second column for
-            # future changes.  The idea is that if a version of BIND 10 is
-            # written for schema M.N, it should be able to work for all
-            # versions of N; if not, M must be incremented.
-            #
-            # For backwards compatibility, the column holding the major
-            # version number is left named "version".
-            "ALTER TABLE schema_version " +
-                "ADD COLUMN minor INTEGER NOT NULL DEFAULT 0"
-        ]
-     },
-
-    {'from': (2, 0), 'to': (2, 1),
-     'statements': [
-            "CREATE INDEX nsec3_byhash_and_rdtype ON nsec3 " +
-                "(hash, rdtype)"
-        ]
-    },
-
-    {'from': (2, 1), 'to': (2, 2),
-        'statements': [
-            "CREATE INDEX records_byrname_and_rdtype ON records (rname, rdtype)"
-        ]
-    }
-
-# To extend this, leave the above statements in place and add another
-# dictionary to the list.  The "from" version should be (2, 2), the "to"
-# version whatever the version the update is to, and the SQL statements are
-# the statements required to perform the upgrade.  This way, the upgrade
-# program will be able to upgrade both a V1.0 and a V2.0 database.
-]
-
-class DbutilException(Exception):
-    """
-    @brief Exception class to indicate error exit
-    """
-    pass
-
-class Database:
-    """
-    @brief Database Encapsulation
-
-    Encapsulates the SQL database, both the connection and the cursor.  The
-    methods will cause a program exit on any error.
-    """
-    def __init__(self, db_file):
-        """
-        @brief Constructor
-
-        @param db_file Name of the database file
-        """
-        self.connection = None
-        self.cursor = None
-        self.db_file = db_file
-        self.backup_file = None
-
-    def open(self):
-        """
-        @brief Open Database
-
-        Opens the passed file as an sqlite3 database and stores a connection
-        and a cursor.
-        """
-        if not os.path.exists(self.db_file):
-            raise DbutilException("database " + self.db_file +
-                                 " does not exist");
-
-        try:
-            self.connection = sqlite3.connect(self.db_file)
-            self.connection.isolation_level = None  # set autocommit
-            self.cursor = self.connection.cursor()
-        except sqlite3.OperationalError as ex:
-            raise DbutilException("unable to open " + self.db_file +
-                                  " - " + str(ex))
-
-    def close(self):
-        """
-        @brief Closes the database
-        """
-        if self.connection is not None:
-            self.connection.close()
-
-    def execute(self, statement):
-        """
-        @brief Execute Statement
-
-        Executes the given statement, exiting the program on error.
-
-        @param statement SQL statement to execute
-        """
-        logger.debug(TRACE_BASIC, DBUTIL_EXECUTE, statement)
-
-        try:
-            self.cursor.execute(statement)
-        except Exception as ex:
-            logger.error(DBUTIL_STATEMENT_ERROR, statement, ex)
-            raise DbutilException(str(ex))
-
-    def result(self):
-        """
-        @brief Return result of last execute
-
-        Returns a single row that is the result of the last "execute".
-        """
-        return self.cursor.fetchone()
-
-    def backup(self):
-        """
-        @brief Backup Database
-
-        Attempts to copy the given database file to a backup database, the
-        backup database file being the file name with ".backup" appended.
-        If the ".backup" file exists, a new name is constructed by appending
-        ".backup-n" (n starting at 1) and the action repeated until an
-        unused filename is found.
-
-        @param db_file Database file to backup
-        """
-        if not os.path.exists(self.db_file):
-            raise DbutilException("database " + self.db_file +
-                                  " does not exist");
-
-        self.backup_file = self.db_file + ".backup"
-        count = 0
-        while os.path.exists(self.backup_file):
-            count = count + 1
-            self.backup_file = self.db_file + ".backup-" + str(count)
-
-        # Do the backup
-        shutil.copyfile(self.db_file, self.backup_file)
-        logger.info(DBUTIL_BACKUP, self.db_file, self.backup_file)
-
-def prompt_user():
-    """
-    @brief Prompt the User
-
-    Explains about the upgrade and requests authorisation to continue.
-
-    @return True if user entered 'Yes', False if 'No'
-    """
-    sys.stdout.write(
-"""You have selected the upgrade option.  This will upgrade the schema of the
-selected BIND 10 zone database to the latest version.
-
-The utility will take a copy of the zone database file before executing so, in
-the event of a problem, you will be able to restore the zone database from
-the backup.  To ensure that the integrity of this backup, please ensure that
-BIND 10 is not running before continuing.
-""")
-    yes_entered = False
-    no_entered = False
-    while (not yes_entered) and (not no_entered):
-        sys.stdout.write("Enter 'Yes' to proceed with the upgrade, " +
-                         "'No' to exit the program: \n")
-        response = sys.stdin.readline()
-        if response.lower() == "yes\n":
-            yes_entered = True
-        elif response.lower() == "no\n":
-            no_entered = True
-        else:
-            sys.stdout.write("Please enter 'Yes' or 'No'\n")
-
-    return yes_entered
-
-
-def version_string(version):
-    """
-    @brief Format Database Version
-
-    Converts a (major, minor) tuple into a 'Vn.m' string.
-
-    @param version Version tuple to convert
-
-    @return Version string
-    """
-    return "V" + str(version[0]) + "." + str(version[1])
-
-
-def compare_versions(first, second):
-    """
-    @brief Compare Versions
-
-    Compares two database version numbers.
-
-    @param first First version number to check (in the form of a
-           "(major, minor)" tuple).
-    @param second Second version number to check (in the form of a
-           "(major, minor)" tuple).
-
-    @return -1, 0, +1 if "first" is <, ==, > "second"
-    """
-    if first == second:
-        return 0
-
-    elif ((first[0] < second[0]) or
-          ((first[0] == second[0]) and (first[1] < second[1]))):
-        return -1
-
-    else:
-        return 1
-
-
-def get_latest_version():
-    """
-    @brief Returns the version to which this utility can upgrade the database
-
-    This is the 'to' version held in the last element of the upgrades list
-    """
-    return UPGRADES[-1]['to']
-
-
-def get_version(db):
-    """
-    @brief Return version of database
-
-    @return Version of database in form (major version, minor version)
-    """
-
-    # Get the version information.
-    db.execute("SELECT * FROM schema_version")
-    result = db.result()
-    if result is None:
-        raise DbutilException("nothing in schema_version table")
-
-    major = result[0]
-    if (major == 1):
-        # If the version number is 1, there will be no "minor" column, so
-        # assume a minor version number of 0.
-        minor = 0
-    else:
-        minor = result[1]
-
-    result = db.result()
-    if result is not None:
-        raise DbutilException("too many rows in schema_version table")
-
-    return (major, minor)
-
-
-def check_version(db):
-    """
-    @brief Check the version
-
-    Checks the version of the database and the latest version, and advises if
-    an upgrade is needed.
-
-    @param db Database object
-
-    returns 0 if the database is up to date
-    returns EXIT_NEED_UPDATE if the database needs updating
-    returns EXIT_VERSION_TOO_HIGH if the database is at a later version
-            than this program knows about
-    These return values are intended to be passed on to sys.exit.
-    """
-    current = get_version(db)
-    latest = get_latest_version()
-
-    match = compare_versions(current, latest)
-    if match == 0:
-        logger.info(DBUTIL_VERSION_CURRENT, version_string(current))
-        logger.info(DBUTIL_CHECK_OK)
-        return EXIT_SUCCESS
-    elif match < 0:
-        logger.info(DBUTIL_VERSION_LOW, version_string(current),
-                    version_string(latest))
-        logger.info(DBUTIL_CHECK_UPGRADE_NEEDED)
-        return EXIT_NEED_UPDATE
-    else:
-        logger.warn(DBUTIL_VERSION_HIGH, version_string(current),
-                    version_string(get_latest_version()))
-        logger.info(DBUTIL_UPGRADE_DBUTIL)
-        return EXIT_VERSION_TOO_HIGH
-
-def perform_upgrade(db, upgrade):
-    """
-    @brief Perform upgrade
-
-    Performs the upgrade.  At the end of the upgrade, updates the schema_version
-    table with the expected version.
-
-    @param db Database object
-    @param upgrade Upgrade dictionary, holding "from", "to" and "statements".
-    """
-    logger.info(DBUTIL_UPGRADING, version_string(upgrade['from']),
-         version_string(upgrade['to']))
-    for statement in upgrade['statements']:
-        db.execute(statement)
-
-    # Update the version information
-    db.execute("DELETE FROM schema_version")
-    db.execute("INSERT INTO schema_version VALUES (" +
-                    str(upgrade['to'][0]) + "," + str(upgrade['to'][1]) + ")")
-
-
-def perform_all_upgrades(db):
-    """
-    @brief Performs all the upgrades
-
-    @brief db Database object
-
-    For each upgrade, checks that the database is at the expected version.
-    If so, calls perform_upgrade to update the database.
-    """
-    match = compare_versions(get_version(db), get_latest_version())
-    if match == 0:
-        logger.info(DBUTIL_UPGRADE_NOT_NEEDED)
-
-    elif match > 0:
-        logger.warn(DBUTIL_UPGRADE_NOT_POSSIBLE)
-
-    else:
-        # Work our way through all upgrade increments
-        count = 0
-        for upgrade in UPGRADES:
-            if compare_versions(get_version(db), upgrade['from']) == 0:
-                perform_upgrade(db, upgrade)
-                count = count + 1
-
-        if count > 0:
-            logger.info(DBUTIL_UPGRADE_SUCCESFUL)
-        else:
-            # Should not get here, as we established earlier that the database
-            # was not at the latest version so we should have upgraded.
-            raise DbutilException("internal error in upgrade tool - no " +
-                                  "upgrade was performed on an old version " +
-                                  "the database")
-
-
-def parse_command():
-    """
-    @brief Parse Command
-
-    Parses the command line and sets the global command options.
-
-    @return Tuple of parser options and parser arguments
-    """
-    usage = ("usage: %prog --check [options] db_file\n" +
-             "       %prog --upgrade [--noconfirm] [options] db_file")
-    parser = OptionParser(usage = usage, version = VERSION)
-    parser.add_option("-c", "--check", action="store_true",
-                      dest="check", default=False,
-                      help="Print database version and check if it " +
-                           "needs upgrading")
-    parser.add_option("-n", "--noconfirm", action="store_true",
-                      dest="noconfirm", default=False,
-                      help="Do not prompt for confirmation before upgrading")
-    parser.add_option("-u", "--upgrade", action="store_true",
-                      dest="upgrade", default=False,
-                      help="Upgrade the database file to the latest version")
-    parser.add_option("-v", "--verbose", action="store_true",
-                      dest="verbose", default=False,
-                      help="Print SQL statements as they are executed")
-    parser.add_option("-q", "--quiet", action="store_true",
-                      dest="quiet", default=False,
-                      help="Don't print any info, warnings or errors")
-    (options, args) = parser.parse_args()
-
-    # Set the database file on which to operate
-    if (len(args) > 1):
-        logger.error(DBUTIL_TOO_MANY_ARGUMENTS)
-        parser.print_usage()
-        sys.exit(EXIT_COMMAND_ERROR)
-    elif len(args) == 0:
-        logger.error(DBUTIL_NO_FILE)
-        parser.print_usage()
-        sys.exit(EXIT_COMMAND_ERROR)
-
-    # Check for conflicting options.  If some are found, output a suitable
-    # error message and print the usage.
-    if options.check and options.upgrade:
-        logger.error(DBUTIL_COMMAND_UPGRADE_CHECK)
-    elif (not options.check) and (not options.upgrade):
-        logger.error(DBUTIL_COMMAND_NONE)
-    elif (options.check and options.noconfirm):
-        logger.error(DBUTIL_CHECK_NOCONFIRM)
-    else:
-        return (options, args)
-
-    # Only get here on conflicting options
-    parser.print_usage()
-    sys.exit(EXIT_COMMAND_ERROR)
-
-
-def main():
-    (options, args) = parse_command()
-
-    global logger
-
-    if options.verbose:
-        isc.log.init("b10-dbutil", "DEBUG", 99)
-        logger = isc.log.Logger("dbutil")
-    elif options.quiet:
-        # We don't use FATAL, so setting the logger to use
-        # it should essentially make it silent.
-        isc.log.init("b10-dbutil", "FATAL")
-        logger = isc.log.Logger("dbutil")
-
-    db = Database(args[0])
-    exit_code = EXIT_SUCCESS
-
-    logger.info(DBUTIL_FILE, args[0])
-    if options.check:
-        # Check database - open, report, and close
-        try:
-            db.open()
-            exit_code = check_version(db)
-            db.close()
-        except Exception as ex:
-            logger.error(DBUTIL_CHECK_ERROR, ex)
-            exit_code = EXIT_READ_ERROR
-
-    elif options.upgrade:
-        # Upgrade.  Check if this is what they really want to do
-        if not options.noconfirm:
-            proceed = prompt_user()
-            if not proceed:
-                logger.info(DBUTIL_UPGRADE_CANCELED)
-                sys.exit(EXIT_SUCCESS)
-
-        # It is.  Do a backup then do the upgrade.
-        in_progress = False
-        try:
-            db.backup()
-            db.open()
-            in_progress = True
-            perform_all_upgrades(db)
-            db.close()
-        except Exception as ex:
-            if in_progress:
-                logger.error(DBUTIL_UPGRADE_FAILED, ex)
-                logger.warn(DBUTIL_DATABASE_MAY_BE_CORRUPT, db.db_file,
-                            db.backup_file)
-            else:
-                logger.error(DBUTIL_UPGRADE_PREPARATION_FAILED, ex)
-                logger.info(DBUTIL_UPGRADE_NOT_ATTEMPTED)
-            exit_code = EXIT_UPGRADE_ERROR
-
-    sys.exit(exit_code)
-
-if __name__ == "__main__":
-    isc.util.traceback_handler.traceback_handler(main)

+ 0 - 114
src/bin/dbutil/dbutil_messages.mes

@@ -1,114 +0,0 @@
-# Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-#
-# Permission to use, copy, modify, and/or distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-# PERFORMANCE OF THIS SOFTWARE.
-
-# No namespace declaration - these constants go in the global namespace
-# of the ddns messages python module.
-
-# When you add a message to this file, it is a good idea to run
-# <topsrcdir>/tools/reorder_message_file.py to make sure the
-# messages are in the correct order.
-
-% DBUTIL_BACKUP created backup of %1 in %2
-A backup for the given database file was created. Same of original file and
-backup are given in the output message.
-
-% DBUTIL_CHECK_ERROR unable to check database version: %1
-There was an error while trying to check the current version of the database
-schema. The error is shown in the message.
-
-% DBUTIL_CHECK_NOCONFIRM --noconfirm is not compatible with --check
-b10-dbutil was called with --check and --noconfirm. --noconfirm only has
-meaning with --upgrade, so this is considered an error.
-
-% DBUTIL_CHECK_OK this is the latest version of the database schema. No upgrade is required
-The database schema version has been checked, and is up to date.
-No action is required.
-
-% DBUTIL_CHECK_UPGRADE_NEEDED re-run this program with the --upgrade switch to upgrade
-The database schema version is not up to date, and an update is required.
-Please run the dbutil tool again, with the --upgrade argument.
-
-% DBUTIL_COMMAND_NONE must select one of --check or --upgrade
-b10-dbutil was called with neither --check nor --upgrade. One action must be
-provided.
-
-% DBUTIL_COMMAND_UPGRADE_CHECK --upgrade is not compatible with --check
-b10-dbutil was called with both the commands --upgrade and --check. Only one
-action can be performed at a time.
-
-% DBUTIL_DATABASE_MAY_BE_CORRUPT database file %1 may be corrupt, restore it from backup (%2)
-The upgrade failed while it was in progress; the database may now be in an
-inconsistent state, and it is advised to restore it from the backup that was
-created when b10-dbutil started.
-
-% DBUTIL_EXECUTE Executing SQL statement: %1
-Debug message; the given SQL statement is executed.
-
-% DBUTIL_FILE Database file: %1
-The database file that is being checked.
-
-% DBUTIL_NO_FILE must supply name of the database file to upgrade
-b10-dbutil was called without a database file. Currently, it cannot find this
-file on its own, and it must be provided.
-
-% DBUTIL_STATEMENT_ERROR failed to execute %1: %2
-The given database statement failed to execute. The error is shown in the
-message.
-
-% DBUTIL_TOO_MANY_ARGUMENTS too many arguments to the command, maximum of one expected
-There were too many command-line arguments to b10-dbutil.
-
-% DBUTIL_UPGRADE_CANCELED upgrade canceled; database has not been changed
-The user aborted the upgrade, and b10-dbutil will now exit.
-
-% DBUTIL_UPGRADE_DBUTIL please get the latest version of b10-dbutil and re-run
-A database schema was found that was newer than this version of dbutil, which
-is apparently out of date and should be upgraded itself.
-
-% DBUTIL_UPGRADE_FAILED upgrade failed: %1
-While the upgrade was in progress, an unexpected error occurred. The error
-is shown in the message.
-
-% DBUTIL_UPGRADE_NOT_ATTEMPTED database upgrade was not attempted
-Due to the earlier failure, the database schema upgrade was not attempted,
-and b10-dbutil will now exit.
-
-% DBUTIL_UPGRADE_NOT_NEEDED database already at latest version, no upgrade necessary
-b10-dbutil was told to upgrade the database schema, but it is already at the
-latest version.
-
-% DBUTIL_UPGRADE_NOT_POSSIBLE database at a later version than this utility can support
-b10-dbutil was told to upgrade the database schema, but it is at a higher
-version than this tool currently supports. Please update b10-dbutil and try
-again.
-
-% DBUTIL_UPGRADE_PREPARATION_FAILED upgrade preparation failed: %1
-An unexpected error occurred while b10-dbutil was preparing to upgrade the
-database schema. The error is shown in the message.
-
-% DBUTIL_UPGRADE_SUCCESFUL database upgrade successfully completed
-The database schema update was completed successfully.
-
-% DBUTIL_UPGRADING upgrading database from %1 to %2
-An upgrade is in progress, the versions of the current upgrade action are shown.
-
-% DBUTIL_VERSION_CURRENT database version %1
-The current version of the database schema.
-
-% DBUTIL_VERSION_HIGH database is at a later version (%1) than this program can cope with (%2)
-The database schema is at a higher version than b10-dbutil knows about.
-
-% DBUTIL_VERSION_LOW database version %1, latest version is %2.
-The database schema is not up to date, the current version and the latest
-version are in the message.

+ 0 - 43
src/bin/dbutil/run_dbutil.sh.in

@@ -1,43 +0,0 @@
-#! /bin/sh
-
-# Copyright (C) 2010  Internet Systems Consortium.
-#
-# Permission to use, copy, modify, and distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
-# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
-# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
-# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
-# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
-# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-PYTHON_EXEC=${PYTHON_EXEC:-@PYTHON@}
-export PYTHON_EXEC
-
-DBUTIL_PATH=@abs_top_builddir@/src/bin/dbutil
-
-# Note: lib/dns/python/.libs is necessary because __init__.py of isc package
-# automatically imports isc.datasrc, which then requires the DNS loadable
-# module.  #2145 should eliminate the need for it.
-PYTHONPATH=@abs_top_srcdir@/src/bin:@abs_top_builddir@/src/lib/python/isc/log_messages:@abs_top_builddir@/src/lib/python/isc/cc:@abs_top_builddir@/src/lib/python:@abs_top_builddir@/src/bin:@abs_top_srcdir@/src/lib/python:@abs_top_builddir@/src/lib/dns/python/.libs
-export PYTHONPATH
-
-# If necessary (rare cases), explicitly specify paths to dynamic libraries
-# required by loadable python modules.
-SET_ENV_LIBRARY_PATH=@SET_ENV_LIBRARY_PATH@
-if test $SET_ENV_LIBRARY_PATH = yes; then
-	@ENV_LIBRARY_PATH@=@abs_top_builddir@/src/lib/dns/.libs:@abs_top_builddir@/src/lib/dns/python/.libs:@abs_top_builddir@/src/lib/cryptolink/.libs:@abs_top_builddir@/src/lib/cc/.libs:@abs_top_builddir@/src/lib/config/.libs:@abs_top_builddir@/src/lib/log/.libs:@abs_top_builddir@/src/lib/util/.libs:@abs_top_builddir@/src/lib/util/threads/.libs:@abs_top_builddir@/src/lib/util/io/.libs:@abs_top_builddir@/src/lib/exceptions/.libs:@abs_top_builddir@/src/lib/datasrc/.libs:$@ENV_LIBRARY_PATH@
-	export @ENV_LIBRARY_PATH@
-fi
-
-B10_FROM_SOURCE=@abs_top_srcdir@
-export B10_FROM_SOURCE
-
-BIND10_MSGQ_SOCKET_FILE=@abs_top_builddir@/msgq_socket
-export BIND10_MSGQ_SOCKET_FILE
-
-exec ${PYTHON_EXEC} -O ${DBUTIL_PATH}/b10-dbutil "$@"

+ 0 - 2
src/bin/dbutil/tests/.gitignore

@@ -1,2 +0,0 @@
-/dbutil_test.sh
-/dbutil_test_verfile_*

+ 0 - 15
src/bin/dbutil/tests/Makefile.am

@@ -1,15 +0,0 @@
-SUBDIRS = . testdata
-
-# Tests of the update script.
-
-noinst_SCRIPTS = dbutil_test.sh
-
-check-local:
-if HAVE_SQLITE3_PROGRAM
-	B10_LOCKFILE_DIR_FROM_BUILD=$(abs_top_builddir) \
-	$(SHELL) $(abs_builddir)/dbutil_test.sh
-else
-	@echo ""
-	@echo " **** The sqlite3 program is required to run dbutil tests **** "
-	@echo ""
-endif

+ 0 - 536
src/bin/dbutil/tests/dbutil_test.sh.in

@@ -1,536 +0,0 @@
-#!/bin/sh
-# Copyright (C) 2012  Internet Systems Consortium, Inc. ("ISC")
-#
-# Permission to use, copy, modify, and/or distribute this software for any
-# purpose with or without fee is hereby granted, provided that the above
-# copyright notice and this permission notice appear in all copies.
-#
-# THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
-# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-# AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
-# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-# OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-# PERFORMANCE OF THIS SOFTWARE.
-
-# Checks that the logger will limit the output of messages less severe than
-# the severity/debug setting.
-
-testname="Database Upgrade Test"
-echo $testname
-
-failcount=0
-tempfile=@abs_builddir@/dbutil_test_tempfile_$$
-backupfile=${tempfile}.backup
-testdata=@abs_srcdir@/testdata
-verfile=@abs_builddir@/dbutil_test_verfile_$$
-
-# @brief Record a success
-succeed() {
-    echo "--- PASS"
-}
-
-
-# @brief Record a fail
-#
-# @param $1 Optional additional reason to output
-fail() {
-    if [ "$1" != "" ]
-    then
-        echo "ERROR: $1"
-    fi
-    echo "*** FAIL"
-    failcount=`expr $failcount + 1`
-}
-
-
-# @brief Record a pass if the argument is zero
-#
-# @param $1 Value to test
-passzero() {
-    if [ $1 -eq 0 ]; then
-        succeed
-    else
-        fail
-    fi
-}
-
-
-# @brief Record a fail if the argument is non-zero
-#
-# @param $1 Value to test
-failzero() {
-    if [ $1 -ne 0 ]; then
-        succeed
-    else
-        fail
-    fi
-}
-
-
-# @brief Copy File
-#
-# Executes a "cp" operation followed by a "chmod" to make the target writeable.
-#
-# @param $1 Source file
-# @param $2 Target file
-copy_file () {
-    cp $1 $2
-    chmod a+w $2
-}
-
-
-
-# @brief Check backup file
-#
-# Record a failure if the backup file does not exist or if it is different
-# to the data file. (N.B. No success is recorded if they are the same.)
-#
-# @param $1 Source database file
-# @param $2 Backup file
-check_backup() {
-    if [ ! -e $1 ]
-    then
-        fail "database file $1 not found"
-
-    elif [ ! -e $2 ]
-    then
-        fail "backup file $2 not found"
-
-    else
-        diff $1 $2 > /dev/null
-        if [ $? -ne 0 ]
-        then
-            fail "database file $1 different to backup file $2"
-        fi
-    fi
-}
-
-
-# @brief Check No Backup File
-#
-# Record a failure if the backup file exists.  (N.B. No success is recorded if
-# it does not.)
-#
-# @param $1 Source database file (unused, present for symmetry)
-# @param $2 Backup file
-check_no_backup() {
-    if [ -e $2 ]
-    then
-        fail "backup of database $2 exists when it should not"
-    fi
-}
-
-
-# @brief Get Database Schema
-#
-# As the schema stored in the database is format-dependent - how it is printed
-# depends on how the commands were entered (on one line, split across two
-# lines etc.) - comparing schema is awkward.
-#
-# The function sets the local variable db_schema to the output of the
-# .schema command, with spaces removed and upper converted to lowercase.
-#
-# The database is copied before the schema is taken (and removed after)
-# as SQLite3 assumes a writeable database, which may not be the case if
-# getting the schema from a reference copy.
-#
-# @param $1 Database for which the schema is required
-get_schema() {
-    db1=@abs_builddir@/dbutil_test_schema_$$
-    copy_file $1 $db1
-
-    # The purpose of the following sed command is to join multi-line SQL
-    # statements to form single-line SQL statements.
-    #
-    # The sed command is explained as follows:
-    # ':a' creates a new label "a"
-    # 'N' appends the next line to the pattern space
-    # '$!ba' if it's not the last line, branch to "a"
-    #
-    # The above makes sed loop over the entire sqlite3 output. At this
-    # point, the pattern space contain all lines in the sqlite3 output.
-    #
-    # 's/,[\ ]*\n/, /g' then substitutes lines trailing with comma
-    # followed by zero or more spaces and the newline character, with
-    # just a comma and a single space.
-
-    db_schema=`sqlite3 $db1 '.schema' | \
-               sed -e ':a' -e 'N' -e '$!ba' -e 's/,[\ ]*\n/, /g' | \
-               sort | \
-               awk '{line = line $0} END {print line}' | \
-               sed -e 's/ //g' | \
-               tr [:upper:] [:lower:]`
-    rm -f $db1
-}
-
-
-# @brief Successful Schema Upgrade Test
-#
-# This test is done where the upgrade is expected to be successful - when
-# the end result of the test is that the test database is upgraded to a
-# database of the expected schema.
-#
-# Note: the caller must ensure that $tempfile and $backupfile do not exist
-#       on entry, and is responsible for removing them afterwards.
-#
-# @param $1 Database to upgrade
-# @param $2 Expected backup file
-upgrade_ok_test() {
-    copy_file $1 $tempfile
-    @SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile
-    if [ $? -eq 0 ]
-    then
-        # Compare schema with the reference
-        get_schema $testdata/v2_2.sqlite3
-        expected_schema=$db_schema
-        get_schema $tempfile
-        actual_schema=$db_schema
-        if [ "$expected_schema" = "$actual_schema" ]
-        then
-            succeed
-        else
-            fail "upgraded schema not as expected"
-        fi
-
-        # Check the version is set correctly
-        check_version $tempfile "V2.2"
-
-        # Check that a backup was made
-        check_backup $1 $2
-    else
-        # Error should have been output already
-        fail
-    fi
-}
-
-
-# @brief Unsuccessful Upgrade Test
-#
-# Checks that an upgrade of the specified database fails.
-#
-# Note: the caller must ensure that $tempfile and $backupfile do not exist
-#       on entry, and is responsible for removing them afterwards.
-#
-# @param $1 Database to upgrade
-# @param $2 Expected backup file
-upgrade_fail_test() {
-    copy_file $1 $tempfile
-    @SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile
-    failzero $?
-    check_backup $1 $backupfile
-}
-
-
-# @brief Record Count Test
-#
-# Checks that the count of records in each table is preserved in the upgrade.
-#
-# Note 1: This test assumes that the "diffs" table is present.
-# Note 2: The caller must ensure that $tempfile and $backupfile do not exist
-#         on entry, and is responsible for removing them afterwards.
-#
-# @brief $1 Database to upgrade
-record_count_test() {
-    copy_file $1 $tempfile
-
-    diffs_count=`sqlite3 $tempfile 'select count(*) from diffs'`
-    nsec3_count=`sqlite3 $tempfile 'select count(*) from nsec3'`
-    records_count=`sqlite3 $tempfile 'select count(*) from records'`
-    zones_count=`sqlite3 $tempfile 'select count(*) from zones'`
-
-    @SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile
-    if [ $? -ne 0 ]
-    then
-        # Reason for failure should already have been output
-        fail
-    else
-        new_diffs_count=`sqlite3 $tempfile 'select count(*) from diffs'`
-        new_nsec3_count=`sqlite3 $tempfile 'select count(*) from nsec3'`
-        new_records_count=`sqlite3 $tempfile 'select count(*) from records'`
-        new_zones_count=`sqlite3 $tempfile 'select count(*) from zones'`
-
-        if [ $diffs_count -ne $new_diffs_count ]
-        then
-            fail "diffs table was not completely copied"
-        fi
-
-        if [ $nsec3_count -ne $new_nsec3_count ]
-        then
-            fail "nsec3 table was not completely copied"
-        fi
-
-        if [ $records_count -ne $new_records_count ]
-        then
-            fail "records table was not completely copied"
-        fi
-
-        if [ $zones_count -ne $new_zones_count ]
-        then
-            fail "zones table was not completely copied"
-        fi
-
-        # As an extra check, test that the backup was successful
-        check_backup $1 $backupfile
-    fi
-}
-
-
-# @brief Version Check
-#
-# Checks that the database is at the specified version (and so checks the
-# --check function).  On success, a pass is recorded.
-#
-# @param $1 Database to check
-# @param $2 Expected version string
-check_version() {
-    copy_file $1 $verfile
-    @SHELL@ ../run_dbutil.sh --check $verfile
-    if [ $? -gt 2 ]
-    then
-        fail "version check failed on database $1; return code $?"
-    else
-        @SHELL@ ../run_dbutil.sh --check $verfile 2>&1 | grep "$2" > /dev/null
-        if [ $? -ne 0 ]
-        then
-            fail "database $1 not at expected version $2 (output: $?)"
-        else
-            succeed
-        fi
-    fi
-    rm -f $verfile
-}
-
-
-# @brief Version Check Fail
-#
-# Does a version check but expected the check to fail
-#
-# @param $1 Database to check
-# @param $2 Backup file
-check_version_fail() {
-    copy_file $1 $verfile
-    @SHELL@ ../run_dbutil.sh --check $verfile
-    failzero $?
-    check_no_backup $tempfile $backupfile
-}
-
-
-# Main test sequence
-
-rm -f $tempfile $backupfile
-
-# This is the section number that is echoed during tests. It is
-# incremented when each section is run.
-sec=0
-
-# Test: check that the utility fails if the database does not exist
-sec=`expr $sec + 1`
-echo $sec".1. Non-existent database - check"
-@SHELL@ ../run_dbutil.sh --check $tempfile
-failzero $?
-check_no_backup $tempfile $backupfile
-
-echo $sec".2. Non-existent database - upgrade"
-@SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile
-failzero $?
-check_no_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-
-# Test: should fail to check an empty file and fail to upgrade it
-sec=`expr $sec + 1`
-echo $sec".1. Database is an empty file - check"
-touch $tempfile
-check_version_fail $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is an empty file - upgrade"
-touch $tempfile
-@SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile
-failzero $?
-# A backup is performed before anything else, so the backup should exist.
-check_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is not an SQLite file - check"
-echo "This is not an sqlite3 database" > $tempfile
-check_version_fail $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is not an SQLite file - upgrade"
-echo "This is not an sqlite3 database" > $tempfile
-@SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile
-failzero $?
-# ...and as before, a backup should have been created
-check_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is an SQLite3 file without the schema table - check"
-check_version_fail $testdata/no_schema.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".1. Database is an SQLite3 file without the schema table - upgrade"
-upgrade_fail_test $testdata/no_schema.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is an old V1 database - check"
-check_version $testdata/old_v1.sqlite3 "V1.0"
-check_no_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is an old V1 database - upgrade"
-upgrade_ok_test $testdata/old_v1.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is new V1 database - check"
-check_version $testdata/new_v1.sqlite3 "V1.0"
-check_no_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is a new V1 database - upgrade"
-upgrade_ok_test $testdata/new_v1.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is V2.0 database - check"
-check_version $testdata/v2_0.sqlite3 "V2.0"
-check_no_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is a V2.0 database - upgrade"
-upgrade_ok_test $testdata/v2_0.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is V2.1 database - check"
-check_version $testdata/v2_1.sqlite3 "V2.1"
-check_no_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is a V2.1 database - upgrade"
-upgrade_ok_test $testdata/v2_1.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is V2.2 database - check"
-check_version $testdata/v2_2.sqlite3 "V2.2"
-check_no_backup $tempfile $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is a V2.2 database - upgrade"
-upgrade_ok_test $testdata/v2_2.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is V2.0 database with empty schema table - check"
-check_version_fail $testdata/empty_version.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is V2.0 database with empty schema table - upgrade"
-upgrade_fail_test $testdata/empty_version.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec".1. Database is V2.0 database with over-full schema table - check"
-check_version_fail $testdata/too_many_version.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-echo $sec".2. Database is V2.0 database with over-full schema table - upgrade"
-upgrade_fail_test $testdata/too_many_version.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec". Upgrade corrupt database"
-upgrade_fail_test $testdata/corrupt.sqlite3 $backupfile
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec". Record count test"
-record_count_test $testdata/new_v1.sqlite3
-rm -f $tempfile $backupfile
-
-
-sec=`expr $sec + 1`
-echo $sec". Backup file already exists"
-touch $backupfile
-touch ${backupfile}-1
-upgrade_ok_test $testdata/v2_0.sqlite3 ${backupfile}-2
-rm -f $tempfile $backupfile ${backupfile}-1 ${backupfile}-2
-
-
-sec=`expr $sec + 1`
-echo $sec".1 Command-line errors"
-copy_file $testdata/old_v1.sqlite3 $tempfile
-@SHELL@ ../run_dbutil.sh $tempfile
-failzero $?
-@SHELL@ ../run_dbutil.sh --upgrade --check $tempfile
-failzero $?
-@SHELL@ ../run_dbutil.sh --noconfirm --check $tempfile
-failzero $?
-@SHELL@ ../run_dbutil.sh --check
-failzero $?
-@SHELL@ ../run_dbutil.sh --upgrade --noconfirm
-failzero $?
-@SHELL@ ../run_dbutil.sh --check $tempfile $backupfile
-failzero $?
-@SHELL@ ../run_dbutil.sh --upgrade --noconfirm $tempfile $backupfile
-failzero $?
-rm -f $tempfile $backupfile
-
-echo $sec".2 verbose flag"
-copy_file $testdata/old_v1.sqlite3 $tempfile
-@SHELL@ ../run_dbutil.sh --upgrade --noconfirm --verbose $tempfile
-passzero $?
-rm -f $tempfile $backupfile
-
-echo $sec".3 Interactive prompt - yes"
-copy_file $testdata/old_v1.sqlite3 $tempfile
-@SHELL@ ../run_dbutil.sh --upgrade $tempfile << .
-Yes
-.
-passzero $?
-check_version $tempfile "V2.2"
-rm -f $tempfile $backupfile
-
-echo $sec".4 Interactive prompt - no"
-copy_file $testdata/old_v1.sqlite3 $tempfile
-@SHELL@ ../run_dbutil.sh --upgrade $tempfile << .
-no
-.
-passzero $?
-diff $testdata/old_v1.sqlite3 $tempfile > /dev/null
-passzero $?
-rm -f $tempfile $backupfile
-
-echo $sec".5 quiet flag"
-copy_file $testdata/old_v1.sqlite3 $tempfile
-@SHELL@ ../run_dbutil.sh --check --quiet $tempfile 2>&1 | grep .
-failzero $?
-rm -f $tempfile $backupfile
-
-# Report the result
-if [ $failcount -eq 0 ]; then
-    echo "PASS: $testname"
-elif [ $failcount -eq 1 ]; then
-    echo "FAIL: $testname - 1 test failed"
-else
-    echo "FAIL: $testname - $failcount tests failed"
-fi
-
-# Exit with appropriate error status
-exit $failcount

+ 0 - 14
src/bin/dbutil/tests/testdata/Makefile.am

@@ -1,14 +0,0 @@
-EXTRA_DIST =
-EXTRA_DIST += corrupt.sqlite3
-EXTRA_DIST += empty_schema.sqlite3
-EXTRA_DIST += empty_v1.sqlite3
-EXTRA_DIST += empty_version.sqlite3
-EXTRA_DIST += invalid_v1.sqlite3
-EXTRA_DIST += new_v1.sqlite3
-EXTRA_DIST += no_schema.sqlite3
-EXTRA_DIST += old_v1.sqlite3
-EXTRA_DIST += README
-EXTRA_DIST += too_many_version.sqlite3
-EXTRA_DIST += v2_0.sqlite3
-EXTRA_DIST += v2_1.sqlite3
-EXTRA_DIST += v2_2.sqlite3

+ 0 - 41
src/bin/dbutil/tests/testdata/README

@@ -1,41 +0,0 @@
-The versioning of BIND 10 databases to date has not been the best:
-
-The original database is known here as the "old V1" schema.  It had a
-schema_version table, with the single "version" value set to 1.
-
-The schema was then updated with a "diffs" table.  This is referred to
-here as the "new V1" schema.
-
-The Spring 2012 release of BIND 10 modified the schema.  The
-schema_version table was updated to include a "minor" column, holding the
-minor version number. Other changes to the database included redefining
-"STRING" columns as "TEXT" columns.  This is referred to as the "V2.0
-schema".
-
-The following test data files are present:
-
-empty_schema.sqlite3: A database conforming to the new V1 schema.
-However, there is nothing in the schema_version table.
-
-empty_v1.sqlite3: A database conforming to the new V1 schema.
-The database is empty, except for the schema_version table, where the
-"version" column is set to 1.
-
-empty_version.sqlite3: A database conforming to the V2.0 schema but without
-anything in the schema_version table.
-
-no_schema.sqlite3: A valid SQLite3 database, but without a schema_version
-table.
-
-old_v1.sqlite3: A valid SQLite3 database conforming to the old V1 schema.
-It does not have a diffs table.
-
-invalid_v1.sqlite3: A valid SQLite3 database that, although the schema
-is marked as V1, does not have the nsec3 table.
-
-new_v1.sqlite3: A valid SQLite3 database with data in all the tables
-(although the single rows in both the nsec3 and diffs table make no
-sense, but are valid).
-
-too_many_version.sqlite3: A database conforming to the V2.0 schema but with
-too many rows of data.

BIN
src/bin/dbutil/tests/testdata/corrupt.sqlite3


BIN
src/bin/dbutil/tests/testdata/empty_schema.sqlite3


BIN
src/bin/dbutil/tests/testdata/empty_v1.sqlite3


BIN
src/bin/dbutil/tests/testdata/empty_version.sqlite3


BIN
src/bin/dbutil/tests/testdata/invalid_v1.sqlite3


BIN
src/bin/dbutil/tests/testdata/new_v1.sqlite3


BIN
src/bin/dbutil/tests/testdata/no_schema.sqlite3


BIN
src/bin/dbutil/tests/testdata/old_v1.sqlite3


BIN
src/bin/dbutil/tests/testdata/too_many_version.sqlite3


BIN
src/bin/dbutil/tests/testdata/v2_0.sqlite3


+ 0 - 0
src/bin/dbutil/tests/testdata/v2_1.sqlite3


Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff