BIND 10 trac2155_2, updated. 61d7c3959eb991b22bc1c0ef8f4ecb96b65d9325 Merge branch 'master' into trac2155_2
BIND 10 source code commits
bind10-changes at lists.isc.org
Tue Oct 30 07:38:33 UTC 2012
The branch, trac2155_2 has been updated
via 61d7c3959eb991b22bc1c0ef8f4ecb96b65d9325 (commit)
via 27e863962f01a9dc8ac5c756ff881cb585c00abf (commit)
via 1c12d2036d9e92d0475f421406bdca6839b04326 (commit)
via 7735c8e85cb8275ee5bd1918bff809612248c43d (commit)
via 59a449f506948e2371ffa87dcd19059388bd1657 (commit)
via 7ec750c09a3828d28362bc557816e24a6b2207cf (commit)
via 041dbf514a284b9c14f3a803dbaa8e4260b804f2 (commit)
via 7dff35a176bcf41d83a14eb5b3fbca6a7dcfafb8 (commit)
via 0187917d0b77b34997c4666d27f916cd8f6b4dd4 (commit)
via 40ae159a7ae9c1c1049bd8c18e37ed086c1aafae (commit)
via 9281b972a87becd0f85b747d5d939f8f2e317247 (commit)
via 61fc577d38615b1a25b5a94fa3bbaca9ec2f6ddf (commit)
via 4163ddf6d718bc6239a92a592687701053a5cf06 (commit)
via 98947382e572f239b57f3f79a928636ea42d3696 (commit)
via b2964261a72d6eff164cafe4b24fd5bfce0fa469 (commit)
via fb8ce6a031254899bc2fdc101e5e279bed51829d (commit)
via 869e658fbc3e33c5037f3866beb2ff76c03cbdf4 (commit)
via 7e2dedc024cd77a301d7e30d180e16fa2132cbf5 (commit)
via 8aa188a10298e3a55b725db36502a99d2a8d638a (commit)
via 4e98f9c8aec4fbe707bf4f5aa8de9e3ce4737f79 (commit)
via 05dbb62986e1b0260156658896c051cde3c6d53f (commit)
via 5a9bc9bc1467bfd5d0be7de9db40824a967be9b0 (commit)
via e62b6417336ebdaeda560e47b177e617ee4551e5 (commit)
via a88ab93f5a8722d16f96a4e58952042ff2564751 (commit)
via 33fd1fb0ed8ebfceb01e8a84b1196af29dffde92 (commit)
via 844348f6a9c5d4670f96750a2c94ade6778891d9 (commit)
via 57b907eddc75241956102dd4de70d882c1b1fe63 (commit)
via a311ab52fe83d602a2ac3daa12314df7de258bae (commit)
via 85ccee0ac4c1397c8a5bf225470467c55623a28c (commit)
via f4dd53d74dfa8496e8f846960ac7424493858848 (commit)
via 1b63f7d9df1621053c71ec3ef546a8cae024dffb (commit)
via 84df8fb3d06ad81e04fee73b6a31890ddc03c33e (commit)
via b9afd797dee6f7ede5c387466547ac5a06277ecd (commit)
via dba0f070ef3f4a78db630b3002eef5fd2ba757e0 (commit)
via b77e7ed31d3121c8fb3826c9a8909044e0f4f6ab (commit)
via cf72f036909c786091f845a736bfd6fcfd15a7ac (commit)
via e4850b8e75f2d8fd4924b5060cbf3c4458d3513d (commit)
via aade8ac800d58c46dad9ab862cf0d6e85174b17d (commit)
via 7900248aec3191e202066f5dfaad98f6469c32df (commit)
via 0c8f4961f3f2b8884e5567e51bf629016a35e9d7 (commit)
via dcf59e93fadc2df047e4cb9dba138ffc0f619d3e (commit)
via 414a83fefbb7374f31f362e80efef262722660eb (commit)
via 9394d67b638a84409c3491fee821f347ca2acbcf (commit)
via 6a8228eb8556681c30c7163010f7fb354a9ef66c (commit)
via a5a98d2f3e44ebec0de30f4f0905b83ca3a5df75 (commit)
via a54864927bc88eebbfb0f9515207ba9a3cacaa3e (commit)
via f49a40682835963334f3d5f2014bfed6b0895400 (commit)
via 462af9f5a374d7c60c8ac2b38e6d663f2af41cc3 (commit)
via f48cb0979513b642ab8cea30be5a3caa10fff958 (commit)
via 30873bc3691ff9be1d9ce56dfb4c3dc30e4dabbc (commit)
via ab6215d2e93f0bc0206f4503a9e5b0ea62bf65f3 (commit)
via fd2e13361be9f4e4fb4e1098bae2058de33432f7 (commit)
via f6af1e6965348482deb45174ba7b4dcb6e9cef61 (commit)
via 1114159c5b113a98db20ecaed992022917300216 (commit)
via dc3884d6b3e3f80144d57a6edc0223d97f5a46af (commit)
via 195617a1fd88af3bfbb397263cd67a148d0e7d67 (commit)
via 6ead8f2bc21f09b34f842dda074d121a9f511ed5 (commit)
via bd8b562bcf016c70f229ba1cb7fa084035eff9e0 (commit)
via 653d1d854ad6574806ed09f6b42aaa4a17f27b57 (commit)
via d8b60408e4843a88d15e3cd95dfeb898cea2a8fd (commit)
via 99bdc7de647ee1abb8401cc1fd8337462173e7f8 (commit)
via a6ca17646b6bdf23f36d523bb56f3bb91e1dbf39 (commit)
via 4b1c96c8a9bba522a512d07b23e36feebaec10bd (commit)
via d12b460fbb26cfbd968bf0db25c1d0d3a8d5fb4a (commit)
via 3b3b42295d636901e0647d0bba3a4f3677af50a0 (commit)
via 0bc630b2e4ab6efd3f837f2dd6f5e771e6a71b3c (commit)
via c37eaa23d920b79d3f344c8fbafbdcda37231b47 (commit)
via a2224a3c4ea8bcfc685190d78e539608e76006f4 (commit)
via eac4d4fdbc978c037d83081a3a7d99db4a8135bd (commit)
via edcbc935eb6ddc4bb5fac1e76e8eac100e783e74 (commit)
via 7ff2ddee910f9a53bd1dd47c432c99a280a6d076 (commit)
via 3519306b1c9d4bcaf8d6758ca65ad4a371296346 (commit)
via 64b2a61c6d242b974169b72542be45a57630ec8d (commit)
via 03499b185e1dca3807f4c09cd36ba066f25bc918 (commit)
via ecabe80cbb2483d8057a83c84faeb84ce903b555 (commit)
via f609865c302b87caa3f5721557b0e5491c3eba3e (commit)
via 70473ce1f70543029936a6c5c6c055ea7a33581b (commit)
via 0eb033a6b10eac2e2767923ccfe5e74f2d2b2680 (commit)
via 5744cc1cf3c348d120ef5dc3f1f97e23a0aa6fea (commit)
via cb330a06847987bfacacc7a9333b70666750b66d (commit)
via c7123c288ebc9a1ac9aa86c43219877c86a6a032 (commit)
via 461164b527fd4b7f047820e7d1f7b22eb1b3458c (commit)
via ad46427a54b6169859924c37e3966625f3a3b0b4 (commit)
via 42c8b84a3fc7c45bfb3df671b5c4a7f7a9b3d376 (commit)
via 2c5059119b843646ca59612cf69c4439b04494c8 (commit)
via fa6cef4dfbadd457c75ef5fc5f7ffe42d916a2de (commit)
via e710685dced3b2f30ecda4ead1d0dc9f6ae64361 (commit)
via 059a2a175193e5c60a3a5e647acf95e0eb6b9a6a (commit)
via 6d1358617343e061a6b2ac16a7830853674d1c5c (commit)
via 29047b54a17c2bc1d27096ea21522e928b51989f (commit)
via dbabdcc3c8c103a56a6da5187a97f2748adfa467 (commit)
via 54ae641d1c1fa87baeb702ec0ee25b28c2b7aebd (commit)
via 1d4d9e796c10786417099a69e8c4e6e4c1cdfb8b (commit)
via 503a7b06ae96ef13d1f1a5344e07c06786b5eb83 (commit)
via 7eb5518a386019fd723fb2484eb40f13ff283515 (commit)
via 0aa3d59397af2c127758616bdd93c22d3176d28b (commit)
via a4560fb5f2093d4619fb159d77501dd7e6978d35 (commit)
via 01c85b2bf83b55be659ebe1526eaa1c5aa55b6aa (commit)
via 07085635d4c12c77ac979ea9755d38a2a40f77b4 (commit)
via 7d777cee74391169cd589dab1330eda699d2b8d6 (commit)
via 54a03955995437e3cb380ef5ffba44d61be04213 (commit)
via 0dfa29e875e3a668e7b6718b510c12df590faec7 (commit)
via b4a991767173f93daa5100909740413530c4445d (commit)
via 71a249c1564261f2643515451a68e388603eaf4c (commit)
via 296e119946e9fb8d6eebdabf6eb166f47c47fbd0 (commit)
via 2ce8ea317bf920ec540ed40f10738cb2f65426df (commit)
via 80210bc17829ab209d714a10daa35bebad2f6dc0 (commit)
via 718ab061bfe0fbad59c5d829d32d1fb71608c324 (commit)
via 265fc0cc3154f8963e5ab68fd2890eeec64e13be (commit)
via 3e189b431fd39c99aaf4fa8f78a3e41d722f37ed (commit)
via 4a9e338f845772c9a0888a276c30449f89beea9c (commit)
via daaa9544987cf61adb4a16fb955885019cce8885 (commit)
via c4690c43b4856170b4da2c789d1605d5430b7cb8 (commit)
via 35300a55ab8bc113428142ea764a54173eb8f07f (commit)
via c59f610bf61bbc374b401a0ac6f595240bd4c629 (commit)
via 3404981c39241b4463e661981614ec0d157b924d (commit)
via aa9c2bbcf4e4522525194310791d94fcf84fc605 (commit)
via d02295dada44afbbfe9c8b7878cecca536ba3a13 (commit)
via d0b0208ae8f3de712fa1329c8b01d16e3eaf8ac4 (commit)
via ebdd232061e3d9ced4660541cd3ad1c2ca8ed645 (commit)
via 5fd4177340e6abaec9f8ca6a1194900001671665 (commit)
via 9ba0013f74bf3ed03d95add7c1d46c2d28a94492 (commit)
via d709ef90b8f23a6c41a05d2f5a62cb91840fde0d (commit)
via 246a87a4a681a574a0ecff9b26a49e471a60138a (commit)
via 113201b72be892ffd8af815806ccbb0e14ad6b67 (commit)
via a8dcc73698a14603967aec4dfb09e183e559f84a (commit)
via a92defd1deceebc13a7bcc93cee6579ed42be41e (commit)
via a09e57e212a102d719315aff8d0f3c4ce74268d8 (commit)
via 6c12b4328d0c49d039abc56ee22e09f8ca431647 (commit)
via 80b0cf61a83ef37110d4b86c15704a923f0b9d6e (commit)
via 5765f9d6485ed12a16a65f89639d0d88bc2c3692 (commit)
via 7c4e02c157bf7a4baaa81c448ff485e7dec31182 (commit)
via 2eaf01995b4c0d6c007afd51c94b8453cbb797ca (commit)
via 8b19f3a80a57b4a0c41e58460920924d5613e606 (commit)
via 98db15a31fea52ec2b1952846c61d20f9f373305 (commit)
via 4f4b3724e1e06933646dcbee14f31eb2713a514d (commit)
via 4ea73cff14dfd8c6898f1c79e7de860a2ca83b33 (commit)
via 77e32834470282fe08ae7fb8c8fb9a4afb163677 (commit)
via a9688bc111e1cf1b62cfad222c2dab1351c81a4e (commit)
via bb59b815c94d86c6d5d34cdfd707b7e6e3522122 (commit)
via e13d083a39e86bcb60867b281ccd0a045bb55993 (commit)
via 07b436b864bd3193ecafbfe1f9c1fa54f90ac342 (commit)
via 1eda789420a1914f61ee720043a15516157f23b4 (commit)
via 61d475331f841b3d5f1b2461ae99fe45f5d554fe (commit)
via 252ef7278171213c9e54338939423e72b3d51257 (commit)
via 812392465ae1ffa4a583186fd48f4c7aff1640dd (commit)
via f0c56bb2f6bc3a8118acd5f27e0be45d23b6be21 (commit)
via 20fdec048d51fa193425ebb284278ffeec37b93f (commit)
via 3a5e410f451b3254df6bf454e50af98b80ce4f16 (commit)
via 9a52c2a5a52c35056f650594216366cac5560af1 (commit)
via c974d3a5e481c63242f128f630b9e7e5ac4f1359 (commit)
via 82d164c20e0dd8a359b8493a2bc1216436549a4d (commit)
via 2fa49003caec9837963fdee5c8ef7ca5ed1b6413 (commit)
via 61256f84ff903ba7f0bddd2569f9fddcdbb194d2 (commit)
via ae2e285fb9abc9295563206d86ebbf94dc4f8918 (commit)
via e6ba20b0907ab7e861e608a71a35f71ab228e79f (commit)
via 4e199b28f4247ba178c4a066d77c6ff6dbebfd19 (commit)
via c3a8f64b91fd9f1b7525fa8d46f0db2d6b4a0889 (commit)
via 73f49fc9d917907e6b8990e137cd8414acb852ce (commit)
via 59d1e7799c13b01d24276dbd6377934d50ca0749 (commit)
via d7a95438792f96696ced4559ee6bd465ae652f2f (commit)
via 1bb3279cc1b0c3b156a749cdef80b625371afaa9 (commit)
via 9a85c00b1675644dcdfea3e344ee72a42558d1aa (commit)
via 9de48090c09919a7926664e26697dca42693b258 (commit)
via 11df86c57f35ed344838b787ecc1caf1382805dc (commit)
via 699a941cab0ce6969a8f93a17e7659b75876b14b (commit)
via a80cd447a1458b6c2d5d654f31e2e4a1a7d3f66e (commit)
via 48bfbccf4e01c6b0b9c8c716b09155f16fabf3ab (commit)
via 13e9951ecd5877f8942fee9af7065d8c6c20d1ac (commit)
via f8fb9a002db020b90f423fd82cf5f7f10a050bc7 (commit)
via 1b638d681316a66b6c1de3ca2937068f81d4f634 (commit)
via 638f92b82b6b3e74e4b7222f238fb9cf2b8a4fe1 (commit)
via 1c5c694f663811e02a40acdaa0ba2b71a38c44fa (commit)
via b09b4308af92511dde35d87a23bf159b2f71848b (commit)
via 2d014223ce8d34ce0efb19fbd78c5123f4a2cd60 (commit)
via 0a4ef3221c7ea7347a11e02b9e8175598e3eb2ec (commit)
via c9ba8373e271fb3c966fb59813c21ca8c575354d (commit)
via 7868cb5a0cb2c276114c8d762a89bc59d8169df8 (commit)
via 08e8d762ad041672b156204c21b42b32a510e94c (commit)
via 6cf94944f1431422449f5740299ee2d6ae5fd988 (commit)
via a61ab28f80639eb289b7b1cf74e89932fb11f1f5 (commit)
via 5ac7c2d114c23a7bdf4c15a96d619027d2092d63 (commit)
via 2f6a2e484a7c4838a11e0696323c5a38efa1c6cc (commit)
via 15a048bef56f34ac35ac38f6b43512129dac0350 (commit)
via a9af8c8a7a7d2448c86949fca578ec942e5413dd (commit)
via 86fe8fce9db80466c67e0553c9f5ef404cdbb185 (commit)
via c9b8a023d197a3726f4177409847c29e523a69fc (commit)
via 0e56f890880b684ebb71245155d0ecd435c75fdf (commit)
via 0e70ad361ad0d42b3d0aa63c51355e20c48b9c32 (commit)
via adc18e7e1019626410a642aa8271627659ff1d3b (commit)
via 8a4c6f4bbfd10a372fa4c4d40a6cb5ec64047cb6 (commit)
via 77d522cf9e3b0cfd5325461b76bbaa2cc8a859f2 (commit)
via eb90dff94fbb2df0632f51982fc2c512af6e9c65 (commit)
via bef1229c90595e4aa4a6c483fc99f7cac768a1b3 (commit)
via 21170f738cf943a5750c26eb8b418972a673a27f (commit)
via 213bd813ebe0eacec4bda6d11301f81315494364 (commit)
via ee7d5cf20406b4ff00a52ce8218304c6623571ea (commit)
via 3a0cd3a067fdf94078764b082c8139220a0ce917 (commit)
via 307b9baac8a90337fc6de440efe0ed3685aa97ed (commit)
via 396d1867ce3420d759bd5eaaed64ce3f83b0b874 (commit)
via c1e16071d91f9db0b3f78f7a09551c66278ace5e (commit)
via 451973cb26da61f3e5d56c441ea54a28c34acaa3 (commit)
via d1c32c6bd6bb7621968266b09ca979ecce428530 (commit)
via f6f16611034e7b8bb0bd1ce506d6d61ed5228b02 (commit)
via c62976b616bd2b44a9f791c47afde5d89ef9913a (commit)
via 7161d9d899723f1be561125087e1daaf820e80ed (commit)
via 3ac353a5a561e5a0ecae750bd0d52afb2fa86037 (commit)
via 9e8803c63d45a0a2abe9cd615c41f0a0f1fd8ac1 (commit)
via 0002fc16bf300d9a2ccfca9e26fdfd5a73eaf519 (commit)
via 6319666e91e5f3f20d9e2fdb920ce90c2539d4ad (commit)
via d97fa9cb68dea0cf8873f9b28ac6671ee321a1f6 (commit)
via 3d7fea6b15278d8f66840bff3cc4f9a3b1d60d23 (commit)
via c13d57b516b4ed381a51916a5b726aebcc564f8f (commit)
via fc846d678c69d29dc9055a943288c4adfe41fb07 (commit)
via f0fc85c74eff8a53f2387e4c48a8043ad3994b08 (commit)
via c627111eeec6f80e5f66020c7613b4e408d2b193 (commit)
via a82ee1d047fe786113491226f7e81a08ed58e8c4 (commit)
via 7c40eaf7779f7fb3b80ad141c58f60e69a2f3e4e (commit)
via fa78c4ba3aff851955576ec7e98f8fe98dacd889 (commit)
via 149df5a690bc874b8814669c19a8666e2cddf961 (commit)
via 2a6f0764001c25acb40eae27d7a2f7691d4c767b (commit)
via 4887037cd08e567596339dbb3d65557b8e25560d (commit)
via 7e1c4328789fc66d6fb7f4840112d89024d00eef (commit)
via 8580400e9333574d49de88aaf34dac87bd270020 (commit)
via 9b439f1bf7dc415312be57570b092459fad4caf7 (commit)
via 7b598ee429c070c4c784e41822a4904ee71ebf95 (commit)
via 8334de9f905bc792b0ec866a03a2dde05e5330fe (commit)
via 667ecc41e7f8c0a47a1d701cb5cf16ecc7264205 (commit)
via 9904c81d783e8e4678ba6de3db438ddbb186dcaa (commit)
via 110a33e6c237d71d2efa42d27ae2434b35ddcaa3 (commit)
via 0582539b207817d0ab63a2f07923d9cd69b520a7 (commit)
via 59ca62327546854c22cf8caae902f023a79f3272 (commit)
via f34ff8e2e66798f4dc2fc63d1aeb4c198431beb1 (commit)
via d5afffd2e3db401cafb5ac2ca80215afffddf7da (commit)
via 949aded6b4682df0f07e78cd4620df303f789236 (commit)
via c2608e7b395881e9953962d923dfd1de6eb50f5f (commit)
via 5080ddf460167c252502db23b97cdb69fce7f240 (commit)
via 6fca5f367bef49f3c3002ee6abb4c5c19ab971d9 (commit)
via b617d1a26e4e4fd536b37848b1dd39ff40f5213b (commit)
via 83f878b651eb1be66dfcb1453cc074c2b5d3dc3f (commit)
via 9bb3d27efdf09dd2e429086767cdee275f3df115 (commit)
via 100929f3fab349338ecbd8cbcdf090e1006f8ab0 (commit)
via 7265ccb300bd2a2e1789d8ce99182e787d97181c (commit)
via 399e4f0030d226010f2156e978fc2b7c179fe7b7 (commit)
via f0f7efe331713b84e4e95f872373d6d2906b5870 (commit)
via 0c3a609fdde1fe14de8d2c032e1350c3f10c3058 (commit)
via ce585a075a28df8b5815b38cd461da1dce17406d (commit)
via 650655fd267d652ec1b0d5e57a261ab767ada447 (commit)
via b4f9ae7bf9569106d47a0ff227552eb6a956aa4e (commit)
via 8422f4dd15cbdd9bd33f3a570bdf40b991665ab9 (commit)
via c450d77e81322fb6a3c6753d721f5d3bb62fff71 (commit)
via 39faa67b7a8e9b3680792582bb65372ddf610b77 (commit)
via 16041df526aeb519ff158aa4cd89e0b4f503aece (commit)
via 6430d56ffc6be92717f50e576101546be2f4d6c9 (commit)
via ccfb2bf2c5226f21e793df4abaa9b98a993b6eb3 (commit)
via 4601f7ef87135a559b4fa7a1daaf2f1de8f040c3 (commit)
via 84e0dc1be1b2f22d46028944a3ce1a599aa24090 (commit)
via 2530e97e662406cb168e80358c764ff8692866cb (commit)
via 5b77cd205f08b1bc76ec5ff4248f4c9cb4e0ac27 (commit)
via 1ae2321d7183470ad3540d2a92436893724ea773 (commit)
via 03b8bddd309adeb39a99474aea530f05989b99ed (commit)
via 0d336b6f23ca4518b38f1e26e8b8b9998f426e5f (commit)
via 4b2997b783ed2f9a29842735dad130cfdb41e38a (commit)
via c857ced99825b35644c2abdbad8be14644da237c (commit)
via e7bcdb44ef51c4f8fcf81a11d247494384fa0c41 (commit)
via e21b1a26b3f78d69975c5735c1965a37c67359c9 (commit)
via 07e1f1ddbd299b60ee4009f53723b4271b5cea16 (commit)
via 2252c5776f5447f47e567262f8a5a05753fc6ce9 (commit)
via f559b99dcccd35703989fce985ff200cd664ccc0 (commit)
via c91151db16e215692830bf9b6211c22aae8619dc (commit)
via 7ffd1e0cad3bd125b490953dbea9f22c67e40fae (commit)
via 34701adba7f7390640c70ba769cdb0b20f01f82c (commit)
via 26313fafb0f28d8bb1e440c83a780cdb6fc6fda2 (commit)
via 42c638e07a45b69d902a51b35838ae21ac19d116 (commit)
via 82c0737d3d63da1a1c2b001d0306a32a1e55f5f5 (commit)
via 5735b337b8e78502bd54cba748bb622b150f6667 (commit)
via b57f65e686286f211ef1b177f69a81fa5baf3021 (commit)
via 579b92381b604c84f70ae5fe6237ca5dc45a9302 (commit)
via 93c198a7b9afd341809b954e76f5e2773e0010ff (commit)
via 8d321e3ea9f85227296cfac94a9ce79c7db70fdf (commit)
via 5bf4005eb7dd34a08b6070bc17f0e416448062d2 (commit)
via 83d00dc305a33e69e4bee379895697742a1eaab7 (commit)
via 15724e5de168271303268a09627c3f197833f20d (commit)
via f8181bb72251fd3d5f33e157d1f2a2a75a58d765 (commit)
via 6adfc244341c07a70eb0984536390486649316ae (commit)
via 16d31a6793cedc28c8acb1bebf4c891c039321cb (commit)
via f05b0be9d267baab1003963e231a3511dfcd7d5e (commit)
via ae89f6e491d018953ac03d1810c1b467564c281b (commit)
via b4ec1b3e236ae2dabfbf6b0fb9c182da27f52596 (commit)
via d2009fd950bc48ec3a2294a9064c4fbd9bfa0f79 (commit)
via 0c6ad26d377dfa84e4cf4ee202b8f1c912d296a1 (commit)
via 8c02f8a83f011816c3fb19f655a1e57edf0c1048 (commit)
via a439004524335feb296ee7477a5b450a2a7d7953 (commit)
via 410987bf3c9299053c07aee46591193c97af6ea4 (commit)
via 7f94f671e0da9c98cabcc38433852732294bee4a (commit)
via 453b58784344390cbc5375624e6e92a86b4ff3f1 (commit)
via 405d85c8a0042ba807a3a123611ff383c4081ee1 (commit)
via 671005eea2c18ad34bb0bad435b538447cdc7a50 (commit)
via b6d2a03ff5dfc0b1269e69e44defb2999e8a5d33 (commit)
via d504c06cbe387363d11ae091eeaa980444cc5190 (commit)
via 50500e62ac0b43e3579e98832b06bde19d01302c (commit)
via 66524e1594263bb19fd73660fef31f4e49dbe81d (commit)
via 6920774dd67be1221c379e9d5161f0cc932fbd73 (commit)
via 3a73fff8f44f18188c1f810f3f5395e6ea107a7d (commit)
via 9565a7939e66bb0f3bbb4f3be8778dec13582db1 (commit)
via 9c2e94bb8ae9368aac3e0991dbebe3738ee914d7 (commit)
via efded5c3713a67a6eaa0284a322195b2f5075a27 (commit)
via d5569a62a30b26294197381dadf4b28317fba3d9 (commit)
via b06d8d764e01652ef5d3e1eb50ed482ddeae8308 (commit)
via 51580fd1a4953d554b80306eec4f9fc89f166241 (commit)
via c55218e6bebfeec753b01e4cd724adcda40b3a5f (commit)
via 5b781744ac6f909958754f7e5947115ec799ac18 (commit)
via 4ed683ce42d061905a4e5b06fcc1a38c64136e7a (commit)
via e6ac5ef47d9885e20e247697c8c3d1fe55fd2500 (commit)
via 48e80a5c7505df708999ef817911d1eb505deaad (commit)
via fff8929b13d8c2cd725b861c7e930c0060b54d83 (commit)
via ecef170dd0af4f282d4426ef663b667c76873737 (commit)
via 350c775f7bd5c7777f0345754dac4ecaa0a9af18 (commit)
via 666bfa9c7b6de4ee31e210d7f3e0f2f68704f2de (commit)
via 932edbb0ec8a4dbb820c6cccf4a0becd9df533c2 (commit)
via 0e2c14089b820cbb0bdef6e813042992896375bc (commit)
via 45f0d1f2e771efaf7ca21e7f0450626847e75d90 (commit)
via 31d092681cc44a6d742474090430c7ddba3f81e6 (commit)
via 3744e7a8584a1c51bc5163751975af8e297c53c5 (commit)
via c0e090f453d3a1627ccd0591e0ec0abc3e80a01b (commit)
via 70aa7bfa24600d5492056c860838d94c9243c6aa (commit)
via 419020c407ac9f1ca0ab1f5a5c8b8b6219fb5d5b (commit)
via 58c41ea9cdb2df726b4b54015500acab3ae34040 (commit)
via 26ea6b0e3045489e542b95d02052fc7565a4ca87 (commit)
via 4629279de0b7bec2a019b063e27074182a8f4ebd (commit)
via d3983e1e68f66bbf6c69838aebe01a8f95b7bc33 (commit)
via 0bacd458152b7909f3d8e9ef4a338f261dad7f99 (commit)
via ae0565a4ed6e8a947120a7bfe826c1cf9d672760 (commit)
via e93e6f3873ca08ae835dfd883c36f19b42df247f (commit)
via 95a47e7f0ac9e87d3d0c6c51c07e4761d0a50932 (commit)
via 26483ea27726d4c1097485196a0908c565478188 (commit)
via 9062cbabaeebead0b95bde1559d107fc35eeda1d (commit)
via f3414d4ba60432e36785c23ca55c633ad35298ab (commit)
via 0e1a1b2ee0fc9a3a510d348d5449a825779c03b2 (commit)
via e2b120a2e016f249eabaf7753b97a79ece0bffa1 (commit)
via 1e6d2102d1402cfcd6d2c1ecd88c6aa83133daa2 (commit)
via 8b59a7d661ce81cb47c2f18d2908a01a8ab9ded0 (commit)
via f17651217197a8006509ef121f1a3d7a5eada1b4 (commit)
via e77ef46d0c78265ab0bd0ca12b541aaee2a52898 (commit)
via 97a6125c538e5f44790b55ded90fccf363416496 (commit)
via 2150123bd60f00e070198b9c9717eb685dd0eebe (commit)
via 6bceaa250bef898410db1555341887b6a6f7e900 (commit)
via 65c54c90ed874825b0418acade6179bd905bd470 (commit)
via c1ce5449aa72d538cbfca94f88cda0b8617081ba (commit)
via 2768eb3551fdaa2c4728563535dfb69f732dc033 (commit)
via 9c655172a298766a37cc83173438f70fff83264c (commit)
via 1e0c106c45251a61579d37a5148e9f258b3e5cea (commit)
via 9e11459509c9223201dcbe10636b15ba923e1516 (commit)
via 9dac9afb2569288bb630b00d2a89a490ad944710 (commit)
via c9de286421049dc1a75a981c511506d16c014501 (commit)
via 92f2cc51478005befb016e410a4fcb9c768ea3b8 (commit)
via c64356e9fdf3be868bb2d624200219d68aca45e8 (commit)
via e5ad36f38f6066c50059ea02e06245d7bc5c7efd (commit)
via f97ecbe97b6b3e098ebde2c984041dd24ce2dbbe (commit)
via e78384f8c6aca75a41ea000d22ecc7648513ad02 (commit)
via bc03b9cc89d6c3cad7308b884679125ab547b5cb (commit)
via e70da63e4aa5a075928c5cdef4fed11d15eeaa5a (commit)
via 55be177fc4f7537143ab6ef5a728bd44bdf9d783 (commit)
via 16823263f5bc357de97f8b5d72f7b4d046583d23 (commit)
via ecdf1aeb4bfd97f636cc081cce30cc3394b38d11 (commit)
via b6501267d7058d8ed879eb4ce63f3d502ccebcc1 (commit)
via 47cfab4fa97829309b1c6093d65c27a142b1c87a (commit)
via bd7ef43a90c7e6f3a9b7140d0cacb2459dcd4091 (commit)
via aea67d494996a4b86a1671591e4cfa0ed1cbee77 (commit)
via 52ba8a9314e28f0f2f39510e66c2dc03531c47e1 (commit)
via ed72f2bf21f13a214106d222f6537a43f6f3318d (commit)
via ff2fabced6d1b9e88a2c6c2da66573ad96ae4e00 (commit)
via dda8b3fa72979fd24d5c3bdca6709408b5bafedb (commit)
via 35bdd068cf6192eba30d94d6a7a73751be4220ff (commit)
via 1645116db47739bc194d10db67a3a085b1ac551d (commit)
via 6207e0ccf7924b0976a21ffb7f901d946a273c41 (commit)
via e3079eb5ceeeca83507f6dfbf712b374661c3935 (commit)
via 5097c34950518370eabcade6cb71ba952bfeefd4 (commit)
via 9f77979fd649eaa9ec1cc3e9ce5b80059e2df3a5 (commit)
via a969883cd42fef3c3782fea117c156b76014df25 (commit)
via 214377d8511c7f8fdb8b8c8052bcb301aad1d06f (commit)
via c76f74659b3bc90b28f4af8940bd47193b92a28a (commit)
via 64bcd98477cfc62851a21aa64ced28d0cff92201 (commit)
via 0fc7d94b29ecc8a267d32047636d6525a3133612 (commit)
via 5703d87a9e031873305da04b88fb49ac5172c3c1 (commit)
via 4d27a4533c2cbdcb3c9e74c12d03024733e79895 (commit)
via a6cafe644f6a9413ba7f917e741b82cc292d3577 (commit)
via 52272e7986c23da3a0b6c4897f94245bfb408420 (commit)
via ed2aceb01d516724a4f289343c4ad1c65b4322b4 (commit)
via b15be74974e7e1d4f9acc0590e8853a064e3b6bf (commit)
via d7e42bb0c48c961c320ba1bf4324c49b9c43c19a (commit)
via 919fe74ccbeecf5d546b60f017c3e9e1b073655a (commit)
via f44918fd6cd6c3357609c82865a1e6c4a0e4d44a (commit)
via 44b1d42219a1787165a01497c21fec2661ba8277 (commit)
via 3efb1402e7d62755971c8e1440d31f85f14053e3 (commit)
via a3953a556b472084d669dcb629fb801dec67c5dd (commit)
via ea4149ff70f0a90ed995a04e41e4fa06664278c4 (commit)
via 7b2aa97d01af2934b408caa6044cbfab4c6679f6 (commit)
via e84770a80501161a4de8ca0fd9d821b0ce7c7da9 (commit)
via fa5076be0c7037c239c00fb7c2c53d02bdc87260 (commit)
via b31ee9e4712a22bd04637aa3222863ab0eb3c2b1 (commit)
via 45ae6bad11071f2b416c267bf2e71f2208487dda (commit)
via a270e0425f64f0fca563b7d49708325250911b96 (commit)
via 0a23277c5bcbd35467652610f7feb2b7f7c65a0b (commit)
via bb347f194134acc2a3d1e7f2c6d6b4f0d56d2a17 (commit)
via 40083686017562d13d812240499a8090383bfa11 (commit)
via a841ad0aec2fa5d0966dc43b3036ff99b5f3ae42 (commit)
via a25609c439090aeb21c01b487a2070b4df8d435b (commit)
via b2eedd0aebf2739acfb5e83363667fd2c1101f7d (commit)
via fa2026935d4738b6b5b7365d2fab53f9dea09cc4 (commit)
via dd752b34220a5b6a07a4d2c057169c6b88394c32 (commit)
via b675d21e2e7b1864b32824c97e180abf47c1f42e (commit)
via fe0e9a269f318aae152fb4b55437b45609bfd6cc (commit)
via 666c34d9e2c70936c264bd0432f874a95af42a1a (commit)
via 4686e5da4ecc7801a232a1858bf11f124aca3ee7 (commit)
via 4e5ca3a84b4c02ffef3bf8b6c6360b05c8600a4e (commit)
via cdbc11cf13f6cc69498b56a23c61748ed67f3631 (commit)
via 0dca4820d8473e8e1db07b49ef54d52d250e9209 (commit)
via 0edff937af7a4fcb6565d2b7ad14e0484b3905b1 (commit)
via ecb43490182626c4e62cded9d02ac9a94feb4cfa (commit)
via 83cdd8bb5d8cb846bfc85e65b33fc57fa56939b7 (commit)
via dc506d0714924ad48c3cd6a93c181ddd663f0059 (commit)
via b2cb1e1e337281fe923f1065fa19eac896d63b15 (commit)
via 4da98b699e5d73acbf7f0a01799b3a006aec4832 (commit)
via 6f008e19162fe3ae3911db0f770d6d38612bcba0 (commit)
via e0f618ac8f36e7fa8dbeab6164d40fd838178831 (commit)
via bb21aa5022e544357f9faa327278680acf5f16e0 (commit)
via f38d24a77f7a146b6a37f912c98af268df40f5e7 (commit)
via da22b37709978a87d276b1d88a92b401ae9a2084 (commit)
via 0e9c2a4c688d85c32e671a1564dd65818b1a6043 (commit)
via f7c0410f7d2f1c3a06f886b548713bae6e78e9fb (commit)
via 13089ae122acefb8d2a632174da4e4dd53ce4473 (commit)
via dd83505acac98d122777883a304465f69ecd03ec (commit)
via 06c667cd025d42798dbce055a24ada9e601f8c35 (commit)
via c66fe1c8ad169c7bd0bc15c0cbe2357194acfaa4 (commit)
via 1eb3ce6df757a23ff59b71469e0f19329893d8c7 (commit)
via 9334389794384c62c517d646608fb23a1abeb40d (commit)
via 3d98322d24b54475ce801880a5d17a27dc8f57ef (commit)
via 1c4ec91a6f44300af78f4964496cf000c97e93f8 (commit)
via b41cca56e918501b7a84cfe31067f786ed1d065e (commit)
via c3a2105cbd7516aada1b954184b699e1ae8200ee (commit)
via 347e333b52c7589ad5bf4fb9cc6f4ff6474b510d (commit)
via fac39dc29a4f858bfe6d1c48f76737926a043f32 (commit)
via adb92afc6f7d0ceda51780577ebe4c2487745cad (commit)
via c28be089b929185c72aba5fe90c5f8d355c833ac (commit)
via 998645aaeb5a7369ae94e71f84d40512ffee996b (commit)
via 55d94bb5f735252542908e9565d7a49c9a6e0966 (commit)
via 3e2a372012e633d017a97029d13894e743199741 (commit)
via 5cc254b16bd0120a7bacd33f90936333fbecfd79 (commit)
via b05952bb39bc7f038e65c5e61aca711278096dee (commit)
via b770f510961784b1cbf766a1b40fb026788d8cb0 (commit)
via 9ef297b7faf705148c7aed37df6c796e55660062 (commit)
via a017390f15c132fdb08f244f2e111ae6964e4cc4 (commit)
via 6fc2942362354dd4960a25d644095f6eb44b6023 (commit)
via 1426bb5c63cd7d79a4a16aedf619aff5ea2394aa (commit)
via 73f22adb3400726277f06f9d1f8760e43bcc133f (commit)
via 030aef19982a37a8b81376adb15864097b208ff8 (commit)
via eb84acab80c1a4f59f7c49ef5214279358e8ed79 (commit)
via 0375b6599cabcefe4e9cf1b326f54b3519bde8b3 (commit)
via 50f42396efa039096dd74c13425d1a2bc0efc978 (commit)
via 64bba5b1c6a4155e8179217c10e998fbe3c2822c (commit)
via 31fdd062b59d6ac480ff48cde57e5abad2b3487c (commit)
via 7ad6e5687c4835d70422ee09d1bfdb032979060a (commit)
via a78e560343b41f0f692c7903c938b2b2b24bf56b (commit)
via de5fd0b12800235b15ee02cbed8e862ea6c974ad (commit)
via 028bed9014b15facf1a29d3d4a822c9d14fc6411 (commit)
via 4784ca566b009035404a5abf1759c2eedf5a7515 (commit)
via a6c74caf3dc0aef52b89c78ebbcd02fcc5e47609 (commit)
via f6616492db24a4831ca25258c4bc234e5bd148bb (commit)
via 07b793c8f104dbb9116e3f94af7098498509288a (commit)
via df196f7609757253c4f2f918cd91012bb3af1163 (commit)
via 5fadea676fc73e068977173bb62b58d04fedf52c (commit)
via 532ac3d0054f6a11b91ee369964f3a84dabc6040 (commit)
via ca61588dc2c1ad17200416ac7f07ac272adc8903 (commit)
via dc5492b8401c85daf1b0c8801e497bac3d5eeea5 (commit)
via 6962458ec49390d007dbf0fa9d5d3befa53deb23 (commit)
via 28b3efcf6100d2eab66c407a8f7ec54a87ac5f87 (commit)
via 43959b29a67ba17054bd4bb70b6fe3b8be3b2f2a (commit)
via c0d50a204134b57f36a9e83cc694abcb5924f357 (commit)
via bc7551cca83bf060410a5645f014ddb0eb233834 (commit)
via 8722bc208f5a232707824f3537fe0f6d073151f1 (commit)
via 1adba86b37b9c11a8120e31cc4eeb137f8cde6d9 (commit)
via e2d1490eb82b26c501df4d0ed7323478b46a1cca (commit)
via 73aebe53f210471b768d79b1f24ee154c56c8554 (commit)
via f2b4e736bb7d4612c33aa2a648b0b9640a015154 (commit)
via 88db890d8d1c64de49be87f03c24a2021bcf63da (commit)
via 65cddb545cbf31c0372ab09e59a727d7cfdf1f89 (commit)
via 99fd73694c6768e36d79563be991d9132adbdd74 (commit)
via 234026e024d6c4f35d2b7e1f34213949f79e614c (commit)
via b10b39f8ac7b07f6b429c0e09fcd9d0a3a873492 (commit)
via a1983f43686919fae5dfb05ad8e6da07e5534111 (commit)
via 56dd56426342f9fa3d63c436f35ba86208512ee0 (commit)
via b6cfd9d20c49a0f292d37e663801987632e9d2a6 (commit)
via a0b7dd977eba590ecd94d4f08ed774a0727fbed0 (commit)
via 7565788d06f216ab254008ffdfae16678bcd00e5 (commit)
via 183ea20803b1dfc0bb6e932c75623864cd0a0def (commit)
via 85627bca2677b4e68d67c8ecd35fbfe409eda251 (commit)
via d042cd04c0784641738a0f06e5a6b193b433d39f (commit)
via 55178c917f014922f8213921a44f0443b3dc40f8 (commit)
via 7bb6309fbc34c32a0e37ea2b2175738b6110bcf7 (commit)
via fd45bcdb5182e09d33b92e222772b54c6e744d01 (commit)
via 08d6f75709a7669481b92fc0b2e4176174bc0f48 (commit)
via c887cb05e27289bf5a80130c1a196dbbc1903234 (commit)
via cd86c2c845e03de172d832256ea3542203f40a5f (commit)
via b59e1eb450e7f4630ee4ee8e67b7dbb3cf6092de (commit)
via 98127986d0baa2f87e455035d778c823bbe59397 (commit)
via e4f9ff3f23810d365e13ee2e204f70eac5ffdc8f (commit)
via fe827c7e47a642f3aead3b5414c6e8cf3a9970b4 (commit)
via c6391ad769265a1f5c2d5594dcdb113420c7eb4d (commit)
via 28a6c7133b1fa8f5334f91c514f5dc8e0802e4eb (commit)
via ed2b8eb0e3f827c89ba16200312424384a54a9a7 (commit)
via 2975fbae44dbaacdff7b9039a395b00c4375f01b (commit)
via 593b348cbb8207fca3e9d01620794cfe118455b2 (commit)
via c16c1ab29b3a52012a806974dd6afaddc01c9436 (commit)
via 2eb96fb05e736e2f16d03174f663d030cc883f00 (commit)
via c6f7cced73d38d5108862be4a104cb89d0f832e4 (commit)
via c0d25c429a4f2026bb97b9e013730b8f265862e6 (commit)
via e71cd13c5cb261635f7115e0d30fbd7dcc5fe151 (commit)
via 86e4008ac1623aef96fd0c6140e5496841c3b9f0 (commit)
via f496bbe69fbff9228c48fc7bf9cc986ed7f420e4 (commit)
via 74911480e9ff1f21f63365ac789ecd30f67891b8 (commit)
via 66424553f3fa05e46e558f3b4e16677463e0e412 (commit)
via e562ac798865d18ece6a7ddd28ed79d8b4abe0ae (commit)
via d12ce3c245fc86e3c34a5fdd5950d899cdf889af (commit)
via 1517f32c9e68baacfc68c2aab412b29045d846b9 (commit)
via f4f708e4e93579989bf716d5851311a2b5aff6b5 (commit)
via 5e39872cc6dc260c91596ee31f1601dbf53de503 (commit)
via ebfe8a5ab083e3ec1ead648709bfba801fb617a5 (commit)
via 71e12e0bc1d27327a0f3f520ae80041af38ce657 (commit)
via d78dd497ecb846ab2545ce1cb7b6e41341ff5995 (commit)
via 3a6ee0d12d06c1f9e5b9f261b3fcaab444a9ae80 (commit)
via 7888a2127db48e004cb1cce24552db230cb3d685 (commit)
via bcf2117983fa80d3f4bb9a13f896963497553b85 (commit)
via fb5aa58dabb47c1ef51890bee7da070c6a567f69 (commit)
via 5879860e006e809fa75fdb78b61f82fdffd69b97 (commit)
via 1e93f1db983cc35b118853b88ab2919decafe2c5 (commit)
via 3a68ea2e8de8d6df97d95c077ff9e2874ca0d9c3 (commit)
via 4e159ffca0b633c817472101087be4a235a42af0 (commit)
via 7b053fd99e6503d3a0a8fb7dbb9d3139df942565 (commit)
via 04db154ec2fdd1d768fe716b0ccabaa1660e872b (commit)
via c7ab107ab6a5f079475085e87851d940863481dc (commit)
via dd191127774034a51d658dfe6799ccb397916103 (commit)
via 4973e638d354d8b56dcadf71123ef23c15662021 (commit)
via d41d8af0c726bb923a48948feb6a8f4f6775ea3e (commit)
via 869d14d7056ee7b0c3cf1dd0db1b375be755bba7 (commit)
via 9a9260c2589a8468b73f2ecc16929acd66aeb81c (commit)
via daedcaea541b1193018cb71d3cc68ba3ba9ff59c (commit)
via 432064bc3ec7c67797898a182c52add8f6012232 (commit)
via 1ab996e4c54f1449b8e72cce411331193868e78c (commit)
via bf260bbc80a813c30bb7499b8a085d7390d83e83 (commit)
via f8261d10f177e52b19af56343ddb5e7548f30195 (commit)
via 7bcaf2b7903ea5a51c2049579f6dc4670746527f (commit)
via f5bd1368b73131abd6e0562e57482310d26ff3eb (commit)
via c629dec43601cd76158bef6aa8b76cea84181fc2 (commit)
via e4bd572168b357f9803ce9c5d96ff3a95d935b81 (commit)
via b211a060119605ebbded0a94f070009b7a8bb5ce (commit)
via d62a1e4250c88e765b3cd7f77fe9a948db0a565d (commit)
via 9ea5133b172ccde43427f9658f5be2ba5d497b34 (commit)
via daf81c8846bf0b4e4308068a019c96beb09c5199 (commit)
via 23da2f078af486c381649611d2987c24a538739a (commit)
via 587a13699275e9a582fb9358463047362ef9f21e (commit)
via ec2aecacc46f071cc6479881418825920e8f8f50 (commit)
via 83a27d452c13b468d2103b0314ecf2bae17cd6b1 (commit)
via ece07281abf99ae142b20b4aead428e3333121a9 (commit)
via d05029362843411c46c6d8d278fcf17ba9d8d32a (commit)
via ef49adadf64f56558c75d34483895e1e8d8bcf66 (commit)
via 00d3de1af86efe6b4df1310a039adad8f6a719ae (commit)
via 73900f62a74bf769b5f6ea7b3cf43428baa19842 (commit)
via 7a628baa1a158b5837d6f383e10b30542d2ac59b (commit)
via 915576b6aa27d020faadf7fbfc4e4d9bb1df129e (commit)
via e1b4bf1cb50160c436f2e5440fd774680b91b7a2 (commit)
via 76243c3ccd7a30484da8478f7457e18fce485492 (commit)
via 86a4bae1ffa68eb38921d6cb3f16dad43b616009 (commit)
via 0b6e74f544b522943436bfdff79c2fa06273b49d (commit)
via d7846ea4a9d811c35641f77384d9825f12488e71 (commit)
via 5d61dba1dc3e51d66ba40d82b1bc378577783dc0 (commit)
via c286e0dec766c3d9b2fff6a8bd55539ec976aae9 (commit)
via d664fca786643e2345d9722da6d8fd35996bbea1 (commit)
via a0a5e207d4a05738f278df6124172f415a43d4ad (commit)
via b160122e462422d82fd122839f9fff1e861aa21d (commit)
via 31c8d5e0b4cdec573baf77f09fca75a362f641b6 (commit)
via 44d9dfa8aad85d583b7b90fa01c50613a9d9d1a5 (commit)
via 273e195ef434e87ebf9838381d4b49e8a3081acb (commit)
via b2d0a03b1efe54b85736d22932f311fd376473ba (commit)
via fbc8d38199a95cc51704c40269d0c4c6625ec6b0 (commit)
via 7a40926af1fd90e0fd685a8db05795f699560245 (commit)
via f8a03432904899e1874f2696ff036322be539022 (commit)
via 74cc637858d0879f33f1828aabbb1f78e9636d4f (commit)
via fa1d1161f76487ceea122baf4dac79c407a07ba8 (commit)
via 17bffd083824af840b8af99a043bcf55e4c0f555 (commit)
via 0ff7d113ebb54889bbcd9be91c37a0e5ffcc2fc4 (commit)
via 3584fbbffa6a633df2988ef8e52a4f367cdc814c (commit)
via bff3846230660040790debeacf8d9432ac302fb9 (commit)
via a1d9278fd64f74a4a0657a2292851157ad3bb43a (commit)
via 93e596c474ed1c637da7d6653eaa8c499b0b6a6d (commit)
via f037ebb23cb966f86d11c07bb0f4a80b6043c9b0 (commit)
via a475756bf185c9e364ed00e245e307789e22fed3 (commit)
via 27be672609dde261c85ffc671f1026277cfc3e9a (commit)
via 18cff787ef721f58322db5c5662ab7980357fe68 (commit)
via 34020849e9b1d560fdc21b25ac0fe03c64f71a01 (commit)
via ae53c8fd697e2cd037facfccc8205d580b27f04e (commit)
via 97fb03f6b015205da25e9c5be3cd90d4f9948d04 (commit)
via 23d2eaf5f8e5febc4732f3fdc851e1b04914daf8 (commit)
via 3a8ea5fd501d131e99ec02c4be10a874a94f2d83 (commit)
via 46c03d26e27417bdce132b90eef18686443bd5a7 (commit)
via 86b1a2387a10ff8e5e646b117c289ebb2e9e57ec (commit)
via 1d3b7eabbb5fa3b6674789428b36d7501768b635 (commit)
via 41538b7ce9d6ab4131b572b79d84292884cf4a11 (commit)
via 78dfd7dcd6d76cb75d288a3887e8b099c12f3080 (commit)
via b1d4ff896a7781d98513fab8d171090ac3d6a1e4 (commit)
via 1137e979e1a22465feb03ee0a48499bebcdf6aae (commit)
via 6b99a39f0ab27939c29a05b0332d5ec255bc0764 (commit)
via 12bc8985691e22aad1811322fe1f550b3f710ab8 (commit)
via bf382bba28e32de82649284620e36749a183472d (commit)
via 47c013b000db7235e1ab798eadebc3b42984b06e (commit)
via 247cb9c1d6ca73bb212cb9dfe0aa85dcf342e924 (commit)
via c91bffdd00deb8b7f3ceda9954a84e31c0cfb9f1 (commit)
via ec6cf17e571f9cf23fd1e7bcd573df55106550b1 (commit)
via 746376902a020e0711bc85fc29a2b339a85b3db2 (commit)
via 05136b55f90375a1a7e3a76570cb95bf0590c0ad (commit)
via 0d4a6b6be1e6ba8b3b5681b5c3be7c86d56c076f (commit)
via 686eb4e9edb4adee0cee357762fe9448fb0cb6bd (commit)
via 25cd191443ffd0cffc036c53a0ff57ad2391cead (commit)
via 3d68f767731a682d4a80e9ba74d953502c2ada7d (commit)
via 3c35688d9945077bceba65131bf0f9954181c7f4 (commit)
via e01716291c402d11710387fa6a9b2cfcd8e3953f (commit)
via f802291f6461f3fa7e13fcf3364bb39b4be42c06 (commit)
via fa51dffbe444e5d2ac6a768da001b60ad16d0341 (commit)
via 9cfcbb9475e1f42b5c8953a5a037b833edc5aa69 (commit)
via 0c38d26f6acc7d156dc6c6871b4fa332e30728ee (commit)
via b89e44112425a8d5ab44c26ce988cfb08087ff7e (commit)
via d5a5e815fc96116ee205256b9cba7c11752f0692 (commit)
via 98692b1e0663b4d167670b7808f26b1bb718851c (commit)
via b3d273056fa988f289ae4bf3f0a677808613b97b (commit)
via b9250ecc03ef6854def286e388e9042fbd579971 (commit)
via 8de132995eade03f030a3a66c0f0bf4bc1b0726c (commit)
via 86fcb73a66e62bda72bf5d6aea7f1f852c7f5739 (commit)
via 61beda153425bfbd855c9bca9ff51fb0e99f2943 (commit)
via 038ba06b6e663343e93e63e0d77d3e3c1abf66bf (commit)
via b643e4ef3098a5671687031b2b1348ef60c780fa (commit)
via 1886c9f3083ce3e04d42b8a91e46838ee5a1e774 (commit)
via 371a652b90f43c0a2759b2be4d2fb6ef95d57ff0 (commit)
via 37fd8a72b131d5de9a6fbe612d3dc3d19bafdf83 (commit)
via 1fb24f540ade83926d311316e77e1a6c8bef8432 (commit)
via c4c3946bad5bf1e9be0f375ac1029e1f95e94d94 (commit)
via 5c975417200358c916a62415caf51a1a73e0d470 (commit)
via 538a160ef48f7dbe927f75cafc335e470a82db33 (commit)
via e45115237b2c8c12f0c2fd3c62ae0aff01248cc9 (commit)
via a072ee8db55261a67dc7041c7c17d0536f8def0b (commit)
via 473e340929d0869bf71d972e1a1843dc81b0fbfa (commit)
via 94656c03d42d0339c79d10be8ccedaea6da55028 (commit)
via a6748eee324ebb4cf4ba99aa225df51d71458c81 (commit)
via 5acf0ff36e8503de33ce04fe16e279ec6ee871f1 (commit)
via 14680316801f9274e5b4d099a4dfbf63d7cb110b (commit)
via d25bb8d27cf235603cb8a1d789066b2aa993eccd (commit)
via f2b62e24805e97f66aeac4f9ab3db2d9778c9314 (commit)
via 4fa694dbee3372b8c310aca2c2dafc3ca7550e80 (commit)
via b4bdc9b1f5ec444d1bc4002fe7d65a50acc9d897 (commit)
via e0ce6d2f3010bfc5998e6c7da202258cbe28c6c6 (commit)
via d73842ed35d5aea29466e25a9a6b2dfb4e550e97 (commit)
via 7eaa1760f3ed6cd57cf1b8458516fa3d457371d7 (commit)
via 5c74085e2f4c16655e77e1bcbc308d4fb0a694f8 (commit)
via b7bff77c9dfefe339a386afcaeeb79b4927cfda3 (commit)
via 4babe763de5b20437e32829024f25a1b902df82f (commit)
via ff7d15330f2a74d983972efd1872d1af7d2cd958 (commit)
via 574a6f8834ffa1ef3faddc637257efcde4eae445 (commit)
via fc7462103f1fb344bf91707a1e2de99534e237b9 (commit)
via eace2551ac4260065fbd7d900d157e77dccc6e26 (commit)
via 1ade0a0c0c8ead227aa7f8d374a1748de2535b15 (commit)
via e00795f47f7d88084973ff831278e4cf4004bfad (commit)
via 9047de5e8f973e12e536f7180738e6b515439448 (commit)
via ae8740e0bf3dc8daf25323d442ef5ba135817caa (commit)
via ed5f58850ca6c58778ec3241968ada3bbca67096 (commit)
via 26e55ce110123f7557732ecaeaaad4816cd0375b (commit)
via 397769f9a994bdf1a2716ee89d6746769c11c13d (commit)
via b9b899343170f79cd26929245180180c850d5594 (commit)
via 84d2f3799c493862a22e7b873352da9db766a19d (commit)
via a2bcf6e5b22df3c9bed473d342485548c60c8773 (commit)
via 408728e4512f08c8e50e3f627cc46eb6ad38a315 (commit)
via 2bed6220f561fa39358fb81fde8a2ee0a1b85c38 (commit)
via 274eddb40bacdf8d5933058e33b7d469cb9258c2 (commit)
via f00da76cb77226e6a6b7487f6c5c0bc62d0c3f48 (commit)
via 75ee32436fa5bae4a8f15e25e587d94bf41a59fd (commit)
via ef8ecac02aa21192fb4af8d573daa11b09b3685a (commit)
via 8f7c28971b48c4ee0ab89a3f88d84c4b6fed8185 (commit)
via 1943079713265d5ad64762b107288b6e501c70cf (commit)
via 5b9ab4bc5c038d3fe6e12a0cf90c33e5f54d0f45 (commit)
via 7a0a89d0cab063bb69e4ec4fede497f9d8d329ba (commit)
via 43636d3f31d1684984eb5337b91a418dd1725fbe (commit)
via f5811cdff640338babcf1ca0b4cfc7a06580a4f5 (commit)
via 723885f4ab0096dbea3a21f63badb18d79f28814 (commit)
via 76fa5523da1da9778a686b39dbba5759dcea34da (commit)
via 938d8b3145666d6f7d7084668b0ee665b3458e4a (commit)
via 0ca39bfe35f856eb54ff77c50f5b2230ed20313b (commit)
via 52d245f139122e86c07a4336fbb2495bdb6499d9 (commit)
via 8bd4cd42e061d49d098cb1387b3614226a161f6d (commit)
via dd5bb15644a8e6d0df49d93ee8e982d2d0d463ea (commit)
via 680279e6e9ac7a15d23b8a4d6d03a391166a7c8b (commit)
via 09e793e3c71fbbc12f8f8461ceafbabc2edcbc9e (commit)
via 936498565a5249df01ad44a808bb447952240c90 (commit)
via c74022e2d7acf6b77979e9c8b646d5da95419ed3 (commit)
via 310150445a17a5043cb5e93ce5ecaddd0336b196 (commit)
via c4e44c1a57326915e7291e982e2271b6574f73fc (commit)
via 6f29861b92742da34be9ae76968e82222b5bfd7d (commit)
via da7375d619b7ba63b77c8430f8d67799d8f26026 (commit)
via 1ab6aafab6660d60a5f2e7cf7125d59d5807f2e5 (commit)
via ae20aca3d9324f9439baaf692f42db76ab15912f (commit)
via 0f0501530b755d42670e7e8d9a044027c20e1f27 (commit)
via eff1c6bcb840aa9a8736c6c29a1eeb68eef30279 (commit)
via 92daff7ee6bbd0a41b9a993a1d5d2b151984233a (commit)
via 003b2878529f02062656b84187edb800bc292c35 (commit)
via a38fe354acb2ba6e641d91bec364a22989f30b16 (commit)
via 66f45b3d67dbcb714d445fb3511e19b83cbc8b05 (commit)
via f284e18628afb282c1f5c9feec74b36abd9352be (commit)
via 362430efc09897c1e7d7bdf2bf7b4cffd9fd2e3b (commit)
via dfa822ebc063f5ae636e55e4f999bce3096483e1 (commit)
via 26cd9b7104c48ecce553cab9c8e7de6f57c8e88f (commit)
via 971e8bc5f615ebf009a4b1a60998151054ca34a5 (commit)
via 5bc38109a4c2775a2a2a8389023836facfe8400d (commit)
via 27e2b20fc709884a145df81553504bfc90b8d539 (commit)
via 805fda7d95ada6af81f17fca2816b3a1fe4a3008 (commit)
via 370861e432e88669b2382954b15dbecf1672e032 (commit)
via dcde0c0b983dd0ce788d7273f0cf7e02b37a711d (commit)
via 46c77cb971eeb52802fba8091529c9947bfda05c (commit)
via ff837bb1fc512920556a796c40cacc20407b165c (commit)
via 7e7171deec8d2a31147a9d5700f4315e2ea3e87b (commit)
via af3d7616a9f65bf3effb25d2432d0955dcb5d03b (commit)
via 9b730d026d634dbefdc50eea9d63df77201e30f4 (commit)
via 6bd433b573a427c85cbbd7c75dd1bb08f672d678 (commit)
via 96da4b2e1aa8c82b1f33103a89d7bd8be8ca390b (commit)
via fa10a89c1e4b03da98f9926f31e1680cf5d4ef5d (commit)
via da0b581e22f7a10931767f4d535cfda1554cc525 (commit)
via e5bf564f734555173b5cae04757bc3f870f3463a (commit)
via 6fad0e38082ed1078acb7add13321212dccdcf88 (commit)
via ac07f31fa2182962f4e958330fc460abeac350d5 (commit)
via 34a2c9541c16578175eb928b9ea3f3c7755965d3 (commit)
via 73b258b1b4284e1017aedacee9ed75301be23e79 (commit)
via 4a6553ba36f68f141e7420b070ad6d621f9a8465 (commit)
via 8e51d2165fb35be71aee1a0c381fc71f08a821b5 (commit)
via 718888317b9fb6b24c20d8d417ea540ff23257c5 (commit)
via ae65cad3fbe923329f674694614e0af560c37018 (commit)
via 6e3d1a58e4ec1857fc0264e8070ce67f569b7e42 (commit)
via 076e5cff040e4da53df8dd60cee37a06e4e557c9 (commit)
via ac98e5dbf31b54eb74917d03e53ac071e8c8c92e (commit)
via 022f55634bf4865a315797abafedfbe43d54603b (commit)
via f759086adfb6c899be7a2201f063af49e88f60b7 (commit)
via 5c7990cd039e4350cf2823e8edc10b509d6d8ba7 (commit)
via 0b9f5f6d4afd45a3482ca0d4aec22f5d00df1865 (commit)
via 6978e7fbdfb9c036e1f0fedf04828d6edc731d9e (commit)
via e2a552fcaa6fcc1f0d39defd990bd5a35a4c73a3 (commit)
via 9b8b55c00ba7bba8e4f95336eb2bb34c0b151efb (commit)
via e3cc1803c6fb2aa3373528b6095eb9cf6e8b24d1 (commit)
via 3690baaf0660af752b00a370fadcd60859c50ca4 (commit)
via 704ca46ac3aa9c93c9964eb3495bacd4050f042e (commit)
via 055d0ff12778c3b37b2060900cfacf59dcec2767 (commit)
via 483011e9e126f02863fc10c69278f55f204b5f17 (commit)
via 1ed45f9349d76439f61d9ab88c0ce1ea84cc6711 (commit)
via 5a0aa214c3e6b52ef738ca574105bf0120ac844b (commit)
via fb86b2f215ca1a08440c5c200f22af7747c9de2a (commit)
via 5ee024c32a3ce4afd33d0d5d4df59fcde90d739d (commit)
via b8f538b9fcf70394e5737269d4bed660721c245d (commit)
via 68621232d6840227c4309c1fd1ee9e1a8b26120f (commit)
via c9bae4745f58fc361ebeb0f91bb15b288e96e5cf (commit)
via beccbfe1acb5e6e309d5dee9cbc4461434091520 (commit)
via daf7bbcc05e24e2e6894ac2cf59fa738cfb199bc (commit)
via d1c7c9057bb24595f9dcefe226dc7f326f390486 (commit)
via a7a5b8a6e3605e3a3788f6920a45e9fa3c215be0 (commit)
via eda12494283d717f4fb095be4ff57608f4003502 (commit)
via a66bc5d487b4b095bb9e322e33ed31c55d8af339 (commit)
via c16a30cbaf082a05c0fbd5c929bf0be6f007503f (commit)
via e9498651c8bc59ba17f353f196c0675dd7b8e2ff (commit)
via 0b7e9646307a6e58d3e1df60c68cbac5dbcbfecb (commit)
via 01eb4277b933cb0537204d98b9200550ee3eb641 (commit)
via 5ff43d80fb8eaae5ac2621a5a754cf94204149de (commit)
via abd88f16af1295f2ff67f5e9593e61d1539ef6e4 (commit)
via a3e7cc6cf85981ed5a8a5e63589dfe1767b01e64 (commit)
via 382204ee795971bf6daeebb95f6134bab10ca18d (commit)
via e25a0b2202650ef749340a1993b427bf99d962e5 (commit)
via 7cd33029c63a0cd0889dba94709cf6cadaea48ab (commit)
via c0128e80648ec83fb9f4e3cbf3bb7bba2ef0bbb5 (commit)
via b52c3d66c1462da3733725d2baf40a21b8f521d6 (commit)
via 10a4833ef74f0cf9aebc3861aa69cae6a25ce1cb (commit)
via 35d60f15a86733bb3bc9db77b3d8c7713d83d70d (commit)
via ff7d2f5f77fab130de8db0d59ce48a483a0a8b45 (commit)
via 99767bbe7b2a278ffa88086c24dcd6363d2ed0e5 (commit)
via 3559ddcbe67e91941139c8c74ed77bb9be501dc4 (commit)
via 53ea5695fbd2a596ffda7c9b7bf0dd503b101462 (commit)
via ec9e57a32cefe7db94c2b8b8bebc782b8e872fa9 (commit)
via 88b2af9980fb431eb97dc72cb39214d7e1700ab7 (commit)
via 2c7936f05e6e2055016cdf7f4c915a80f465cde5 (commit)
via a49d8187d7b89c1f40b520b4af324096eb69fa5d (commit)
from 566ab87733df04e288749e8ab5fb7c1a2c1156cf (commit)
Those revisions listed above that are new to this repository have
not appeared on any other notification email; so we list those
revisions in full, below.
- Log -----------------------------------------------------------------
commit 61d7c3959eb991b22bc1c0ef8f4ecb96b65d9325
Merge: 566ab87 27e8639
Author: Yoshitaka Aharen <aharen at jprs.co.jp>
Date: Tue Oct 30 16:38:10 2012 +0900
Merge branch 'master' into trac2155_2
Conflicts:
doc/Doxyfile
src/bin/auth/Makefile.am
src/bin/auth/benchmarks/Makefile.am
src/bin/auth/statistics.h
src/bin/auth/tests/Makefile.am
src/bin/auth/tests/auth_srv_unittest.cc
-----------------------------------------------------------------------
Summary of changes:
ChangeLog | 139 +++-
INSTALL | 4 +
configure.ac | 228 +++---
doc/Doxyfile | 5 +-
doc/devel/02-dhcp.dox | 95 ---
doc/devel/mainpage.dox | 9 +
doc/guide/bind10-guide.xml | 99 ++-
NEWS => examples/AUTHORS | 0
examples/COPYING | 13 +
TODO => examples/ChangeLog | 0
INSTALL => examples/INSTALL | 4 +-
examples/Makefile.am | 4 +
NEWS => examples/NEWS | 0
examples/README | 32 +
examples/configure.ac | 28 +
{src/bin => examples}/host/.gitignore | 0
examples/host/Makefile.am | 6 +
{src/bin => examples}/host/README | 0
{src/bin => examples}/host/b10-host.xml | 0
{src/bin => examples}/host/host.cc | 0
examples/m4/ax_boost_include.m4 | 64 ++
examples/m4/ax_isc_bind10.m4 | 122 +++
src/bin/Makefile.am | 2 +-
src/bin/auth/Makefile.am | 4 +-
src/bin/auth/auth_config.h | 8 +-
src/bin/auth/auth_log.cc | 6 +
src/bin/auth/auth_log.h | 16 +-
src/bin/auth/auth_messages.mes | 95 +++
src/bin/auth/auth_srv.cc | 64 +-
src/bin/auth/auth_srv.h | 55 +-
src/bin/auth/benchmarks/Makefile.am | 2 +
src/bin/auth/benchmarks/query_bench.cc | 42 +-
src/bin/auth/command.cc | 10 +-
src/bin/auth/command.h | 6 +-
src/bin/auth/common.h | 6 +-
src/bin/auth/datasrc_clients_mgr.h | 586 ++++++++++++++
.../tempdir.h.in => bin/auth/datasrc_config.cc} | 23 +-
src/bin/auth/datasrc_config.h | 82 ++
src/bin/auth/datasrc_configurator.h | 223 ------
src/bin/auth/main.cc | 78 +-
src/bin/auth/statistics.h | 6 +-
src/bin/auth/tests/Makefile.am | 7 +-
src/bin/auth/tests/auth_srv_unittest.cc | 136 ++--
src/bin/auth/tests/command_unittest.cc | 139 ++--
.../auth/tests/datasrc_clients_builder_unittest.cc | 523 +++++++++++++
src/bin/auth/tests/datasrc_clients_mgr_unittest.cc | 205 +++++
...ator_unittest.cc => datasrc_config_unittest.cc} | 203 ++---
src/bin/auth/tests/datasrc_util.h | 6 +-
src/bin/auth/tests/query_unittest.cc | 17 +-
src/bin/auth/tests/test_datasrc_clients_mgr.cc | 95 +++
src/bin/auth/tests/test_datasrc_clients_mgr.h | 223 ++++++
src/bin/bind10/bind10_messages.mes | 41 +-
src/bin/bind10/bind10_src.py.in | 61 +-
src/bin/bind10/tests/bind10_test.py.in | 71 +-
src/bin/bindctl/bindcmd.py | 131 +++-
src/bin/bindctl/bindctl_main.py.in | 49 +-
src/bin/bindctl/cmdparse.py | 36 +-
src/bin/bindctl/tests/bindctl_test.py | 210 ++++--
src/bin/cfgmgr/Makefile.am | 2 +-
src/bin/cfgmgr/local_plugins/Makefile.am | 11 +
src/bin/cfgmgr/plugins/Makefile.am | 2 +-
src/bin/cfgmgr/plugins/datasrc.spec.pre.in | 4 +-
src/bin/dbutil/dbutil.py.in | 9 +-
src/bin/dbutil/tests/Makefile.am | 2 +
src/bin/dbutil/tests/dbutil_test.sh.in | 48 +-
src/bin/dbutil/tests/testdata/Makefile.am | 1 +
.../dbutil/tests/testdata/v2_1.sqlite3} | Bin 16384 -> 15360 bytes
src/bin/dhcp4/dhcp4_log.h | 6 +-
src/bin/dhcp4/tests/Makefile.am | 1 +
src/bin/dhcp6/Makefile.am | 2 +
src/bin/dhcp6/config_parser.cc | 797 ++++++++++++++++++++
src/bin/dhcp6/config_parser.h | 147 ++++
src/bin/dhcp6/ctrl_dhcp6_srv.cc | 30 +-
src/bin/dhcp6/dhcp6.dox | 79 ++
src/bin/dhcp6/dhcp6.spec | 92 ++-
src/bin/dhcp6/dhcp6_log.h | 6 +-
src/bin/dhcp6/dhcp6_messages.mes | 20 +
src/bin/dhcp6/dhcp6_srv.cc | 7 +
src/bin/dhcp6/tests/Makefile.am | 4 +
src/bin/dhcp6/tests/config_parser_unittest.cc | 243 ++++++
src/bin/host/Makefile.am | 37 -
src/bin/resolver/resolver.h | 6 +-
src/bin/resolver/resolver_log.h | 6 +-
src/bin/resolver/resolver_messages.mes | 2 +-
src/bin/resolver/response_scrubber.h | 6 +-
src/bin/sockcreator/sockcreator.h | 6 +-
src/bin/sysinfo/.gitignore | 3 +-
src/bin/sysinfo/Makefile.am | 1 +
src/bin/sysinfo/run_sysinfo.sh.in | 38 +
src/bin/sysinfo/sysinfo.py.in | 6 +-
src/bin/tests/process_rename_test.py.in | 7 +
src/cppcheck-suppress.lst | 15 +
src/lib/acl/dns.cc | 23 +-
src/lib/acl/dnsname_check.h | 6 +-
src/lib/acl/ip_check.h | 6 +-
src/lib/acl/tests/sockaddr.h | 6 +-
src/lib/asiodns/asiodns.h | 6 +-
src/lib/asiodns/dns_answer.h | 6 +-
src/lib/asiodns/dns_lookup.h | 6 +-
src/lib/asiodns/dns_server.h | 6 +-
src/lib/asiodns/dns_service.h | 6 +-
src/lib/asiodns/io_fetch.h | 6 +-
src/lib/asiodns/sync_udp_server.h | 6 +-
src/lib/asiodns/tcp_server.h | 6 +-
src/lib/asiodns/udp_server.h | 6 +-
src/lib/asiolink/asiolink.h | 6 +-
src/lib/asiolink/dummy_io_cb.h | 6 +-
src/lib/asiolink/interval_timer.h | 6 +-
src/lib/asiolink/io_address.h | 61 +-
src/lib/asiolink/io_asio_socket.h | 6 +-
src/lib/asiolink/io_endpoint.h | 6 +-
src/lib/asiolink/io_error.h | 6 +-
src/lib/asiolink/io_message.h | 6 +-
src/lib/asiolink/io_service.h | 6 +-
src/lib/asiolink/io_socket.h | 6 +-
src/lib/asiolink/simple_callback.h | 6 +-
src/lib/asiolink/tcp_endpoint.h | 6 +-
src/lib/asiolink/tcp_socket.h | 6 +-
src/lib/asiolink/tests/io_address_unittest.cc | 32 +
src/lib/asiolink/udp_endpoint.h | 6 +-
src/lib/asiolink/udp_socket.h | 6 +-
src/lib/bench/benchmark.h | 6 +-
src/lib/bench/benchmark_util.h | 6 +-
src/lib/cache/cache_entry_key.h | 6 +-
src/lib/cache/local_zone_data.h | 6 +-
src/lib/cache/logger.h | 4 +-
src/lib/cache/message_cache.h | 6 +-
src/lib/cache/message_entry.h | 6 +-
src/lib/cache/message_utility.h | 6 +-
src/lib/cache/resolver_cache.h | 6 +-
src/lib/cache/rrset_cache.h | 6 +-
src/lib/cache/rrset_copy.h | 6 +-
src/lib/cache/rrset_entry.h | 6 +-
src/lib/cache/tests/rrset_entry_unittest.cc | 3 -
src/lib/cc/data.cc | 24 +-
src/lib/cc/data.h | 50 +-
src/lib/cc/session.h | 6 +-
src/lib/cc/tests/data_unittests.cc | 249 ++++--
src/lib/config/ccsession.cc | 6 +-
src/lib/config/ccsession.h | 19 +-
src/lib/config/config_data.h | 4 +-
src/lib/config/config_log.h | 6 +-
src/lib/config/module_spec.h | 4 +-
src/lib/config/tests/fake_session.h | 6 +-
src/lib/config/tests/testdata/Makefile.am | 1 +
src/lib/config/tests/testdata/spec32.spec | 16 +
src/lib/config/tests/testdata/spec42.spec | 17 +
src/lib/cryptolink/crypto_hmac.h | 6 +-
src/lib/cryptolink/cryptolink.h | 6 +-
src/lib/datasrc/Makefile.am | 4 +-
src/lib/datasrc/client.h | 4 +-
src/lib/datasrc/client_list.cc | 123 ++-
src/lib/datasrc/client_list.h | 59 +-
src/lib/datasrc/data_source.h | 4 +-
src/lib/datasrc/database.cc | 16 +-
src/lib/datasrc/database.h | 6 +-
src/lib/datasrc/datasrc_config.h.pre.in | 7 +-
src/lib/datasrc/factory.h | 4 +-
src/lib/datasrc/iterator.h | 6 +-
src/lib/datasrc/logger.h | 4 +-
src/lib/datasrc/memory/Makefile.am | 10 +-
src/lib/datasrc/memory/domaintree.h | 78 +-
.../memory/load_action.h} | 55 +-
src/lib/datasrc/memory/memory_client.cc | 688 ++---------------
src/lib/datasrc/memory/memory_client.h | 91 +--
src/lib/datasrc/memory/treenode_rrset.cc | 2 +-
src/lib/datasrc/memory/zone_data_loader.cc | 250 ++++++
src/lib/datasrc/memory/zone_data_loader.h | 80 ++
src/lib/datasrc/memory/zone_data_updater.cc | 347 +++++++++
src/lib/datasrc/memory/zone_data_updater.h | 180 +++++
src/lib/datasrc/memory/zone_finder.cc | 153 ++--
src/lib/datasrc/memory/zone_finder.h | 2 +-
src/lib/datasrc/memory/zone_table.cc | 53 +-
src/lib/datasrc/memory/zone_table.h | 79 +-
.../memory/zone_table_segment.cc} | 37 +-
src/lib/datasrc/memory/zone_table_segment.h | 149 ++++
src/lib/datasrc/memory/zone_table_segment_local.cc | 69 ++
src/lib/datasrc/memory/zone_table_segment_local.h | 69 ++
src/lib/datasrc/memory/zone_writer.h | 92 +++
src/lib/datasrc/memory/zone_writer_local.cc | 93 +++
src/lib/datasrc/memory/zone_writer_local.h | 95 +++
src/lib/datasrc/memory_datasrc.cc | 12 +-
src/lib/datasrc/memory_datasrc.h | 6 +-
src/lib/datasrc/memory_datasrc_link.cc | 2 +-
src/lib/datasrc/rbnode_rrset.h | 6 +-
src/lib/datasrc/rbtree.h | 6 +-
src/lib/datasrc/result.h | 4 +-
src/lib/datasrc/sqlite3_accessor.cc | 170 +++--
src/lib/datasrc/sqlite3_accessor.h | 6 +-
src/lib/datasrc/tests/client_list_unittest.cc | 175 +++--
src/lib/datasrc/tests/memory/Makefile.am | 4 +
.../datasrc/tests/memory/domaintree_unittest.cc | 31 +-
.../datasrc/tests/memory/memory_client_unittest.cc | 215 +++---
src/lib/datasrc/tests/memory/zone_data_unittest.cc | 2 +-
.../datasrc/tests/memory/zone_finder_unittest.cc | 278 ++-----
.../datasrc/tests/memory/zone_table_segment_test.h | 116 +++
.../tests/memory/zone_table_segment_unittest.cc | 97 +++
.../datasrc/tests/memory/zone_table_unittest.cc | 119 +--
.../datasrc/tests/memory/zone_writer_unittest.cc | 240 ++++++
src/lib/datasrc/tests/memory_datasrc_unittest.cc | 1 -
src/lib/datasrc/tests/sqlite3_accessor_unittest.cc | 15 +-
src/lib/datasrc/tests/test_client.h | 6 +-
src/lib/datasrc/tests/testdata/contexttest.zone | 3 +-
src/lib/datasrc/tests/testdata/example.org.sqlite3 | Bin 16384 -> 15360 bytes
.../datasrc/tests/zone_finder_context_unittest.cc | 22 +-
src/lib/datasrc/zone.h | 136 +++-
src/lib/datasrc/zone_finder_context.cc | 17 +-
src/lib/datasrc/zonetable.h | 6 +-
src/lib/dhcp/Makefile.am | 21 +-
src/lib/dhcp/README | 14 +-
src/lib/dhcp/addr_utilities.cc | 181 +++++
src/lib/dhcp/addr_utilities.h | 53 ++
src/lib/dhcp/alloc_engine.cc | 274 +++++++
src/lib/dhcp/alloc_engine.h | 228 ++++++
src/lib/dhcp/cfgmgr.cc | 111 +++
src/lib/dhcp/cfgmgr.h | 165 ++++
src/lib/dhcp/duid.cc | 90 +++
src/lib/dhcp/duid.h | 104 +++
src/lib/dhcp/lease_mgr.cc | 107 +++
src/lib/dhcp/lease_mgr.h | 516 +++++++++++++
src/lib/dhcp/libdhcp++.dox | 79 ++
src/lib/dhcp/libdhcsrv.dox | 86 +++
src/lib/dhcp/option4_addrlst.h | 1 +
src/lib/dhcp/option6_int.h | 189 +++++
src/lib/dhcp/option6_int_array.h | 228 ++++++
src/lib/dhcp/option_data_types.h | 89 +++
src/lib/dhcp/option_definition.cc | 252 +++++++
src/lib/dhcp/option_definition.h | 383 ++++++++++
src/lib/dhcp/pool.cc | 118 +++
src/lib/dhcp/pool.h | 184 +++++
src/lib/dhcp/subnet.cc | 196 +++++
src/lib/dhcp/subnet.h | 494 ++++++++++++
src/lib/dhcp/tests/.gitignore | 1 +
src/lib/dhcp/tests/Makefile.am | 30 +-
src/lib/dhcp/tests/addr_utilities_unittest.cc | 154 ++++
src/lib/dhcp/tests/alloc_engine_unittest.cc | 349 +++++++++
src/lib/dhcp/tests/cfgmgr_unittest.cc | 99 +++
src/lib/dhcp/tests/duid_unittest.cc | 169 +++++
src/lib/dhcp/tests/iface_mgr_unittest.cc | 2 +-
src/lib/dhcp/tests/lease_mgr_unittest.cc | 170 +++++
src/lib/dhcp/tests/memfile_lease_mgr.cc | 113 +++
src/lib/dhcp/tests/memfile_lease_mgr.h | 228 ++++++
src/lib/dhcp/tests/option6_int_array_unittest.cc | 420 +++++++++++
src/lib/dhcp/tests/option6_int_unittest.cc | 413 ++++++++++
src/lib/dhcp/tests/option_definition_unittest.cc | 610 +++++++++++++++
src/lib/dhcp/tests/pool_unittest.cc | 181 +++++
src/lib/dhcp/tests/run_unittests.cc | 1 -
src/lib/dhcp/tests/subnet_unittest.cc | 421 +++++++++++
src/lib/dhcp/tests/triplet_unittest.cc | 104 +++
src/lib/dhcp/triplet.h | 115 +++
src/lib/dns/Makefile.am | 6 +-
src/lib/dns/benchmarks/message_renderer_bench.cc | 2 +-
src/lib/dns/benchmarks/oldmessagerenderer.h | 6 +-
src/lib/dns/benchmarks/rdatarender_bench.cc | 5 +-
src/lib/dns/character_string.h | 6 +-
src/lib/dns/edns.h | 6 +-
src/lib/dns/exceptions.h | 6 +-
src/lib/dns/gen-rdatacode.py.in | 2 +-
src/lib/dns/labelsequence.h | 4 +-
.../unittests/resource.h => dns/master_lexer.cc} | 50 +-
src/lib/dns/master_lexer.h | 241 ++++++
src/lib/dns/masterload.h | 6 +-
src/lib/dns/message.h | 6 +-
src/lib/dns/messagerenderer.h | 6 +-
src/lib/dns/name.h | 6 +-
src/lib/dns/name_internal.h | 6 +-
src/lib/dns/nsec3hash.h | 6 +-
src/lib/dns/opcode.h | 4 +-
src/lib/dns/python/edns_python.cc | 3 +-
src/lib/dns/python/edns_python.h | 6 +-
src/lib/dns/python/message_python.h | 6 +-
src/lib/dns/python/messagerenderer_python.h | 6 +-
src/lib/dns/python/name_python.h | 6 +-
src/lib/dns/python/nsec3hash_python.h | 6 +-
src/lib/dns/python/opcode_python.h | 6 +-
src/lib/dns/python/pydnspp_common.h | 6 +-
src/lib/dns/python/pydnspp_towire.h | 6 +-
src/lib/dns/python/question_python.h | 6 +-
src/lib/dns/python/rcode_python.h | 6 +-
src/lib/dns/python/rdata_python.h | 6 +-
src/lib/dns/python/rrclass_python.h | 6 +-
src/lib/dns/python/rrset_python.h | 6 +-
src/lib/dns/python/rrttl_python.h | 6 +-
src/lib/dns/python/rrtype_python.h | 6 +-
src/lib/dns/python/serial_python.h | 6 +-
src/lib/dns/python/tsig_python.h | 6 +-
src/lib/dns/python/tsig_rdata_python.h | 6 +-
src/lib/dns/python/tsigerror_python.h | 6 +-
src/lib/dns/python/tsigkey_python.h | 6 +-
src/lib/dns/python/tsigrecord_python.h | 6 +-
src/lib/dns/question.h | 6 +-
src/lib/dns/rcode.h | 4 +-
src/lib/dns/rdata.h | 6 +-
src/lib/dns/rdata/generic/afsdb_18.cc | 1 -
src/lib/dns/rdata/generic/detail/ds_like.h | 6 +-
.../dns/rdata/generic/detail/nsec3param_common.h | 6 +-
src/lib/dns/rdata/generic/detail/nsec_bitmap.h | 6 +-
src/lib/dns/rdata/generic/detail/txt_like.h | 6 +-
src/lib/dns/rdatafields.h | 6 +-
src/lib/dns/rrclass-placeholder.h | 6 +-
src/lib/dns/rrparamregistry.h | 6 +-
src/lib/dns/rrset.cc | 6 +-
src/lib/dns/rrset.h | 11 +-
src/lib/dns/rrsetlist.cc | 60 --
src/lib/dns/rrsetlist.h | 132 ----
src/lib/dns/rrttl.h | 6 +-
src/lib/dns/rrtype-placeholder.h | 14 +-
src/lib/dns/serial.h | 6 +-
src/lib/dns/tests/Makefile.am | 3 +-
src/lib/dns/tests/labelsequence_unittest.cc | 8 +-
src/lib/dns/tests/master_lexer_token_unittest.cc | 156 ++++
src/lib/dns/tests/rdata_unittest.h | 6 +-
src/lib/dns/tests/rrparamregistry_unittest.cc | 5 +-
src/lib/dns/tests/rrset_unittest.cc | 8 +
src/lib/dns/tests/rrsetlist_unittest.cc | 188 -----
src/lib/dns/tests/unittest_util.h | 6 +-
src/lib/dns/tsig.h | 6 +-
src/lib/dns/tsigerror.h | 6 +-
src/lib/dns/tsigkey.h | 6 +-
src/lib/dns/tsigrecord.h | 6 +-
src/lib/exceptions/exceptions.h | 6 +-
src/lib/log/compiler/message.cc | 14 +-
src/lib/log/dummylog.h | 6 +-
src/lib/log/log_dbglevels.h | 6 +-
src/lib/log/log_formatter.h | 4 +-
src/lib/log/log_messages.h | 6 +-
src/lib/log/logger.h | 16 +-
src/lib/log/logger_impl.h | 6 +-
src/lib/log/logger_level.h | 6 +-
src/lib/log/logger_level_impl.h | 6 +-
src/lib/log/logger_manager.h | 6 +-
src/lib/log/logger_manager_impl.h | 6 +-
src/lib/log/logger_name.h | 6 +-
src/lib/log/logger_specification.h | 8 +-
src/lib/log/logger_support.h | 6 +-
src/lib/log/logger_unittest_support.h | 6 +-
src/lib/log/logimpl_messages.h | 6 +-
src/lib/log/macros.h | 4 +-
src/lib/log/message_dictionary.h | 6 +-
src/lib/log/message_exception.h | 6 +-
src/lib/log/message_initializer.h | 6 +-
src/lib/log/message_reader.h | 6 +-
src/lib/log/message_types.h | 6 +-
src/lib/log/output_option.h | 6 +-
src/lib/log/tests/log_formatter_unittest.cc | 14 +-
src/lib/log/tests/logger_example.cc | 1 -
src/lib/log/tests/logger_unittest.cc | 21 +-
.../log/tests/message_initializer_2_unittest.cc | 11 +-
src/lib/log/tests/tempdir.h.in | 6 +-
src/lib/nsas/address_entry.h | 6 +-
src/lib/nsas/address_request_callback.h | 6 +-
src/lib/nsas/asiolink.h | 6 +-
src/lib/nsas/fetchable.h | 6 +-
src/lib/nsas/glue_hints.h | 6 +-
src/lib/nsas/hash.h | 6 +-
src/lib/nsas/hash_deleter.h | 6 +-
src/lib/nsas/hash_key.h | 6 +-
src/lib/nsas/hash_table.h | 6 +-
src/lib/nsas/nameserver_address.h | 6 +-
src/lib/nsas/nameserver_address_store.h | 6 +-
src/lib/nsas/nameserver_entry.h | 6 +-
src/lib/nsas/nsas_entry.h | 6 +-
src/lib/nsas/nsas_entry_compare.h | 6 +-
src/lib/nsas/nsas_log.h | 6 +-
src/lib/nsas/nsas_types.h | 6 +-
src/lib/nsas/tests/nsas_test.h | 6 +-
src/lib/nsas/zone_entry.h | 6 +-
src/lib/python/bind10_config.py.in | 4 +-
src/lib/python/isc/acl/dns.h | 6 +-
src/lib/python/isc/acl/dns_requestacl_python.h | 6 +-
src/lib/python/isc/acl/dns_requestcontext_python.h | 6 +-
src/lib/python/isc/acl/dns_requestloader_python.h | 6 +-
src/lib/python/isc/bind10/component.py | 36 +-
src/lib/python/isc/bind10/sockcreator.py | 5 +
src/lib/python/isc/bind10/tests/component_test.py | 65 +-
src/lib/python/isc/config/ccsession.py | 8 +-
src/lib/python/isc/config/config_data.py | 99 ++-
src/lib/python/isc/config/tests/ccsession_test.py | 16 +-
.../python/isc/config/tests/config_data_test.py | 99 ++-
src/lib/python/isc/datasrc/client_python.h | 6 +-
.../isc/datasrc/configurableclientlist_python.h | 6 +-
src/lib/python/isc/datasrc/datasrc.h | 6 +-
src/lib/python/isc/datasrc/finder_python.h | 6 +-
src/lib/python/isc/datasrc/iterator_python.h | 6 +-
src/lib/python/isc/datasrc/journal_reader_python.h | 6 +-
src/lib/python/isc/datasrc/sqlite3_ds.py | 3 +-
src/lib/python/isc/datasrc/updater_python.h | 6 +-
src/lib/python/isc/sysinfo/sysinfo.py | 37 +-
src/lib/python/isc/sysinfo/tests/sysinfo_test.py | 65 +-
src/lib/python/isc/util/cio/socketsession_python.h | 6 +-
.../isc/util/cio/socketsessionforwarder_python.h | 6 +-
.../isc/util/cio/socketsessionreceiver_python.h | 6 +-
src/lib/resolve/recursive_query.cc | 85 ++-
src/lib/resolve/recursive_query.h | 51 +-
src/lib/resolve/resolve.h | 4 +-
src/lib/resolve/resolve_log.h | 6 +-
src/lib/resolve/resolver_callback.h | 4 +-
src/lib/resolve/resolver_interface.h | 6 +-
src/lib/resolve/response_classifier.h | 6 +-
src/lib/resolve/tests/recursive_query_unittest.cc | 87 +--
.../resolve/tests/recursive_query_unittest_2.cc | 35 +-
.../resolve/tests/recursive_query_unittest_3.cc | 36 +-
src/lib/server_common/client.h | 6 +-
src/lib/server_common/logger.h | 4 +-
src/lib/server_common/socket_request.h | 6 +-
src/lib/server_common/tests/portconfig_unittest.cc | 67 +-
.../server_common/tests/socket_requestor_test.cc | 4 +-
src/lib/statistics/counter.h | 4 +-
src/lib/statistics/counter_dict.h | 4 +-
src/lib/testutils/dnsmessage_test.h | 122 +--
src/lib/testutils/mockups.h | 6 +-
src/lib/testutils/portconfig.h | 6 +-
src/lib/testutils/socket_request.h | 6 +-
src/lib/testutils/srv_test.h | 6 +-
src/lib/util/Makefile.am | 5 +-
src/lib/util/buffer.h | 6 +-
src/lib/util/encode/base32hex.h | 6 +-
src/lib/util/encode/base64.h | 6 +-
src/lib/util/encode/hex.h | 6 +-
src/lib/util/filename.h | 6 +-
src/lib/util/hash/sha1.cc | 4 +-
src/lib/util/hash/sha1.h | 4 +-
src/lib/util/interprocess_sync.h | 6 +-
src/lib/util/interprocess_sync_file.h | 6 +-
src/lib/util/interprocess_sync_null.h | 6 +-
src/lib/util/io/fd.h | 6 +-
src/lib/util/io/fd_share.cc | 1 +
src/lib/util/io/pktinfo_utilities.h | 6 +-
src/lib/util/io/sockaddr_util.h | 6 +-
src/lib/util/io/socketsession.h | 6 +-
src/lib/util/io_utilities.h | 6 +-
src/lib/util/locks.h | 14 +-
src/lib/util/lru_list.h | 6 +-
src/lib/util/memory_segment.h | 6 +-
src/lib/util/memory_segment_local.h | 6 +-
src/lib/util/python/pycppwrapper_util.h | 6 +-
src/lib/util/python/wrapper_template.h | 6 +-
src/lib/util/random/qid_gen.h | 6 +-
src/lib/util/random/random_number_generator.h | 6 +-
src/lib/util/range_utilities.h | 25 +-
src/lib/util/strutil.h | 6 +-
src/lib/util/tests/buffer_unittest.cc | 23 +-
src/lib/util/tests/fd_tests.cc | 4 +-
src/lib/util/tests/lru_list_unittest.cc | 6 +-
src/lib/util/threads/Makefile.am | 12 +
src/lib/util/threads/sync.cc | 240 ++++++
src/lib/util/threads/sync.h | 229 ++++++
.../auth => lib/util/threads}/tests/.gitignore | 0
src/lib/util/threads/tests/Makefile.am | 37 +
src/lib/util/threads/tests/condvar_unittest.cc | 169 +++++
src/lib/util/threads/tests/lock_unittest.cc | 127 ++++
.../{dhcp => util/threads}/tests/run_unittests.cc | 12 +-
src/lib/util/threads/tests/thread_unittest.cc | 98 +++
src/lib/util/threads/thread.cc | 172 +++++
src/lib/util/threads/thread.h | 112 +++
src/lib/util/time_utilities.h | 8 +-
src/lib/util/unittests/Makefile.am | 1 +
.../unittests/{resource.h => check_valgrind.cc} | 32 +-
src/lib/util/unittests/check_valgrind.h | 50 ++
src/lib/util/unittests/fork.h | 6 +-
src/lib/util/unittests/mock_socketsession.h | 6 +-
src/lib/util/unittests/newhook.h | 6 +-
src/lib/util/unittests/resource.h | 6 +-
src/lib/util/unittests/run_all.h | 6 +-
src/lib/util/unittests/testdata.h | 6 +-
src/lib/util/unittests/textdata.h | 6 +-
src/lib/util/unittests/wiredata.h | 6 +-
src/lib/xfr/xfrout_client.h | 4 +-
tests/lettuce/configurations/auth/.gitignore | 1 +
.../configurations/auth/auth_basic.config.orig | 22 +
tests/lettuce/features/auth_basic.feature | 20 +
tests/lettuce/features/terrain/terrain.py | 2 +
tests/tools/badpacket/command_options.h | 6 +-
tests/tools/badpacket/header_flags.h | 6 +-
tests/tools/badpacket/option_info.h | 6 +-
tests/tools/badpacket/scan.h | 6 +-
tests/tools/badpacket/version.h | 6 +-
tests/tools/perfdhcp/command_options.h | 6 +-
tests/tools/perfdhcp/localized_option.h | 6 +-
tests/tools/perfdhcp/perf_pkt4.h | 6 +-
tests/tools/perfdhcp/perf_pkt6.h | 6 +-
tests/tools/perfdhcp/pkt_transform.h | 6 +-
tests/tools/perfdhcp/stats_mgr.h | 6 +-
tests/tools/perfdhcp/templates/.gitignore | 5 +
tests/tools/perfdhcp/test_control.h | 8 +-
.../tools/perfdhcp/tests/command_options_helper.h | 6 +-
486 files changed, 19115 insertions(+), 4259 deletions(-)
copy NEWS => examples/AUTHORS (100%)
create mode 100644 examples/COPYING
rename TODO => examples/ChangeLog (100%)
copy INSTALL => examples/INSTALL (52%)
create mode 100644 examples/Makefile.am
rename NEWS => examples/NEWS (100%)
create mode 100644 examples/README
create mode 100644 examples/configure.ac
rename {src/bin => examples}/host/.gitignore (100%)
create mode 100644 examples/host/Makefile.am
rename {src/bin => examples}/host/README (100%)
rename {src/bin => examples}/host/b10-host.xml (100%)
rename {src/bin => examples}/host/host.cc (100%)
create mode 100644 examples/m4/ax_boost_include.m4
create mode 100644 examples/m4/ax_isc_bind10.m4
create mode 100644 src/bin/auth/datasrc_clients_mgr.h
copy src/{lib/log/tests/tempdir.h.in => bin/auth/datasrc_config.cc} (62%)
create mode 100644 src/bin/auth/datasrc_config.h
delete mode 100644 src/bin/auth/datasrc_configurator.h
create mode 100644 src/bin/auth/tests/datasrc_clients_builder_unittest.cc
create mode 100644 src/bin/auth/tests/datasrc_clients_mgr_unittest.cc
rename src/bin/auth/tests/{datasrc_configurator_unittest.cc => datasrc_config_unittest.cc} (59%)
create mode 100644 src/bin/auth/tests/test_datasrc_clients_mgr.cc
create mode 100644 src/bin/auth/tests/test_datasrc_clients_mgr.h
create mode 100644 src/bin/cfgmgr/local_plugins/Makefile.am
copy src/{lib/datasrc/tests/testdata/example.org.sqlite3 => bin/dbutil/tests/testdata/v2_1.sqlite3} (55%)
create mode 100644 src/bin/dhcp6/config_parser.cc
create mode 100644 src/bin/dhcp6/config_parser.h
create mode 100644 src/bin/dhcp6/dhcp6.dox
create mode 100644 src/bin/dhcp6/tests/config_parser_unittest.cc
delete mode 100644 src/bin/host/Makefile.am
create mode 100755 src/bin/sysinfo/run_sysinfo.sh.in
create mode 100644 src/lib/config/tests/testdata/spec42.spec
copy src/lib/{python/isc/datasrc/configurableclientlist_python.h => datasrc/memory/load_action.h} (50%)
create mode 100644 src/lib/datasrc/memory/zone_data_loader.cc
create mode 100644 src/lib/datasrc/memory/zone_data_loader.h
create mode 100644 src/lib/datasrc/memory/zone_data_updater.cc
create mode 100644 src/lib/datasrc/memory/zone_data_updater.h
copy src/lib/{python/isc/datasrc/configurableclientlist_python.h => datasrc/memory/zone_table_segment.cc} (58%)
create mode 100644 src/lib/datasrc/memory/zone_table_segment.h
create mode 100644 src/lib/datasrc/memory/zone_table_segment_local.cc
create mode 100644 src/lib/datasrc/memory/zone_table_segment_local.h
create mode 100644 src/lib/datasrc/memory/zone_writer.h
create mode 100644 src/lib/datasrc/memory/zone_writer_local.cc
create mode 100644 src/lib/datasrc/memory/zone_writer_local.h
create mode 100644 src/lib/datasrc/tests/memory/zone_table_segment_test.h
create mode 100644 src/lib/datasrc/tests/memory/zone_table_segment_unittest.cc
create mode 100644 src/lib/datasrc/tests/memory/zone_writer_unittest.cc
create mode 100644 src/lib/dhcp/addr_utilities.cc
create mode 100644 src/lib/dhcp/addr_utilities.h
create mode 100644 src/lib/dhcp/alloc_engine.cc
create mode 100644 src/lib/dhcp/alloc_engine.h
create mode 100644 src/lib/dhcp/cfgmgr.cc
create mode 100644 src/lib/dhcp/cfgmgr.h
create mode 100644 src/lib/dhcp/duid.cc
create mode 100644 src/lib/dhcp/duid.h
create mode 100644 src/lib/dhcp/lease_mgr.cc
create mode 100644 src/lib/dhcp/lease_mgr.h
create mode 100644 src/lib/dhcp/libdhcp++.dox
create mode 100644 src/lib/dhcp/libdhcsrv.dox
create mode 100644 src/lib/dhcp/option6_int.h
create mode 100644 src/lib/dhcp/option6_int_array.h
create mode 100644 src/lib/dhcp/option_data_types.h
create mode 100644 src/lib/dhcp/option_definition.cc
create mode 100644 src/lib/dhcp/option_definition.h
create mode 100644 src/lib/dhcp/pool.cc
create mode 100644 src/lib/dhcp/pool.h
create mode 100644 src/lib/dhcp/subnet.cc
create mode 100644 src/lib/dhcp/subnet.h
create mode 100644 src/lib/dhcp/tests/addr_utilities_unittest.cc
create mode 100644 src/lib/dhcp/tests/alloc_engine_unittest.cc
create mode 100644 src/lib/dhcp/tests/cfgmgr_unittest.cc
create mode 100644 src/lib/dhcp/tests/duid_unittest.cc
create mode 100644 src/lib/dhcp/tests/lease_mgr_unittest.cc
create mode 100644 src/lib/dhcp/tests/memfile_lease_mgr.cc
create mode 100644 src/lib/dhcp/tests/memfile_lease_mgr.h
create mode 100644 src/lib/dhcp/tests/option6_int_array_unittest.cc
create mode 100644 src/lib/dhcp/tests/option6_int_unittest.cc
create mode 100644 src/lib/dhcp/tests/option_definition_unittest.cc
create mode 100644 src/lib/dhcp/tests/pool_unittest.cc
create mode 100644 src/lib/dhcp/tests/subnet_unittest.cc
create mode 100644 src/lib/dhcp/tests/triplet_unittest.cc
create mode 100644 src/lib/dhcp/triplet.h
copy src/lib/{util/unittests/resource.h => dns/master_lexer.cc} (51%)
create mode 100644 src/lib/dns/master_lexer.h
delete mode 100644 src/lib/dns/rrsetlist.cc
delete mode 100644 src/lib/dns/rrsetlist.h
create mode 100644 src/lib/dns/tests/master_lexer_token_unittest.cc
delete mode 100644 src/lib/dns/tests/rrsetlist_unittest.cc
create mode 100644 src/lib/util/threads/Makefile.am
create mode 100644 src/lib/util/threads/sync.cc
create mode 100644 src/lib/util/threads/sync.h
copy src/{bin/auth => lib/util/threads}/tests/.gitignore (100%)
create mode 100644 src/lib/util/threads/tests/Makefile.am
create mode 100644 src/lib/util/threads/tests/condvar_unittest.cc
create mode 100644 src/lib/util/threads/tests/lock_unittest.cc
copy src/lib/{dhcp => util/threads}/tests/run_unittests.cc (77%)
create mode 100644 src/lib/util/threads/tests/thread_unittest.cc
create mode 100644 src/lib/util/threads/thread.cc
create mode 100644 src/lib/util/threads/thread.h
copy src/lib/util/unittests/{resource.h => check_valgrind.cc} (62%)
create mode 100644 src/lib/util/unittests/check_valgrind.h
create mode 100644 tests/lettuce/configurations/auth/.gitignore
create mode 100644 tests/lettuce/configurations/auth/auth_basic.config.orig
create mode 100644 tests/lettuce/features/auth_basic.feature
create mode 100644 tests/tools/perfdhcp/templates/.gitignore
-----------------------------------------------------------------------
diff --git a/ChangeLog b/ChangeLog
index 84d4378..e8944f8 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,134 @@
+497. [bug] jinmei
+ Fixed several issues in isc-sysinfo:
+ - make sure it doesn't report a negative value for free memory
+ size (this happened on FreeBSD, but can possibly occur on other
+ BSD variants)
+ - correctly identifies the SMP support in kernel on FreeBSD
+ - print more human readable uptime as well as the time in seconds
+ (Trac #2297, git 59a449f506948e2371ffa87dcd19059388bd1657)
+
+496. [func] tomek
+ DHCPv6 Allocation Engine implemented. It allows address allocation
+ from the configured subnets/pools. It currently features a single
+ allocator: IterativeAllocator, which assigns addresses iteratively.
+ Other allocators (hashed, random) are planned.
+ (Trac #2324, git 8aa188a10298e3a55b725db36502a99d2a8d638a)
+
+495. [func] team
+ b10-auth now handles reconfiguration of data sources in
+ background using a separate thread. This means even if the new
+ configuration includes a large amount of data to be loaded into
+ memory (very large zones and/or a very large number of zones),
+ the reconfiguration doesn't block query handling.
+ (Multiple Trac tickets up to #2211)
+
+494. [bug] jinmei
+ Fixed a problem that shutting down BIND 10 kept some of the
+ processes alive. It was two-fold: when the main bind10 process
+ started as a root, started b10-sockcreator with the privilege, and
+ then dropped the privilege, the bind10 process cannot kill the
+ sockcreator via signal any more (when it has to), but it kept
+ sending the signal and didn't stop. Also, when running on Python
+ 3.1 (or older), the sockcreator had some additional file
+ descriptor open, which prevented it from exiting even after the
+ bind10 process terminated. Now the bind10 process simply gives up
+ killing a subprocess if it fails due to lack of permission, and it
+ makes sure the socket creator is spawned without any unnecessary
+ FDs open.
+ (Trac #1858, git 405d85c8a0042ba807a3a123611ff383c4081ee1)
+
+493. [build] jinmei
+ Fixed build failure with newer versions of clang++. These
+ versions are stricter regarding "unused variable" and "unused
+ (driver) arguments" warnings, and cause fatal build error
+ with -Werror. The affected versions of clang++ include Apple's
+ customized version 4.1 included in Xcode 4.5.1. So this fix
+ will solve build errors for Mac OS X that uses newer versions of
+ Xcode.
+ (Trac #2340, git 55be177fc4f7537143ab6ef5a728bd44bdf9d783,
+ 3e2a372012e633d017a97029d13894e743199741 and commits before it
+ with [2340] in the commit log)
+
+492. [func] tomek
+ libdhcpsrv: The DHCP Configuration Manager is now able to store
+ information about IPv4 subnets and pools. It is still not possible
+ to configure that information. Such capability will be implemented
+ in a near future.
+ (Trac #2237, git a78e560343b41f0f692c7903c938b2b2b24bf56b)
+
+491. [func] tomek
+ b10-dhcp6: Configuration for DHCPv6 has been implemented.
+ Currently it is possible to configure IPv6 subnets and pools
+ within those subnets, global and per subnet values of renew,
+ rebind, preferred and valid lifetimes. Configured parameters
+ are accepted, but are not used yet by the allocation engine yet.
+ (Trac #2269, git 028bed9014b15facf1a29d3d4a822c9d14fc6411)
+
+490. [func] tomek
+ libdhcpsrv: An abstract API for lease database has been
+ implemented. It offers a common interface to all concrete
+ database backends.
+ (Trac #2140, git df196f7609757253c4f2f918cd91012bb3af1163)
+
+489. [func] muks
+ The isc::dns::RRsetList class has been removed. It was now unused
+ inside the BIND 10 codebase, and the interface was considered
+ prone to misuse.
+ (Trac #2266, git 532ac3d0054f6a11b91ee369964f3a84dabc6040)
+
+488. [build] jinmei
+ On configure, changed the search order for Python executable.
+ It first tries more specific file names such as "python3.2" before
+ more generic "python3". This will prevent configure failure on
+ Mac OS X that installs Python3 via recent versions of Homebrew.
+ (Trac #2339, git 88db890d8d1c64de49be87f03c24a2021bcf63da)
+
+487. [bug] jinmei
+ The bind10 process now terminates a component (subprocess) by the
+ "config remove Boss/components" bindctl command even if the
+ process crashes immediately before the command is sent to bind10.
+ Previously this led to an inconsistent state between the
+ configuration and an internal component list of bind10, and bind10
+ kept trying to restart the component. A known specific case of
+ this problem is that b10-ddns could keep failing (due to lack of
+ dependency modules) and the administrator couldn't stop the
+ restart via bindctl.
+ (Trac #2244, git 7565788d06f216ab254008ffdfae16678bcd00e5)
+
+486. [bug]* jinmei
+ All public header files for libb10-dns++ are now installed.
+ Template configure.ac and utility AC macros for external projects
+ using the library are provided under the "examples" directory.
+ The src/bin/host was moved as part of the examples (and not
+ installed with other BIND 10 programs any more).
+ (Trac #1870, git 4973e638d354d8b56dcadf71123ef23c15662021)
+
+485. [bug] jelte
+ Several bugs have been fixed in bindctl; tab-completion now works
+ within configuration lists, the problem where sometimes the
+ completion added a part twice has been solved, and it no longer
+ suggests the confusing value 'argument' as a completion-hint for
+ configuration items. Additionally, bindctl no longer crashes upon
+ input like 'config remove Boss'.
+ (Trac #2254, git 9047de5e8f973e12e536f7180738e6b515439448)
+
+484. [func] tomek
+ A new library (libb10-dhcpsrv) has been created. At present, it
+ only holds the code for the DHCP Configuration Manager. Currently
+ this object only supports basic configuration storage for the DHCPv6
+ server, but that capability will be expanded.
+ (Trac #2238, git 6f29861b92742da34be9ae76968e82222b5bfd7d)
+
+bind10-devel-20120927 released on September 27, 2012
+
+483. [func] marcin
+ libdhcp++: Added new parameter to define sub-second timeout
+ for DHCP packet reception. The total timeout is now specified
+ by two parameters: first specifies integral number of
+ seconds, second (which defaults to 0) specifies fractional
+ seconds with microsecond resolution.
+ (Trac #2231, git 15560cac16e4c52129322e3cb1787e0f47cf7850)
+
482. [func] team
Memory footprint of the in-memory data source has been
substantially improved. For example, b10-auth now requires much
@@ -9,11 +140,11 @@
of the memory image. Also, loading zones in memory still suspends
query processing, so manual reloading or reloading after incoming
transfer may cause service disruption for huge zones.
- (Multiple Trac tickets)
+ (Multiple Trac tickets, Summarized in Trac #2101)
481. [bug] vorner
The abbreviated form of IP addresses in ACLs is accepted
- (eg. "from": ["127.0.01", "::1"] now works).
+ (eg. "from": ["127.0.0.1", "::1"] now works).
(Trac #2191, git 48b6e91386b46eed383126ad98dddfafc9f7e75e)
480. [doc] vorner
@@ -45,10 +176,10 @@
(Trac #2190, git e0ffa11d49ab949ee5a4ffe7682b0e6906667baa)
476. [bug] vorner
- The XfrIn now accepts transfers with some TSIG signatures omitted, as
+ The Xfrin now accepts transfers with some TSIG signatures omitted, as
allowed per RFC2845, section 4.4. This solves a compatibility
issues with Knot and NSD.
- (Trac #1375, git 7ca65cb9ec528118f370142d7e7b792fcc31c9cf)
+ (Trac #1357, git 7ca65cb9ec528118f370142d7e7b792fcc31c9cf)
475. [func] naokikambe
Added Xfrout statistics counters: notifyoutv4, notifyoutv6,
diff --git a/INSTALL b/INSTALL
index 839f120..944cb25 100644
--- a/INSTALL
+++ b/INSTALL
@@ -7,3 +7,7 @@ To then build from source:
For detailed installation directions, see the guide
at doc/guide/bind10-guide.txt or doc/guide/bind10-guide.html.
+
+You can find user-contributed OS-specific build/installation
+instructions on the BIND 10 wiki:
+http://bind10.isc.org/wiki/SystemSpecificNotes
diff --git a/NEWS b/NEWS
deleted file mode 100644
index e69de29..0000000
diff --git a/TODO b/TODO
deleted file mode 100644
index e69de29..0000000
diff --git a/configure.ac b/configure.ac
index b064480..a037fdf 100644
--- a/configure.ac
+++ b/configure.ac
@@ -4,7 +4,7 @@
AC_PREREQ([2.59])
AC_INIT(bind10-devel, 20120817, bind10-dev at isc.org)
AC_CONFIG_SRCDIR(README)
-AM_INIT_AUTOMAKE
+AM_INIT_AUTOMAKE([foreign])
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])dnl be backward compatible
AC_CONFIG_HEADERS([config.h])
AC_CONFIG_MACRO_DIR([m4macros])
@@ -12,6 +12,20 @@ AC_CONFIG_MACRO_DIR([m4macros])
# Checks for programs.
AC_PROG_CXX
+# Enable low-performing debugging facilities? This option optionally
+# enables some debugging aids that perform slowly and hence aren't built
+# by default.
+AC_ARG_ENABLE([debug],
+ AS_HELP_STRING([--enable-debug],
+ [enable debugging (default is no)]),
+ [case "${enableval}" in
+ yes) debug_enabled=yes ;;
+ no) debug_enabled=no ;;
+ *) AC_MSG_ERROR([bad value ${enableval} for --enable-debug]) ;;
+ esac],[debug_enabled=no])
+AM_CONDITIONAL([DEBUG_ENABLED], [test x$debug_enabled = xyes])
+AM_COND_IF([DEBUG_ENABLED], [AC_DEFINE([ENABLE_DEBUG], [1], [Enable low-performing debugging facilities?])])
+
# Libtool configuration
#
@@ -70,6 +84,106 @@ AC_TRY_LINK([],[],
])
LDFLAGS=$LDFLAGS_SAVED
+# Compiler dependent settings: define some mandatory CXXFLAGS here.
+# We also use a separate variable B10_CXXFLAGS. This will (and should) be
+# used as the default value for each specific AM_CXXFLAGS:
+# AM_CXXFLAGS = $(B10_CXXFLAGS)
+# AM_CXXFLAGS += ... # add module specific flags
+# We need this so that we can disable some specific compiler warnings per
+# module basis; since AM_CXXFLAGS are placed before CXXFLAGS, and since
+# gcc's -Wno-XXX option must be specified after -Wall or -Wextra, we cannot
+# specify the default warning flags in CXXFLAGS and let specific modules
+# "override" the default.
+
+# This may be used to try linker flags.
+AC_DEFUN([BIND10_CXX_TRY_FLAG], [
+ AC_MSG_CHECKING([whether $CXX supports $1])
+
+ bind10_save_CXXFLAGS="$CXXFLAGS"
+ CXXFLAGS="$CXXFLAGS $1"
+
+ AC_LINK_IFELSE([AC_LANG_SOURCE([int main(void){ return 0;}])],
+ [bind10_cxx_flag=yes], [bind10_cxx_flag=no])
+ CXXFLAGS="$bind10_save_CXXFLAGS"
+
+ if test "x$bind10_cxx_flag" = "xyes"; then
+ ifelse([$2], , :, [$2])
+ else
+ ifelse([$3], , :, [$3])
+ fi
+
+ AC_MSG_RESULT([$bind10_cxx_flag])
+])
+
+# SunStudio compiler requires special compiler options for boost
+# (http://blogs.sun.com/sga/entry/boost_mini_howto)
+if test "$SUNCXX" = "yes"; then
+CXXFLAGS="$CXXFLAGS -library=stlport4 -features=tmplife -features=tmplrefstatic"
+MULTITHREADING_FLAG="-mt"
+fi
+
+# Newer versions of clang++ promotes "unused driver arguments" warnings to
+# a fatal error with -Werror, causing build failure. Since we use multiple
+# compilers on multiple systems, this can easily happen due to settings for
+# non clang++ environments that could be just ignored otherwise. It can also
+# happen if clang++ is used via ccache. So, although probably suboptimal,
+# we suppress this particular warning. Note that it doesn't weaken checks
+# on the source code.
+if test "$CLANGPP" = "yes"; then
+ B10_CXXFLAGS="$B10_CXXFLAGS -Qunused-arguments"
+fi
+
+BIND10_CXX_TRY_FLAG([-Wno-missing-field-initializers],
+ [WARNING_NO_MISSING_FIELD_INITIALIZERS_CFLAG="-Wno-missing-field-initializers"])
+AC_SUBST(WARNING_NO_MISSING_FIELD_INITIALIZERS_CFLAG)
+
+# gcc specific settings:
+if test "X$GXX" = "Xyes"; then
+B10_CXXFLAGS="$B10_CXXFLAGS -Wall -Wextra -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare"
+case "$host" in
+*-solaris*)
+ MULTITHREADING_FLAG=-pthreads
+ # In Solaris, IN6ADDR_ANY_INIT and IN6ADDR_LOOPBACK_INIT need -Wno-missing-braces
+ B10_CXXFLAGS="$B10_CXXFLAGS -Wno-missing-braces"
+ ;;
+*)
+ MULTITHREADING_FLAG=-pthread
+ ;;
+esac
+
+# Don't use -Werror if configured not to
+AC_ARG_WITH(werror,
+ AC_HELP_STRING([--with-werror], [Compile using -Werror (default=yes)]),
+ [
+ case "${withval}" in
+ yes) with_werror=1 ;;
+ no) with_werror=0 ;;
+ *) AC_MSG_ERROR(bad value ${withval} for --with-werror) ;;
+ esac],
+ [with_werror=1])
+
+werror_ok=0
+
+# Certain versions of gcc (g++) have a bug that incorrectly warns about
+# the use of anonymous name spaces even if they're closed in a single
+# translation unit. For these versions we have to disable -Werror.
+if test $with_werror = 1; then
+ CXXFLAGS_SAVED="$CXXFLAGS"
+ CXXFLAGS="$CXXFLAGS $B10_CXXFLAGS -Werror"
+ AC_MSG_CHECKING(for in-TU anonymous namespace breakage)
+ AC_TRY_COMPILE([namespace { class Foo {}; }
+ namespace isc {class Bar {Foo foo_;};} ],,
+ [AC_MSG_RESULT(no)
+ werror_ok=1
+ B10_CXXFLAGS="$B10_CXXFLAGS -Werror"],
+ [AC_MSG_RESULT(yes)])
+ CXXFLAGS="$CXXFLAGS_SAVED"
+fi
+
+fi dnl GXX = yes
+
+AM_CONDITIONAL(GCC_WERROR_OK, test $werror_ok = 1)
+
# allow building programs with static link. we need to make it selective
# because loadable modules cannot be statically linked.
AC_ARG_ENABLE([static-link],
@@ -103,6 +217,10 @@ case "$host" in
CPPFLAGS="$CPPFLAGS -D_XPG4_2 -D__EXTENSIONS__"
# "now" binding is necessary to prevent deadlocks in C++ static initialization code
LDFLAGS="$LDFLAGS -z now"
+ # Destroying locked mutexes, condition variables being waited
+ # on, etc. are undefined behavior on Solaris, so we set it as
+ # such here.
+ AC_DEFINE([HAS_UNDEFINED_PTHREAD_BEHAVIOR], [1], [Does this platform have some undefined pthreads behavior?])
;;
*-apple-darwin*)
# Starting with OSX 10.7 (Lion) we must choose which IPv6 API to use
@@ -132,7 +250,7 @@ AM_CONDITIONAL(SET_ENV_LIBRARY_PATH, test $SET_ENV_LIBRARY_PATH = yes)
AC_SUBST(SET_ENV_LIBRARY_PATH)
AC_SUBST(ENV_LIBRARY_PATH)
-m4_define([_AM_PYTHON_INTERPRETER_LIST], [python python3 python3.1 python3.2])
+m4_define([_AM_PYTHON_INTERPRETER_LIST], [python python3.2 python3.1 python3])
AC_ARG_WITH([pythonpath],
AC_HELP_STRING([--with-pythonpath=PATH],
[specify an absolute path to python executable when automatic version check (incorrectly) fails]),
@@ -256,95 +374,11 @@ fi
# TODO: check for _sqlite3.py module
-# Compiler dependent settings: define some mandatory CXXFLAGS here.
-# We also use a separate variable B10_CXXFLAGS. This will (and should) be
-# used as the default value for each specific AM_CXXFLAGS:
-# AM_CXXFLAGS = $(B10_CXXFLAGS)
-# AM_CXXFLAGS += ... # add module specific flags
-# We need this so that we can disable some specific compiler warnings per
-# module basis; since AM_CXXFLAGS are placed before CXXFLAGS, and since
-# gcc's -Wno-XXX option must be specified after -Wall or -Wextra, we cannot
-# specify the default warning flags in CXXFLAGS and let specific modules
-# "override" the default.
-
-# This may be used to try linker flags.
-AC_DEFUN([BIND10_CXX_TRY_FLAG], [
- AC_MSG_CHECKING([whether $CXX supports $1])
-
- bind10_save_CXXFLAGS="$CXXFLAGS"
- CXXFLAGS="$CXXFLAGS $1"
-
- AC_LINK_IFELSE([AC_LANG_SOURCE([int main(void){ return 0;}])],
- [bind10_cxx_flag=yes], [bind10_cxx_flag=no])
- CXXFLAGS="$bind10_save_CXXFLAGS"
-
- if test "x$bind10_cxx_flag" = "xyes"; then
- ifelse([$2], , :, [$2])
- else
- ifelse([$3], , :, [$3])
- fi
-
- AC_MSG_RESULT([$bind10_cxx_flag])
-])
-
-# SunStudio compiler requires special compiler options for boost
-# (http://blogs.sun.com/sga/entry/boost_mini_howto)
-if test "$SUNCXX" = "yes"; then
-CXXFLAGS="$CXXFLAGS -library=stlport4 -features=tmplife -features=tmplrefstatic"
-MULTITHREADING_FLAG="-mt"
-fi
-
-BIND10_CXX_TRY_FLAG([-Wno-missing-field-initializers],
- [WARNING_NO_MISSING_FIELD_INITIALIZERS_CFLAG="-Wno-missing-field-initializers"])
-AC_SUBST(WARNING_NO_MISSING_FIELD_INITIALIZERS_CFLAG)
-
-# gcc specific settings:
-if test "X$GXX" = "Xyes"; then
-B10_CXXFLAGS="-Wall -Wextra -Wwrite-strings -Woverloaded-virtual -Wno-sign-compare"
-case "$host" in
-*-solaris*)
- MULTITHREADING_FLAG=-pthreads
- # In Solaris, IN6ADDR_ANY_INIT and IN6ADDR_LOOPBACK_INIT need -Wno-missing-braces
- B10_CXXFLAGS="$B10_CXXFLAGS -Wno-missing-braces"
- ;;
-*)
- MULTITHREADING_FLAG=-pthread
- ;;
-esac
-
-# Don't use -Werror if configured not to
-AC_ARG_WITH(werror,
- AC_HELP_STRING([--with-werror], [Compile using -Werror (default=yes)]),
- [
- case "${withval}" in
- yes) with_werror=1 ;;
- no) with_werror=0 ;;
- *) AC_MSG_ERROR(bad value ${withval} for --with-werror) ;;
- esac],
- [with_werror=1])
-
-werror_ok=0
-
-# Certain versions of gcc (g++) have a bug that incorrectly warns about
-# the use of anonymous name spaces even if they're closed in a single
-# translation unit. For these versions we have to disable -Werror.
-if test $with_werror = 1; then
- CXXFLAGS_SAVED="$CXXFLAGS"
- CXXFLAGS="$CXXFLAGS $B10_CXXFLAGS -Werror"
- AC_MSG_CHECKING(for in-TU anonymous namespace breakage)
- AC_TRY_COMPILE([namespace { class Foo {}; }
- namespace isc {class Bar {Foo foo_;};} ],,
- [AC_MSG_RESULT(no)
- werror_ok=1
- B10_CXXFLAGS="$B10_CXXFLAGS -Werror"],
- [AC_MSG_RESULT(yes)])
- CXXFLAGS="$CXXFLAGS_SAVED"
-fi
-
+# (g++ only check)
# Python 3.2 has an unused parameter in one of its headers. This
# has been reported, but not fixed as of yet, so we check if we need
# to set -Wno-unused-parameter.
-if test $werror_ok = 1; then
+if test "X$GXX" = "Xyes" -a $werror_ok = 1; then
CPPFLAGS_SAVED="$CPPFLAGS"
CPPFLAGS=${PYTHON_INCLUDES}
CXXFLAGS_SAVED="$CXXFLAGS"
@@ -370,10 +404,6 @@ if test $werror_ok = 1; then
CPPFLAGS="$CPPFLAGS_SAVED"
fi
-fi dnl GXX = yes
-
-AM_CONDITIONAL(GCC_WERROR_OK, test $werror_ok = 1)
-
# produce PIC unless we disable shared libraries. need this for python bindings.
if test $enable_shared != "no" -a "X$GXX" = "Xyes"; then
B10_CXXFLAGS="$B10_CXXFLAGS -fPIC"
@@ -1055,6 +1085,13 @@ AM_COND_IF([ENABLE_LOGGER_CHECKS], [AC_DEFINE([ENABLE_LOGGER_CHECKS], [1], [Chec
AC_PATH_PROG(VALGRIND, valgrind, no)
AM_CONDITIONAL(HAVE_VALGRIND, test "x$VALGRIND" != "xno")
+# Also check for valgrind headers
+# We could consider adding them to the source code tree, as this
+# is the encouraged method of using them; they are BSD-licensed.
+# However, until we find that this is a problem, we just use
+# the system-provided ones, if available
+AC_CHECK_HEADERS(valgrind/valgrind.h, [AC_DEFINE([HAVE_VALGRIND_HEADERS], [1], [Check valgrind headers])])
+
found_valgrind="not found"
if test "x$VALGRIND" != "xno"; then
found_valgrind="found"
@@ -1093,13 +1130,13 @@ AC_CONFIG_FILES([Makefile
src/bin/bindctl/Makefile
src/bin/bindctl/tests/Makefile
src/bin/cfgmgr/Makefile
+ src/bin/cfgmgr/local_plugins/Makefile
src/bin/cfgmgr/plugins/Makefile
src/bin/cfgmgr/plugins/tests/Makefile
src/bin/cfgmgr/tests/Makefile
src/bin/dbutil/Makefile
src/bin/dbutil/tests/Makefile
src/bin/dbutil/tests/testdata/Makefile
- src/bin/host/Makefile
src/bin/loadzone/Makefile
src/bin/loadzone/tests/correct/Makefile
src/bin/loadzone/tests/error/Makefile
@@ -1215,6 +1252,8 @@ AC_CONFIG_FILES([Makefile
src/lib/server_common/tests/Makefile
src/lib/util/Makefile
src/lib/util/io/Makefile
+ src/lib/util/threads/Makefile
+ src/lib/util/threads/tests/Makefile
src/lib/util/unittests/Makefile
src/lib/util/python/Makefile
src/lib/util/pyunittests/Makefile
@@ -1260,6 +1299,7 @@ AC_OUTPUT([doc/version.ent
src/bin/zonemgr/tests/zonemgr_test
src/bin/zonemgr/run_b10-zonemgr.sh
src/bin/sysinfo/sysinfo.py
+ src/bin/sysinfo/run_sysinfo.sh
src/bin/stats/stats.py
src/bin/stats/stats_httpd.py
src/bin/bind10/bind10_src.py
@@ -1338,6 +1378,7 @@ AC_OUTPUT([doc/version.ent
chmod +x src/bin/loadzone/run_loadzone.sh
chmod +x src/bin/loadzone/tests/correct/correct_test.sh
chmod +x src/bin/loadzone/tests/error/error_test.sh
+ chmod +x src/bin/sysinfo/run_sysinfo.sh
chmod +x src/bin/usermgr/run_b10-cmdctl-usermgr.sh
chmod +x src/bin/msgq/run_msgq.sh
chmod +x src/bin/msgq/tests/msgq_test
@@ -1401,6 +1442,7 @@ Features:
$enable_features
Developer:
+ Enable Debugging: $debug_enabled
Google Tests: $enable_gtest
Valgrind: $found_valgrind
C++ Code Coverage: $USE_LCOV
diff --git a/doc/Doxyfile b/doc/Doxyfile
index 9f0f7f1..cc3b595 100644
--- a/doc/Doxyfile
+++ b/doc/Doxyfile
@@ -579,8 +579,9 @@ INPUT = ../src/lib/exceptions ../src/lib/cc \
../src/lib/log/compiler ../src/lib/asiolink/ ../src/lib/nsas \
../src/lib/testutils ../src/lib/cache ../src/lib/server_common/ \
../src/bin/sockcreator/ ../src/lib/util/ ../src/lib/util/io/ \
- ../src/lib/resolve ../src/lib/acl ../src/lib/statistics ../src/lib/dhcp \
- ../src/bin/dhcp6 ../src/bin/dhcp4 ../tests/tools/perfdhcp devel
+ ../src/lib/util/threads/ ../src/lib/resolve ../src/lib/acl \
+ ../src/lib/statistics ../src/bin/dhcp6 ../src/lib/dhcp ../src/bin/dhcp4 \
+ ../tests/tools/perfdhcp devel
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
diff --git a/doc/devel/02-dhcp.dox b/doc/devel/02-dhcp.dox
index 5217f73..5c59daa 100644
--- a/doc/devel/02-dhcp.dox
+++ b/doc/devel/02-dhcp.dox
@@ -57,99 +57,4 @@
* that does not support msgq. That is useful for embedded environments.
* It may also be useful in validation.
*
- * @page dhcpv6 DHCPv6 Server Component
- *
- * BIND10 offers DHCPv6 server implementation. It is implemented as
- * b10-dhcp6 component. Its primary code is located in
- * isc::dhcp::Dhcpv6Srv class. It uses \ref libdhcp extensively,
- * especially lib::dhcp::Pkt6, isc::dhcp::Option and
- * isc::dhcp::IfaceMgr classes. Currently this code offers skeleton
- * functionality, i.e. it is able to receive and process incoming
- * requests and trasmit responses. However, it does not have database
- * management, so it returns only one, hardcoded lease to whoever asks
- * for it.
- *
- * DHCPv6 server component does not support relayed traffic yet, as
- * support for relay decapsulation is not implemented yet.
- *
- * DHCPv6 server component does not use BIND10 logging yet.
- *
- * @section dhcpv6Session BIND10 message queue integration
- *
- * DHCPv4 server component is now integrated with BIND10 message queue.
- * It follows the same principle as DHCPv4. See \ref dhcpv4Session for
- * details.
- *
- * @page libdhcp libdhcp++
- *
- * @section libdhcpIntro Libdhcp++ Library Introduction
- *
- * libdhcp++ is an all-purpose DHCP-manipulation library, written in
- * C++. It offers packet parsing and assembly, DHCPv4 and DHCPv6
- * options parsing and ssembly, interface detection (currently on
- * Linux systems only) and socket operations. Following classes are
- * implemented:
- *
- * - isc::dhcp::Pkt4 - represents DHCPv4 packet.
- * - isc::dhcp::Pkt6 - represents DHCPv6 packet.
- *
- * There are two pointer types defined: Pkt4Ptr and Pkt6Ptr. They are
- * smart pointer and are using boost::shared_ptr. There are not const
- * versions defined, as we assume that hooks can modify any aspect of
- * the packet at almost any stage of processing.
- *
- * Both packets use collection of Option objects to represent DHCPv4
- * and DHCPv6 options. The base class -- Option -- can be used to
- * represent generic option that contains collection of
- * bytes. Depending on if the option is instantiated as v4 or v6
- * option, it will adjust its header (DHCPv4 options use 1 octet for
- * type and 1 octet for length, while DHCPv6 options use 2 bytes for
- * each).
- *
- * There are many specialized classes that are intended to handle options with
- * specific content:
- * - isc::dhcp::Option4AddrLst -- DHCPv4 option, contains one or more IPv4 addresses;
- * - isc::dhcp::Option6AddrLst -- DHCPv6 option, contains one or more IPv6 addresses;
- * - isc::dhcp::Option6IAAddr -- DHCPv6 option, represents IAADDR_OPTION (an option that
- * contains IPv6 address with extra parameters);
- * - isc::dhcp::Option6IA -- DHCPv6 option used to store IA_NA and its suboptions.
- *
- * All options can store sub-options (i.e. options that are stored within option
- * rather than in a message directly). This functionality is commonly used in
- * DHCPv6, but is rarely used in DHCPv4. isc::dhcp::Option::addOption(),
- * isc::dhcp::Option::delOption(), isc::dhcp::Option::getOption() can be used
- * for that purpose.
- *
- * @section libdhcpIfaceMgr Interface Manager
- *
- * Interface Manager (or IfaceMgr) is an abstraction layer about low-level
- * network operations. In particlar, it provides information about existing
- * network interfaces See isc::dhcp::IfaceMgr::Iface class and
- * isc::dhcp::IfaceMgr::detectIfaces() and isc::dhcp::IfaceMgr::getIface().
- *
- * Currently there is interface detection is implemented in Linux only. There
- * are plans to implement such support for other OSes, but they remain low
- * priority for now.
- *
- * Generic parts of the code are isc::dhcp::IfaceMgr class in
- * src/lib/dhcp/iface_mgr.cc file. OS-specific code is located in separate
- * files, e.g. iface_mgr_linux.cc. Such separation should be maintained when
- * additional code will be developed.
- *
- * For systems that interface detection is not supported on, there is a stub
- * mechanism implemented. It assumes that interface name is read from a text
- * file. This is a temporary solution and will be removed as soon as proper
- * interface detection is implemented. It is not going to be developed further.
- * To use this feature, store interfaces.txt file. It uses a simple syntax.
- * Each line represents an interface name, followed by IPv4 or IPv6 address
- * that follows it. This is usually link-local IPv6 address that the server
- * should bind to. In theory this mechanism also supports IPv4, but it was
- * never tested. The code currently supports only a single interface defined
- * that way.
- *
- * Another useful methods are dedicated to transmission
- * (isc::dhcp::IfaceMgr::send(), 2 overloads) and reception
- * (isc::dhcp::IfaceMgr::receive4() and isc::dhcp::IfaceMgr::receive6()).
- * Note that receive4() and receive6() methods may return NULL, e.g.
- * when timeout is reached or if dhcp daemon receives a signal.
*/
\ No newline at end of file
diff --git a/doc/devel/mainpage.dox b/doc/devel/mainpage.dox
index ca9d881..e1761ec 100644
--- a/doc/devel/mainpage.dox
+++ b/doc/devel/mainpage.dox
@@ -15,15 +15,24 @@
* <a href="http://bind10.isc.org/">BIND10 webpage (http://bind10.isc.org)</a>
*
* @section DNS
+ * - Authoritative DNS (todo)
+ * - Recursive resolver (todo)
* - @subpage DataScrubbing
*
* @section DHCP
* - @subpage dhcpv4
* - @subpage dhcpv4Session
* - @subpage dhcpv6
+ * - @subpage dhcpv6-session
+ * - @subpage dhcpv6-config-parser
+ * - @subpage dhcpv6-config-inherit
* - @subpage libdhcp
* - @subpage libdhcpIntro
* - @subpage libdhcpIfaceMgr
+ * - @subpage libdhcpsrv
+ * - @subpage leasemgr
+ * - @subpage cfgmgr
+ * - @subpage allocengine
* - @subpage perfdhcpInternals
*
* @section misc Miscellaneous topics
diff --git a/doc/guide/bind10-guide.xml b/doc/guide/bind10-guide.xml
index 2e66ad5..6065616 100644
--- a/doc/guide/bind10-guide.xml
+++ b/doc/guide/bind10-guide.xml
@@ -2751,13 +2751,13 @@ then change those defaults with config set Resolver/forward_addresses[0]/address
<title>DHCPv4 Server Configuration</title>
<para>
The DHCPv4 server does not have a lease database implemented yet
- nor any support for configuration, so every time the same set
+ nor any support for configuration, so the same set
of configuration options (including the same fixed address)
will be assigned every time.
</para>
<para>
At this stage of development, the only way to alter the server
- configuration is to tweak its source code. To do so, please
+ configuration is to modify its source code. To do so, please
edit src/bin/dhcp4/dhcp4_srv.cc file and modify following
parameters and recompile:
<screen>
@@ -2944,16 +2944,95 @@ const std::string HARDCODED_SERVER_ID = "192.0.2.1";</screen>
<section id="dhcp6-config">
<title>DHCPv6 Server Configuration</title>
<para>
- The DHCPv6 server does not have lease database implemented yet
- or any support for configuration, so every time the same set
- of configuration options (including the same fixed address)
- will be assigned every time.
+ Once the server is started, it can be configured. To view the
+ current configuration, use the following command in <command>bindctl</command>:
+ <screen>
+ > <userinput>config show Dhcp6</userinput></screen>
+ When starting Dhcp6 daemon for the first time, the default configuration
+ will be available. It will look similar to this:
+ <screen>
+> <userinput>config show Dhcp6</userinput>
+Dhcp6/interface "eth0" string (default)
+Dhcp6/renew-timer 1000 integer (default)
+Dhcp6/rebind-timer 2000 integer (default)
+Dhcp6/preferred-lifetime 3000 integer (default)
+Dhcp6/valid-lifetime 4000 integer (default)
+Dhcp6/subnet6 [] list (default)</screen>
</para>
+
<para>
- At this stage of development, the only way to alter server
- configuration is to tweak its source code. To do so, please
- edit src/bin/dhcp6/dhcp6_srv.cc file, modify the following
- parameters and recompile:
+ To change one of the parameters, simply follow
+ the usual <command>bindctl</command> procedure. For example, to make the
+ leases longer, change their valid-lifetime parameter:
+ <screen>
+> <userinput>config set Dhcp6/valid-lifetime 7200</userinput>
+> <userinput>config commit</userinput></screen>
+ Please note that most Dhcp6 parameters are of global scope
+ and apply to all defined subnets, unless they are overridden on a
+ per-subnet basis.
+ </para>
+
+ <para>
+ The essential role of DHCPv6 server is address assignment. The server
+ has to be configured with at least one subnet and one pool of dynamic
+ addresses to be managed. For example, assume that the server
+ is connected to a network segment that uses the 2001:db8:1::/64
+ prefix. The Administrator of that network has decided that addresses from range
+ 2001:db8:1::1 to 2001:db8:1::ffff are going to be managed by the Dhcp6
+ server. Such a configuration can be achieved in the following way:
+ <screen>
+> <userinput>config add Dhcp6/subnet6</userinput>
+> <userinput>config set Dhcp6/subnet6[0]/subnet "2001:db8:1::/64"</userinput>
+> <userinput>config set Dhcp6/subnet6[0]/pool [ "2001:db8:1::0 - 2001:db8:1::ffff" ]</userinput>
+> <userinput>config commit</userinput></screen>
+ Note that subnet is defined as a simple string, but the pool parameter
+ is actually a list of pools: for this reason, the pool definition is
+ enclosed in square brackets, even though only one range of addresses
+ is specified.</para>
+ <para>It is possible to define more than one pool in a
+ subnet: continuing the previous example, further assume that
+ 2001:db8:1:0:5::/80 should be also be managed by the server. It could be written as
+ 2001:db8:1:0:5:: to 2001:db8:1::5:ffff:ffff:ffff, but typing so many 'f's
+ is cumbersome. It can be expressed more simply as 2001:db8:1:0:5::/80. Both
+ formats are supported by Dhcp6 and can be mixed in the pool list.
+ For example, one could define the following pools:
+ <screen>
+> <userinput>config set Dhcp6/subnet6[0]/pool [ "2001:db8:1::1 - 2001:db8:1::ffff", "2001:db8:1:0:5::/80" ]</userinput>
+> <userinput>config commit</userinput></screen>
+ The number of pools is not limited, but for performance reasons it is recommended to
+ use as few as possible.
+ </para>
+ <para>
+ The server may be configured to serve more than one subnet. To add a second subnet,
+ use a command similar to the following:
+ <screen>
+> <userinput>config add Dhcp6/subnet6</userinput>
+> <userinput>config set Dhcp6/subnet6[1]/subnet "2001:db8:beef::/48"</userinput>
+> <userinput>config set Dhcp6/subnet6[1]/pool [ "2001:db8:beef::/48" ]</userinput>
+> <userinput>config commit</userinput></screen>
+ Arrays are counted from 0. subnet[0] refers to the subnet defined in the
+ previous example. The <command>config add Dhcp6/subnet6</command> adds
+ another (second) subnet. It can be referred to as
+ <command>Dhcp6/subnet6[1]</command>. In this example, we allow server to
+ dynamically assign all addresses available in the whole subnet. Although
+ very wasteful, it is certainly a valid configuration to dedicate the
+ whole /48 subnet for that purpose.
+ </para>
+ <para>
+ When configuring a DHCPv6 server using prefix/length notation, please pay
+ attention to the boundary values. When specifying that the server should use
+ a given pool, it will be able to allocate also first (typically network
+ address) address from that pool. For example for pool 2001:db8::/64 the
+ 2001:db8:: address may be assigned as well. If you want to avoid this,
+ please use min-max notation.
+ </para>
+
+ <para>
+ Note: Although configuration is now accepted, it is not internally used
+ by they server yet. At this stage of development, the only way to alter
+ server configuration is to modify its source code. To do so, please edit
+ src/bin/dhcp6/dhcp6_srv.cc file, modify the following parameters and
+ recompile:
<screen>
const std::string HARDCODED_LEASE = "2001:db8:1::1234:abcd";
const uint32_t HARDCODED_T1 = 1500; // in seconds
diff --git a/examples/AUTHORS b/examples/AUTHORS
new file mode 100644
index 0000000..e69de29
diff --git a/examples/COPYING b/examples/COPYING
new file mode 100644
index 0000000..f3febbe
--- /dev/null
+++ b/examples/COPYING
@@ -0,0 +1,13 @@
+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.
diff --git a/examples/ChangeLog b/examples/ChangeLog
new file mode 100644
index 0000000..e69de29
diff --git a/examples/INSTALL b/examples/INSTALL
new file mode 100644
index 0000000..43436c2
--- /dev/null
+++ b/examples/INSTALL
@@ -0,0 +1,9 @@
+If using git (not the tarball), build the "configure" file:
+ autoreconf --install
+
+To then build from source:
+ ./configure
+ make
+
+You may have to specify the location of BIND 10 header files and
+library objects. See configure options by ./configure --help.
diff --git a/examples/Makefile.am b/examples/Makefile.am
new file mode 100644
index 0000000..ef437eb
--- /dev/null
+++ b/examples/Makefile.am
@@ -0,0 +1,4 @@
+SUBDIRS = host
+
+# Make sure macros under m4 will be included
+ACLOCAL_AMFLAGS = -I m4
diff --git a/examples/NEWS b/examples/NEWS
new file mode 100644
index 0000000..e69de29
diff --git a/examples/README b/examples/README
new file mode 100644
index 0000000..65f777b
--- /dev/null
+++ b/examples/README
@@ -0,0 +1,32 @@
+This is the top directory for sample programs that can be developed
+using public BIND 10 libraries outside of the BIND 10 project. It's
+intended to be built with installed BIND 10 header files and library
+objects, so it's not a target of the main build tree, and does not
+refer to any other part of the BIND 10 source tree that contains
+this directory.
+
+On the top (sub) directory (where this README file is stored), we
+provide a sample configure.ac and Makefile.am files for GNU automake
+environments with helper autoconf macros to detect the availability and
+location of BIND 10 header files and library objects.
+
+You can use the configure.ac and Makefile.am files with macros under
+the "m4" subdirectory as a template for your own project. The key is
+to call the AX_ISC_BIND10 function (as the sample configure.ac does)
+from your configure.ac. Then it will check the availability of
+necessary stuff and set some corresponding AC variables. You can then
+use the resulting variables in your Makefile.in or Makefile.ac.
+
+If you use automake, don't forget adding the following line to the top
+level Makefile.am:
+
+ACLOCAL_AMFLAGS = -I m4
+
+This is necessary to incorporate the helper macro definitions.
+
+If you don't use automake but autoconf, make sure to add the following
+to the configure.ac file:
+
+sinclude(m4/ax_boost_include.m4)
+sinclude(m4/ax_isc_bind10.m4)
+(and same for other m4 files as they are added under m4/)
diff --git a/examples/configure.ac b/examples/configure.ac
new file mode 100644
index 0000000..9379687
--- /dev/null
+++ b/examples/configure.ac
@@ -0,0 +1,28 @@
+# -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+
+AC_PREREQ([2.59])
+AC_INIT(bind10-examples, 20120817, bind10-dev at isc.org)
+AC_CONFIG_SRCDIR([README])
+AM_INIT_AUTOMAKE
+AC_CONFIG_HEADERS([config.h])
+
+# Checks for programs.
+AC_PROG_CXX
+AC_LANG([C++])
+
+# Checks for BIND 10 headers and libraries
+AX_ISC_BIND10
+
+# For the example host program, we require the BIND 10 DNS library
+if test "x$BIND10_DNS_LIB" = "x"; then
+ AC_MSG_ERROR([unable to find BIND 10 DNS library needed to build 'host'])
+fi
+
+# Checks for typedefs, structures, and compiler characteristics.
+AC_HEADER_STDBOOL
+
+AC_CONFIG_FILES([Makefile
+ host/Makefile])
+
+AC_OUTPUT
diff --git a/examples/host/.gitignore b/examples/host/.gitignore
new file mode 100644
index 0000000..01ef357
--- /dev/null
+++ b/examples/host/.gitignore
@@ -0,0 +1,2 @@
+/b10-host
+/b10-host.1
diff --git a/examples/host/Makefile.am b/examples/host/Makefile.am
new file mode 100644
index 0000000..dbd57a2
--- /dev/null
+++ b/examples/host/Makefile.am
@@ -0,0 +1,6 @@
+AM_CPPFLAGS = $(BOOST_CPPFLAGS) $(BIND10_CPPFLAGS)
+
+bin_PROGRAMS = b10-host
+b10_host_SOURCES = host.cc
+b10_host_LDFLAGS = ${BIND10_LDFLAGS}
+b10_host_LDADD = ${BIND10_DNS_LIB}
diff --git a/examples/host/README b/examples/host/README
new file mode 100644
index 0000000..5cc4068
--- /dev/null
+++ b/examples/host/README
@@ -0,0 +1,4 @@
+Rewriting host(1) in C++ from scratch using BIND 10's libdns++.
+
+The bugs and incompatibilities are listed in the manual page
+and in the source code.
diff --git a/examples/host/b10-host.xml b/examples/host/b10-host.xml
new file mode 100644
index 0000000..a17ef67
--- /dev/null
+++ b/examples/host/b10-host.xml
@@ -0,0 +1,196 @@
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
+ "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
+ [<!ENTITY mdash "—">]>
+<!--
+ - 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.
+-->
+
+<!-- $Id$ -->
+<refentry>
+
+ <refentryinfo>
+ <date>May 4, 2011</date>
+ </refentryinfo>
+
+ <refmeta>
+ <refentrytitle>b10-host</refentrytitle>
+ <manvolnum>1</manvolnum>
+ <refmiscinfo>BIND10</refmiscinfo>
+ </refmeta>
+
+ <refnamediv>
+ <refname>b10-host</refname>
+ <refpurpose>DNS lookup utility</refpurpose>
+ </refnamediv>
+
+ <docinfo>
+ <copyright>
+ <year>2011</year>
+ <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
+ </copyright>
+ </docinfo>
+
+ <refsynopsisdiv>
+ <cmdsynopsis>
+ <command>b10-host</command>
+ <arg><option>-a</option></arg>
+ <arg><option>-c <replaceable>class</replaceable></option></arg>
+ <arg><option>-d</option></arg>
+ <arg><option>-p <replaceable>port</replaceable></option></arg>
+ <arg><option>-r</option></arg>
+ <arg><option>-t <replaceable>type</replaceable></option></arg>
+ <arg><option>-v</option></arg>
+ <arg><replaceable>name</replaceable></arg>
+ <arg><option><replaceable>server</replaceable></option></arg>
+ </cmdsynopsis>
+ </refsynopsisdiv>
+
+ <refsect1>
+ <title>DESCRIPTION</title>
+ <para>
+ The <command>b10-host</command> utility does DNS lookups.
+ Its initial goal is to be a
+ <citerefentry><refentrytitle>host</refentrytitle>
+ <manvolnum>1</manvolnum></citerefentry>
+ clone, but also add a few features useful for BIND 10 development
+ testing.
+ </para>
+
+ <para>
+ By default, it looks up the A, AAAA, and MX record sets for the
+ <replaceable>name</replaceable>.
+ Optionally, you may select a name server to query against by adding
+ the <replaceable>server</replaceable> argument.
+ </para>
+ </refsect1>
+
+ <refsect1>
+ <title>OPTIONS</title>
+
+ <para>The arguments are as follows:</para>
+
+ <variablelist>
+
+ <varlistentry>
+ <term><option>-a</option></term>
+ <listitem><para>
+ Enable verbose mode and do a query for type ANY.
+ (If the <option>-t</option> option is also set, then the
+ ANY query is not done, but it still uses verbose mode.)
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-c <replaceable>class</replaceable></option></term>
+ <listitem><para>
+ Define the class for the query.
+ The default is IN (Internet).
+<!-- TODO: bug if class is unknown causes seg fault and possible core dump -->
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-d</option></term>
+ <listitem><para>
+ Enable verbose output mode, including elapsed time in
+ milliseconds.
+ Verbose mode shows the header, question, answer, authority,
+ and additional sections (if provided).
+ (Same as <option>-v</option>.)
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-p <replaceable>port</replaceable></option></term>
+ <listitem><para>
+ Select an alternative port for the query.
+ This may be a number or a service name.
+ The default is 53 (domain).
+ This is not a standard feature of
+ <citerefentry><refentrytitle>host</refentrytitle>
+ <manvolnum>1</manvolnum></citerefentry>.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-r</option></term>
+ <listitem><para>
+ Disable recursive processing by not setting the
+ Recursion Desired flag in the query.
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-t <replaceable>type</replaceable></option></term>
+ <listitem><para>
+ Select a specific resource record type for the query.
+ By default, it looks up the A, AAAA, and MX record sets.
+<!-- TODO: bug if class is unknown causes seg fault and possible core dump -->
+ (This overrides the <option>-a</option> option.)
+ </para></listitem>
+ </varlistentry>
+
+ <varlistentry>
+ <term><option>-v</option></term>
+ <listitem><para>
+ Same as <option>-d</option> option.
+ </para></listitem>
+ </varlistentry>
+
+ </variablelist>
+
+ </refsect1>
+
+ <refsect1>
+ <title>COMPATIBILITY / BUGS</title>
+ <para>
+ <command>b10-host</command> does not do reverse lookups by
+ default yet (by detecting if name is a IPv4 or IPv6 address).
+ </para>
+
+ <para>
+ Unknown <option>-c</option> class or <option>-t</option> type
+ causes <command>b10-host</command> to Abort.
+ </para>
+
+ <para>
+ Not all types are supported yet for formatting.
+ Not all switches are supported yet.
+ </para>
+
+ <para>
+ It doesn't use <filename>/etc/resolv.conf</filename> at this time.
+ The default name server used is 127.0.0.1.
+ </para>
+
+ <para>
+ <option>-p</option> is not a standard feature.
+ </para>
+ </refsect1>
+
+ <refsect1>
+ <title>HISTORY</title>
+ <para>
+ The C++ version of <command>b10-host</command> was started in
+ October 2009 by Jeremy C. Reed of ISC.
+ Its usage and output were based on the standard <command>host</command>
+ command.
+ </para>
+ </refsect1>
+</refentry><!--
+ - Local variables:
+ - mode: sgml
+ - End:
+-->
diff --git a/examples/host/host.cc b/examples/host/host.cc
new file mode 100644
index 0000000..a5c6522
--- /dev/null
+++ b/examples/host/host.cc
@@ -0,0 +1,253 @@
+// Copyright (C) 2010-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.
+
+// host rewritten in C++ using BIND 10 DNS library
+
+#include <arpa/inet.h>
+#include <netdb.h> // for getaddrinfo
+#include <sys/time.h> // for gettimeofday
+#include <sys/socket.h> // networking functions and definitions on FreeBSD
+
+#include <unistd.h>
+
+#include <string>
+#include <iostream>
+
+#include <util/buffer.h>
+
+#include <dns/name.h>
+#include <dns/message.h>
+#include <dns/messagerenderer.h>
+#include <dns/opcode.h>
+#include <dns/rcode.h>
+#include <dns/rrclass.h>
+#include <dns/rrtype.h>
+#include <dns/rrset.h>
+#include <dns/message.h>
+
+using namespace std;
+using namespace isc::dns;
+using namespace isc::util;
+
+namespace {
+char* dns_type = NULL; // not set, so A, AAAA, MX
+const char* server = "127.0.0.1";
+const char* server_port = "53";
+const char* dns_class = "IN";
+bool verbose = false;
+bool dns_any = false;
+int first_time = 1;
+bool recursive_bit = true;
+struct timeval before_time, after_time;
+
+int
+host_lookup(const char* const name, const char* const dns_class,
+ const char* const type, bool any) {
+
+ Message msg(Message::RENDER);
+
+ msg.setQid(0); // does this matter?
+
+ // TODO: add switch for this
+ msg.setOpcode(Opcode::QUERY());
+ msg.setRcode(Rcode::NOERROR());
+ if (recursive_bit) {
+ msg.setHeaderFlag(Message::HEADERFLAG_RD); // set recursive bit
+ }
+
+ msg.addQuestion(Question(Name(name),
+ RRClass(dns_class),
+ any ? RRType::ANY() : RRType(type))); // if NULL then:
+
+ MessageRenderer renderer;
+ msg.toWire(renderer);
+
+ struct addrinfo hints, *res;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_DGRAM;
+ hints.ai_flags = 0; // not using AI_NUMERICHOST in case to bootstrap
+ if (getaddrinfo(server, server_port, &hints, &res) != 0) {
+ cerr << "address/port conversion for " << server << ":"
+ << server_port << " failed" << endl;
+ return (1);
+ }
+
+ if (verbose) {
+ cout << "Trying \"" << name << "\"\n";
+ }
+
+ if (verbose && first_time) {
+ // this is only output the first time
+ first_time = 0;
+ cout << "Using domain server:\n";
+ cout << "Name: " << server << "\n";
+ // TODO: I guess I have to do a lookup to get that address and aliases
+ // too
+ //cout << "Address: " << address << "\n" ; // "#" << port << "\n";
+ //cout << "Aliases: " << server << "\n";
+ }
+
+ int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
+
+ if (s < 0) {
+ cerr << "failed to open socket" << endl;
+ return (1);
+ }
+
+ if (verbose) {
+ gettimeofday(&before_time, NULL);
+ }
+
+ sendto(s, renderer.getData(), renderer.getLength(), 0, res->ai_addr,
+ res->ai_addrlen);
+
+ struct sockaddr_storage ss;
+ struct sockaddr* sa;
+ socklen_t sa_len;
+
+ sa_len = sizeof(ss);
+ sa = static_cast<struct sockaddr*>((void*)&ss);
+
+ char recvbuf[4096];
+ int cc;
+ if ((cc = recvfrom(s, recvbuf, sizeof(recvbuf), 0, sa, &sa_len)) > 0) {
+ try {
+ Message rmsg(Message::PARSE);
+ InputBuffer ibuffer(recvbuf, cc);
+
+ rmsg.fromWire(ibuffer);
+ if (!verbose) {
+ string description = "";
+ for (RRsetIterator it =
+ rmsg.beginSection(Message::SECTION_ANSWER);
+ it != rmsg.endSection(Message::SECTION_ANSWER);
+ ++it) {
+
+ if ((*it)->getType() == RRType::A()) {
+ description = "has address";
+ }
+ else if ((*it)->getType() == RRType::AAAA()) {
+ description = "has IPv6 address";
+ }
+ else if ((*it)->getType() == RRType::MX()) {
+ description = "mail is handled by";
+ }
+ else if ((*it)->getType() == RRType::TXT()) {
+ description = "descriptive text";
+ }
+
+ RdataIteratorPtr rit = (*it)->getRdataIterator();
+ for (; !rit->isLast(); rit->next()) {
+ // instead of using my name, maybe use returned label?
+ cout << name << " " << description << " " <<
+ (*rit).getCurrent().toText() << endl;
+ }
+ }
+ } else {
+ gettimeofday(&after_time, NULL);
+
+ // HEADER and QUESTION, ANSWER, AUTHORITY, and ADDITIONAL
+ std::cout << rmsg.toText() << std::endl;
+
+ if (before_time.tv_usec > after_time.tv_usec) {
+ after_time.tv_usec += 1000000;
+ --after_time.tv_sec;
+ }
+
+ int elapsed_time =
+ (after_time.tv_sec - before_time.tv_sec)
+ + ((after_time.tv_usec - before_time.tv_usec))/1000;
+
+ // TODO: if NXDOMAIN, host(1) doesn't show HEADER
+ // Host hsdjkfhksjhdfkj not found: 3(NXDOMAIN)
+ // TODO: test if NXDOMAIN
+
+ std::cout << "Received " << cc <<
+ " bytes in " << elapsed_time << " ms\n";
+ // TODO: " bytes from 127.0.0.1#53 in 0 ms
+
+ } //verbose
+/*
+TODO: handle InvalidRRClass
+TODO: handle invalid type exception
+ } catch (InvalidType ivt) {
+ std::cerr << "invalid type:" << ivt.what();
+*/
+ } catch (const exception& ex) {
+ std::cerr << "parse failed for " <<
+ string(name) << "/" << type << ": " << ex.what() << std::endl;
+ } catch (...) {
+ std::cerr << "parse failed for " << string(name) << "/" << type;
+ }
+ }
+
+ freeaddrinfo(res);
+
+ return (0);
+} // host_lookup()
+}
+
+int
+main(int argc, char* argv[]) {
+ int c;
+
+ while ((c = getopt(argc, argv, "ac:dp:rt:v")) != -1)
+ switch (c) {
+ case 'a':
+ dns_any = true;
+ verbose = true;
+ break;
+ case 'c':
+ dns_class = optarg;
+ break;
+ // p for port is a non-standard switch
+ case 'p':
+ server_port = optarg;
+ break;
+ case 'r':
+ recursive_bit = false;
+ break;
+ case 't':
+ dns_type = optarg;
+ break;
+ case 'd':
+ // drop through to v, because debug and verbose are equivalent
+ case 'v':
+ verbose = true;
+ break;
+ }
+ argc -= optind;
+ argv += optind;
+
+ if (argc < 1) {
+ cout << "Usage: host [-adrv] [-c class] [-p port] [-t type] hostname [server]\n";
+ exit(1);
+ }
+
+ if (argc >= 2) {
+ server = argv[1];
+ }
+
+ if (dns_type == NULL) {
+ host_lookup(argv[0], dns_class, "A", dns_any);
+ // TODO: don't do next if A doesn't exist
+ host_lookup(argv[0], dns_class, "AAAA", dns_any);
+ host_lookup(argv[0], dns_class, "MX", dns_any);
+ } else {
+ // -t overrides -a, regardless of order
+ host_lookup(argv[0], dns_class, dns_type, false);
+ }
+ return (0);
+}
diff --git a/examples/m4/ax_boost_include.m4 b/examples/m4/ax_boost_include.m4
new file mode 100644
index 0000000..e41614d
--- /dev/null
+++ b/examples/m4/ax_boost_include.m4
@@ -0,0 +1,64 @@
+dnl @synopsis AX_BOOST_INCLUDE
+dnl
+dnl Test for the Boost C++ header files
+dnl
+dnl If no path to the installed boost header files is given via the
+dnl --with-boost-include option, the macro searchs under
+dnl /usr/local /usr/pkg /opt /opt/local directories.
+dnl
+dnl This macro calls:
+dnl
+dnl AC_SUBST(BOOST_CPPFLAGS)
+dnl
+
+AC_DEFUN([AX_BOOST_INCLUDE], [
+AC_LANG_SAVE
+AC_LANG([C++])
+
+#
+# Configure Boost header path
+#
+# If explicitly specified, use it.
+AC_ARG_WITH([boost-include],
+ AS_HELP_STRING([--with-boost-include=PATH],
+ [specify exact directory for Boost headers]),
+ [boost_include_path="$withval"])
+# If not specified, try some common paths.
+if test -z "$with_boost_include"; then
+ boostdirs="/usr/local /usr/pkg /opt /opt/local"
+ for d in $boostdirs
+ do
+ if test -f $d/include/boost/shared_ptr.hpp; then
+ boost_include_path=$d/include
+ break
+ fi
+ done
+fi
+CPPFLAGS_SAVES="$CPPFLAGS"
+if test "${boost_include_path}" ; then
+ BOOST_CPPFLAGS="-I${boost_include_path}"
+ CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
+fi
+# Make sure some commonly used headers are available
+AC_CHECK_HEADERS([boost/shared_ptr.hpp boost/bind.hpp boost/function.hpp],,
+ AC_MSG_ERROR([Missing required Boost header files.]))
+
+# Detect whether Boost tries to use threads by default, and, if not,
+# make it sure explicitly. In some systems the automatic detection
+# may depend on preceding header files, and if inconsistency happens
+# it could lead to a critical disruption.
+AC_MSG_CHECKING([whether Boost tries to use threads])
+AC_TRY_COMPILE([
+#include <boost/config.hpp>
+#ifdef BOOST_HAS_THREADS
+#error "boost will use threads"
+#endif],,
+[AC_MSG_RESULT(no)
+ CPPFLAGS_BOOST_THREADCONF="-DBOOST_DISABLE_THREADS=1"],
+[AC_MSG_RESULT(yes)])
+
+CPPFLAGS="$CPPFLAGS_SAVES $CPPFLAGS_BOOST_THREADCONF"
+AC_SUBST(BOOST_CPPFLAGS)
+
+AC_LANG_RESTORE
+])dnl AX_BOOST_INCLUDE
diff --git a/examples/m4/ax_isc_bind10.m4 b/examples/m4/ax_isc_bind10.m4
new file mode 100644
index 0000000..63e028c
--- /dev/null
+++ b/examples/m4/ax_isc_bind10.m4
@@ -0,0 +1,122 @@
+dnl @synopsis AX_BIND10
+dnl
+dnl @summary figure out how to build C++ programs using ISC BIND 10 libraries
+dnl
+dnl If no path to the installed BIND 10 header files or libraries is given
+dnl via the --with-bind10-include or --with-bind10-lib option, the macro
+dnl searchs under /usr/local/{include, lib}, /usr/pkg/{include, lib},
+dnl /opt/{include, lib}, /opt/local/{include, lib} directories, respectively.
+dnl
+dnl This macro calls:
+dnl
+dnl AC_SUBST(BIND10_CPPFLAGS)
+dnl AC_SUBST(BIND10_LDFLAGS)
+dnl AC_SUBST(BIND10_COMMON_LIB)
+dnl AC_SUBST(BIND10_DNS_LIB)
+dnl
+dnl If this macro finds CPPFLAGS, LDFLAGS or COMMON_LIB unavailable, it treats
+dnl that as a fatal error.
+dnl Checks for other BIND 10 module libraries are option, as not all
+dnl applications need all libraries. The main configure.ac can handle any
+dnl missing library as fatal by checking whether the corresponding
+dnl BIND10_xxx_LIB is defined.
+
+AC_DEFUN([AX_ISC_BIND10], [
+AC_REQUIRE([AX_BOOST_INCLUDE])
+AC_LANG_SAVE
+AC_LANG([C++])
+
+# Check for BIND10 common headers
+
+AC_ARG_WITH(bind10-include,
+ AS_HELP_STRING([--with-bind10-include=PATH],
+ [specify a path to BIND 10 header files]),
+ bind10_inc_path="$withval", bind10_inc_path="no")
+# If not specified, try some common paths.
+if test "$bind10_inc_path" = "no"; then
+ for d in /usr/local /usr/pkg /opt /opt/local
+ do
+ if test -f $d/include/util/buffer.h; then
+ bind10_inc_path=$d
+ break
+ fi
+ done
+fi
+CPPFLAGS_SAVES="$CPPFLAGS"
+if test "${bind10_inc_path}" != "no"; then
+ BIND10_CPPFLAGS="-I${bind10_inc_path}"
+ CPPFLAGS="$CPPFLAGS $BIND10_CPPFLAGS"
+fi
+AC_CHECK_HEADERS([util/buffer.h],,
+ AC_MSG_ERROR([Missing a commonly used BIND 10 header files]))
+CPPFLAGS="$CPPFLAGS_SAVES"
+AC_SUBST(BIND10_CPPFLAGS)
+
+# Check for BIND10 libraries
+CPPFLAGS_SAVED="$CPPFLAGS"
+CPPFLAGS="$CPPFLAGS $BIND10_CPPFLAGS"
+
+AC_ARG_WITH(bind10-lib,
+ AS_HELP_STRING([--with-bind10-lib=PATH],
+ [specify a path to BIND 10 library files]),
+ bind10_lib_path="$withval", bind10_lib_path="no")
+if test $bind10_lib_path != "no"; then
+ bind10_lib_dirs=$bind10_lib_path
+else
+ # If not specified, try some common paths.
+ bind10_lib_dirs="/usr/local/lib /usr/pkg/lib /opt/lib /opt/local/lib"
+fi
+
+# make sure we have buildable libraries
+AC_MSG_CHECKING([for BIND 10 common library])
+BIND10_COMMON_LIB="-lb10-util -lb10-exceptions"
+LDFLAGS="$LDFLAGS $BIND10_LDFLAGS"
+LIBS="$LIBS $BIND10_COMMON_LIB"
+for d in $bind10_lib_dirs
+do
+ LDFLAGS_SAVED="$LDFLAGS"
+ LDFLAGS="$LDFLAGS -L$d"
+ AC_TRY_LINK([
+#include <util/buffer.h>
+],[
+isc::util::OutputBuffer buffer(0);
+], [BIND10_LDFLAGS="-L${d}"])
+ if test "x$BIND10_LDFLAGS" != "x"; then
+ break
+ fi
+ LDFLAGS="$LDFLAGS_SAVED"
+done
+if test "x$BIND10_LDFLAGS" != "x"; then
+ AC_MSG_RESULT(yes)
+else
+ AC_MSG_RESULT(no)
+ AC_MSG_ERROR([unable to find required BIND 10 libraries])
+fi
+
+# restore LIBS once at this point
+LIBS="$LIBS_SAVES"
+
+AC_SUBST(BIND10_LDFLAGS)
+AC_SUBST(BIND10_COMMON_LIB)
+
+# Check per-module BIND 10 libraries
+
+# DNS library
+AC_MSG_CHECKING([for BIND 10 DNS library])
+LIBS="$LIBS $BIND10_COMMON_LIB -lb10-dns++"
+AC_TRY_LINK([
+#include <dns/rrtype.h>
+],[
+isc::dns::RRType rrtype(1);
+], [BIND10_DNS_LIB="-lb10-dns++"
+ AC_MSG_RESULT(yes)],
+ [AC_MSG_RESULT(no)])
+LIBS="$LIBS_SAVES"
+AC_SUBST(BIND10_DNS_LIB)
+
+# Restore other flags
+CPPFLAGS="$CPPFLAGS_SAVED"
+LDFLAGS="$LDFLAGS_SAVES"
+
+AC_LANG_RESTORE
+])dnl AX_ISC_BIND10
diff --git a/src/bin/Makefile.am b/src/bin/Makefile.am
index 7af44f9..0b4c1ae 100644
--- a/src/bin/Makefile.am
+++ b/src/bin/Makefile.am
@@ -1,4 +1,4 @@
-SUBDIRS = bind10 bindctl cfgmgr ddns loadzone msgq host cmdctl auth xfrin \
+SUBDIRS = bind10 bindctl cfgmgr ddns loadzone msgq cmdctl auth xfrin \
xfrout usermgr zonemgr stats tests resolver sockcreator dhcp4 dhcp6 \
dbutil sysinfo
diff --git a/src/bin/auth/Makefile.am b/src/bin/auth/Makefile.am
index 2060ad6..7d29fcc 100644
--- a/src/bin/auth/Makefile.am
+++ b/src/bin/auth/Makefile.am
@@ -55,7 +55,8 @@ 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.cc statistics.h statistics_items.h
-b10_auth_SOURCES += datasrc_configurator.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
@@ -73,6 +74,7 @@ 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
diff --git a/src/bin/auth/auth_config.h b/src/bin/auth/auth_config.h
index 6f18810..57fd270 100644
--- a/src/bin/auth/auth_config.h
+++ b/src/bin/auth/auth_config.h
@@ -18,8 +18,8 @@
#include <cc/data.h>
-#ifndef __CONFIG_H
-#define __CONFIG_H 1
+#ifndef CONFIG_H
+#define CONFIG_H 1
class AuthSrv;
@@ -93,7 +93,7 @@ public:
/// 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 an data \c Element storing an integer whose value
+ /// 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
@@ -195,7 +195,7 @@ void configureAuthServer(AuthSrv& server,
AuthConfigParser* createAuthConfigParser(AuthSrv& server,
const std::string& config_id);
-#endif // __CONFIG_H
+#endif // CONFIG_H
// Local Variables:
// mode: c++
diff --git a/src/bin/auth/auth_log.cc b/src/bin/auth/auth_log.cc
index d41eaea..fae7bd3 100644
--- a/src/bin/auth/auth_log.cc
+++ b/src/bin/auth/auth_log.cc
@@ -21,6 +21,12 @@ 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
diff --git a/src/bin/auth/auth_log.h b/src/bin/auth/auth_log.h
index 33d4432..52b973e 100644
--- a/src/bin/auth/auth_log.h
+++ b/src/bin/auth/auth_log.h
@@ -12,8 +12,8 @@
// 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
+#ifndef AUTH_LOG_H
+#define AUTH_LOG_H
#include <log/macros.h>
#include <auth/auth_messages.h>
@@ -28,21 +28,21 @@ namespace auth {
/// output.
// Debug messages indicating normal startup are logged at this debug level.
-const int DBG_AUTH_START = DBGLVL_START_SHUT;
+extern const int DBG_AUTH_START;
// Debug messages upon shutdown
-const int DBG_AUTH_SHUT = DBGLVL_START_SHUT;
+extern const int DBG_AUTH_SHUT;
// Debug level used to log setting information (such as configuration changes).
-const int DBG_AUTH_OPS = DBGLVL_COMMAND;
+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.)
-const int DBG_AUTH_DETAIL = DBGLVL_TRACE_BASIC;
+extern const int DBG_AUTH_DETAIL;
// This level is used to log the contents of packets received and sent.
-const int DBG_AUTH_MESSAGES = DBGLVL_TRACE_DETAIL_DATA;
+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
@@ -53,4 +53,4 @@ extern isc::log::Logger auth_logger;
} // namespace nsas
} // namespace isc
-#endif // __AUTH_LOG__H
+#endif // AUTH_LOG_H
diff --git a/src/bin/auth/auth_messages.mes b/src/bin/auth/auth_messages.mes
index ae7be1e..163b6ba 100644
--- a/src/bin/auth/auth_messages.mes
+++ b/src/bin/auth/auth_messages.mes
@@ -57,6 +57,101 @@ 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_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 succesfully
+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_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_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
datebase data source, listing the file that is being accessed.
diff --git a/src/bin/auth/auth_srv.cc b/src/bin/auth/auth_srv.cc
index c31f5d5..dca8fd0 100644
--- a/src/bin/auth/auth_srv.cc
+++ b/src/bin/auth/auth_srv.cc
@@ -52,6 +52,7 @@
#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>
@@ -68,6 +69,8 @@
using namespace std;
+using boost::shared_ptr;
+
using namespace isc;
using namespace isc::cc;
using namespace isc::datasrc;
@@ -264,23 +267,10 @@ public:
AddressList listen_addresses_;
/// The TSIG keyring
- const boost::shared_ptr<TSIGKeyRing>* keyring_;
+ const shared_ptr<TSIGKeyRing>* keyring_;
- /// The client list
- std::map<RRClass, boost::shared_ptr<ConfigurableClientList> >
- client_lists_;
-
- boost::shared_ptr<ConfigurableClientList> getClientList(const RRClass&
- rrclass)
- {
- const std::map<RRClass, boost::shared_ptr<ConfigurableClientList> >::
- const_iterator it(client_lists_.find(rrclass));
- if (it == client_lists_.end()) {
- return (boost::shared_ptr<ConfigurableClientList>());
- } else {
- return (it->second);
- }
- }
+ /// The data source client list manager
+ auth::DataSrcClientsMgr datasrc_clients_mgr_;
/// Bind the ModuleSpec object in config_session_ with
/// isc:config::ModuleSpec::validateStatistics.
@@ -481,6 +471,11 @@ 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;
@@ -656,11 +651,15 @@ AuthSrvImpl::processNormalQuery(const IOMessage& io_message, Message& message,
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 inter-thread
+ // race.
+ auth::DataSrcClientsMgr::Holder datasrc_holder(datasrc_clients_mgr_);
try {
const ConstQuestionPtr question = *message.beginQuestion();
- const boost::shared_ptr<datasrc::ClientList>
- list(getClientList(question->getClass()));
+ const shared_ptr<datasrc::ClientList>
+ list(datasrc_holder.findClientList(question->getClass()));
if (list) {
const RRType& qtype = question->getType();
const Name& qname = question->getName();
@@ -687,6 +686,8 @@ AuthSrvImpl::processNormalQuery(const IOMessage& io_message, Message& message,
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.
}
bool
@@ -892,7 +893,7 @@ AuthSrv::setDNSService(isc::asiodns::DNSServiceBase& dnss) {
}
void
-AuthSrv::setTSIGKeyRing(const boost::shared_ptr<TSIGKeyRing>* keyring) {
+AuthSrv::setTSIGKeyRing(const shared_ptr<TSIGKeyRing>* keyring) {
impl_->keyring_ = keyring;
}
@@ -912,31 +913,6 @@ AuthSrv::destroyDDNSForwarder() {
}
void
-AuthSrv::setClientList(const RRClass& rrclass,
- const boost::shared_ptr<ConfigurableClientList>& list) {
- if (list) {
- impl_->client_lists_[rrclass] = list;
- } else {
- impl_->client_lists_.erase(rrclass);
- }
-}
-boost::shared_ptr<ConfigurableClientList>
-AuthSrv::getClientList(const RRClass& rrclass) {
- return (impl_->getClientList(rrclass));
-}
-
-vector<RRClass>
-AuthSrv::getClientListClasses() const {
- vector<RRClass> result;
- for (std::map<RRClass, boost::shared_ptr<ConfigurableClientList> >::
- const_iterator it(impl_->client_lists_.begin());
- it != impl_->client_lists_.end(); ++it) {
- result.push_back(it->first);
- }
- return (result);
-}
-
-void
AuthSrv::setTCPRecvTimeout(size_t timeout) {
dnss_->setTCPRecvTimeout(timeout);
}
diff --git a/src/bin/auth/auth_srv.h b/src/bin/auth/auth_srv.h
index a3d8402..ebd3034 100644
--- a/src/bin/auth/auth_srv.h
+++ b/src/bin/auth/auth_srv.h
@@ -12,13 +12,15 @@
// 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 <string>
+#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>
@@ -33,13 +35,23 @@
#include <asiolink/asiolink.h>
#include <server_common/portconfig.h>
+
#include <auth/statistics.h>
+#include <auth/datasrc_clients_mgr.h>
+
+#include <boost/shared_ptr.hpp>
+
+#include <map>
+#include <string>
namespace isc {
namespace util {
namespace io {
class BaseSocketSessionForwarder;
}
+namespace thread {
+class Mutex;
+}
}
namespace datasrc {
class ConfigurableClientList;
@@ -184,6 +196,11 @@ public:
/// \brief Return pointer to the Checkin callback function
isc::asiolink::SimpleCallback* getCheckinProvider() const { return (checkin_); }
+ /// \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.
///
@@ -249,36 +266,10 @@ public:
/// If there was no forwarder yet, this method does nothing.
void destroyDDNSForwarder();
- /// \brief Sets the currently used list for data sources of given
- /// class.
- ///
- /// Replaces the internally used client list with a new one. Other
- /// classes are not changed.
- ///
- /// \param rrclass The class to modify.
- /// \param list Shared pointer to the client list. If it is NULL,
- /// the list is removed instead.
- void setClientList(const isc::dns::RRClass& rrclass, const
- boost::shared_ptr<isc::datasrc::ConfigurableClientList>&
- list);
-
- /// \brief Returns the currently used client list for the class.
- ///
- /// \param rrclass The class for which to get the list.
- /// \return The list, or NULL if no list is set for the class.
- boost::shared_ptr<isc::datasrc::ConfigurableClientList>
- getClientList(const isc::dns::RRClass& rrclass);
-
- /// \brief Returns a list of classes that have a client list.
- ///
- /// \return List of classes for which a non-NULL client list
- /// has been set by setClientList.
- std::vector<isc::dns::RRClass> getClientListClasses() const;
-
/// \brief Sets the timeout for incoming TCP connections
///
/// Incoming TCP connections that have not sent their data
- /// withing this time are dropped.
+ /// within this time are dropped.
///
/// \param timeout The timeout (in milliseconds). If se to
/// zero, no timeouts are used, and the connection will remain
@@ -293,7 +284,7 @@ private:
isc::asiodns::DNSServiceBase* dnss_;
};
-#endif // __AUTH_SRV_H
+#endif // AUTH_SRV_H
// Local Variables:
// mode: c++
diff --git a/src/bin/auth/benchmarks/Makefile.am b/src/bin/auth/benchmarks/Makefile.am
index 35e3179..27ddfc5 100644
--- a/src/bin/auth/benchmarks/Makefile.am
+++ b/src/bin/auth/benchmarks/Makefile.am
@@ -17,6 +17,7 @@ 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
@@ -33,5 +34,6 @@ 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)
diff --git a/src/bin/auth/benchmarks/query_bench.cc b/src/bin/auth/benchmarks/query_bench.cc
index 93253db..77b3377 100644
--- a/src/bin/auth/benchmarks/query_bench.cc
+++ b/src/bin/auth/benchmarks/query_bench.cc
@@ -18,6 +18,7 @@
#include <bench/benchmark_util.h>
#include <util/buffer.h>
+
#include <dns/message.h>
#include <dns/name.h>
#include <dns/question.h>
@@ -30,7 +31,8 @@
#include <auth/auth_srv.h>
#include <auth/auth_config.h>
-#include <auth/datasrc_configurator.h>
+#include <auth/datasrc_config.h>
+#include <auth/datasrc_clients_mgr.h>
#include <auth/query.h>
#include <asiodns/asiodns.h>
@@ -125,13 +127,15 @@ public:
OutputBuffer& buffer) :
QueryBenchMark(queries, query_message, buffer)
{
- DataSourceConfigurator::testReconfigure(
- server_.get(),
- Element::fromJSON("{\"IN\":"
- " [{\"type\": \"sqlite3\","
- " \"params\": {"
- " \"database_file\": \"" +
- string(datasrc_file) + "\"}}]}"));
+ // 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) + "\"}}]}")));
}
};
@@ -139,19 +143,19 @@ class MemoryQueryBenchMark : public QueryBenchMark {
public:
MemoryQueryBenchMark(const char* const zone_file,
const char* const zone_origin,
- const BenchQueries& queries,
- Message& query_message,
- OutputBuffer& buffer) :
+ const BenchQueries& queries,
+ Message& query_message,
+ OutputBuffer& buffer) :
QueryBenchMark(queries, query_message, buffer)
{
- DataSourceConfigurator::testReconfigure(
- server_.get(),
- Element::fromJSON("{\"IN\":"
- " [{\"type\": \"MasterFiles\","
- " \"cache-enable\": true, "
- " \"params\": {\"" +
- string(zone_origin) + "\": \"" +
- string(zone_file) + "\"}}]}"));
+ server_->getDataSrcClientsMgr().setDataSrcClientLists(
+ configureDataSource(
+ Element::fromJSON("{\"IN\":"
+ " [{\"type\": \"MasterFiles\","
+ " \"cache-enable\": true, "
+ " \"params\": {\"" +
+ string(zone_origin) + "\": \"" +
+ string(zone_file) + "\"}}]}")));
}
};
diff --git a/src/bin/auth/command.cc b/src/bin/auth/command.cc
index 43b2422..606fd3f 100644
--- a/src/bin/auth/command.cc
+++ b/src/bin/auth/command.cc
@@ -15,6 +15,7 @@
#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>
@@ -187,10 +188,11 @@ public:
if (!origin_elem) {
isc_throw(AuthCommandError, "Zone origin is missing");
}
- Name origin(origin_elem->stringValue());
+ const Name origin(origin_elem->stringValue());
- const boost::shared_ptr<isc::datasrc::ConfigurableClientList>
- list(server.getClientList(zone_class));
+ DataSrcClientsMgr::Holder holder(server.getDataSrcClientsMgr());
+ boost::shared_ptr<ConfigurableClientList> list =
+ holder.findClientList(zone_class);
if (!list) {
isc_throw(AuthCommandError, "There's no client list for "
@@ -198,7 +200,7 @@ public:
}
switch (list->reload(origin)) {
- case ConfigurableClientList::ZONE_RELOADED:
+ case ConfigurableClientList::ZONE_SUCCESS:
// Everything worked fine.
LOG_DEBUG(auth_logger, DBG_AUTH_OPS, AUTH_LOAD_ZONE)
.arg(zone_class).arg(origin);
diff --git a/src/bin/auth/command.h b/src/bin/auth/command.h
index 7db5cd6..5058b81 100644
--- a/src/bin/auth/command.h
+++ b/src/bin/auth/command.h
@@ -16,8 +16,8 @@
#include <cc/data.h>
-#ifndef __COMMAND_H
-#define __COMMAND_H 1
+#ifndef COMMAND_H
+#define COMMAND_H 1
class AuthSrv;
@@ -54,7 +54,7 @@ isc::data::ConstElementPtr
execAuthServerCommand(AuthSrv& server, const std::string& command_id,
isc::data::ConstElementPtr args);
-#endif // __COMMAND_H
+#endif // COMMAND_H
// Local Variables:
// mode: c++
diff --git a/src/bin/auth/common.h b/src/bin/auth/common.h
index 0964217..908a7d1 100644
--- a/src/bin/auth/common.h
+++ b/src/bin/auth/common.h
@@ -12,8 +12,8 @@
// 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
+#ifndef COMMON_H
+#define COMMON_H 1
#include <stdexcept>
#include <string>
@@ -62,7 +62,7 @@ extern const char* const AUTH_NAME;
/// This is sent to interested modules (currently only b10-ddns)
extern const char* const AUTH_STARTED_NOTIFICATION;
-#endif // __COMMON_H
+#endif // COMMON_H
// Local Variables:
// mode: c++
diff --git a/src/bin/auth/datasrc_clients_mgr.h b/src/bin/auth/datasrc_clients_mgr.h
new file mode 100644
index 0000000..854b1fe
--- /dev/null
+++ b/src/bin/auth/datasrc_clients_mgr.h
@@ -0,0 +1,586 @@
+// 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/data_source.h>
+#include <datasrc/client_list.h>
+#include <datasrc/memory/zone_writer.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 <exception>
+#include <cassert>
+#include <list>
+#include <utility>
+
+namespace isc {
+namespace auth {
+
+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.
+ SHUTDOWN, ///< Shutdown the builder; no argument
+ NUM_COMMANDS
+};
+
+/// \brief The data type passed from DataSrcClientsMgr to
+/// DataSrcClientsBuilder.
+///
+/// The first element of the pair is the command ID, and the second element
+/// is its argument. If the command doesn't take an argument it should be
+/// a null pointer.
+typedef std::pair<CommandID, data::ConstElementPtr> Command;
+} // 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;
+
+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);
+ }
+ }
+ 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() :
+ clients_map_(new ClientListsMap),
+ builder_(&command_queue_, &cond_, &queue_mutex_, &clients_map_,
+ &map_mutex_),
+ builder_thread_(boost::bind(&BuilderType::run, &builder_))
+ {}
+
+ /// \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);
+ }
+
+ 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.
+ void reconfigure(data::ConstElementPtr config_arg) {
+ if (!config_arg) {
+ isc_throw(InvalidParameter, "Invalid null config argument");
+ }
+ sendCommand(datasrc_clientmgr_internal::RECONFIGURE, config_arg);
+ 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;
+ }
+
+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,
+ data::ConstElementPtr arg)
+ {
+ // 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));
+ cond_.signal();
+ }
+
+ //
+ // 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_;
+ 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
+ MutexType map_mutex_; // mutex to protect the clients map
+
+ BuilderType builder_;
+ ThreadType builder_thread_; // for safety this should be placed last
+};
+
+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.
+ ///
+ /// Note: this will take actual set (map) of data source clients and
+ /// a mutex object for it in #2210 or #2212.
+ ///
+ /// \throw None
+ DataSrcClientsBuilderBase(std::list<Command>* command_queue,
+ CondVarType* cond, MutexType* queue_mutex,
+ datasrc::ClientListMapPtr* clients_map,
+ MutexType* map_mutex
+ ) :
+ command_queue_(command_queue), cond_(cond), queue_mutex_(queue_mutex),
+ clients_map_(clients_map), map_mutex_(map_mutex)
+ {}
+
+ /// \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 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_;
+ CondVarType* cond_;
+ MutexType* queue_mutex_;
+ datasrc::ClientListMapPtr* clients_map_;
+ MutexType* map_mutex_;
+};
+
+// 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());
+ }
+ 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.first;
+ 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", "SHUTDOWN"}
+ };
+ LOG_DEBUG(auth_logger, DBGLVL_TRACE_BASIC,
+ AUTH_DATASRC_CLIENTS_BUILDER_COMMAND).arg(command_desc.at(cid));
+ switch (command.first) {
+ case RECONFIGURE:
+ doReconfigure(command.second);
+ break;
+ case LOADZONE:
+ doLoadZone(command.second);
+ 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("class"));
+ assert(arg->get("origin"));
+
+ const dns::RRClass rrclass(arg->get("class")->stringValue());
+ 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);
+
+ 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)
+{
+ const datasrc::ConfigurableClientList::ZoneWriterPair writerpair =
+ client_list.getCachedZoneWriter(origin);
+
+ 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:
+ isc_throw(InternalCommandError, "failed to load zone " << origin
+ << "/" << rrclass << ": not served from memory");
+ 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");
+ }
+
+ // all cases above should either return or throw, but some compilers
+ // still need a return statement
+ 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:
diff --git a/src/bin/auth/datasrc_config.cc b/src/bin/auth/datasrc_config.cc
new file mode 100644
index 0000000..4869050
--- /dev/null
+++ b/src/bin/auth/datasrc_config.cc
@@ -0,0 +1,24 @@
+// 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));
+}
diff --git a/src/bin/auth/datasrc_config.h b/src/bin/auth/datasrc_config.h
new file mode 100644
index 0000000..1723161
--- /dev/null
+++ b/src/bin/auth/datasrc_config.h
@@ -0,0 +1,82 @@
+// 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:
diff --git a/src/bin/auth/datasrc_configurator.h b/src/bin/auth/datasrc_configurator.h
deleted file mode 100644
index f305a0d..0000000
--- a/src/bin/auth/datasrc_configurator.h
+++ /dev/null
@@ -1,223 +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_CONFIGURATOR_H
-#define DATASRC_CONFIGURATOR_H
-
-#include "auth_srv.h"
-
-#include <datasrc/client_list.h>
-#include <config/ccsession.h>
-#include <cc/data.h>
-
-#include <set>
-
-/// \brief A class to configure the authoritative server's data source lists
-///
-/// This will hook into the data_sources module configuration and it will
-/// keep the local copy of data source clients in the list in the authoritative
-/// server.
-///
-/// The class is slightly unusual. Due to some technical limitations, the hook
-/// needs to be static method. Therefore it is not possible to create instances
-/// of the class.
-///
-/// Also, the class is a template. This is simply because of easier testing.
-/// You don't need to pay attention to it, use the DataSourceConfigurator
-/// type alias instead.
-template<class Server, class List>
-class DataSourceConfiguratorGeneric {
-private:
- /// \brief Disallow creation of instances
- DataSourceConfiguratorGeneric();
- /// \brief Internal method to hook into the ModuleCCSession
- ///
- /// It simply calls reconfigure.
- static void reconfigureInternal(const std::string&,
- isc::data::ConstElementPtr config,
- const isc::config::ConfigData&)
- {
- if (config->contains("classes")) {
- reconfigure(config->get("classes"));
- }
- }
- static Server* server_;
- static isc::config::ModuleCCSession* session_;
- typedef boost::shared_ptr<List> ListPtr;
-public:
- /// \brief Initializes the class.
- ///
- /// This configures which session and server should be used.
- /// It hooks to the session now and downloads the configuration.
- /// It is synchronous (it may block for some time).
- ///
- /// Note that you need to call cleanup before the server or
- /// session dies, otherwise it might access them after they
- /// are destroyed.
- ///
- /// \param session The session to hook into and to access the configuration
- /// through.
- /// \param server It is the server to configure.
- /// \throw isc::InvalidOperation if this is called when already initialized.
- /// \throw isc::InvalidParameter if any of the parameters is NULL
- /// \throw isc::config::ModuleCCError if the remote configuration is not
- /// available for some reason.
- static void init(isc::config::ModuleCCSession* session,
- Server* server)
- {
- if (session == NULL) {
- isc_throw(isc::InvalidParameter, "The session must not be NULL");
- }
- if (server == NULL) {
- isc_throw(isc::InvalidParameter, "The server must not be NULL");
- }
- if (server_ != NULL) {
- isc_throw(isc::InvalidOperation,
- "The configurator is already initialized");
- }
- server_ = server;
- session_ = session;
- session->addRemoteConfig("data_sources", reconfigureInternal, false);
- }
- /// \brief Deinitializes the class.
- ///
- /// This detaches from the session and removes the server from internal
- /// storage. The current configuration in the server is preserved.
- ///
- /// This can be called even if it is not initialized currently. You
- /// can initialize it again after this.
- static void cleanup() {
- if (session_ != NULL) {
- session_->removeRemoteConfig("data_sources");
- }
- session_ = NULL;
- server_ = NULL;
- }
- /// \brief Reads new configuration and replaces the old one.
- ///
- /// It instructs the server to replace the lists with new ones as needed.
- /// You don't need to call it directly (but you could, though the benefit
- /// is unknown and it would be questionable at least). It is called
- /// automatically on normal updates.
- ///
- /// \param config The configuration value to parse. It is in the form
- /// as an update from the config manager.
- /// \throw InvalidOperation if it is called when not initialized.
- static void reconfigure(const isc::data::ConstElementPtr& config) {
- if (server_ == NULL) {
- isc_throw(isc::InvalidOperation,
- "Can't reconfigure while not initialized by init()");
- }
- typedef std::map<std::string, isc::data::ConstElementPtr> Map;
- typedef std::pair<isc::dns::RRClass, ListPtr> RollbackPair;
- typedef std::pair<isc::dns::RRClass, isc::data::ConstElementPtr>
- RollbackConfiguration;
- // Some structures to be able to perform a rollback
- std::vector<RollbackPair> rollback_sets;
- std::vector<RollbackConfiguration> rollback_configurations;
- try {
- // Get the configuration and current state.
- const Map& map(config->mapValue());
- const std::vector<isc::dns::RRClass>
- activeVector(server_->getClientListClasses());
- std::set<isc::dns::RRClass> active(activeVector.begin(),
- activeVector.end());
- // Go through the configuration and change everything.
- for (Map::const_iterator it(map.begin()); it != map.end(); ++it) {
- isc::dns::RRClass rrclass(it->first);
- active.erase(rrclass);
- ListPtr list(server_->getClientList(rrclass));
- bool need_set(false);
- if (list) {
- rollback_configurations.
- push_back(RollbackConfiguration(rrclass,
- list->getConfiguration()));
- } else {
- list.reset(new List(rrclass));
- need_set = true;
- rollback_sets.push_back(RollbackPair(rrclass, ListPtr()));
- }
- list->configure(it->second, true);
- if (need_set) {
- server_->setClientList(rrclass, list);
- }
- }
- // Remove the ones that are not in the configuration.
- for (std::set<isc::dns::RRClass>::iterator it(active.begin());
- it != active.end(); ++it) {
- // There seems to be no way the setClientList could throw.
- // But this is just to make sure in case it did to restore
- // the original.
- rollback_sets.push_back(
- RollbackPair(*it, server_->getClientList(*it)));
- server_->setClientList(*it, ListPtr());
- }
- } catch (...) {
- // Perform a rollback of the changes. The old configuration should
- // work.
- for (typename std::vector<RollbackPair>::const_iterator
- it(rollback_sets.begin()); it != rollback_sets.end(); ++it) {
- server_->setClientList(it->first, it->second);
- }
- for (typename std::vector<RollbackConfiguration>::const_iterator
- it(rollback_configurations.begin());
- it != rollback_configurations.end(); ++it) {
- server_->getClientList(it->first)->configure(it->second, true);
- }
- throw;
- }
- }
- /// \brief Version of reconfigure for easier testing.
- ///
- /// This method can be used to reconfigure a server without first
- /// initializing the configurator. This does not need a session.
- /// Otherwise, it acts the same as reconfigure.
- ///
- /// This is not meant for production code. Do not use there.
- ///
- /// \param server The server to configure.
- /// \param config The config to use.
- /// \throw isc::InvalidOperation if the configurator is initialized.
- /// \throw anything that reconfigure does.
- static void testReconfigure(Server* server,
- const isc::data::ConstElementPtr& config)
- {
- if (server_ != NULL) {
- isc_throw(isc::InvalidOperation, "Currently initialized.");
- }
- try {
- server_ = server;
- reconfigure(config);
- server_ = NULL;
- } catch (...) {
- server_ = NULL;
- throw;
- }
- }
-};
-
-template<class Server, class List>
-isc::config::ModuleCCSession*
-DataSourceConfiguratorGeneric<Server, List>::session_(NULL);
-
-template<class Server, class List>
-Server* DataSourceConfiguratorGeneric<Server, List>::server_(NULL);
-
-/// \brief Concrete version of DataSourceConfiguratorGeneric for the
-/// use in authoritative server.
-typedef DataSourceConfiguratorGeneric<AuthSrv,
- isc::datasrc::ConfigurableClientList>
- DataSourceConfigurator;
-
-#endif
diff --git a/src/bin/auth/main.cc b/src/bin/auth/main.cc
index 3cca3c0..1fe0f48 100644
--- a/src/bin/auth/main.cc
+++ b/src/bin/auth/main.cc
@@ -14,17 +14,6 @@
#include <config.h>
-#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>
-
#include <exceptions/exceptions.h>
#include <util/buffer.h>
@@ -45,13 +34,28 @@
#include <auth/command.h>
#include <auth/auth_srv.h>
#include <auth/auth_log.h>
-#include <auth/datasrc_configurator.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 <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;
@@ -70,7 +74,7 @@ namespace {
/* need global var for config/command handlers.
* todo: turn this around, and put handlers in the authserver
* class itself? */
-AuthSrv *auth_server;
+AuthSrv* auth_server;
ConstElementPtr
my_config_handler(ConstElementPtr new_config) {
@@ -84,6 +88,33 @@ my_command_handler(const string& command, ConstElementPtr 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"));
+ } else if (config->contains("classes")) {
+ server->getDataSrcClientsMgr().reconfigure(config->get("classes"));
+ }
+}
+
+void
usage() {
cerr << "Usage: b10-auth [-v]"
<< endl;
@@ -191,13 +222,15 @@ main(int argc, char* argv[]) {
isc::server_common::initKeyring(*config_session);
auth_server->setTSIGKeyRing(&isc::server_common::keyring);
- // Start the data source configuration
- DataSourceConfigurator::init(config_session, auth_server);
- // HACK: The default is not passed to the handler. This one will
- // get the default (or, current value). Further updates will work
- // the usual way.
- DataSourceConfigurator::reconfigure(
- config_session->getRemoteConfigValue("data_sources", "classes"));
+ // 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,
+ _1, _2, _3),
+ false);
// Now start asynchronous read.
config_session->start();
@@ -221,7 +254,10 @@ main(int argc, char* argv[]) {
xfrin_session->disconnect();
}
- DataSourceConfigurator::cleanup();
+ // If we haven't registered callback for data sources, this will be just
+ // no-op.
+ config_session->removeRemoteConfig("data_sources");
+
delete xfrin_session;
delete config_session;
delete cc_session;
diff --git a/src/bin/auth/statistics.h b/src/bin/auth/statistics.h
index 323c32f..d60c681 100644
--- a/src/bin/auth/statistics.h
+++ b/src/bin/auth/statistics.h
@@ -12,8 +12,8 @@
// 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
+#ifndef STATISTICS_H
+#define STATISTICS_H 1
#include <cc/session.h>
#include <cc/data.h>
@@ -223,7 +223,7 @@ public:
} // namespace auth
} // namespace isc
-#endif // __STATISTICS_H
+#endif // STATISTICS_H
// Local Variables:
// mode: c++
diff --git a/src/bin/auth/tests/Makefile.am b/src/bin/auth/tests/Makefile.am
index 482a4f7..6a91309 100644
--- a/src/bin/auth/tests/Makefile.am
+++ b/src/bin/auth/tests/Makefile.am
@@ -42,6 +42,7 @@ 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 += auth_srv_unittest.cc
run_unittests_SOURCES += config_unittest.cc
@@ -50,7 +51,10 @@ run_unittests_SOURCES += command_unittest.cc
run_unittests_SOURCES += common_unittest.cc
run_unittests_SOURCES += query_unittest.cc
run_unittests_SOURCES += statistics_unittest.cc
-run_unittests_SOURCES += datasrc_configurator_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
@@ -72,6 +76,7 @@ run_unittests_LDADD += $(top_builddir)/src/lib/server_common/libb10-server-commo
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)
diff --git a/src/bin/auth/tests/auth_srv_unittest.cc b/src/bin/auth/tests/auth_srv_unittest.cc
index 77ecccf..0cd3420 100644
--- a/src/bin/auth/tests/auth_srv_unittest.cc
+++ b/src/bin/auth/tests/auth_srv_unittest.cc
@@ -15,7 +15,6 @@
#include <config.h>
#include <util/io/sockaddr_util.h>
-#include <util/memory_segment_local.h>
#include <dns/message.h>
#include <dns/messagerenderer.h>
@@ -37,7 +36,7 @@
#include <auth/common.h>
#include <auth/statistics.h>
#include <auth/statistics_items.h>
-#include <auth/datasrc_configurator.h>
+#include <auth/datasrc_config.h>
#include <util/unittests/mock_socketsession.h>
#include <dns/tests/unittest_util.h>
@@ -63,16 +62,19 @@
using namespace std;
using namespace isc::cc;
using namespace isc::dns;
+using namespace isc::datasrc;
using namespace isc::util;
using namespace isc::util::io::internal;
using namespace isc::util::unittests;
using namespace isc::dns::rdata;
using namespace isc::data;
using namespace isc::xfr;
+using namespace isc::auth;
using namespace isc::asiodns;
using namespace isc::asiolink;
using namespace isc::testutils;
using namespace isc::server_common::portconfig;
+using isc::datasrc::memory::ZoneTableSegment;
using isc::UnitTestUtil;
using boost::scoped_ptr;
using isc::auth::statistics::Counters;
@@ -91,6 +93,9 @@ const char* const STATIC_DSRC_FILE = DSRC_DIR "/static.zone";
// a signed example zone.
const char* const CONFIG_INMEMORY_EXAMPLE = TEST_DATA_DIR "/rfc5155-example.zone.signed";
+// shortcut commonly used in tests
+typedef boost::shared_ptr<ConfigurableClientList> ListPtr;
+
class AuthSrvTest : public SrvTestBase {
protected:
AuthSrvTest() :
@@ -766,17 +771,25 @@ TEST_F(AuthSrvTest, notifyWithSessionMessageError) {
}
void
-updateDatabase(AuthSrv* server, const char* params) {
+installDataSrcClientLists(AuthSrv& server, ClientListMapPtr lists) {
+ // For now, we use explicit swap than reconfigure() because the latter
+ // involves a separate thread and cannot guarantee the new config is
+ // available for the subsequent test.
+ server.getDataSrcClientsMgr().setDataSrcClientLists(lists);
+}
+
+void
+updateDatabase(AuthSrv& server, const char* params) {
const ConstElementPtr config(Element::fromJSON("{"
"\"IN\": [{"
" \"type\": \"sqlite3\","
" \"params\": " + string(params) +
"}]}"));
- DataSourceConfigurator::testReconfigure(server, config);
+ installDataSrcClientLists(server, configureDataSource(config));
}
void
-updateInMemory(AuthSrv* server, const char* origin, const char* filename) {
+updateInMemory(AuthSrv& server, const char* origin, const char* filename) {
const ConstElementPtr config(Element::fromJSON("{"
"\"IN\": [{"
" \"type\": \"MasterFiles\","
@@ -789,17 +802,17 @@ updateInMemory(AuthSrv* server, const char* origin, const char* filename) {
" \"type\": \"static\","
" \"params\": \"" + string(STATIC_DSRC_FILE) + "\""
"}]}"));
- DataSourceConfigurator::testReconfigure(server, config);
+ installDataSrcClientLists(server, configureDataSource(config));
}
void
-updateBuiltin(AuthSrv* server) {
+updateBuiltin(AuthSrv& server) {
const ConstElementPtr config(Element::fromJSON("{"
"\"CH\": [{"
" \"type\": \"static\","
" \"params\": \"" + string(STATIC_DSRC_FILE) + "\""
"}]}"));
- DataSourceConfigurator::testReconfigure(server, config);
+ installDataSrcClientLists(server, configureDataSource(config));
}
// Try giving the server a TSIG signed request and see it can anwer signed as
@@ -810,7 +823,7 @@ TEST_F(AuthSrvTest, DISABLED_TSIGSigned) { // Needs builtin
TEST_F(AuthSrvTest, TSIGSigned) {
#endif
// Prepare key, the client message, etc
- updateBuiltin(&server);
+ updateBuiltin(server);
const TSIGKey key("key:c2VjcmV0Cg==:hmac-sha1");
TSIGContext context(key);
UnitTestUtil::createRequestMessage(request_message, opcode, default_qid,
@@ -858,7 +871,7 @@ TEST_F(AuthSrvTest, DISABLED_builtInQueryViaDNSServer) {
#else
TEST_F(AuthSrvTest, builtInQueryViaDNSServer) {
#endif
- updateBuiltin(&server);
+ updateBuiltin(server);
UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
default_qid, Name("VERSION.BIND."),
RRClass::CH(), RRType::TXT());
@@ -890,7 +903,7 @@ TEST_F(AuthSrvTest, DISABLED_builtInQuery) {
#else
TEST_F(AuthSrvTest, builtInQuery) {
#endif
- updateBuiltin(&server);
+ updateBuiltin(server);
UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
default_qid, Name("VERSION.BIND."),
RRClass::CH(), RRType::TXT());
@@ -911,7 +924,7 @@ TEST_F(AuthSrvTest, DISABLED_iqueryViaDNSServer) { // Needs builtin
#else
TEST_F(AuthSrvTest, iqueryViaDNSServer) { // Needs builtin
#endif
- updateBuiltin(&server);
+ updateBuiltin(server);
createDataFromFile("iquery_fromWire.wire");
(*server.getDNSLookupProvider())(*io_message, parse_message,
response_message,
@@ -933,7 +946,7 @@ TEST_F(AuthSrvTest, DISABLED_updateConfig) {
#else
TEST_F(AuthSrvTest, updateConfig) {
#endif
- updateDatabase(&server, CONFIG_TESTDB);
+ updateDatabase(server, CONFIG_TESTDB);
// query for existent data in the installed data source. The resulting
// response should have the AA flag on, and have an RR in each answer
@@ -951,7 +964,7 @@ TEST_F(AuthSrvTest, DISABLED_datasourceFail) {
#else
TEST_F(AuthSrvTest, datasourceFail) {
#endif
- updateDatabase(&server, CONFIG_TESTDB);
+ updateDatabase(server, CONFIG_TESTDB);
// This query will hit a corrupted entry of the data source (the zoneload
// tool and the data source itself naively accept it). This will result
@@ -971,10 +984,10 @@ TEST_F(AuthSrvTest, DISABLED_updateConfigFail) {
TEST_F(AuthSrvTest, updateConfigFail) {
#endif
// First, load a valid data source.
- updateDatabase(&server, CONFIG_TESTDB);
+ updateDatabase(server, CONFIG_TESTDB);
// Next, try to update it with a non-existent one. This should fail.
- EXPECT_THROW(updateDatabase(&server, BADCONFIG_TESTDB),
+ EXPECT_THROW(updateDatabase(server, BADCONFIG_TESTDB),
isc::datasrc::DataSourceError);
// The original data source should still exist.
@@ -997,7 +1010,7 @@ TEST_F(AuthSrvTest, updateWithInMemoryClient) {
" \"params\": {},"
" \"cache-enable\": true"
"}]}"));
- DataSourceConfigurator::testReconfigure(&server, config);
+ installDataSrcClientLists(server, configureDataSource(config));
// after successful configuration, we should have one (with empty zoneset).
// The memory data source is empty, should return REFUSED rcode.
@@ -1018,7 +1031,7 @@ TEST_F(AuthSrvTest, queryWithInMemoryClientNoDNSSEC) {
// query handler class, and confirm it returns no error and a non empty
// answer section. Detailed examination on the response content
// for various types of queries are tested in the query tests.
- updateInMemory(&server, "example.", CONFIG_INMEMORY_EXAMPLE);
+ updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
createDataFromFile("nsec3query_nodnssec_fromWire.wire");
server.processMessage(*io_message, *parse_message, *response_obuffer,
@@ -1037,7 +1050,7 @@ TEST_F(AuthSrvTest, queryWithInMemoryClientDNSSEC) {
// Similar to the previous test, but the query has the DO bit on.
// The response should contain RRSIGs, and should have more RRs than
// the previous case.
- updateInMemory(&server, "example.", CONFIG_INMEMORY_EXAMPLE);
+ updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
createDataFromFile("nsec3query_fromWire.wire");
server.processMessage(*io_message, *parse_message, *response_obuffer,
@@ -1057,7 +1070,7 @@ TEST_F(AuthSrvTest,
)
{
// Set up the in-memory
- updateInMemory(&server, "example.", CONFIG_INMEMORY_EXAMPLE);
+ updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
// This shouldn't affect the result of class CH query
UnitTestUtil::createRequestMessage(request_message, Opcode::QUERY(),
@@ -1407,7 +1420,7 @@ public:
if (fake_rrset_ && fake_rrset_->getName() == name &&
fake_rrset_->getType() == type)
{
- return (ZoneFinderContextPtr(new ZoneFinder::Context(
+ return (ZoneFinderContextPtr(new ZoneFinder::GenericContext(
*this, options,
ResultContext(SUCCESS,
fake_rrset_))));
@@ -1509,7 +1522,9 @@ public:
real_list, ThrowWhen throw_when, bool isc_exception,
ConstRRsetPtr fake_rrset = ConstRRsetPtr()) :
ConfigurableClientList(RRClass::IN()),
- real_(real_list)
+ real_(real_list),
+ config_(Element::fromJSON("{}")),
+ ztable_segment_(ZoneTableSegment::create(*config_, RRClass::IN()))
{
BOOST_FOREACH(const DataSourceInfo& info, real_->getDataSources()) {
const isc::datasrc::DataSourceClientPtr
@@ -1521,13 +1536,14 @@ public:
data_sources_.push_back(
DataSourceInfo(client.get(),
isc::datasrc::DataSourceClientContainerPtr(),
- false, RRClass::IN(), mem_sgmt_));
+ false, RRClass::IN(), ztable_segment_));
}
}
private:
const boost::shared_ptr<isc::datasrc::ConfigurableClientList> real_;
+ const ConstElementPtr config_;
+ boost::shared_ptr<ZoneTableSegment> ztable_segment_;
vector<isc::datasrc::DataSourceClientPtr> clients_;
- MemorySegmentLocal mem_sgmt_;
};
} // end anonymous namespace for throwing proxy classes
@@ -1545,11 +1561,17 @@ TEST_F(AuthSrvTest,
)
{
// Set real inmem client to proxy
- updateInMemory(&server, "example.", CONFIG_INMEMORY_EXAMPLE);
- boost::shared_ptr<isc::datasrc::ConfigurableClientList>
- list(new FakeList(server.getClientList(RRClass::IN()), THROW_NEVER,
- false));
- server.setClientList(RRClass::IN(), list);
+ updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
+ boost::shared_ptr<isc::datasrc::ConfigurableClientList> list;
+ DataSrcClientsMgr& mgr = server.getDataSrcClientsMgr();
+ {
+ DataSrcClientsMgr::Holder holder(mgr);
+ list.reset(new FakeList(holder.findClientList(RRClass::IN()),
+ THROW_NEVER, false));
+ }
+ ClientListMapPtr lists(new std::map<RRClass, ListPtr>);
+ lists->insert(pair<RRClass, ListPtr>(RRClass::IN(), list));
+ server.getDataSrcClientsMgr().setDataSrcClientLists(lists);
createDataFromFile("nsec3query_nodnssec_fromWire.wire");
server.processMessage(*io_message, *parse_message, *response_obuffer,
@@ -1567,15 +1589,21 @@ TEST_F(AuthSrvTest,
// If non null rrset is given, it will be passed to the proxy so it can
// return some faked response.
void
-setupThrow(AuthSrv* server, ThrowWhen throw_when, bool isc_exception,
+setupThrow(AuthSrv& server, ThrowWhen throw_when, bool isc_exception,
ConstRRsetPtr rrset = ConstRRsetPtr())
{
updateInMemory(server, "example.", CONFIG_INMEMORY_EXAMPLE);
- boost::shared_ptr<isc::datasrc::ConfigurableClientList>
- list(new FakeList(server->getClientList(RRClass::IN()), throw_when,
- isc_exception, rrset));
- server->setClientList(RRClass::IN(), list);
+ boost::shared_ptr<isc::datasrc::ConfigurableClientList> list;
+ DataSrcClientsMgr& mgr = server.getDataSrcClientsMgr();
+ { // we need to limit the scope so swap is outside of it
+ DataSrcClientsMgr::Holder holder(mgr);
+ list.reset(new FakeList(holder.findClientList(RRClass::IN()),
+ throw_when, isc_exception, rrset));
+ }
+ ClientListMapPtr lists(new std::map<RRClass, ListPtr>);
+ lists->insert(pair<RRClass, ListPtr>(RRClass::IN(), list));
+ mgr.setDataSrcClientLists(lists);
}
TEST_F(AuthSrvTest,
@@ -1598,11 +1626,11 @@ TEST_F(AuthSrvTest,
RRClass::IN(), RRType::TXT());
for (ThrowWhen* when(throws); *when != THROW_NEVER; ++when) {
createRequestPacket(request_message, IPPROTO_UDP);
- setupThrow(&server, *when, true);
+ setupThrow(server, *when, true);
processAndCheckSERVFAIL();
// To be sure, check same for non-isc-exceptions
createRequestPacket(request_message, IPPROTO_UDP);
- setupThrow(&server, *when, false);
+ setupThrow(server, *when, false);
processAndCheckSERVFAIL();
}
}
@@ -1618,7 +1646,7 @@ TEST_F(AuthSrvTest,
)
{
createDataFromFile("nsec3query_nodnssec_fromWire.wire");
- setupThrow(&server, THROW_AT_GET_CLASS, true);
+ setupThrow(server, THROW_AT_GET_CLASS, true);
// getClass is not called so it should just answer
server.processMessage(*io_message, *parse_message, *response_obuffer,
@@ -1642,7 +1670,7 @@ TEST_F(AuthSrvTest,
ConstRRsetPtr empty_rrset(new RRset(Name("foo.example"),
RRClass::IN(), RRType::TXT(),
RRTTL(0)));
- setupThrow(&server, THROW_NEVER, true, empty_rrset);
+ setupThrow(server, THROW_NEVER, true, empty_rrset);
// Repeat the query processing two times. Due to the faked RRset,
// toWire() should throw, and it should result in SERVFAIL.
@@ -1882,36 +1910,4 @@ TEST_F(AuthSrvTest, DDNSForwardCreateDestroy) {
Opcode::UPDATE().getCode(), QR_FLAG, 0, 0, 0, 0);
}
-// Check the client list accessors
-TEST_F(AuthSrvTest, clientList) {
- // The lists don't exist. Therefore, the list of RRClasses is empty.
- // We also have no IN list.
- EXPECT_TRUE(server.getClientListClasses().empty());
- EXPECT_EQ(boost::shared_ptr<const isc::datasrc::ClientList>(),
- server.getClientList(RRClass::IN()));
- // Put something in.
- const boost::shared_ptr<isc::datasrc::ConfigurableClientList>
- list(new isc::datasrc::ConfigurableClientList(RRClass::IN()));
- const boost::shared_ptr<isc::datasrc::ConfigurableClientList>
- list2(new isc::datasrc::ConfigurableClientList(RRClass::CH()));
- server.setClientList(RRClass::IN(), list);
- server.setClientList(RRClass::CH(), list2);
- // There are two things in the list and they are IN and CH
- vector<RRClass> classes(server.getClientListClasses());
- ASSERT_EQ(2, classes.size());
- EXPECT_EQ(RRClass::IN(), classes[0]);
- EXPECT_EQ(RRClass::CH(), classes[1]);
- // And the lists can be retrieved.
- EXPECT_EQ(list, server.getClientList(RRClass::IN()));
- EXPECT_EQ(list2, server.getClientList(RRClass::CH()));
- // Remove one of them
- server.setClientList(RRClass::CH(),
- boost::shared_ptr<isc::datasrc::ConfigurableClientList>());
- // This really got deleted, including the class.
- classes = server.getClientListClasses();
- ASSERT_EQ(1, classes.size());
- EXPECT_EQ(RRClass::IN(), classes[0]);
- EXPECT_EQ(list, server.getClientList(RRClass::IN()));
-}
-
}
diff --git a/src/bin/auth/tests/command_unittest.cc b/src/bin/auth/tests/command_unittest.cc
index a22725e..280def6 100644
--- a/src/bin/auth/tests/command_unittest.cc
+++ b/src/bin/auth/tests/command_unittest.cc
@@ -17,9 +17,8 @@
#include "datasrc_util.h"
#include <auth/auth_srv.h>
-#include <auth/auth_config.h>
#include <auth/command.h>
-#include <auth/datasrc_configurator.h>
+#include <auth/datasrc_config.h>
#include <dns/name.h>
#include <dns/rrclass.h>
@@ -56,6 +55,7 @@ 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 {
@@ -174,18 +174,26 @@ TEST_F(AuthCommandTest, shutdownIncorrectPID) {
// zones, and checks the zones are correctly loaded.
void
zoneChecks(AuthSrv& server) {
- EXPECT_EQ(ZoneFinder::SUCCESS, server.getClientList(RRClass::IN())->
- find(Name("ns.test1.example")).finder_->
- find(Name("ns.test1.example"), RRType::A())->code);
- EXPECT_EQ(ZoneFinder::NXRRSET, server.getClientList(RRClass::IN())->
- find(Name("ns.test1.example")).finder_->
- find(Name("ns.test1.example"), RRType::AAAA())->code);
- EXPECT_EQ(ZoneFinder::SUCCESS, server.getClientList(RRClass::IN())->
- find(Name("ns.test2.example")).finder_->
- find(Name("ns.test2.example"), RRType::A())->code);
- EXPECT_EQ(ZoneFinder::NXRRSET, server.getClientList(RRClass::IN())->
- find(Name("ns.test2.example")).finder_->
- find(Name("ns.test2.example"), RRType::AAAA())->code);
+ const RRClass rrclass(RRClass::IN());
+
+ DataSrcClientsMgr::Holder holder(server.getDataSrcClientsMgr());
+ EXPECT_EQ(ZoneFinder::SUCCESS,
+ holder.findClientList(rrclass)->find(Name("ns.test1.example"))
+ .finder_->find(Name("ns.test1.example"), RRType::A())->code);
+ EXPECT_EQ(ZoneFinder::NXRRSET,
+ holder.findClientList(rrclass)->find(Name("ns.test1.example")).
+ finder_->find(Name("ns.test1.example"), RRType::AAAA())->code);
+ EXPECT_EQ(ZoneFinder::SUCCESS,
+ holder.findClientList(rrclass)->find(Name("ns.test2.example")).
+ finder_->find(Name("ns.test2.example"), RRType::A())->code);
+ EXPECT_EQ(ZoneFinder::NXRRSET,
+ holder.findClientList(rrclass)->find(Name("ns.test2.example")).
+ finder_->find(Name("ns.test2.example"), RRType::AAAA())->code);
+}
+
+void
+installDataSrcClientLists(AuthSrv& server, ClientListMapPtr lists) {
+ server.getDataSrcClientsMgr().setDataSrcClientLists(lists);
}
void
@@ -207,26 +215,31 @@ configureZones(AuthSrv& server) {
" \"cache-enable\": true"
"}]}"));
- DataSourceConfigurator::testReconfigure(&server, config);
+ installDataSrcClientLists(server, configureDataSource(config));
zoneChecks(server);
}
void
newZoneChecks(AuthSrv& server) {
- EXPECT_EQ(ZoneFinder::SUCCESS, server.getClientList(RRClass::IN())->
+ const RRClass rrclass(RRClass::IN());
+
+ DataSrcClientsMgr::Holder holder(server.getDataSrcClientsMgr());
+ EXPECT_EQ(ZoneFinder::SUCCESS, holder.findClientList(rrclass)->
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, server.getClientList(RRClass::IN())->
+ EXPECT_EQ(ZoneFinder::SUCCESS, holder.findClientList(rrclass)->
find(Name("ns.test1.example")).finder_->
find(Name("ns.test1.example"), RRType::AAAA())->code);
// test2.example shouldn't change
- EXPECT_EQ(ZoneFinder::SUCCESS, server.getClientList(RRClass::IN())->
+ EXPECT_EQ(ZoneFinder::SUCCESS, holder.findClientList(rrclass)->
find(Name("ns.test2.example")).finder_->
find(Name("ns.test2.example"), RRType::A())->code);
- EXPECT_EQ(ZoneFinder::NXRRSET, server.getClientList(RRClass::IN())->
+ EXPECT_EQ(ZoneFinder::NXRRSET,
+ holder.findClientList(rrclass)->
find(Name("ns.test2.example")).finder_->
find(Name("ns.test2.example"), RRType::AAAA())->code);
}
@@ -269,32 +282,38 @@ TEST_F(AuthCommandTest,
" \"cache-enable\": true,"
" \"cache-zones\": [\"example.org\"]"
"}]}"));
- DataSourceConfigurator::testReconfigure(&server_, config);
-
- // Check that the A record at www.example.org does not exist
- EXPECT_EQ(ZoneFinder::NXDOMAIN, server_.getClientList(RRClass::IN())->
- 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);
- RRsetPtr rrset(new RRset(Name("www.example.org."), RRClass::IN(),
- RRType::A(), RRTTL(60)));
- rrset->addRdata(rdata::createRdata(rrset->getType(),
- rrset->getClass(),
- "192.0.2.1"));
- sql_updater->addRRset(*rrset);
- sql_updater->commit();
-
- EXPECT_EQ(ZoneFinder::NXDOMAIN, server_.getClientList(RRClass::IN())->
- find(Name("example.org")).finder_->
- find(Name("www.example.org"), RRType::A())->code);
+ installDataSrcClientLists(server_, configureDataSource(config));
+
+ {
+ DataSrcClientsMgr::Holder holder(server_.getDataSrcClientsMgr());
+
+ // Check that the A record at www.example.org does not exist
+ EXPECT_EQ(ZoneFinder::NXDOMAIN,
+ holder.findClientList(RRClass::IN())->
+ 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);
+ RRsetPtr rrset(new RRset(Name("www.example.org."), RRClass::IN(),
+ RRType::A(), RRTTL(60)));
+ rrset->addRdata(rdata::createRdata(rrset->getType(),
+ rrset->getClass(),
+ "192.0.2.1"));
+ sql_updater->addRRset(*rrset);
+ sql_updater->commit();
+
+ EXPECT_EQ(ZoneFinder::NXDOMAIN,
+ holder.findClientList(RRClass::IN())->
+ find(Name("example.org")).finder_->
+ find(Name("www.example.org"), RRType::A())->code);
+ }
// Now send the command to reload it
result_ = execAuthServerCommand(server_, "loadzone",
@@ -302,20 +321,28 @@ TEST_F(AuthCommandTest,
"{\"origin\": \"example.org\"}"));
checkAnswer(0, "Successful load");
- // And now it should be present too.
- EXPECT_EQ(ZoneFinder::SUCCESS, server_.getClientList(RRClass::IN())->
- find(Name("example.org")).finder_->
- find(Name("www.example.org"), RRType::A())->code);
+ {
+ DataSrcClientsMgr::Holder holder(server_.getDataSrcClientsMgr());
+ // And now it should be present too.
+ EXPECT_EQ(ZoneFinder::SUCCESS,
+ holder.findClientList(RRClass::IN())->
+ find(Name("example.org")).finder_->
+ find(Name("www.example.org"), RRType::A())->code);
+ }
// Some error cases. First, the zone has no configuration. (note .com here)
result_ = execAuthServerCommand(server_, "loadzone",
Element::fromJSON("{\"origin\": \"example.com\"}"));
checkAnswer(1, "example.com");
- // The previous zone is not hurt in any way
- EXPECT_EQ(ZoneFinder::SUCCESS, server_.getClientList(RRClass::IN())->
- find(Name("example.org")).finder_->
- find(Name("example.org"), RRType::SOA())->code);
+ {
+ DataSrcClientsMgr::Holder holder(server_.getDataSrcClientsMgr());
+ // The previous zone is not hurt in any way
+ EXPECT_EQ(ZoneFinder::SUCCESS,
+ holder.findClientList(RRClass::IN())->
+ find(Name("example.org")).finder_->
+ find(Name("example.org"), RRType::SOA())->code);
+ }
const ConstElementPtr config2(Element::fromJSON("{"
"\"IN\": [{"
@@ -324,15 +351,17 @@ TEST_F(AuthCommandTest,
" \"cache-enable\": true,"
" \"cache-zones\": [\"example.com\"]"
"}]}"));
- EXPECT_THROW(DataSourceConfigurator::testReconfigure(&server_, config2),
+ EXPECT_THROW(configureDataSource(config2),
ConfigurableClientList::ConfigurationError);
result_ = execAuthServerCommand(server_, "loadzone",
Element::fromJSON("{\"origin\": \"example.com\"}"));
checkAnswer(1, "Unreadable");
+ DataSrcClientsMgr::Holder holder(server_.getDataSrcClientsMgr());
// The previous zone is not hurt in any way
- EXPECT_EQ(ZoneFinder::SUCCESS, server_.getClientList(RRClass::IN())->
+ EXPECT_EQ(ZoneFinder::SUCCESS,
+ holder.findClientList(RRClass::IN())->
find(Name("example.org")).finder_->
find(Name("example.org"), RRType::SOA())->code);
}
diff --git a/src/bin/auth/tests/datasrc_clients_builder_unittest.cc b/src/bin/auth/tests/datasrc_clients_builder_unittest.cc
new file mode 100644
index 0000000..0712ef7
--- /dev/null
+++ b/src/bin/auth/tests/datasrc_clients_builder_unittest.cc
@@ -0,0 +1,523 @@
+// 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 <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 <cstdlib>
+#include <string>
+#include <sstream>
+
+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> >),
+ builder(&command_queue, &cond, &queue_mutex, &clients_map, &map_mutex),
+ cond(command_queue, delayed_command_queue), rrclass(RRClass::IN()),
+ shutdown_cmd(SHUTDOWN, ConstElementPtr()),
+ noop_cmd(NOOP, ConstElementPtr())
+ {}
+
+ 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
+ TestDataSrcClientsBuilder builder;
+ TestCondVar cond;
+ TestMutex queue_mutex;
+ TestMutex map_mutex;
+ const RRClass rrclass;
+ const Command shutdown_cmd;
+ const Command noop_cmd;
+};
+
+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);
+}
+
+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());
+
+ // 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.second = 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.second = 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.second = 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.second = 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.second = 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.second = 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())),
+ 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\"}"));
+ EXPECT_TRUE(builder.handleCommand(loadzone_cmd));
+ EXPECT_EQ(1, map_mutex.lock_count); // we should have acquired the lock
+ EXPECT_EQ(1, map_mutex.unlock_count); // and released it.
+
+ 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");
+ 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\"}"));
+ 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\"}"));
+ 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.
+ const ConstElementPtr config2(Element::fromJSON("{"
+ "\"IN\": [{"
+ " \"type\": \"sqlite3\","
+ " \"params\": {\"database_file\": \"" + test_db + "\"},"
+ " \"cache-enable\": false,"
+ " \"cache-zones\": [\"example.org\"]"
+ "}]}"));
+ clients_map = configureDataSource(config2);
+ EXPECT_THROW(builder.handleCommand(
+ Command(LOADZONE, Element::fromJSON(
+ "{\"class\": \"IN\","
+ " \"origin\": \"example.org\"}"))),
+ 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\"}"))),
+ 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\"}"));
+ EXPECT_THROW(builder.handleCommand(loadzone_cmd),
+ TestDataSrcClientsBuilder::InternalCommandError);
+ zoneChecks(clients_map, rrclass); // zone shouldn't be replaced
+}
+
+TEST_F(DataSrcClientsBuilderTest, loadUnreadableZone) {
+ 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\"}"));
+ 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\"}"))),
+ 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()));
+ }, "");
+ }
+
+ // 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\"}"))),
+ InvalidRRClass);
+
+ // not a string
+ EXPECT_THROW(builder.handleCommand(
+ Command(LOADZONE,
+ Element::fromJSON(
+ "{\"origin\": \"test1.example\","
+ " \"class\": 1}"))),
+ 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(
+ "{\"origin\": \"test1.example\"}")));
+ }, "");
+ EXPECT_DEATH_IF_SUPPORTED({
+ builder.handleCommand(Command(LOADZONE,
+ Element::fromJSON(
+ "{\"class\": \"IN\"}")));
+ }, "");
+ }
+
+ // zone doesn't exist in the data source
+ EXPECT_THROW(
+ builder.handleCommand(
+ Command(LOADZONE,
+ Element::fromJSON(
+ "{\"class\": \"IN\", \"origin\": \"xx\"}"))),
+ TestDataSrcClientsBuilder::InternalCommandError);
+
+ // origin is bogus
+ EXPECT_THROW(builder.handleCommand(
+ Command(LOADZONE,
+ Element::fromJSON(
+ "{\"class\": \"IN\", \"origin\": \"...\"}"))),
+ EmptyLabel);
+ EXPECT_THROW(builder.handleCommand(
+ Command(LOADZONE,
+ Element::fromJSON(
+ "{\"origin\": 10, \"class\": 1}"))),
+ isc::data::TypeError);
+}
+
+} // unnamed namespace
diff --git a/src/bin/auth/tests/datasrc_clients_mgr_unittest.cc b/src/bin/auth/tests/datasrc_clients_mgr_unittest.cc
new file mode 100644
index 0000000..7d1eb4d
--- /dev/null
+++ b/src/bin/auth/tests/datasrc_clients_mgr_unittest.cc
@@ -0,0 +1,205 @@
+// 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.
+ EXPECT_EQ(1, 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.first);
+ EXPECT_FALSE(cmd.second); // 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.first);
+ EXPECT_EQ(reconfigure_arg, cmd1.second);
+
+ // 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.first);
+ EXPECT_EQ(reconfigure_arg, cmd2.second);
+
+ // 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()));
+ // 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()));
+ }
+ // 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()));
+ }
+
+ // 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, realThread) {
+ // Using the non-test definition with a real thread. Just checking
+ // no disruption happens.
+ DataSrcClientsMgr mgr;
+}
+
+} // unnamed namespace
diff --git a/src/bin/auth/tests/datasrc_config_unittest.cc b/src/bin/auth/tests/datasrc_config_unittest.cc
new file mode 100644
index 0000000..b555aa6
--- /dev/null
+++ b/src/bin/auth/tests/datasrc_config_unittest.cc
@@ -0,0 +1,299 @@
+// 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;
+using namespace boost;
+
+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 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(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.
+ 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());
+}
+
+}
diff --git a/src/bin/auth/tests/datasrc_configurator_unittest.cc b/src/bin/auth/tests/datasrc_configurator_unittest.cc
deleted file mode 100644
index 78e3688..0000000
--- a/src/bin/auth/tests/datasrc_configurator_unittest.cc
+++ /dev/null
@@ -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_configurator.h>
-
-#include <config/tests/fake_session.h>
-#include <config/ccsession.h>
-
-#include <gtest/gtest.h>
-#include <memory>
-#include <boost/shared_ptr.hpp>
-
-using namespace isc;
-using namespace isc::cc;
-using namespace isc::config;
-using namespace isc::data;
-using namespace isc::dns;
-using namespace std;
-using namespace boost;
-
-namespace {
-
-class DatasrcConfiguratorTest;
-
-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 shared_ptr<FakeList> ListPtr;
-
-// We use the test fixture as both parameters, this makes it possible
-// to easily fake all needed methods and look that they were called.
-typedef DataSourceConfiguratorGeneric<DatasrcConfiguratorTest,
- FakeList> Configurator;
-
-class DatasrcConfiguratorTest : public ::testing::Test {
-public:
- // These pretend to be the server
- ListPtr getClientList(const RRClass& rrclass) {
- log_ += "get " + rrclass.toText() + "\n";
- return (lists_[rrclass]);
- }
- void setClientList(const RRClass& rrclass, const ListPtr& list) {
- log_ += "set " + rrclass.toText() + " " +
- (list ? list->getConf() : "") + "\n";
- lists_[rrclass] = list;
- }
- vector<RRClass> getClientListClasses() const {
- vector<RRClass> result;
- for (std::map<RRClass, ListPtr>::const_iterator it(lists_.begin());
- it != lists_.end(); ++it) {
- result.push_back(it->first);
- }
- return (result);
- }
-protected:
- DatasrcConfiguratorTest() :
- 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.
- Configurator::cleanup();
- }
- void init(const ElementPtr& config = ElementPtr()) {
- session.getMessages()->
- add(createAnswer(0,
- moduleSpecFromFile(string(PLUGIN_DATA_PATH) +
- "/datasrc.spec").
- getFullSpec()));
- if (config) {
- session.getMessages()->add(createAnswer(0, config));
- } else {
- session.getMessages()->
- add(createAnswer(0, ElementPtr(new MapElement)));
- }
- Configurator::init(mccs.get(), this);
- }
- void SetUp() {
- init();
- }
- 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 ElementPtr
- config(buildConfig("{\"IN\": [{\"type\": \"xxx\"}]}"));
- session.addMessage(createCommand("config_update", config), "data_sources",
- "*");
- mccs->checkCommand();
- // Check it called the correct things (check that there's no IN yet and
- // set a new one.
- EXPECT_EQ("get IN\nset 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_;
-};
-
-// Check the initialization (and cleanup)
-TEST_F(DatasrcConfiguratorTest, initialization) {
- // It can't be initialized again
- EXPECT_THROW(init(), InvalidOperation);
- EXPECT_TRUE(session.haveSubscription("data_sources", "*"));
- // Deinitialize to make the tests reasonable
- Configurator::cleanup();
- EXPECT_FALSE(session.haveSubscription("data_sources", "*"));
- // We can't reconfigure now (not even manually)
- EXPECT_THROW(Configurator::reconfigure(ElementPtr(new MapElement())),
- InvalidOperation);
- // If one of them is NULL, it does not work
- EXPECT_THROW(Configurator::init(NULL, this), InvalidParameter);
- EXPECT_FALSE(session.haveSubscription("data_sources", "*"));
- EXPECT_THROW(Configurator::init(mccs.get(), NULL), InvalidParameter);
- EXPECT_FALSE(session.haveSubscription("data_sources", "*"));
- // But we can initialize it again now
- EXPECT_NO_THROW(init());
- EXPECT_TRUE(session.haveSubscription("data_sources", "*"));
-}
-
-// Push there a configuration with a single list.
-TEST_F(DatasrcConfiguratorTest, createList) {
- initializeINList();
-}
-
-TEST_F(DatasrcConfiguratorTest, modifyList) {
- // First, initialize the list
- initializeINList();
- // 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();
- // This one does not set
- EXPECT_EQ("get IN\n", log_);
- // But this should contain the yyy configuration
- EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
- EXPECT_EQ(1, lists_.size());
-}
-
-// Check we can have multiple lists at once
-TEST_F(DatasrcConfiguratorTest, 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("get CH\nset CH xxx\nget IN\nset IN yyy\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(DatasrcConfiguratorTest, updateAdd) {
- initializeINList();
- const ElementPtr
- config(buildConfig("{\"IN\": [{\"type\": \"yyy\"}], "
- "\"CH\": [{\"type\": \"xxx\"}]}"));
- session.addMessage(createCommand("config_update", config), "data_sources",
- "*");
- log_ = "";
- mccs->checkCommand();
- // The CH is set, IN not
- EXPECT_EQ("get CH\nset CH xxx\nget IN\n", log_);
- // But this should contain the yyy configuration
- 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(DatasrcConfiguratorTest, updateDelete) {
- initializeINList();
- const ElementPtr
- config(buildConfig("{}"));
- session.addMessage(createCommand("config_update", config), "data_sources",
- "*");
- log_ = "";
- mccs->checkCommand();
- EXPECT_EQ("get IN\nset IN \n", log_);
- EXPECT_FALSE(lists_[RRClass::IN()]);
- // In real auth server, the NULL one would be removed. However, we just
- // store it, so the IN bucket is still in there. This checks there's nothing
- // else.
- EXPECT_EQ(1, lists_.size());
-}
-
-// Check that we can rollback an addition if something else fails
-TEST_F(DatasrcConfiguratorTest, rollbackAddition) {
- initializeINList();
- // The configuration is wrong. However, the CH one will get done 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()]);
-}
-
-// Check that we can rollback a deletion if something else fails
-TEST_F(DatasrcConfiguratorTest, rollbackDeletion) {
- initializeINList();
- // Put the CH there
- const ElementPtr
- config1(Element::fromJSON("{\"IN\": [{\"type\": \"yyy\"}], "
- "\"CH\": [{\"type\": \"xxx\"}]}"));
- Configurator::reconfigure(config1);
- const ElementPtr
- config2(Element::fromJSON("{\"IN\": [{\"type\": 13}]}"));
- // This would delete CH. However, the IN one fails.
- // As the deletions happen after the additions/settings
- // and there's no known way to cause an exception during the
- // deletions, it is not a true rollback, but the result should
- // be the same.
- EXPECT_THROW(Configurator::reconfigure(config2), TypeError);
- EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
- EXPECT_EQ("xxx", lists_[RRClass::CH()]->getConf());
-}
-
-// Check that we can roll back configuration change if something
-// fails later on.
-TEST_F(DatasrcConfiguratorTest, rollbackConfiguration) {
- initializeINList();
- // Put the CH there
- const ElementPtr
- config1(Element::fromJSON("{\"IN\": [{\"type\": \"yyy\"}], "
- "\"CH\": [{\"type\": \"xxx\"}]}"));
- Configurator::reconfigure(config1);
- // Now, the CH happens first. But nevertheless, it should be
- // restored to the previoeus version.
- const ElementPtr
- config2(Element::fromJSON("{\"IN\": [{\"type\": 13}], "
- "\"CH\": [{\"type\": \"yyy\"}]}"));
- EXPECT_THROW(Configurator::reconfigure(config2), TypeError);
- EXPECT_EQ("yyy", lists_[RRClass::IN()]->getConf());
- EXPECT_EQ("xxx", lists_[RRClass::CH()]->getConf());
-}
-
-}
diff --git a/src/bin/auth/tests/datasrc_util.h b/src/bin/auth/tests/datasrc_util.h
index 07ebc0c..9748332 100644
--- a/src/bin/auth/tests/datasrc_util.h
+++ b/src/bin/auth/tests/datasrc_util.h
@@ -12,8 +12,8 @@
// 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
+#ifndef AUTH_DATA_SOURCE_UTIL_H
+#define AUTH_DATA_SOURCE_UTIL_H 1
#include <dns/name.h>
#include <dns/rrclass.h>
@@ -51,7 +51,7 @@ createSQLite3DB(dns::RRClass zclass, const dns::Name& zname,
} // end of auth
} // end of isc
-#endif // __AUTH_DATA_SOURCE_UTIL_H
+#endif // AUTH_DATA_SOURCE_UTIL_H
// Local Variables:
// mode: c++
diff --git a/src/bin/auth/tests/query_unittest.cc b/src/bin/auth/tests/query_unittest.cc
index 603bf5c..84b7f8a 100644
--- a/src/bin/auth/tests/query_unittest.cc
+++ b/src/bin/auth/tests/query_unittest.cc
@@ -442,10 +442,9 @@ public:
ConstRRsetPtr rrset)
{
nsec_name_ = nsec_name;
- nsec_context_.reset(new Context(*this,
- FIND_DEFAULT, // a fake value
- ResultContext(code, rrset,
- RESULT_NSEC_SIGNED)));
+ nsec_context_.reset(
+ new GenericContext(*this, FIND_DEFAULT, // a fake value
+ ResultContext(code, rrset, RESULT_NSEC_SIGNED)));
}
// Once called, the findNSEC3 will return the provided result for the next
@@ -487,8 +486,8 @@ protected:
{
ConstRRsetPtr rp = stripRRsigs(rrset, options);
return (ZoneFinderContextPtr(
- new Context(*this, options,
- ResultContext(code, rp, flags))));
+ new GenericContext(*this, options,
+ ResultContext(code, rp, flags))));
}
private:
@@ -604,9 +603,9 @@ MockZoneFinder::findAll(const Name& name, std::vector<ConstRRsetPtr>& target,
target.push_back(stripRRsigs(found_rrset->second, options));
}
return (ZoneFinderContextPtr(
- new Context(*this, options,
- ResultContext(SUCCESS, RRsetPtr()),
- target)));
+ new GenericContext(*this, options,
+ ResultContext(SUCCESS, RRsetPtr()),
+ target)));
}
}
diff --git a/src/bin/auth/tests/test_datasrc_clients_mgr.cc b/src/bin/auth/tests/test_datasrc_clients_mgr.cc
new file mode 100644
index 0000000..82937c0
--- /dev/null
+++ b/src/bin/auth/tests/test_datasrc_clients_mgr.cc
@@ -0,0 +1,95 @@
+// 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<Command> FakeDataSrcClientsBuilder::command_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;
+
+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
+TestDataSrcClientsMgr::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;
+}
+
+template<>
+void
+TestDataSrcClientsMgr::reconfigureHook() {
+ using namespace datasrc_clientmgr_internal;
+
+ // Simply replace the local map, ignoring bogus config value.
+ assert(command_queue_.front().first == RECONFIGURE);
+ try {
+ clients_map_ = configureDataSource(command_queue_.front().second);
+ } catch (...) {}
+}
+
+} // namespace auth
+} // namespace isc
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/bin/auth/tests/test_datasrc_clients_mgr.h b/src/bin/auth/tests/test_datasrc_clients_mgr.h
new file mode 100644
index 0000000..9b1a367
--- /dev/null
+++ b/src/bin/auth/tests/test_datasrc_clients_mgr.h
@@ -0,0 +1,223 @@
+// 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 <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 three 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 TestCondVar* cond;
+ static TestMutex* queue_mutex;
+ static isc::datasrc::ClientListMapPtr* clients_map;
+ static TestMutex* map_mutex;
+ static std::list<Command> command_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,
+ TestCondVar* cond,
+ TestMutex* queue_mutex,
+ isc::datasrc::ClientListMapPtr* clients_map,
+ TestMutex* map_mutex)
+ {
+ FakeDataSrcClientsBuilder::started = false;
+ FakeDataSrcClientsBuilder::command_queue = command_queue;
+ FakeDataSrcClientsBuilder::cond = cond;
+ FakeDataSrcClientsBuilder::queue_mutex = queue_mutex;
+ 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> TestDataSrcClientsMgr;
+
+// 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
+TestDataSrcClientsMgr::cleanup();
+
+template<>
+void
+TestDataSrcClientsMgr::reconfigureHook();
+} // namespace auth
+} // namespace isc
+
+#endif // TEST_DATASRC_CLIENTS_MGR_H
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/bin/bind10/bind10_messages.mes b/src/bin/bind10/bind10_messages.mes
index c751583..ed2a5d9 100644
--- a/src/bin/bind10/bind10_messages.mes
+++ b/src/bin/bind10/bind10_messages.mes
@@ -141,6 +141,16 @@ it now. The new configuration is printed.
% BIND10_RECEIVED_SIGNAL received signal %1
The boss module received the given signal.
+% BIND10_RESTART_COMPONENT_SKIPPED Skipped restarting a component %1
+The boss module tried to restart a component after it failed (crashed)
+unexpectedly, but the boss then found that the component had been removed
+from its local configuration of components to run. This is an unusal
+situation but can happen if the administrator removes the component from
+the configuration after the component's crash and before the restart time.
+The boss module simply skipped restarting that module, and the whole system
+went back to the expected state (except that the crash itself is likely
+to be a bug).
+
% BIND10_RESURRECTED_PROCESS resurrected %1 (PID %2)
The given process has been restarted successfully, and is now running
with the given process id.
@@ -157,6 +167,30 @@ so BIND 10 will now shut down. The specific error is printed.
% BIND10_SEND_SIGKILL sending SIGKILL to %1 (PID %2)
The boss module is sending a SIGKILL signal to the given process.
+% BIND10_SEND_SIGNAL_FAIL sending %1 to %2 (PID %3) failed: %4
+The boss module sent a single (either SIGTERM or SIGKILL) to a process,
+but it failed due to some system level error. There are two major cases:
+the target process has already terminated but the boss module had sent
+the signal before it noticed the termination. In this case an error
+message should indicate something like "no such process". This can be
+safely ignored. The other case is that the boss module doesn't have
+the privilege to send a signal to the process. It can typically
+happen when the boss module started as a privileged process, spawned a
+subprocess, and then dropped the privilege. It includes the case for
+the socket creator when the boss process runs with the -u command line
+option. In this case, the boss module simply gives up to terminate
+the process explicitly because it's unlikely to succeed by keeping
+sending the signal. Although the socket creator is implemented so
+that it will terminate automatically when the boss process exits
+(and that should be the case for any other future process running with
+a higher privilege), but it's recommended to check if there's any
+remaining BIND 10 process if this message is logged. For all other
+cases, the boss module will keep sending the signal until it confirms
+all child processes terminate. Although unlikely, this could prevent
+the boss module from exiting, just keeping sending the signals. So,
+again, it's advisable to check if it really terminates when this
+message is logged.
+
% BIND10_SEND_SIGTERM sending SIGTERM to %1 (PID %2)
The boss module is sending a SIGTERM signal to the given process.
@@ -264,13 +298,6 @@ During the startup process, a number of messages are exchanged between the
Boss process and the processes it starts. This error is output when a
message received by the Boss process is not recognised.
-% BIND10_START_AS_NON_ROOT_AUTH starting b10-auth as a user, not root. This might fail.
-The authoritative server is being started or restarted without root privileges.
-If the module needs these privileges, it may have problems starting.
-Note that this issue should be resolved by the pending 'socket-creator'
-process; once that has been implemented, modules should not need root
-privileges anymore. See tickets #800 and #801 for more information.
-
% BIND10_START_AS_NON_ROOT_RESOLVER starting b10-resolver as a user, not root. This might fail.
The resolver is being started or restarted without root privileges.
If the module needs these privileges, it may have problems starting.
diff --git a/src/bin/bind10/bind10_src.py.in b/src/bin/bind10/bind10_src.py.in
index bb2edaf..45a2ccb 100755
--- a/src/bin/bind10/bind10_src.py.in
+++ b/src/bin/bind10/bind10_src.py.in
@@ -546,8 +546,6 @@ class BoB:
"""
Start the Authoritative server
"""
- if self.uid is not None and self.__started:
- logger.warn(BIND10_START_AS_NON_ROOT_AUTH)
authargs = ['b10-auth']
if self.verbose:
authargs += ['-v']
@@ -693,32 +691,42 @@ class BoB:
# from doing so
if not self.nokill:
# next try sending a SIGTERM
- components_to_stop = list(self.components.values())
- for component in components_to_stop:
- logger.info(BIND10_SEND_SIGTERM, component.name(), component.pid())
- try:
- component.kill()
- except OSError:
- # ignore these (usually ESRCH because the child
- # finally exited)
- pass
- # finally, send SIGKILL (unmaskable termination) until everybody dies
+ self.__kill_children(False)
+ # finally, send SIGKILL (unmaskable termination) until everybody
+ # dies
while self.components:
# XXX: some delay probably useful... how much is uncertain
time.sleep(0.1)
self.reap_children()
- components_to_stop = list(self.components.values())
- for component in components_to_stop:
- logger.info(BIND10_SEND_SIGKILL, component.name(),
- component.pid())
- try:
- component.kill(True)
- except OSError:
- # ignore these (usually ESRCH because the child
- # finally exited)
- pass
+ self.__kill_children(True)
logger.info(BIND10_SHUTDOWN_COMPLETE)
+ def __kill_children(self, forceful):
+ '''Terminate remaining subprocesses by sending a signal.
+
+ The forceful paramter will be passed Component.kill().
+ This is a dedicated subroutine of shutdown(), just to unify two
+ similar cases.
+
+ '''
+ logmsg = BIND10_SEND_SIGKILL if forceful else BIND10_SEND_SIGTERM
+ # We need to make a copy of values as the components may be modified
+ # in the loop.
+ for component in list(self.components.values()):
+ logger.info(logmsg, component.name(), component.pid())
+ try:
+ component.kill(forceful)
+ except OSError as ex:
+ # If kill() failed due to EPERM, it doesn't make sense to
+ # keep trying, so we just log the fact and forget that
+ # component. Ignore other OSErrors (usually ESRCH because
+ # the child finally exited)
+ signame = "SIGKILL" if forceful else "SIGTERM"
+ logger.info(BIND10_SEND_SIGNAL_FAIL, signame,
+ component.name(), component.pid(), ex)
+ if ex.errno == errno.EPERM:
+ del self.components[component.pid()]
+
def _get_process_exit_status(self):
return os.waitpid(-1, os.WNOHANG)
@@ -739,7 +747,7 @@ class BoB:
component = self.components.pop(pid)
logger.info(BIND10_PROCESS_ENDED, component.name(), pid,
exit_status)
- if component.running() and self.runnable:
+ if component.is_running() and self.runnable:
# Tell it it failed. But only if it matters (we are
# not shutting down and the component considers itself
# to be running.
@@ -771,7 +779,12 @@ class BoB:
next_restart_time = None
now = time.time()
for component in self.components_to_restart:
- if not component.restart(now):
+ # If the component was removed from the configurator between since
+ # scheduled to restart, just ignore it. The object will just be
+ # dropped here.
+ if not self._component_configurator.has_component(component):
+ logger.info(BIND10_RESTART_COMPONENT_SKIPPED, component.name())
+ elif not component.restart(now):
still_dead.append(component)
if next_restart_time is None or\
next_restart_time > component.get_restart_time():
diff --git a/src/bin/bind10/tests/bind10_test.py.in b/src/bin/bind10/tests/bind10_test.py.in
index 9a40e42..ece6370 100644
--- a/src/bin/bind10/tests/bind10_test.py.in
+++ b/src/bin/bind10/tests/bind10_test.py.in
@@ -929,7 +929,14 @@ class MockComponent:
self.name = lambda: name
self.pid = lambda: pid
self.address = lambda: address
+ self.restarted = False
+ def get_restart_time(self):
+ return 0 # arbitrary dummy value
+
+ def restart(self, now):
+ self.restarted = True
+ return True
class TestBossCmd(unittest.TestCase):
def test_ping(self):
@@ -1174,7 +1181,7 @@ class TestBossComponents(unittest.TestCase):
# We check somewhere else that the shutdown is actually called
# from there (the test_kills).
- def __real_test_kill(self, nokill = False):
+ def __real_test_kill(self, nokill=False, ex_on_kill=None):
"""
Helper function that does the actual kill functionality testing.
"""
@@ -1188,8 +1195,23 @@ class TestBossComponents(unittest.TestCase):
(anyway it is not told so). It does not die if it is killed
the first time. It dies only when killed forcefully.
"""
+ def __init__(self):
+ # number of kill() calls, preventing infinite loop.
+ self.__call_count = 0
+
def kill(self, forceful=False):
+ self.__call_count += 1
+ if self.__call_count > 2:
+ raise Exception('Too many calls to ImmortalComponent.kill')
+
killed.append(forceful)
+ if ex_on_kill is not None:
+ # If exception is given by the test, raise it here.
+ # In the case of ESRCH, the process should have gone
+ # somehow, so we clear the components.
+ if ex_on_kill.errno == errno.ESRCH:
+ bob.components = {}
+ raise ex_on_kill
if forceful:
bob.components = {}
def pid(self):
@@ -1217,7 +1239,10 @@ class TestBossComponents(unittest.TestCase):
if nokill:
self.assertEqual([], killed)
else:
- self.assertEqual([False, True], killed)
+ if ex_on_kill is not None:
+ self.assertEqual([False], killed)
+ else:
+ self.assertEqual([False, True], killed)
self.assertTrue(self.__called)
@@ -1229,6 +1254,20 @@ class TestBossComponents(unittest.TestCase):
"""
self.__real_test_kill()
+ def test_kill_fail(self):
+ """Test cases where kill() results in an exception due to OS error.
+
+ The behavior should be different for EPERM, so we test two cases.
+
+ """
+
+ ex = OSError()
+ ex.errno, ex.strerror = errno.ESRCH, 'No such process'
+ self.__real_test_kill(ex_on_kill=ex)
+
+ ex.errno, ex.strerror = errno.EPERM, 'Operation not permitted'
+ self.__real_test_kill(ex_on_kill=ex)
+
def test_nokill(self):
"""
Test that the boss *doesn't* kill components which don't want to
@@ -1266,6 +1305,34 @@ class TestBossComponents(unittest.TestCase):
bob.start_all_components()
self.__check_extended(self.__param)
+ def __setup_restart(self, bob, component):
+ '''Common procedure for restarting a component used below.'''
+ bob.components_to_restart = { component }
+ component.restarted = False
+ bob.restart_processes()
+
+ def test_restart_processes(self):
+ '''Check some behavior on restarting processes.'''
+ bob = MockBob()
+ bob.runnable = True
+ component = MockComponent('test', 53)
+
+ # A component to be restarted will actually be restarted iff it's
+ # in the configurator's configuration.
+ # We bruteforce the configurator internal below; ugly, but the easiest
+ # way for the test.
+ bob._component_configurator._components['test'] = (None, component)
+ self.__setup_restart(bob, component)
+ self.assertTrue(component.restarted)
+ self.assertFalse(component in bob.components_to_restart)
+
+ # Remove the component from the configuration. It won't be restarted
+ # even if scheduled, nor will remain in the to-be-restarted list.
+ del bob._component_configurator._components['test']
+ self.__setup_restart(bob, component)
+ self.assertFalse(component.restarted)
+ self.assertFalse(component in bob.components_to_restart)
+
class SocketSrvTest(unittest.TestCase):
"""
This tests some methods of boss related to the unix domain sockets used
diff --git a/src/bin/bindctl/bindcmd.py b/src/bin/bindctl/bindcmd.py
index f1a622e..b4e71bf 100644
--- a/src/bin/bindctl/bindcmd.py
+++ b/src/bin/bindctl/bindcmd.py
@@ -22,7 +22,7 @@ import sys
from cmd import Cmd
from bindctl.exception import *
from bindctl.moduleinfo import *
-from bindctl.cmdparse import BindCmdParse
+from bindctl.cmdparse import BindCmdParser
from bindctl import command_sets
from xml.dom import minidom
import isc
@@ -48,20 +48,21 @@ except ImportError:
# if we have readline support, use that, otherwise use normal stdio
try:
import readline
- # This is a fix for the problem described in
- # http://bind10.isc.org/ticket/1345
- # If '-' is seen as a word-boundary, the final completion-step
- # (as handled by the cmd module, and hence outside our reach) can
- # mistakenly add data twice, resulting in wrong completion results
- # The solution is to remove it.
- delims = readline.get_completer_delims()
- delims = delims.replace('-', '')
- readline.set_completer_delims(delims)
+ # Only consider spaces as word boundaries; identifiers can contain
+ # '/' and '[]', and configuration item names can in theory use any
+ # printable character. See the discussion in tickets #1345 and
+ # #2254 for more information.
+ readline.set_completer_delims(' ')
my_readline = readline.get_line_buffer
except ImportError:
my_readline = sys.stdin.readline
+# Used for tab-completion of 'identifiers' (i.e. config values)
+# If a command parameter has this name, the tab completion hints
+# are derived from config data
+CFGITEM_IDENTIFIER_PARAM = 'identifier'
+
CSV_FILE_NAME = 'default_user.csv'
CONFIG_MODULE_NAME = 'config'
CONST_BINDCTL_HELP = """
@@ -463,41 +464,101 @@ class BindCmdInterpreter(Cmd):
Cmd.onecmd(self, line)
- def remove_prefix(self, list, prefix):
- """Removes the prefix already entered, and all elements from the
- list that don't match it"""
- if prefix.startswith('/'):
- prefix = prefix[1:]
-
- new_list = []
- for val in list:
- if val.startswith(prefix):
- new_val = val[len(prefix):]
- if new_val.startswith("/"):
- new_val = new_val[1:]
- new_list.append(new_val)
- return new_list
+ def _get_identifier_startswith(self, id_text):
+ """Return the tab-completion hints for identifiers starting with
+ id_text.
+
+ Parameters:
+ id_text (string): the currently entered identifier part, which
+ is to be completed.
+ """
+ # Strip starting "/" from id_text
+ if id_text.startswith('/'):
+ id_text = id_text[1:]
+ # Get all items from the given module (up to the first /)
+ list = self.config_data.get_config_item_list(
+ id_text.rpartition("/")[0], recurse=True)
+ # filter out all possibilities that don't match currently entered
+ # text part
+ hints = [val for val in list if val.startswith(id_text)]
+ return hints
+
+ def _cmd_has_identifier_param(self, cmd):
+ """
+ Returns True if the given (parsed) command is known and has a
+ parameter which points to a config data identifier
+
+ Parameters:
+ cmd (cmdparse.BindCmdParser): command context, including given params
+
+ """
+ if cmd.module not in self.modules:
+ return False
+ command = self.modules[cmd.module].get_command_with_name(cmd.command)
+ return command.has_param_with_name(CFGITEM_IDENTIFIER_PARAM)
def complete(self, text, state):
- if 0 == state:
+ """
+ Returns tab-completion hints. See the python documentation of the
+ readline and Cmd modules for more information.
+
+ The first time this is called (within one 'completer' action), it
+ has state 0, and a list of possible completions is made. This list
+ is stored; complete() will then be called with increasing values of
+ state, until it returns None. For each call it returns the state'th
+ element of the hints it collected in the first call.
+
+ The hints list contents depend on which part of the full command
+ line; if no module is given yet, it will list all modules. If a
+ module is given, but no command, it will complete with module
+ commands. If both have been given, it will create the hints based on
+ the command parameters.
+
+ If module and command have already been specified, and the command
+ has a parameter 'identifier', the configuration data is used to
+ create the hints list.
+
+ Parameters:
+ text (string): The text entered so far in the 'current' part of
+ the command (module, command, parameters)
+ state (int): state used in the readline tab-completion logic;
+ 0 on first call, increasing by one until there are
+ no (more) hints to return.
+
+ Returns the string value of the hints list with index 'state',
+ or None if no (more) hints are available.
+ """
+ if state == 0:
self._update_all_modules_info()
text = text.strip()
hints = []
cur_line = my_readline()
try:
- cmd = BindCmdParse(cur_line)
+ cmd = BindCmdParser(cur_line)
if not cmd.params and text:
hints = self._get_command_startswith(cmd.module, text)
+ elif self._cmd_has_identifier_param(cmd):
+ # If the command has an argument that is a configuration
+ # identifier (currently, this is only a subset of
+ # the config commands), then don't tab-complete with
+ # hints derived from command parameters, but from
+ # possible configuration identifiers.
+ #
+ # This solves the issue reported in #2254, where
+ # there were hints such as 'argument' and 'identifier'.
+ #
+ # Since they are replaced, the tab-completion no longer
+ # adds 'help' as an option (but it still works)
+ #
+ # Also, currently, tab-completion does not work
+ # together with 'config go' (it does not take 'current
+ # position' into account). But config go currently has
+ # problems by itself, unrelated to completion.
+ hints = self._get_identifier_startswith(text)
else:
hints = self._get_param_startswith(cmd.module, cmd.command,
text)
- if cmd.module == CONFIG_MODULE_NAME:
- # grm text has been stripped of slashes...
- my_text = self.location + "/" + cur_line.rpartition(" ")[2]
- list = self.config_data.get_config_item_list(my_text.rpartition("/")[0], True)
- hints.extend([val for val in list if val.startswith(my_text[1:])])
- # remove the common prefix from the hints so we don't get it twice
- hints = self.remove_prefix(hints, my_text.rpartition("/")[0])
+
except CmdModuleNameFormatError:
if not text:
hints = self.get_module_names()
@@ -562,7 +623,7 @@ class BindCmdInterpreter(Cmd):
def _parse_cmd(self, line):
try:
- cmd = BindCmdParse(line)
+ cmd = BindCmdParser(line)
self._validate_cmd(cmd)
self._handle_cmd(cmd)
except (IOError, http.client.HTTPException) as err:
@@ -794,7 +855,7 @@ class BindCmdInterpreter(Cmd):
else:
print("Warning: ignoring unknown directive: " + line)
else:
- cmd = BindCmdParse(line)
+ cmd = BindCmdParser(line)
self._validate_cmd(cmd)
self._handle_cmd(cmd)
except (isc.config.ModuleCCSessionError,
diff --git a/src/bin/bindctl/bindctl_main.py.in b/src/bin/bindctl/bindctl_main.py.in
index 1685355..546ecc0 100755
--- a/src/bin/bindctl/bindctl_main.py.in
+++ b/src/bin/bindctl/bindctl_main.py.in
@@ -42,16 +42,19 @@ def prepare_config_commands(tool):
cmd = CommandInfo(name = "show", desc = "Show configuration.")
param = ParamInfo(name = "argument", type = "string", optional=True, desc = "If you specify the argument 'all' (before the identifier), recursively show all child elements for the given identifier.")
cmd.add_param(param)
- param = ParamInfo(name = "identifier", type = "string", optional=True, desc = DEFAULT_IDENTIFIER_DESC)
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=True, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
module.add_command(cmd)
- cmd = CommandInfo(name = "show_json", desc = "Show full configuration in JSON format.")
- param = ParamInfo(name = "identifier", type = "string", optional=True, desc = DEFAULT_IDENTIFIER_DESC)
+ cmd = CommandInfo(name="show_json",
+ desc="Show full configuration in JSON format.")
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=True, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
module.add_command(cmd)
- cmd = CommandInfo(name = "add", desc =
+ cmd = CommandInfo(name="add", desc=
"Add an entry to configuration list or a named set. "
"When adding to a list, the command has one optional argument, "
"a value to add to the list. The value must be in correct JSON "
@@ -60,45 +63,53 @@ def prepare_config_commands(tool):
"parameter value, similar to when adding to a list. "
"In either case, when no value is given, an entry will be "
"constructed with default values.")
- param = ParamInfo(name = "identifier", type = "string", optional=True, desc = DEFAULT_IDENTIFIER_DESC)
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=True, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
- param = ParamInfo(name = "value_or_name", type = "string", optional=True, desc = "Specifies a value to add to the list, or the name when adding to a named set. It must be in correct JSON format and complete.")
+ param = ParamInfo(name="value_or_name", type="string", optional=True,
+ desc="Specifies a value to add to the list, or the name when adding to a named set. It must be in correct JSON format and complete.")
cmd.add_param(param)
module.add_command(cmd)
- param = ParamInfo(name = "value_for_set", type = "string", optional=True, desc = "Specifies an optional value to add to the named map. It must be in correct JSON format and complete.")
+ param = ParamInfo(name="value_for_set", type="string", optional=True,
+ desc="Specifies an optional value to add to the named map. It must be in correct JSON format and complete.")
cmd.add_param(param)
module.add_command(cmd)
- cmd = CommandInfo(name = "remove", desc = "Remove entry from configuration list or named set.")
- param = ParamInfo(name = "identifier", type = "string", optional=True, desc = DEFAULT_IDENTIFIER_DESC)
+ cmd = CommandInfo(name="remove", desc="Remove entry from configuration list or named set.")
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=True, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
param = ParamInfo(name = "value", type = "string", optional=True, desc = "When identifier is a list, specifies a value to remove from the list. It must be in correct JSON format and complete. When it is a named set, specifies the name to remove.")
cmd.add_param(param)
module.add_command(cmd)
- cmd = CommandInfo(name = "set", desc = "Set a configuration value.")
- param = ParamInfo(name = "identifier", type = "string", optional=True, desc = DEFAULT_IDENTIFIER_DESC)
+ cmd = CommandInfo(name="set", desc="Set a configuration value.")
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=True, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
- param = ParamInfo(name = "value", type = "string", optional=False, desc = "Specifies a value to set. It must be in correct JSON format and complete.")
+ param = ParamInfo(name="value", type="string", optional=False,
+ desc="Specifies a value to set. It must be in correct JSON format and complete.")
cmd.add_param(param)
module.add_command(cmd)
- cmd = CommandInfo(name = "unset", desc = "Unset a configuration value (i.e. revert to the default, if any).")
- param = ParamInfo(name = "identifier", type = "string", optional=False, desc = DEFAULT_IDENTIFIER_DESC)
+ cmd = CommandInfo(name="unset", desc="Unset a configuration value (i.e. revert to the default, if any).")
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=False, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
module.add_command(cmd)
- cmd = CommandInfo(name = "diff", desc = "Show all local changes that have not been committed.")
+ cmd = CommandInfo(name="diff", desc="Show all local changes that have not been committed.")
module.add_command(cmd)
- cmd = CommandInfo(name = "revert", desc = "Revert all local changes.")
+ cmd = CommandInfo(name="revert", desc="Revert all local changes.")
module.add_command(cmd)
- cmd = CommandInfo(name = "commit", desc = "Commit all local changes.")
+ cmd = CommandInfo(name="commit", desc="Commit all local changes.")
module.add_command(cmd)
- cmd = CommandInfo(name = "go", desc = "Go to a specific configuration part.")
- param = ParamInfo(name = "identifier", type="string", optional=False, desc = DEFAULT_IDENTIFIER_DESC)
+ cmd = CommandInfo(name="go", desc="Go to a specific configuration part.")
+ param = ParamInfo(name=CFGITEM_IDENTIFIER_PARAM, type="string",
+ optional=False, desc=DEFAULT_IDENTIFIER_DESC)
cmd.add_param(param)
module.add_command(cmd)
diff --git a/src/bin/bindctl/cmdparse.py b/src/bin/bindctl/cmdparse.py
index c624cba..30909a3 100644
--- a/src/bin/bindctl/cmdparse.py
+++ b/src/bin/bindctl/cmdparse.py
@@ -25,7 +25,7 @@ except ImportError:
param_name_str = "^\s*(?P<param_name>[\w]+)\s*=\s*"
-# The value string can be a sequence without space or comma
+# The value string can be a sequence without space or comma
# characters, or a string surroundedby quotation marks(such marks
# can be part of string in an escaped form)
#param_value_str = "(?P<param_value>[\"\'].+?(?<!\\\)[\"\']|[^\'\"][^, ]+)"
@@ -34,8 +34,8 @@ param_value_with_quota_str = "[\"\'](?P<param_value>.+?)(?<!\\\)[\"\']"
next_params_str = "(?P<blank>\s*)(?P<comma>,?)(?P<next_params>.*)$"
-PARAM_WITH_QUOTA_PATTERN = re.compile(param_name_str +
- param_value_with_quota_str +
+PARAM_WITH_QUOTA_PATTERN = re.compile(param_name_str +
+ param_value_with_quota_str +
next_params_str)
PARAM_PATTERN = re.compile(param_name_str + param_value_str + next_params_str)
# Used for module and command name
@@ -83,52 +83,52 @@ def _remove_list_and_map_whitespace(text):
if map_count == 0:
result.append(_remove_unquoted_whitespace(text[cur_start_map_pos:pos + 1]))
start_pos = pos + 1
-
+
pos = pos + 1
if start_pos <= len(text):
result.append(text[start_pos:len(text)])
return "".join(result)
-
-
-class BindCmdParse:
+
+
+class BindCmdParser:
""" This class will parse the command line user input into three parts:
module name, command, parameters
- the first two parts are strings and parameter is one hash,
+ the first two parts are strings and parameter is one hash,
parameters part is optional
-
- Example: zone reload, zone_name=example.com
+
+ Example: zone reload, zone_name=example.com
module == zone
command == reload
params == [zone_name = 'example.com']
"""
-
+
def __init__(self, cmd):
self.params = OrderedDict()
self.module = ''
self.command = ''
self._parse_cmd(cmd)
- def _parse_cmd(self, text_str):
+ def _parse_cmd(self, text_str):
'''Parse command line. '''
# Get module name
groups = NAME_PATTERN.match(text_str)
if not groups:
raise CmdModuleNameFormatError
-
+
self.module = groups.group('name')
cmd_str = groups.group('others')
if cmd_str:
if not groups.group('blank'):
raise CmdModuleNameFormatError
- else:
+ else:
raise CmdMissCommandNameFormatError(self.module)
-
+
# Get command name
groups = NAME_PATTERN.match(cmd_str)
if (not groups):
raise CmdCommandNameFormatError(self.module)
-
+
self.command = groups.group('name')
param_str = groups.group('others')
if param_str:
@@ -143,7 +143,7 @@ class BindCmdParse:
def _parse_params(self, param_text):
"""convert a=b,c=d into one hash """
param_text = _remove_list_and_map_whitespace(param_text)
-
+
# Check parameter name "help"
param = NAME_PATTERN.match(param_text)
if param and param.group('name') == "help":
@@ -153,7 +153,7 @@ class BindCmdParse:
while True:
if not param_text.strip():
break
-
+
groups = PARAM_PATTERN.match(param_text) or \
PARAM_WITH_QUOTA_PATTERN.match(param_text)
if not groups:
diff --git a/src/bin/bindctl/tests/bindctl_test.py b/src/bin/bindctl/tests/bindctl_test.py
index bcfb6c5..f598472 100644
--- a/src/bin/bindctl/tests/bindctl_test.py
+++ b/src/bin/bindctl/tests/bindctl_test.py
@@ -40,14 +40,14 @@ except ImportError:
class TestCmdLex(unittest.TestCase):
def my_assert_raise(self, exception_type, cmd_line):
- self.assertRaises(exception_type, cmdparse.BindCmdParse, cmd_line)
+ self.assertRaises(exception_type, cmdparse.BindCmdParser, cmd_line)
def testCommandWithoutParameter(self):
- cmd = cmdparse.BindCmdParse("zone add")
- assert cmd.module == "zone"
- assert cmd.command == "add"
- self.assertEqual(len(cmd.params), 0)
+ cmd_parser = cmdparse.BindCmdParser("zone add")
+ assert cmd_parser.module == "zone"
+ assert cmd_parser.command == "add"
+ self.assertEqual(len(cmd_parser.params), 0)
def testCommandWithParameters(self):
@@ -56,45 +56,51 @@ class TestCmdLex(unittest.TestCase):
"zone add zone_name = 'cnnic.cn\", file ='cnnic.cn.file' master=1.1.1.1, " }
for cmd_line in lines:
- cmd = cmdparse.BindCmdParse(cmd_line)
- assert cmd.module == "zone"
- assert cmd.command == "add"
- assert cmd.params["zone_name"] == "cnnic.cn"
- assert cmd.params["file"] == "cnnic.cn.file"
- assert cmd.params["master"] == '1.1.1.1'
+ cmd_parser = cmdparse.BindCmdParser(cmd_line)
+ assert cmd_parser.module == "zone"
+ assert cmd_parser.command == "add"
+ assert cmd_parser.params["zone_name"] == "cnnic.cn"
+ assert cmd_parser.params["file"] == "cnnic.cn.file"
+ assert cmd_parser.params["master"] == '1.1.1.1'
def testCommandWithParamters_2(self):
'''Test whether the parameters in key=value can be parsed properly.'''
- cmd = cmdparse.BindCmdParse('zone cmd name = 1:34::2')
- self.assertEqual(cmd.params['name'], '1:34::2')
-
- cmd = cmdparse.BindCmdParse('zone cmd name = 1\"\'34**&2 value=44\"\'\"')
- self.assertEqual(cmd.params['name'], '1\"\'34**&2')
- self.assertEqual(cmd.params['value'], '44\"\'\"')
-
- cmd = cmdparse.BindCmdParse('zone cmd name = 1\"\'34**&2 ,value= 44\"\'\"')
- self.assertEqual(cmd.params['name'], '1\"\'34**&2')
- self.assertEqual(cmd.params['value'], '44\"\'\"')
-
- cmd = cmdparse.BindCmdParse('zone cmd name = 1\'34**&2value=44\"\'\" value = \"==============\'')
- self.assertEqual(cmd.params['name'], '1\'34**&2value=44\"\'\"')
- self.assertEqual(cmd.params['value'], '==============')
-
- cmd = cmdparse.BindCmdParse('zone cmd name = \"1234, 567890 \" value ==&*/')
- self.assertEqual(cmd.params['name'], '1234, 567890 ')
- self.assertEqual(cmd.params['value'], '=&*/')
+ cmd_parser = cmdparse.BindCmdParser('zone cmd name = 1:34::2')
+ self.assertEqual(cmd_parser.params['name'], '1:34::2')
+
+ cmd_parser = cmdparse.BindCmdParser('zone cmd name = 1\"\'34**&2'
+ ' value=44\"\'\"')
+ self.assertEqual(cmd_parser.params['name'], '1\"\'34**&2')
+ self.assertEqual(cmd_parser.params['value'], '44\"\'\"')
+
+ cmd_parser = cmdparse.BindCmdParser('zone cmd name = 1\"\'34**&2'
+ ',value= 44\"\'\"')
+ self.assertEqual(cmd_parser.params['name'], '1\"\'34**&2')
+ self.assertEqual(cmd_parser.params['value'], '44\"\'\"')
+
+ cmd_parser = cmdparse.BindCmdParser('zone cmd name = 1\'34**&2'
+ 'value=44\"\'\" value = '
+ '\"==============\'')
+ self.assertEqual(cmd_parser.params['name'], '1\'34**&2value=44\"\'\"')
+ self.assertEqual(cmd_parser.params['value'], '==============')
+
+ cmd_parser = cmdparse.BindCmdParser('zone cmd name = \"1234, '
+ '567890 \" value ==&*/')
+ self.assertEqual(cmd_parser.params['name'], '1234, 567890 ')
+ self.assertEqual(cmd_parser.params['value'], '=&*/')
def testCommandWithListParam(self):
- cmd = cmdparse.BindCmdParse("zone set zone_name='cnnic.cn', master='1.1.1.1, 2.2.2.2'")
- assert cmd.params["master"] == '1.1.1.1, 2.2.2.2'
+ cmd_parser = cmdparse.BindCmdParser("zone set zone_name='cnnic.cn', "
+ "master='1.1.1.1, 2.2.2.2'")
+ assert cmd_parser.params["master"] == '1.1.1.1, 2.2.2.2'
def testCommandWithHelpParam(self):
- cmd = cmdparse.BindCmdParse("zone add help")
- assert cmd.params["help"] == "help"
+ cmd_parser = cmdparse.BindCmdParser("zone add help")
+ assert cmd_parser.params["help"] == "help"
- cmd = cmdparse.BindCmdParse("zone add help *&)&)*&&$#$^%")
- assert cmd.params["help"] == "help"
- self.assertEqual(len(cmd.params), 1)
+ cmd_parser = cmdparse.BindCmdParser("zone add help *&)&)*&&$#$^%")
+ assert cmd_parser.params["help"] == "help"
+ self.assertEqual(len(cmd_parser.params), 1)
def testCmdModuleNameFormatError(self):
@@ -130,15 +136,20 @@ class TestCmdSyntax(unittest.TestCase):
int_spec = { 'item_type' : 'integer',
'item_optional' : False,
'item_default' : 10}
- zone_file_param = ParamInfo(name = "zone_file", param_spec = string_spec)
+ zone_file_param = ParamInfo(name = "zone_file",
+ param_spec = string_spec)
zone_name = ParamInfo(name = 'zone_name', param_spec = string_spec)
load_cmd = CommandInfo(name = "load")
load_cmd.add_param(zone_file_param)
load_cmd.add_param(zone_name)
- param_master = ParamInfo(name = "master", optional = True, param_spec = string_spec)
- param_master = ParamInfo(name = "port", optional = True, param_spec = int_spec)
- param_allow_update = ParamInfo(name = "allow_update", optional = True, param_spec = string_spec)
+ param_master = ParamInfo(name = "master", optional = True,
+ param_spec = string_spec)
+ param_master = ParamInfo(name = "port", optional = True,
+ param_spec = int_spec)
+ param_allow_update = ParamInfo(name = "allow_update",
+ optional = True,
+ param_spec = string_spec)
set_cmd = CommandInfo(name = "set")
set_cmd.add_param(param_master)
set_cmd.add_param(param_allow_update)
@@ -160,13 +171,14 @@ class TestCmdSyntax(unittest.TestCase):
def no_assert_raise(self, cmd_line):
- cmd = cmdparse.BindCmdParse(cmd_line)
- self.bindcmd._validate_cmd(cmd)
+ cmd_parser = cmdparse.BindCmdParser(cmd_line)
+ self.bindcmd._validate_cmd(cmd_parser)
def my_assert_raise(self, exception_type, cmd_line):
- cmd = cmdparse.BindCmdParse(cmd_line)
- self.assertRaises(exception_type, self.bindcmd._validate_cmd, cmd)
+ cmd_parser = cmdparse.BindCmdParser(cmd_line)
+ self.assertRaises(exception_type, self.bindcmd._validate_cmd,
+ cmd_parser)
def testValidateSuccess(self):
@@ -177,7 +189,8 @@ class TestCmdSyntax(unittest.TestCase):
self.no_assert_raise("zone help help='dd' ")
self.no_assert_raise("zone set allow_update='1.1.1.1' zone_name='cn'")
self.no_assert_raise("zone set zone_name='cn'")
- self.my_assert_raise(isc.cc.data.DataTypeError, "zone set zone_name ='cn', port='cn'")
+ self.my_assert_raise(isc.cc.data.DataTypeError,
+ "zone set zone_name ='cn', port='cn'")
self.no_assert_raise("zone reload_all")
def testCmdUnknownModuleSyntaxError(self):
@@ -188,15 +201,22 @@ class TestCmdSyntax(unittest.TestCase):
self.my_assert_raise(CmdUnknownCmdSyntaxError, "zone dd")
def testCmdMissParamSyntaxError(self):
- self.my_assert_raise(CmdMissParamSyntaxError, "zone load zone_file='cn'")
- self.my_assert_raise(CmdMissParamSyntaxError, "zone load zone_name='cn'")
- self.my_assert_raise(CmdMissParamSyntaxError, "zone set allow_update='1.1.1.1'")
- self.my_assert_raise(CmdMissParamSyntaxError, "zone set ")
+ self.my_assert_raise(CmdMissParamSyntaxError,
+ "zone load zone_file='cn'")
+ self.my_assert_raise(CmdMissParamSyntaxError,
+ "zone load zone_name='cn'")
+ self.my_assert_raise(CmdMissParamSyntaxError,
+ "zone set allow_update='1.1.1.1'")
+ self.my_assert_raise(CmdMissParamSyntaxError,
+ "zone set ")
def testCmdUnknownParamSyntaxError(self):
- self.my_assert_raise(CmdUnknownParamSyntaxError, "zone load zone_d='cn'")
- self.my_assert_raise(CmdUnknownParamSyntaxError, "zone reload_all zone_name = 'cn'")
- self.my_assert_raise(CmdUnknownParamSyntaxError, "zone help a b c")
+ self.my_assert_raise(CmdUnknownParamSyntaxError,
+ "zone load zone_d='cn'")
+ self.my_assert_raise(CmdUnknownParamSyntaxError,
+ "zone reload_all zone_name = 'cn'")
+ self.my_assert_raise(CmdUnknownParamSyntaxError,
+ "zone help a b c")
class TestModuleInfo(unittest.TestCase):
@@ -233,7 +253,8 @@ class TestNameSequence(unittest.TestCase):
self.tool.add_module_info(ModuleInfo(name = random_str))
def setUp(self):
- self.random_names = ['1erdfeDDWsd', '3fe', '2009erd', 'Fe231', 'tere142', 'rei8WD']
+ self.random_names = ['1erdfeDDWsd', '3fe', '2009erd',
+ 'Fe231', 'tere142', 'rei8WD']
self._create_bindcmd()
def testSequence(self):
@@ -321,7 +342,8 @@ class TestConfigCommands(unittest.TestCase):
def precmd(line):
self.tool.precmd(line)
self.tool._update_all_modules_info = update_all_modules_info
- # If line is equals to 'EOF', _update_all_modules_info() shouldn't be called
+ # If line is equals to 'EOF', _update_all_modules_info()
+ # shouldn't be called
precmd('EOF')
self.assertRaises(socket.error, precmd, 'continue')
@@ -360,34 +382,41 @@ class TestConfigCommands(unittest.TestCase):
self.assertEqual((1, MultiConfigData.DEFAULT),
self.tool.config_data.get_value("/foo/an_int"))
- cmd = cmdparse.BindCmdParse("config set identifier=\"foo/an_int\" value=\"5\"")
- self.tool.apply_config_cmd(cmd)
+ cmd_parser = cmdparse.BindCmdParser('config set identifier='
+ '"foo/an_int" value="5"')
+ self.tool.apply_config_cmd(cmd_parser)
self.assertEqual((5, MultiConfigData.LOCAL),
self.tool.config_data.get_value("/foo/an_int"))
- cmd = cmdparse.BindCmdParse("config unset identifier=\"foo/an_int\"")
- self.tool.apply_config_cmd(cmd)
+ cmd_parser = cmdparse.BindCmdParser('config unset identifier='
+ '"foo/an_int"')
+ self.tool.apply_config_cmd(cmd_parser)
self.assertEqual((1, MultiConfigData.DEFAULT),
self.tool.config_data.get_value("/foo/an_int"))
# this should raise a NotFoundError
- cmd = cmdparse.BindCmdParse("config set identifier=\"foo/bar\" value=\"[]\"")
- self.assertRaises(isc.cc.data.DataNotFoundError, self.tool.apply_config_cmd, cmd)
+ cmd_parser = cmdparse.BindCmdParser('config set identifier='
+ '"foo/bar" value="[]"')
+ self.assertRaises(isc.cc.data.DataNotFoundError,
+ self.tool.apply_config_cmd, cmd_parser)
- cmd = cmdparse.BindCmdParse("config unset identifier=\"foo/bar\"")
+ cmd_parser = cmdparse.BindCmdParser('config unset identifier='
+ '"foo/bar"')
self.assertRaises(isc.cc.data.DataNotFoundError,
- self.tool.apply_config_cmd, cmd)
+ self.tool.apply_config_cmd, cmd_parser)
# this should raise a TypeError
- cmd = cmdparse.BindCmdParse("config set identifier=\"foo/an_int\" value=\"[]\"")
- self.assertRaises(isc.cc.data.DataTypeError, self.tool.apply_config_cmd, cmd)
+ cmd_parser = cmdparse.BindCmdParser('config set identifier='
+ '"foo/an_int" value="[]"')
+ self.assertRaises(isc.cc.data.DataTypeError,
+ self.tool.apply_config_cmd, cmd_parser)
# this is a very specific one for use with a set of list tests
# to try out the flexibility of the parser (only in the next test)
def clt(self, full_cmd_string, item_value):
- cmd = cmdparse.BindCmdParse(full_cmd_string)
- self.tool.apply_config_cmd(cmd)
+ cmd_parser = cmdparse.BindCmdParser(full_cmd_string)
+ self.tool.apply_config_cmd(cmd_parser)
self.assertEqual(([item_value], MultiConfigData.LOCAL),
self.tool.config_data.get_value("/foo/a_list"))
@@ -410,15 +439,56 @@ class TestConfigCommands(unittest.TestCase):
self.clt("config set identifier = \"foo/a_list\" value=[ \"k\" ]", "k")
# this should raise a TypeError
- cmd = cmdparse.BindCmdParse("config set identifier=\"foo/a_list\" value=\"a\"")
- self.assertRaises(isc.cc.data.DataTypeError, self.tool.apply_config_cmd, cmd)
+ cmd_parser = cmdparse.BindCmdParser('config set identifier='
+ '"foo/a_list" value="a"')
+ self.assertRaises(isc.cc.data.DataTypeError,
+ self.tool.apply_config_cmd, cmd_parser)
- cmd = cmdparse.BindCmdParse("config set identifier=\"foo/a_list\" value=[1]")
- self.assertRaises(isc.cc.data.DataTypeError, self.tool.apply_config_cmd, cmd)
+ cmd_parser = cmdparse.BindCmdParser('config set identifier='
+ '"foo/a_list" value=[1]')
+ self.assertRaises(isc.cc.data.DataTypeError,
+ self.tool.apply_config_cmd, cmd_parser)
def tearDown(self):
sys.stdout = self.stdout_backup
+ def test_cmd_has_identifier_param(self):
+ module = ModuleInfo(name="test_module")
+
+ cmd = CommandInfo(name="command_with_identifier")
+ param = ParamInfo(name=bindcmd.CFGITEM_IDENTIFIER_PARAM)
+ cmd.add_param(param)
+ module.add_command(cmd)
+
+ cmd = CommandInfo(name="command_without_identifier")
+ param = ParamInfo(name="some_argument")
+ cmd.add_param(param)
+ module.add_command(cmd)
+
+ self.tool.add_module_info(module)
+
+ cmd_parser = cmdparse.BindCmdParser('test_module '
+ 'command_with_identifier')
+ self.assertTrue(self.tool._cmd_has_identifier_param(cmd_parser))
+
+ cmd_parser = cmdparse.BindCmdParser('test_module '
+ 'command_without_identifier')
+ self.assertFalse(self.tool._cmd_has_identifier_param(cmd_parser))
+
+ cmd_parser = cmdparse.BindCmdParser('badmodule '
+ 'command_without_identifier')
+ self.assertFalse(self.tool._cmd_has_identifier_param(cmd_parser))
+
+ def test_get_identifier_startswith(self):
+ hints = self.tool._get_identifier_startswith("/")
+ self.assertEqual(['foo/an_int', 'foo/a_list'], hints)
+
+ hints = self.tool._get_identifier_startswith("/foo/an")
+ self.assertEqual(['foo/an_int'], hints)
+
+ hints = self.tool._get_identifier_startswith("/bar")
+ self.assertEqual([], hints)
+
class FakeBindCmdInterpreter(bindcmd.BindCmdInterpreter):
def __init__(self):
pass
diff --git a/src/bin/cfgmgr/Makefile.am b/src/bin/cfgmgr/Makefile.am
index e9e0cca..9c73f79 100644
--- a/src/bin/cfgmgr/Makefile.am
+++ b/src/bin/cfgmgr/Makefile.am
@@ -1,4 +1,4 @@
-SUBDIRS = . plugins tests
+SUBDIRS = . plugins local_plugins tests
pkglibexecdir = $(libexecdir)/@PACKAGE@
diff --git a/src/bin/cfgmgr/local_plugins/Makefile.am b/src/bin/cfgmgr/local_plugins/Makefile.am
new file mode 100644
index 0000000..2f4dd39
--- /dev/null
+++ b/src/bin/cfgmgr/local_plugins/Makefile.am
@@ -0,0 +1,11 @@
+# Nothing is installed from this directory. This local_plugins
+# directory overrides the plugins directory when lettuce is run, and the
+# spec file here is used to serve the static zone from the source tree
+# for testing (instead of installation prefix).
+
+noinst_DATA = datasrc.spec
+
+datasrc.spec: ../plugins/datasrc.spec.pre
+ $(SED) -e "s|@@STATIC_ZONE_FILE@@|$(abs_top_builddir)/src/lib/datasrc/static.zone|;s|@@SQLITE3_DATABASE_FILE@@|$(abs_top_builddir)/local.zone.sqlite3|" ../plugins/datasrc.spec.pre >$@
+
+CLEANFILES = datasrc.spec
diff --git a/src/bin/cfgmgr/plugins/Makefile.am b/src/bin/cfgmgr/plugins/Makefile.am
index e6ed127..5967abd 100644
--- a/src/bin/cfgmgr/plugins/Makefile.am
+++ b/src/bin/cfgmgr/plugins/Makefile.am
@@ -3,7 +3,7 @@ SUBDIRS = tests
EXTRA_DIST = README logging.spec tsig_keys.spec
datasrc.spec: datasrc.spec.pre
- $(SED) -e "s|@@PKGDATADIR@@|$(pkgdatadir)|;s|@@LOCALSTATEDIR@@|$(localstatedir)|" datasrc.spec.pre >$@
+ $(SED) -e "s|@@STATIC_ZONE_FILE@@|$(pkgdatadir)/static.zone|;s|@@SQLITE3_DATABASE_FILE@@|$(localstatedir)/$(PACKAGE)/zone.sqlite3|" datasrc.spec.pre >$@
config_plugindir = @prefix@/share/@PACKAGE@/config_plugins
config_plugin_DATA = logging.spec tsig_keys.spec datasrc.spec
diff --git a/src/bin/cfgmgr/plugins/datasrc.spec.pre.in b/src/bin/cfgmgr/plugins/datasrc.spec.pre.in
index f2c6a97..6d5bd77 100644
--- a/src/bin/cfgmgr/plugins/datasrc.spec.pre.in
+++ b/src/bin/cfgmgr/plugins/datasrc.spec.pre.in
@@ -12,7 +12,7 @@
{
"type": "sqlite3",
"params": {
- "database_file": "@@LOCALSTATEDIR@@/@PACKAGE@/zone.sqlite3"
+ "database_file": "@@SQLITE3_DATABASE_FILE@@"
}
}
],
@@ -20,7 +20,7 @@
{
"type": "static",
"cache-enable": false,
- "params": "@@PKGDATADIR@@/static.zone"
+ "params": "@@STATIC_ZONE_FILE@@"
}
]
},
diff --git a/src/bin/dbutil/dbutil.py.in b/src/bin/dbutil/dbutil.py.in
index 4b76a56..a844484 100755
--- a/src/bin/dbutil/dbutil.py.in
+++ b/src/bin/dbutil/dbutil.py.in
@@ -193,10 +193,17 @@ UPGRADES = [
"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)"
+ ]
}
# To extend this, leave the above statements in place and add another
-# dictionary to the list. The "from" version should be (2, 0), the "to"
+# dictionary to the list. The "from" version should be (2, 1), 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.
diff --git a/src/bin/dbutil/tests/Makefile.am b/src/bin/dbutil/tests/Makefile.am
index b4231b3..aaa57cc 100644
--- a/src/bin/dbutil/tests/Makefile.am
+++ b/src/bin/dbutil/tests/Makefile.am
@@ -2,6 +2,8 @@ SUBDIRS = . testdata
# Tests of the update script.
+noinst_SCRIPTS = dbutil_test.sh
+
check-local:
B10_LOCKFILE_DIR_FROM_BUILD=$(abs_top_builddir) \
$(SHELL) $(abs_builddir)/dbutil_test.sh
diff --git a/src/bin/dbutil/tests/dbutil_test.sh.in b/src/bin/dbutil/tests/dbutil_test.sh.in
index f82eeb0..d60f186 100755
--- a/src/bin/dbutil/tests/dbutil_test.sh.in
+++ b/src/bin/dbutil/tests/dbutil_test.sh.in
@@ -161,11 +161,11 @@ get_schema() {
# @param $2 Expected backup file
upgrade_ok_test() {
copy_file $1 $tempfile
- ../run_dbutil.sh --upgrade --noconfirm $tempfile
+ ${SHELL} ../run_dbutil.sh --upgrade --noconfirm $tempfile
if [ $? -eq 0 ]
then
# Compare schema with the reference
- get_schema $testdata/v2_0.sqlite3
+ get_schema $testdata/v2_1.sqlite3
expected_schema=$db_schema
get_schema $tempfile
actual_schema=$db_schema
@@ -177,7 +177,7 @@ upgrade_ok_test() {
fi
# Check the version is set correctly
- check_version $tempfile "V2.0"
+ check_version $tempfile "V2.1"
# Check that a backup was made
check_backup $1 $2
@@ -199,7 +199,7 @@ upgrade_ok_test() {
# @param $2 Expected backup file
upgrade_fail_test() {
copy_file $1 $tempfile
- ../run_dbutil.sh --upgrade --noconfirm $tempfile
+ ${SHELL} ../run_dbutil.sh --upgrade --noconfirm $tempfile
failzero $?
check_backup $1 $backupfile
}
@@ -222,7 +222,7 @@ record_count_test() {
records_count=`sqlite3 $tempfile 'select count(*) from records'`
zones_count=`sqlite3 $tempfile 'select count(*) from zones'`
- ../run_dbutil.sh --upgrade --noconfirm $tempfile
+ ${SHELL} ../run_dbutil.sh --upgrade --noconfirm $tempfile
if [ $? -ne 0 ]
then
# Reason for failure should already have been output
@@ -268,12 +268,12 @@ record_count_test() {
# @param $2 Expected version string
check_version() {
copy_file $1 $verfile
- ../run_dbutil.sh --check $verfile
+ ${SHELL} ../run_dbutil.sh --check $verfile
if [ $? -gt 2 ]
then
fail "version check failed on database $1; return code $?"
else
- ../run_dbutil.sh --check $verfile 2>&1 | grep "$2" > /dev/null
+ ${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: $?)"
@@ -293,7 +293,7 @@ check_version() {
# @param $2 Backup file
check_version_fail() {
copy_file $1 $verfile
- ../run_dbutil.sh --check $verfile
+ ${SHELL} ../run_dbutil.sh --check $verfile
failzero $?
check_no_backup $tempfile $backupfile
}
@@ -305,12 +305,12 @@ rm -f $tempfile $backupfile
# Test 1 - check that the utility fails if the database does not exist
echo "1.1. Non-existent database - check"
-../run_dbutil.sh --check $tempfile
+${SHELL} ../run_dbutil.sh --check $tempfile
failzero $?
check_no_backup $tempfile $backupfile
echo "1.2. Non-existent database - upgrade"
-../run_dbutil.sh --upgrade --noconfirm $tempfile
+${SHELL} ../run_dbutil.sh --upgrade --noconfirm $tempfile
failzero $?
check_no_backup $tempfile $backupfile
rm -f $tempfile $backupfile
@@ -324,7 +324,7 @@ rm -f $tempfile $backupfile
echo "2.2. Database is an empty file - upgrade"
touch $tempfile
-../run_dbutil.sh --upgrade --noconfirm $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
@@ -338,7 +338,7 @@ rm -f $tempfile $backupfile
echo "3.2. Database is not an SQLite file - upgrade"
echo "This is not an sqlite3 database" > $tempfile
-../run_dbutil.sh --upgrade --noconfirm $tempfile
+${SHELL} ../run_dbutil.sh --upgrade --noconfirm $tempfile
failzero $?
# ...and as before, a backup should have been created
check_backup $tempfile $backupfile
@@ -421,40 +421,40 @@ rm -f $tempfile $backupfile ${backupfile}-1 ${backupfile}-2
echo "13.1 Command-line errors"
copy_file $testdata/old_v1.sqlite3 $tempfile
-../run_dbutil.sh $tempfile
+${SHELL} ../run_dbutil.sh $tempfile
failzero $?
-../run_dbutil.sh --upgrade --check $tempfile
+${SHELL} ../run_dbutil.sh --upgrade --check $tempfile
failzero $?
-../run_dbutil.sh --noconfirm --check $tempfile
+${SHELL} ../run_dbutil.sh --noconfirm --check $tempfile
failzero $?
-../run_dbutil.sh --check
+${SHELL} ../run_dbutil.sh --check
failzero $?
-../run_dbutil.sh --upgrade --noconfirm
+${SHELL} ../run_dbutil.sh --upgrade --noconfirm
failzero $?
-../run_dbutil.sh --check $tempfile $backupfile
+${SHELL} ../run_dbutil.sh --check $tempfile $backupfile
failzero $?
-../run_dbutil.sh --upgrade --noconfirm $tempfile $backupfile
+${SHELL} ../run_dbutil.sh --upgrade --noconfirm $tempfile $backupfile
failzero $?
rm -f $tempfile $backupfile
echo "13.2 verbose flag"
copy_file $testdata/old_v1.sqlite3 $tempfile
-../run_dbutil.sh --upgrade --noconfirm --verbose $tempfile
+${SHELL} ../run_dbutil.sh --upgrade --noconfirm --verbose $tempfile
passzero $?
rm -f $tempfile $backupfile
echo "13.3 Interactive prompt - yes"
copy_file $testdata/old_v1.sqlite3 $tempfile
-../run_dbutil.sh --upgrade $tempfile << .
+${SHELL} ../run_dbutil.sh --upgrade $tempfile << .
Yes
.
passzero $?
-check_version $tempfile "V2.0"
+check_version $tempfile "V2.1"
rm -f $tempfile $backupfile
echo "13.4 Interactive prompt - no"
copy_file $testdata/old_v1.sqlite3 $tempfile
-../run_dbutil.sh --upgrade $tempfile << .
+${SHELL} ../run_dbutil.sh --upgrade $tempfile << .
no
.
passzero $?
@@ -464,7 +464,7 @@ rm -f $tempfile $backupfile
echo "13.5 quiet flag"
copy_file $testdata/old_v1.sqlite3 $tempfile
-../run_dbutil.sh --check --quiet $tempfile 2>&1 | grep .
+${SHELL} ../run_dbutil.sh --check --quiet $tempfile 2>&1 | grep .
failzero $?
rm -f $tempfile $backupfile
diff --git a/src/bin/dbutil/tests/testdata/Makefile.am b/src/bin/dbutil/tests/testdata/Makefile.am
index 0d850a7..f4873f4 100644
--- a/src/bin/dbutil/tests/testdata/Makefile.am
+++ b/src/bin/dbutil/tests/testdata/Makefile.am
@@ -10,3 +10,4 @@ EXTRA_DIST += old_v1.sqlite3
EXTRA_DIST += README
EXTRA_DIST += too_many_version.sqlite3
EXTRA_DIST += v2_0.sqlite3
+EXTRA_DIST += v2_1.sqlite3
diff --git a/src/bin/dbutil/tests/testdata/v2_1.sqlite3 b/src/bin/dbutil/tests/testdata/v2_1.sqlite3
new file mode 100644
index 0000000..ca2dee9
Binary files /dev/null and b/src/bin/dbutil/tests/testdata/v2_1.sqlite3 differ
diff --git a/src/bin/dhcp4/dhcp4_log.h b/src/bin/dhcp4/dhcp4_log.h
index 3717b62..b042ea4 100644
--- a/src/bin/dhcp4/dhcp4_log.h
+++ b/src/bin/dhcp4/dhcp4_log.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DHCP4_LOG__H
-#define __DHCP4_LOG__H
+#ifndef DHCP4_LOG_H
+#define DHCP4_LOG_H
#include <log/macros.h>
#include <log/logger_support.h>
@@ -56,4 +56,4 @@ extern isc::log::Logger dhcp4_logger;
} // namespace dhcp4
} // namespace isc
-#endif // __DHCP4_LOG__H
+#endif // DHCP4_LOG_H
diff --git a/src/bin/dhcp4/tests/Makefile.am b/src/bin/dhcp4/tests/Makefile.am
index 906b5d1..ddc3000 100644
--- a/src/bin/dhcp4/tests/Makefile.am
+++ b/src/bin/dhcp4/tests/Makefile.am
@@ -16,6 +16,7 @@ check-local:
for pytest in $(PYTESTS) ; do \
echo Running test: $$pytest ; \
PYTHONPATH=$(COMMON_PYTHON_PATH):$(abs_top_srcdir)/src/bin:$(abs_top_builddir)/src/bin/bind10:$(abs_top_builddir)/src/lib/util/io/.libs \
+ B10_LOCKFILE_DIR_FROM_BUILD=$(abs_top_builddir) \
$(LIBRARY_PATH_PLACEHOLDER) \
$(PYCOVERAGE_RUN) $(abs_srcdir)/$$pytest || exit ; \
done
diff --git a/src/bin/dhcp6/Makefile.am b/src/bin/dhcp6/Makefile.am
index 4dec4e7..68aadea 100644
--- a/src/bin/dhcp6/Makefile.am
+++ b/src/bin/dhcp6/Makefile.am
@@ -46,6 +46,7 @@ pkglibexec_PROGRAMS = b10-dhcp6
b10_dhcp6_SOURCES = main.cc
b10_dhcp6_SOURCES += ctrl_dhcp6_srv.cc ctrl_dhcp6_srv.h
+b10_dhcp6_SOURCES += config_parser.cc config_parser.h
b10_dhcp6_SOURCES += dhcp6_log.cc dhcp6_log.h
b10_dhcp6_SOURCES += dhcp6_srv.cc dhcp6_srv.h
@@ -62,6 +63,7 @@ b10_dhcp6_LDADD = $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
b10_dhcp6_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
b10_dhcp6_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
b10_dhcp6_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcp++.la
+b10_dhcp6_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcpsrv.la
b10_dhcp6_LDADD += $(top_builddir)/src/lib/config/libb10-cfgclient.la
b10_dhcp6_LDADD += $(top_builddir)/src/lib/cc/libb10-cc.la
diff --git a/src/bin/dhcp6/config_parser.cc b/src/bin/dhcp6/config_parser.cc
new file mode 100644
index 0000000..dbffc40
--- /dev/null
+++ b/src/bin/dhcp6/config_parser.cc
@@ -0,0 +1,797 @@
+// 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 <stdint.h>
+#include <iostream>
+#include <vector>
+#include <map>
+#include <boost/foreach.hpp>
+#include <boost/shared_ptr.hpp>
+#include <boost/scoped_ptr.hpp>
+#include <boost/lexical_cast.hpp>
+#include <boost/algorithm/string.hpp>
+#include <asiolink/io_address.h>
+#include <cc/data.h>
+#include <config/ccsession.h>
+#include <log/logger_support.h>
+#include <dhcp/triplet.h>
+#include <dhcp/pool.h>
+#include <dhcp/subnet.h>
+#include <dhcp/cfgmgr.h>
+#include <dhcp6/config_parser.h>
+#include <dhcp6/dhcp6_log.h>
+
+using namespace std;
+using namespace isc::data;
+using namespace isc::asiolink;
+
+namespace isc {
+namespace dhcp {
+
+/// @brief auxiliary type used for storing element name and its parser
+typedef pair<string, ConstElementPtr> ConfigPair;
+
+/// @brief a factory method that will create a parser for a given element name
+typedef DhcpConfigParser* ParserFactory(const std::string& config_id);
+
+/// @brief a collection of factories that creates parsers for specified element names
+typedef std::map<std::string, ParserFactory*> FactoryMap;
+
+/// @brief a collection of elements that store uint32 values (e.g. renew-timer = 900)
+typedef std::map<string, uint32_t> Uint32Storage;
+
+/// @brief a collection of elements that store string values
+typedef std::map<string, string> StringStorage;
+
+/// @brief a collection of pools
+///
+/// That type is used as intermediate storage, when pools are parsed, but there is
+/// no subnet object created yet to store them.
+typedef std::vector<Pool6Ptr> PoolStorage;
+
+/// @brief Global uint32 parameters that will be used as defaults.
+Uint32Storage uint32_defaults;
+
+/// @brief global string parameters that will be used as defaults.
+StringStorage string_defaults;
+
+/// @brief a dummy configuration parser
+///
+/// It is a debugging parser. It does not configure anything,
+/// will accept any configuration and will just print it out
+/// on commit. Useful for debugging existing configurations and
+/// adding new ones.
+class DebugParser : public DhcpConfigParser {
+public:
+
+ /// @brief Constructor
+ ///
+ /// See \ref DhcpConfigParser class for details.
+ ///
+ /// @param param_name name of the parsed parameter
+ DebugParser(const std::string& param_name)
+ :param_name_(param_name) {
+ }
+
+ /// @brief builds parameter value
+ ///
+ /// See \ref DhcpConfigParser class for details.
+ ///
+ /// @param new_config pointer to the new configuration
+ virtual void build(ConstElementPtr new_config) {
+ std::cout << "Build for token: [" << param_name_ << "] = ["
+ << value_->str() << "]" << std::endl;
+ value_ = new_config;
+ }
+
+ /// @brief pretends to apply the configuration
+ ///
+ /// This is a method required by base class. It pretends to apply the
+ /// configuration, but in fact it only prints the parameter out.
+ ///
+ /// See \ref DhcpConfigParser class for details.
+ virtual void commit() {
+ // Debug message. The whole DebugParser class is used only for parser
+ // debugging, and is not used in production code. It is very convenient
+ // to keep it around. Please do not turn this cout into logger calls.
+ std::cout << "Commit for token: [" << param_name_ << "] = ["
+ << value_->str() << "]" << std::endl;
+ }
+
+ /// @brief factory that constructs DebugParser objects
+ ///
+ /// @param param_name name of the parameter to be parsed
+ static DhcpConfigParser* Factory(const std::string& param_name) {
+ return (new DebugParser(param_name));
+ }
+
+protected:
+ /// name of the parsed parameter
+ std::string param_name_;
+
+ /// pointer to the actual value of the parameter
+ ConstElementPtr value_;
+};
+
+/// @brief Configuration parser for uint32 parameters
+///
+/// This class is a generic parser that is able to handle any uint32 integer
+/// type. By default it stores the value in external global container
+/// (uint32_defaults). If used in smaller scopes (e.g. to parse parameters
+/// in subnet config), it can be pointed to a different storage, using
+/// setStorage() method. This class follows the parser interface, laid out
+/// in its base class, \ref DhcpConfigParser.
+///
+/// For overview of usability of this generic purpose parser, see
+/// \ref dhcpv6-config-inherit page.
+class Uint32Parser : public DhcpConfigParser {
+public:
+
+ /// @brief constructor for Uint32Parser
+ /// @param param_name name of the configuration parameter being parsed
+ Uint32Parser(const std::string& param_name)
+ :storage_(&uint32_defaults), param_name_(param_name) {
+ }
+
+ /// @brief builds parameter value
+ ///
+ /// Parses configuration entry and stores it in a storage. See
+ /// \ref setStorage() for details.
+ ///
+ /// @param value pointer to the content of parsed values
+ virtual void build(ConstElementPtr value) {
+ try {
+ value_ = boost::lexical_cast<uint32_t>(value->str());
+ } catch (const boost::bad_lexical_cast &) {
+ isc_throw(BadValue, "Failed to parse value " << value->str()
+ << " as unsigned 32-bit integer.");
+ }
+ storage_->insert(pair<string, uint32_t>(param_name_, value_));
+ }
+
+ /// @brief does nothing
+ ///
+ /// This method is required for all parser. The value itself
+ /// is not commited anywhere. Higher level parsers are expected to
+ /// use values stored in the storage, e.g. renew-timer for a given
+ /// subnet is stored in subnet-specific storage. It is not commited
+ /// here, but is rather used by \ref Subnet6Parser when constructing
+ /// the subnet.
+ virtual void commit() {
+ }
+
+ /// @brief factory that constructs Uint32Parser objects
+ ///
+ /// @param param_name name of the parameter to be parsed
+ static DhcpConfigParser* Factory(const std::string& param_name) {
+ return (new Uint32Parser(param_name));
+ }
+
+ /// @brief sets storage for value of this parameter
+ ///
+ /// See \ref dhcpv6-config-inherit for details.
+ ///
+ /// @param storage pointer to the storage container
+ void setStorage(Uint32Storage* storage) {
+ storage_ = storage;
+ }
+
+protected:
+ /// pointer to the storage, where parsed value will be stored
+ Uint32Storage* storage_;
+
+ /// name of the parameter to be parsed
+ std::string param_name_;
+
+ /// the actual parsed value
+ uint32_t value_;
+};
+
+/// @brief Configuration parser for string parameters
+///
+/// This class is a generic parser that is able to handle any string
+/// parameter. By default it stores the value in external global container
+/// (string_defaults). If used in smaller scopes (e.g. to parse parameters
+/// in subnet config), it can be pointed to a different storage, using
+/// setStorage() method. This class follows the parser interface, laid out
+/// in its base class, \ref DhcpConfigParser.
+///
+/// For overview of usability of this generic purpose parser, see
+/// \ref dhcpv6-config-inherit page.
+class StringParser : public DhcpConfigParser {
+public:
+
+ /// @brief constructor for StringParser
+ /// @param param_name name of the configuration parameter being parsed
+ StringParser(const std::string& param_name)
+ :storage_(&string_defaults), param_name_(param_name) {
+ }
+
+ /// @brief parses parameter value
+ ///
+ /// Parses configuration entry and stored it in storage. See
+ /// \ref setStorage() for details.
+ ///
+ /// @param value pointer to the content of parsed values
+ virtual void build(ConstElementPtr value) {
+ value_ = value->str();
+ boost::erase_all(value_, "\"");
+ storage_->insert(pair<string, string>(param_name_, value_));
+ }
+
+ /// @brief does nothing
+ ///
+ /// This method is required for all parser. The value itself
+ /// is not commited anywhere. Higher level parsers are expected to
+ /// use values stored in the storage, e.g. renew-timer for a given
+ /// subnet is stored in subnet-specific storage. It is not commited
+ /// here, but is rather used by its parent parser when constructing
+ /// an object, e.g. the subnet.
+ virtual void commit() {
+ }
+
+ /// @brief factory that constructs StringParser objects
+ ///
+ /// @param param_name name of the parameter to be parsed
+ static DhcpConfigParser* Factory(const std::string& param_name) {
+ return (new StringParser(param_name));
+ }
+
+ /// @brief sets storage for value of this parameter
+ ///
+ /// See \ref dhcpv6-config-inherit for details.
+ ///
+ /// @param storage pointer to the storage container
+ void setStorage(StringStorage* storage) {
+ storage_ = storage;
+ }
+
+protected:
+ /// pointer to the storage, where parsed value will be stored
+ StringStorage* storage_;
+
+ /// name of the parameter to be parsed
+ std::string param_name_;
+
+ /// the actual parsed value
+ std::string value_;
+};
+
+
+/// @brief parser for interface list definition
+///
+/// This parser handles Dhcp6/interface entry.
+/// It contains a list of network interfaces that the server listens on.
+/// In particular, it can contain an entry called "all" or "any" that
+/// designates all interfaces.
+///
+/// It is useful for parsing Dhcp6/interface parameter.
+class InterfaceListConfigParser : public DhcpConfigParser {
+public:
+
+ /// @brief constructor
+ ///
+ /// As this is a dedicated parser, it must be used to parse
+ /// "interface" parameter only. All other types will throw exception.
+ ///
+ /// @param param_name name of the configuration parameter being parsed
+ InterfaceListConfigParser(const std::string& param_name) {
+ if (param_name != "interface") {
+ isc_throw(NotImplemented, "Internal error. Interface configuration "
+ "parser called for the wrong parameter: " << param_name);
+ }
+ }
+
+ /// @brief parses parameters value
+ ///
+ /// Parses configuration entry (list of parameters) and stores it in
+ /// storage. See \ref setStorage() for details.
+ ///
+ /// @param value pointer to the content of parsed values
+ virtual void build(ConstElementPtr value) {
+ BOOST_FOREACH(ConstElementPtr iface, value->listValue()) {
+ interfaces_.push_back(iface->str());
+ }
+ }
+
+ /// @brief commits interfaces list configuration
+ virtual void commit() {
+ /// @todo: Implement per interface listening. Currently always listening
+ /// on all interfaces.
+ }
+
+ /// @brief factory that constructs InterfaceListConfigParser objects
+ ///
+ /// @param param_name name of the parameter to be parsed
+ static DhcpConfigParser* Factory(const std::string& param_name) {
+ return (new InterfaceListConfigParser(param_name));
+ }
+
+protected:
+ /// contains list of network interfaces
+ vector<string> interfaces_;
+};
+
+/// @brief parser for pool definition
+///
+/// This parser handles pool definitions, i.e. a list of entries of one
+/// of two syntaxes: min-max and prefix/len. Pool6 objects are created
+/// and stored in chosen PoolStorage container.
+///
+/// As there are no default values for pool, setStorage() must be called
+/// before build(). Otherwise exception will be thrown.
+///
+/// It is useful for parsing Dhcp6/subnet6[X]/pool parameters.
+class PoolParser : public DhcpConfigParser {
+public:
+
+ /// @brief constructor.
+ PoolParser(const std::string& /*param_name*/)
+ :pools_(NULL) {
+ // ignore parameter name, it is always Dhcp6/subnet6[X]/pool
+ }
+
+ /// @brief parses the actual list
+ ///
+ /// This method parses the actual list of interfaces.
+ /// No validation is done at this stage, everything is interpreted as
+ /// interface name.
+ void build(ConstElementPtr pools_list) {
+ // setStorage() should have been called before build
+ if (!pools_) {
+ isc_throw(NotImplemented, "Parser logic error. No pool storage set,"
+ " but pool parser asked to parse pools");
+ }
+
+ BOOST_FOREACH(ConstElementPtr text_pool, pools_list->listValue()) {
+
+ // That should be a single pool representation. It should contain
+ // text is form prefix/len or first - last. Note that spaces
+ // are allowed
+ string txt = text_pool->stringValue();
+
+ // first let's remove any whitespaces
+ boost::erase_all(txt, " "); // space
+ boost::erase_all(txt, "\t"); // tabulation
+
+ // Is this prefix/len notation?
+ size_t pos = txt.find("/");
+ if (pos != string::npos) {
+ IOAddress addr("::");
+ uint8_t len = 0;
+ try {
+ addr = IOAddress(txt.substr(0, pos));
+
+ // start with the first character after /
+ string prefix_len = txt.substr(pos + 1);
+
+ // It is lexical cast to int and then downcast to uint8_t.
+ // Direct cast to uint8_t (which is really an unsigned char)
+ // will result in interpreting the first digit as output
+ // value and throwing exception if length is written on two
+ // digits (because there are extra characters left over).
+
+ // No checks for values over 128. Range correctness will
+ // be checked in Pool6 constructor.
+ len = boost::lexical_cast<int>(prefix_len);
+ } catch (...) {
+ isc_throw(Dhcp6ConfigError, "Failed to parse pool "
+ "definition: " << text_pool->stringValue());
+ }
+
+ Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, addr, len));
+ pools_->push_back(pool);
+ continue;
+ }
+
+ // Is this min-max notation?
+ pos = txt.find("-");
+ if (pos != string::npos) {
+ // using min-max notation
+ IOAddress min(txt.substr(0,pos - 1));
+ IOAddress max(txt.substr(pos + 1));
+
+ Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, min, max));
+
+ pools_->push_back(pool);
+ continue;
+ }
+
+ isc_throw(Dhcp6ConfigError, "Failed to parse pool definition:"
+ << text_pool->stringValue() <<
+ ". Does not contain - (for min-max) nor / (prefix/len)");
+ }
+ }
+
+ /// @brief sets storage for value of this parameter
+ ///
+ /// See \ref dhcpv6-config-inherit for details.
+ ///
+ /// @param storage pointer to the storage container
+ void setStorage(PoolStorage* storage) {
+ pools_ = storage;
+ }
+
+ /// @brief does nothing.
+ ///
+ /// This method is required for all parser. The value itself
+ /// is not commited anywhere. Higher level parsers (for subnet) are expected
+ /// to use values stored in the storage.
+ virtual void commit() {}
+
+ /// @brief factory that constructs PoolParser objects
+ ///
+ /// @param param_name name of the parameter to be parsed
+ static DhcpConfigParser* Factory(const std::string& param_name) {
+ return (new PoolParser(param_name));
+ }
+
+protected:
+ /// @brief pointer to the actual Pools storage
+ ///
+ /// That is typically a storage somewhere in Subnet parser
+ /// (an upper level parser).
+ PoolStorage* pools_;
+};
+
+/// @brief this class parses a single subnet
+///
+/// This class parses the whole subnet definition. It creates parsers
+/// for received configuration parameters as needed.
+class Subnet6ConfigParser : public DhcpConfigParser {
+public:
+
+ /// @brief constructor
+ Subnet6ConfigParser(const std::string& ) {
+ // The parameter should always be "subnet", but we don't check here
+ // against it in case some wants to reuse this parser somewhere.
+ }
+
+ /// @brief parses parameter value
+ ///
+ /// @param subnet pointer to the content of subnet definition
+ void build(ConstElementPtr subnet) {
+
+ BOOST_FOREACH(ConfigPair param, subnet->mapValue()) {
+
+ ParserPtr parser(createSubnet6ConfigParser(param.first));
+
+ // if this is an Uint32 parser, tell it to store the values
+ // in values_, rather than in global storage
+ boost::shared_ptr<Uint32Parser> uintParser =
+ boost::dynamic_pointer_cast<Uint32Parser>(parser);
+ if (uintParser) {
+ uintParser->setStorage(&uint32_values_);
+ } else {
+
+ boost::shared_ptr<StringParser> stringParser =
+ boost::dynamic_pointer_cast<StringParser>(parser);
+ if (stringParser) {
+ stringParser->setStorage(&string_values_);
+ } else {
+
+ boost::shared_ptr<PoolParser> poolParser =
+ boost::dynamic_pointer_cast<PoolParser>(parser);
+ if (poolParser) {
+ poolParser->setStorage(&pools_);
+ }
+ }
+ }
+
+ parser->build(param.second);
+ parsers_.push_back(parser);
+ }
+
+ // Ok, we now have subnet parsed
+ }
+
+ /// @brief commits received configuration.
+ ///
+ /// This method does most of the configuration. Many other parsers are just
+ /// storing the values that are actually consumed here. Pool definitions
+ /// created in other parsers are used here and added to newly created Subnet6
+ /// objects. Subnet6 are then added to DHCP CfgMgr.
+ void commit() {
+
+ StringStorage::const_iterator it = string_values_.find("subnet");
+ if (it == string_values_.end()) {
+ isc_throw(Dhcp6ConfigError,
+ "Mandatory subnet definition in subnet missing");
+ }
+ string subnet_txt = it->second;
+ boost::erase_all(subnet_txt, " ");
+ boost::erase_all(subnet_txt, "\t");
+
+ size_t pos = subnet_txt.find("/");
+ if (pos == string::npos) {
+ isc_throw(Dhcp6ConfigError,
+ "Invalid subnet syntax (prefix/len expected):" << it->second);
+ }
+ IOAddress addr(subnet_txt.substr(0, pos));
+ uint8_t len = boost::lexical_cast<unsigned int>(subnet_txt.substr(pos + 1));
+
+ Triplet<uint32_t> t1 = getParam("renew-timer");
+ Triplet<uint32_t> t2 = getParam("rebind-timer");
+ Triplet<uint32_t> pref = getParam("preferred-lifetime");
+ Triplet<uint32_t> valid = getParam("valid-lifetime");
+
+ /// @todo: Convert this to logger once the parser is working reliably
+ stringstream tmp;
+ tmp << addr.toText() << "/" << (int)len
+ << " with params t1=" << t1 << ", t2=" << t2 << ", pref="
+ << pref << ", valid=" << valid;
+
+ LOG_INFO(dhcp6_logger, DHCP6_CONFIG_NEW_SUBNET).arg(tmp.str());
+
+ Subnet6Ptr subnet(new Subnet6(addr, len, t1, t2, pref, valid));
+
+ for (PoolStorage::iterator it = pools_.begin(); it != pools_.end(); ++it) {
+ subnet->addPool6(*it);
+ }
+
+ CfgMgr::instance().addSubnet6(subnet);
+ }
+
+protected:
+
+ /// @brief creates parsers for entries in subnet definition
+ ///
+ /// @todo Add subnet-specific things here (e.g. subnet-specific options)
+ ///
+ /// @param config_id name od the entry
+ /// @return parser object for specified entry name
+ DhcpConfigParser* createSubnet6ConfigParser(const std::string& config_id) {
+ FactoryMap factories;
+
+ factories.insert(pair<string, ParserFactory*>(
+ "preferred-lifetime", Uint32Parser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "valid-lifetime", Uint32Parser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "renew-timer", Uint32Parser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "rebind-timer", Uint32Parser::Factory));
+
+ factories.insert(pair<string, ParserFactory*>(
+ "subnet", StringParser::Factory));
+
+ factories.insert(pair<string, ParserFactory*>(
+ "pool", PoolParser::Factory));
+
+ FactoryMap::iterator f = factories.find(config_id);
+ if (f == factories.end()) {
+ // Used for debugging only.
+ // return new DebugParser(config_id);
+
+ isc_throw(NotImplemented,
+ "Parser error: Subnet6 parameter not supported: "
+ << config_id);
+ }
+ return (f->second(config_id));
+ }
+
+ /// @brief returns value for a given parameter (after using inheritance)
+ ///
+ /// This method implements inheritance. For a given parameter name, it first
+ /// checks if there is a global value for it and overwrites it with specific
+ /// value if such value was defined in subnet.
+ ///
+ /// @param name name of the parameter
+ /// @return triplet with the parameter name
+ Triplet<uint32_t> getParam(const std::string& name) {
+ uint32_t value = 0;
+ bool found = false;
+ Uint32Storage::iterator global = uint32_defaults.find(name);
+ if (global != uint32_defaults.end()) {
+ value = global->second;
+ found = true;
+ }
+
+ Uint32Storage::iterator local = uint32_values_.find(name);
+ if (local != uint32_values_.end()) {
+ value = local->second;
+ found = true;
+ }
+
+ if (found) {
+ return (Triplet<uint32_t>(value));
+ } else {
+ isc_throw(Dhcp6ConfigError, "Mandatory parameter " << name
+ << " missing (no global default and no subnet-"
+ << "specific value)");
+ }
+ }
+
+ /// storage for subnet-specific uint32 values
+ Uint32Storage uint32_values_;
+
+ /// storage for subnet-specific integer values
+ StringStorage string_values_;
+
+ /// storage for pools belonging to this subnet
+ PoolStorage pools_;
+
+ /// parsers are stored here
+ ParserCollection parsers_;
+};
+
+/// @brief this class parses list of subnets
+///
+/// This is a wrapper parser that handles the whole list of Subnet6
+/// definitions. It iterates over all entries and creates Subnet6ConfigParser
+/// for each entry.
+class Subnets6ListConfigParser : public DhcpConfigParser {
+public:
+
+ /// @brief constructor
+ ///
+ Subnets6ListConfigParser(const std::string&) {
+ /// parameter name is ignored
+ }
+
+ /// @brief parses contents of the list
+ ///
+ /// Iterates over all entries on the list and creates Subnet6ConfigParser
+ /// for each entry.
+ ///
+ /// @param subnets_list pointer to a list of IPv6 subnets
+ void build(ConstElementPtr subnets_list) {
+
+ // No need to define FactoryMap here. There's only one type
+ // used: Subnet6ConfigParser
+
+ BOOST_FOREACH(ConstElementPtr subnet, subnets_list->listValue()) {
+
+ ParserPtr parser(new Subnet6ConfigParser("subnet"));
+ parser->build(subnet);
+ subnets_.push_back(parser);
+ }
+
+ }
+
+ /// @brief commits subnets definitions.
+ ///
+ /// Iterates over all Subnet6 parsers. Each parser contains definitions
+ /// of a single subnet and its parameters and commits each subnet separately.
+ void commit() {
+ // @todo: Implement more subtle reconfiguration than toss
+ // the old one and replace with the new one.
+
+ // remove old subnets
+ CfgMgr::instance().deleteSubnets6();
+
+ BOOST_FOREACH(ParserPtr subnet, subnets_) {
+ subnet->commit();
+ }
+
+ }
+
+ /// @brief Returns Subnet6ListConfigParser object
+ /// @param param_name name of the parameter
+ /// @return Subnets6ListConfigParser object
+ static DhcpConfigParser* Factory(const std::string& param_name) {
+ return (new Subnets6ListConfigParser(param_name));
+ }
+
+ /// @brief collection of subnet parsers.
+ ParserCollection subnets_;
+};
+
+/// @brief creates global parsers
+///
+/// This method creates global parsers that parse global parameters, i.e.
+/// those that take format of Dhcp6/param1, Dhcp6/param2 and so forth.
+///
+/// @param config_id pointer to received global configuration entry
+/// @return parser for specified global DHCPv6 parameter
+DhcpConfigParser* createGlobalDhcpConfigParser(const std::string& config_id) {
+ FactoryMap factories;
+
+ //
+ factories.insert(pair<string, ParserFactory*>(
+ "preferred-lifetime", Uint32Parser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "valid-lifetime", Uint32Parser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "renew-timer", Uint32Parser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "rebind-timer", Uint32Parser::Factory));
+
+ factories.insert(pair<string, ParserFactory*>(
+ "interface", InterfaceListConfigParser::Factory));
+ factories.insert(pair<string, ParserFactory*>(
+ "subnet6", Subnets6ListConfigParser::Factory));
+
+ factories.insert(pair<string, ParserFactory*>(
+ "version", StringParser::Factory));
+
+ FactoryMap::iterator f = factories.find(config_id);
+ if (f == factories.end()) {
+ // Used for debugging only.
+ // return new DebugParser(config_id);
+
+ isc_throw(NotImplemented,
+ "Parser error: Global configuration parameter not supported: "
+ << config_id);
+ }
+ return (f->second(config_id));
+}
+
+/// @brief configures DHCPv6 server
+///
+/// This function is called every time a new configuration is received. The extra
+/// parameter is a reference to DHCPv6 server component. It is currently not used
+/// and CfgMgr::instance() is accessed instead.
+///
+/// This method does not throw. It catches all exceptions and returns them as
+/// reconfiguration statuses. It may return the following response codes:
+/// 0 - configuration successful
+/// 1 - malformed configuration (parsing failed)
+/// 2 - logical error (parsing was successful, but the values are invalid)
+///
+/// @param config_set a new configuration for DHCPv6 server
+/// @return answer that contains result of reconfiguration
+ConstElementPtr
+configureDhcp6Server(Dhcpv6Srv& , ConstElementPtr config_set) {
+ if (!config_set) {
+ isc_throw(Dhcp6ConfigError,
+ "Null pointer is passed to configuration parser");
+ }
+
+ /// @todo: append most essential info here (like "2 new subnets configured")
+ string config_details;
+
+ LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_START).arg(config_set->str());
+
+ ParserCollection parsers;
+ try {
+ BOOST_FOREACH(ConfigPair config_pair, config_set->mapValue()) {
+
+ ParserPtr parser(createGlobalDhcpConfigParser(config_pair.first));
+ parser->build(config_pair.second);
+ parsers.push_back(parser);
+ }
+ } catch (const isc::Exception& ex) {
+ ConstElementPtr answer = isc::config::createAnswer(1,
+ string("Configuration parsing failed:") + ex.what());
+ return (answer);
+ } catch (...) {
+ // for things like bad_cast in boost::lexical_cast
+ ConstElementPtr answer = isc::config::createAnswer(1,
+ string("Configuration parsing failed"));
+ }
+
+ try {
+ BOOST_FOREACH(ParserPtr parser, parsers) {
+ parser->commit();
+ }
+ }
+ catch (const isc::Exception& ex) {
+ ConstElementPtr answer = isc::config::createAnswer(2,
+ string("Configuration commit failed:") + ex.what());
+ return (answer);
+ } catch (...) {
+ // for things like bad_cast in boost::lexical_cast
+ ConstElementPtr answer = isc::config::createAnswer(2,
+ string("Configuration commit failed"));
+ }
+
+ LOG_INFO(dhcp6_logger, DHCP6_CONFIG_COMPLETE).arg(config_details);
+
+ ConstElementPtr answer = isc::config::createAnswer(0, "Configuration commited.");
+ return (answer);
+}
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
diff --git a/src/bin/dhcp6/config_parser.h b/src/bin/dhcp6/config_parser.h
new file mode 100644
index 0000000..6758c99
--- /dev/null
+++ b/src/bin/dhcp6/config_parser.h
@@ -0,0 +1,147 @@
+// 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 <string>
+#include <exceptions/exceptions.h>
+#include <cc/data.h>
+
+#ifndef DHCP6_CONFIG_PARSER_H
+#define DHCP6_CONFIG_PARSER_H
+
+namespace isc {
+namespace dhcp {
+
+class Dhcpv6Srv;
+
+/// An exception that is thrown if an error occurs while configuring an
+/// \c Dhcpv6Srv object.
+class Dhcp6ConfigError : public isc::Exception {
+public:
+
+/// @brief constructor
+///
+/// @param file name of the file, where exception occurred
+/// @param line line of the file, where exception occurred
+/// @param what text description of the issue that caused exception
+Dhcp6ConfigError(const char* file, size_t line, const char* what) :
+ isc::Exception(file, line, what) {}
+};
+
+class DhcpConfigParser {
+ ///
+ /// \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:
+ DhcpConfigParser(const DhcpConfigParser& source);
+ DhcpConfigParser& operator=(const DhcpConfigParser& 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).
+ DhcpConfigParser() {}
+public:
+ /// The destructor.
+ virtual ~DhcpConfigParser() {}
+ //@}
+
+ /// \brief 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.
+ ///
+ /// 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 in the
+ /// life of the object. 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;
+
+ /// \brief 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 configureDhcp6Server(), 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;
+};
+
+/// @brief a pointer to configuration parser
+typedef boost::shared_ptr<DhcpConfigParser> ParserPtr;
+
+/// @brief a collection of parsers
+///
+/// This container is used to store pointer to parsers for a given scope.
+typedef std::vector<ParserPtr> ParserCollection;
+
+
+/// \brief Configure an \c Dhcpv6Srv 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 DhcpConfigParser 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 Dhcp6ConfigError.
+/// 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 Dhcp6ConfigError.
+/// 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 Dhcpv6Srv object to be configured.
+/// \param config_set A JSON style configuration to apply to \c server.
+isc::data::ConstElementPtr
+configureDhcp6Server(Dhcpv6Srv& server,
+ isc::data::ConstElementPtr config_set);
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
+
+#endif // DHCP6_CONFIG_PARSER_H
diff --git a/src/bin/dhcp6/ctrl_dhcp6_srv.cc b/src/bin/dhcp6/ctrl_dhcp6_srv.cc
index 4afb203..7370583 100644
--- a/src/bin/dhcp6/ctrl_dhcp6_srv.cc
+++ b/src/bin/dhcp6/ctrl_dhcp6_srv.cc
@@ -25,6 +25,7 @@
#include <dhcp6/ctrl_dhcp6_srv.h>
#include <dhcp6/dhcp6_log.h>
#include <dhcp6/spec_config.h>
+#include <dhcp6/config_parser.h>
#include <dhcp/iface_mgr.h>
#include <exceptions/exceptions.h>
#include <util/buffer.h>
@@ -47,8 +48,15 @@ ConstElementPtr
ControlledDhcpv6Srv::dhcp6ConfigHandler(ConstElementPtr new_config) {
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_UPDATE)
.arg(new_config->str());
- ConstElementPtr answer = isc::config::createAnswer(0,
- "Thank you for sending config.");
+
+ if (server_) {
+ return (configureDhcp6Server(*server_, new_config));
+ }
+
+ // That should never happen as we install config_handler after we instantiate
+ // the server.
+ ConstElementPtr answer = isc::config::createAnswer(1,
+ "Configuration rejected, server is during startup/shutdown phase.");
return (answer);
}
@@ -86,7 +94,7 @@ void ControlledDhcpv6Srv::sessionReader(void) {
}
void ControlledDhcpv6Srv::establishSession() {
-
+
string specfile;
if (getenv("B10_FROM_BUILD")) {
specfile = string(getenv("B10_FROM_BUILD")) +
@@ -96,15 +104,27 @@ void ControlledDhcpv6Srv::establishSession() {
}
/// @todo: Check if session is not established already. Throw, if it is.
-
+
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_CCSESSION_STARTING)
.arg(specfile);
cc_session_ = new Session(io_service_.get_io_service());
config_session_ = new ModuleCCSession(specfile, *cc_session_,
- dhcp6ConfigHandler,
+ NULL,
dhcp6CommandHandler, false);
config_session_->start();
+ // We initially create ModuleCCSession() without configHandler, as
+ // the session module is too eager to send partial configuration.
+ // We want to get the full configuration, so we explicitly call
+ // getFullConfig() and then pass it to our configHandler.
+ config_session_->setConfigHandler(dhcp6ConfigHandler);
+
+ try {
+ configureDhcp6Server(*this, config_session_->getFullConfig());
+ } catch (const Dhcp6ConfigError& ex) {
+ LOG_ERROR(dhcp6_logger, DHCP6_CONFIG_LOAD_FAIL).arg(ex.what());
+ }
+
/// Integrate the asynchronous I/O model of BIND 10 configuration
/// control with the "select" model of the DHCP server. This is
/// fully explained in \ref dhcpv6Session.
diff --git a/src/bin/dhcp6/dhcp6.dox b/src/bin/dhcp6/dhcp6.dox
new file mode 100644
index 0000000..ff47e31
--- /dev/null
+++ b/src/bin/dhcp6/dhcp6.dox
@@ -0,0 +1,79 @@
+/**
+ @page dhcpv6 DHCPv6 Server Component
+
+ BIND10 offers DHCPv6 server implementation. It is implemented as
+ b10-dhcp6 component. Its primary code is located in
+ isc::dhcp::Dhcpv6Srv class. It uses \ref libdhcp extensively,
+ especially lib::dhcp::Pkt6, isc::dhcp::Option and
+ isc::dhcp::IfaceMgr classes. Currently this code offers skeleton
+ functionality, i.e. it is able to receive and process incoming
+ requests and trasmit responses. However, it does not have database
+ management, so it returns only one, hardcoded lease to whoever asks
+ for it.
+
+ DHCPv6 server component does not support relayed traffic yet, as
+ support for relay decapsulation is not implemented yet.
+
+ DHCPv6 server component does not use BIND10 logging yet.
+
+ @section dhcpv6-session BIND10 message queue integration
+
+ DHCPv4 server component is now integrated with BIND10 message queue.
+ It follows the same principle as DHCPv4. See \ref dhcpv4Session for
+ details.
+
+ @section dhcpv6-config-parser Configuration Parser in DHCPv6
+
+ b10-dhcp6 component uses BIND10 cfgmgr for commands and configuration. During
+ initial configuration (See \ref
+ isc::dhcp::ControlledDhcpv6Srv::establishSession()), the configuration handler
+ callback is installed (see isc::dhcp::ControlledDhcpv6Srv::dhcp6ConfigHandler().
+ It is called every time there is a new configuration. In particular, it is
+ called every time during daemon start process. It contains a
+ isc::data::ConstElementPtr to a new configuration. This simple handler calls
+ \ref isc::dhcp::configureDhcp6Server() method that processes received configuration.
+
+ This method iterates over list of received configuration elements and creates a
+ list of parsers for each received entry. Parser is an object that is derived
+ from a \ref isc::dhcp::DhcpConfigParser class. Once a parser is created
+ (constructor), its value is set (using build() method). Once all parsers are
+ build, the configuration is then applied ("commited") and commit() method is
+ called.
+
+ All parsers are defined in src/bin/dhcp6/config_parser.cc file. Some of them
+ are generic (e.g. \ref isc::dhcp::Uint32Parser that is able to handle any
+ unsigned 32 bit integer), but some are very specialized (e.g. \ref
+ isc::dhcp::Subnets6ListConfigParser parses definitions of Subnet6 lists). In
+ some cases, e.g. subnet6 definitions, the configuration entry is not a simple
+ value, but a map or a list itself. In such case, the parser iterates over all
+ elements and creates parsers for a given scope. This process may be repeated
+ (sort of) recursively.
+
+ @section dhcpv6-config-inherit DHCPv6 Configuration Inheritance
+
+ One notable useful feature of DHCP configuration is its parameter inheritance.
+ For example, renew-timer value may be specified at a global scope and it then
+ applies to all subnets. However, some subnets may have it overwritten with more
+ specific values that takes precedence over global values that are considered
+ defaults. Some parsers (e.g. \ref isc::dhcp::Uint32Parser and \ref
+ isc::dhcp::StringParser) implement that inheritance. By default, they store
+ values in global uint32_defaults and string_defaults storages. However, it is
+ possible to instruct them to store parsed values in more specific
+ storages. That capability is used, e.g. in \ref isc::dhcp::Subnet6ConfigParser
+ that has its own storage that is unique for each subnet. Finally, during commit
+ phase (commit() method), appropriate parsers can use apply parameter inheritance.
+
+ Debugging configuration parser may be confusing. Therefore there is a special
+ class called \ref isc::dhcp::DebugParser. It does not configure anything, but just
+ accepts any parameter of any type. If requested to commit configuration, it will
+ print out received parameter name and its value. This class is not currently used,
+ but it is convenient to have it every time a new parameter is added to DHCP
+ configuration. For that purpose it should be left in the code.
+
+ Parameter inheritance is done during reconfiguration phase, as reconfigurations
+ are rare, so extra logic here is not a problem. On the other hand, values of
+ those parameters may be used thousands times per second, so its use must be as
+ simple as possible. In fact, currently the code has to call Subnet6->getT1() and
+ do not implement any fancy inheritance logic.
+
+ */
diff --git a/src/bin/dhcp6/dhcp6.spec b/src/bin/dhcp6/dhcp6.spec
index 2a82a2d..f35f606 100644
--- a/src/bin/dhcp6/dhcp6.spec
+++ b/src/bin/dhcp6/dhcp6.spec
@@ -4,9 +4,97 @@
"module_description": "DHCPv6 server daemon",
"config_data": [
{ "item_name": "interface",
- "item_type": "string",
+ "item_type": "list",
"item_optional": false,
- "item_default": "eth0"
+ "item_default": [ "all" ],
+ "list_item_spec":
+ {
+ "item_name": "interface_name",
+ "item_type": "string",
+ "item_optional": false,
+ "item_default": "all"
+ }
+ } ,
+
+ { "item_name": "renew-timer",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 1000
+ },
+
+ { "item_name": "rebind-timer",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 2000
+ },
+
+ { "item_name": "preferred-lifetime",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 3000
+ },
+
+ { "item_name": "valid-lifetime",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 4000
+ },
+
+ { "item_name": "subnet6",
+ "item_type": "list",
+ "item_optional": false,
+ "item_default": [],
+ "list_item_spec":
+ {
+ "item_name": "single-subnet6",
+ "item_type": "map",
+ "item_optional": false,
+ "item_default": {},
+ "map_item_spec": [
+
+ { "item_name": "subnet",
+ "item_type": "string",
+ "item_optional": false,
+ "item_default": ""
+ },
+
+ { "item_name": "renew-timer",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 1000
+ },
+
+ { "item_name": "rebind-timer",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 2000
+ },
+
+ { "item_name": "preferred-lifetime",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 3000
+ },
+
+ { "item_name": "valid-lifetime",
+ "item_type": "integer",
+ "item_optional": false,
+ "item_default": 7200
+ },
+ { "item_name": "pool",
+ "item_type": "list",
+ "item_optional": false,
+ "item_default": [],
+ "list_item_spec":
+ {
+ "item_name": "type",
+ "item_type": "string",
+ "item_optional": false,
+ "item_default": ""
+ }
+ }
+ ]
+ }
}
],
"commands": [
diff --git a/src/bin/dhcp6/dhcp6_log.h b/src/bin/dhcp6/dhcp6_log.h
index 6d7f4e3..fb3c3f9 100644
--- a/src/bin/dhcp6/dhcp6_log.h
+++ b/src/bin/dhcp6/dhcp6_log.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DHCP6_LOG__H
-#define __DHCP6_LOG__H
+#ifndef DHCP6_LOG_H
+#define DHCP6_LOG_H
#include <log/macros.h>
#include <log/logger_support.h>
@@ -56,4 +56,4 @@ extern isc::log::Logger dhcp6_logger;
} // namespace dhcp6
} // namespace isc
-#endif // __DHCP6_LOG__H
+#endif // DHCP6_LOG_H
diff --git a/src/bin/dhcp6/dhcp6_messages.mes b/src/bin/dhcp6/dhcp6_messages.mes
index 1564940..2399c19 100644
--- a/src/bin/dhcp6/dhcp6_messages.mes
+++ b/src/bin/dhcp6/dhcp6_messages.mes
@@ -109,3 +109,23 @@ processed any command-line switches and is starting.
This is a debug message issued during the IPv6 DHCP server startup.
It lists some information about the parameters with which the server
is running.
+
+% DHCP6_CONFIG_LOAD_FAIL failed to load configuration: %1
+This critical error message indicates that the initial DHCPv6
+configuration has failed. The server will start, but nothing will be
+served until the configuration has been corrected.
+
+% DHCP6_CONFIG_START DHCPv6 server is processing the following configuration: %1
+This is a debug message that is issued every time the server receives a
+configuration. That happens start up and also when a server configuration
+change is committed by the administrator.
+
+% DHCP6_CONFIG_NEW_SUBNET A new subnet has been added to configuration: %1
+This is an informational message reporting that the configuration has
+been extended to include the specified subnet.
+
+% DHCP6_CONFIG_COMPLETE DHCPv6 server has completed configuration: %1
+This is an informational message announcing the successful processing of a
+new configuration. it is output during server startup, and when an updated
+configuration is committed by the administrator. Additional information
+may be provided.
diff --git a/src/bin/dhcp6/dhcp6_srv.cc b/src/bin/dhcp6/dhcp6_srv.cc
index 54fa2b5..7c57a61 100644
--- a/src/bin/dhcp6/dhcp6_srv.cc
+++ b/src/bin/dhcp6/dhcp6_srv.cc
@@ -42,6 +42,13 @@ const uint32_t HARDCODED_VALID_LIFETIME = 7200; // in seconds
const std::string HARDCODED_DNS_SERVER = "2001:db8:1::1";
Dhcpv6Srv::Dhcpv6Srv(uint16_t port) {
+ if (port == 0) {
+ // used for testing purposes. Some tests, e.g. configuration parser,
+ // require Dhcpv6Srv object, but they don't really need it to do
+ // anything. This speed up and simplifies the tests.
+ return;
+ }
+
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_START, DHCP6_OPEN_SOCKET).arg(port);
// First call to instance() will create IfaceMgr (it's a singleton)
diff --git a/src/bin/dhcp6/tests/Makefile.am b/src/bin/dhcp6/tests/Makefile.am
index 1d9308f..1629ae6 100644
--- a/src/bin/dhcp6/tests/Makefile.am
+++ b/src/bin/dhcp6/tests/Makefile.am
@@ -15,6 +15,7 @@ check-local:
for pytest in $(PYTESTS) ; do \
echo Running test: $$pytest ; \
$(LIBRARY_PATH_PLACEHOLDER) \
+ B10_LOCKFILE_DIR_FROM_BUILD=$(abs_top_builddir) \
PYTHONPATH=$(COMMON_PYTHON_PATH):$(abs_top_srcdir)/src/bin:$(abs_top_builddir)/src/bin/bind10:$(abs_top_builddir)/src/lib/util/io/.libs \
$(PYCOVERAGE_RUN) $(abs_srcdir)/$$pytest || exit ; \
done
@@ -45,9 +46,11 @@ TESTS += dhcp6_unittests
dhcp6_unittests_SOURCES = dhcp6_unittests.cc
dhcp6_unittests_SOURCES += dhcp6_srv_unittest.cc
dhcp6_unittests_SOURCES += ctrl_dhcp6_srv_unittest.cc
+dhcp6_unittests_SOURCES += config_parser_unittest.cc
dhcp6_unittests_SOURCES += ../dhcp6_srv.h ../dhcp6_srv.cc
dhcp6_unittests_SOURCES += ../dhcp6_log.h ../dhcp6_log.cc
dhcp6_unittests_SOURCES += ../ctrl_dhcp6_srv.cc
+dhcp6_unittests_SOURCES += ../config_parser.cc ../config_parser.h
nodist_dhcp6_unittests_SOURCES = ../dhcp6_messages.h ../dhcp6_messages.cc
if USE_CLANGPP
@@ -61,6 +64,7 @@ dhcp6_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
dhcp6_unittests_LDADD = $(GTEST_LDADD)
dhcp6_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
dhcp6_unittests_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcp++.la
+dhcp6_unittests_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcpsrv.la
dhcp6_unittests_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
dhcp6_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
dhcp6_unittests_LDADD += $(top_builddir)/src/lib/config/libb10-cfgclient.la
diff --git a/src/bin/dhcp6/tests/config_parser_unittest.cc b/src/bin/dhcp6/tests/config_parser_unittest.cc
new file mode 100644
index 0000000..22592e8
--- /dev/null
+++ b/src/bin/dhcp6/tests/config_parser_unittest.cc
@@ -0,0 +1,243 @@
+// 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 <iostream>
+#include <fstream>
+#include <sstream>
+
+#include <arpa/inet.h>
+#include <gtest/gtest.h>
+
+#include <dhcp6/dhcp6_srv.h>
+#include <dhcp6/config_parser.h>
+#include <config/ccsession.h>
+#include <dhcp/subnet.h>
+#include <dhcp/cfgmgr.h>
+
+using namespace std;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+using namespace isc::data;
+using namespace isc::config;
+
+namespace {
+
+class Dhcp6ParserTest : public ::testing::Test {
+public:
+ Dhcp6ParserTest()
+ :rcode_(-1) {
+ // Open port 0 means to not do anything at all. We don't want to
+ // deal with sockets here, just check if configuration handling
+ // is sane.
+ srv_ = new Dhcpv6Srv(0);
+ }
+
+ ~Dhcp6ParserTest() {
+ delete srv_;
+ };
+
+ Dhcpv6Srv* srv_;
+
+ int rcode_;
+ ConstElementPtr comment_;
+};
+
+// Goal of this test is a verification if a very simple config update
+// with just a bumped version number. That's the simplest possible
+// config update.
+TEST_F(Dhcp6ParserTest, version) {
+
+ ConstElementPtr x;
+
+ EXPECT_NO_THROW(x = configureDhcp6Server(*srv_,
+ Element::fromJSON("{\"version\": 0}")));
+
+ // returned value must be 0 (configuration accepted)
+ ASSERT_TRUE(x);
+ comment_ = parseAnswer(rcode_, x);
+ EXPECT_EQ(0, rcode_);
+}
+
+/// The goal of this test is to verify that the code accepts only
+/// valid commands and malformed or unsupported parameters are rejected.
+TEST_F(Dhcp6ParserTest, bogus_command) {
+
+ ConstElementPtr x;
+
+ EXPECT_NO_THROW(x = configureDhcp6Server(*srv_,
+ Element::fromJSON("{\"bogus\": 5}")));
+
+ // returned value must be 1 (configuration parse error)
+ ASSERT_TRUE(x);
+ comment_ = parseAnswer(rcode_, x);
+ EXPECT_EQ(1, rcode_);
+}
+
+/// The goal of this test is to verify if wrongly defined subnet will
+/// be rejected. Properly defined subnet must include at least one
+/// pool definition.
+TEST_F(Dhcp6ParserTest, empty_subnet) {
+
+ ConstElementPtr status;
+
+ EXPECT_NO_THROW(status = configureDhcp6Server(*srv_,
+ Element::fromJSON("{ \"interface\": [ \"all\" ],"
+ "\"preferred-lifetime\": 3000,"
+ "\"rebind-timer\": 2000, "
+ "\"renew-timer\": 1000, "
+ "\"subnet6\": [ ], "
+ "\"valid-lifetime\": 4000 }")));
+
+ // returned value should be 0 (success)
+ ASSERT_TRUE(status);
+ comment_ = parseAnswer(rcode_, status);
+ EXPECT_EQ(0, rcode_);
+}
+
+/// The goal of this test is to verify if defined subnet uses global
+/// parameter timer definitions.
+TEST_F(Dhcp6ParserTest, subnet_global_defaults) {
+
+ ConstElementPtr status;
+
+ string config = "{ \"interface\": [ \"all\" ],"
+ "\"preferred-lifetime\": 3000,"
+ "\"rebind-timer\": 2000, "
+ "\"renew-timer\": 1000, "
+ "\"subnet6\": [ { "
+ " \"pool\": [ \"2001:db8:1::1 - 2001:db8:1::ffff\" ],"
+ " \"subnet\": \"2001:db8:1::/64\" } ],"
+ "\"valid-lifetime\": 4000 }";
+ cout << config << endl;
+
+ ElementPtr json = Element::fromJSON(config);
+
+ EXPECT_NO_THROW(status = configureDhcp6Server(*srv_, json));
+
+ // check if returned status is OK
+ ASSERT_TRUE(status);
+ comment_ = parseAnswer(rcode_, status);
+ EXPECT_EQ(0, rcode_);
+
+ // Now check if the configuration was indeed handled and we have
+ // expected pool configured.
+ Subnet6Ptr subnet = CfgMgr::instance().getSubnet6(IOAddress("2001:db8:1::5"));
+ ASSERT_TRUE(subnet);
+ EXPECT_EQ(1000, subnet->getT1());
+ EXPECT_EQ(2000, subnet->getT2());
+ EXPECT_EQ(3000, subnet->getPreferred());
+ EXPECT_EQ(4000, subnet->getValid());
+}
+
+// This test checks if it is possible to override global values
+// on a per subnet basis.
+TEST_F(Dhcp6ParserTest, subnet_local) {
+
+ ConstElementPtr status;
+
+ string config = "{ \"interface\": [ \"all\" ],"
+ "\"preferred-lifetime\": 3000,"
+ "\"rebind-timer\": 2000, "
+ "\"renew-timer\": 1000, "
+ "\"subnet6\": [ { "
+ " \"pool\": [ \"2001:db8:1::1 - 2001:db8:1::ffff\" ],"
+ " \"renew-timer\": 1, "
+ " \"rebind-timer\": 2, "
+ " \"preferred-lifetime\": 3,"
+ " \"valid-lifetime\": 4,"
+ " \"subnet\": \"2001:db8:1::/64\" } ],"
+ "\"valid-lifetime\": 4000 }";
+ cout << config << endl;
+
+ ElementPtr json = Element::fromJSON(config);
+
+ EXPECT_NO_THROW(status = configureDhcp6Server(*srv_, json));
+
+ // returned value should be 0 (configuration success)
+ ASSERT_TRUE(status);
+ comment_ = parseAnswer(rcode_, status);
+ EXPECT_EQ(0, rcode_);
+
+ Subnet6Ptr subnet = CfgMgr::instance().getSubnet6(IOAddress("2001:db8:1::5"));
+ ASSERT_TRUE(subnet);
+ EXPECT_EQ(1, subnet->getT1());
+ EXPECT_EQ(2, subnet->getT2());
+ EXPECT_EQ(3, subnet->getPreferred());
+ EXPECT_EQ(4, subnet->getValid());
+}
+
+// Test verifies that a subnet with pool values that do not belong to that
+// pool are rejected.
+TEST_F(Dhcp6ParserTest, pool_out_of_subnet) {
+
+ ConstElementPtr status;
+
+ string config = "{ \"interface\": [ \"all\" ],"
+ "\"preferred-lifetime\": 3000,"
+ "\"rebind-timer\": 2000, "
+ "\"renew-timer\": 1000, "
+ "\"subnet6\": [ { "
+ " \"pool\": [ \"4001:db8:1::/80\" ],"
+ " \"subnet\": \"2001:db8:1::/64\" } ],"
+ "\"valid-lifetime\": 4000 }";
+ cout << config << endl;
+
+ ElementPtr json = Element::fromJSON(config);
+
+ EXPECT_NO_THROW(status = configureDhcp6Server(*srv_, json));
+
+ // returned value must be 2 (values error)
+ // as the pool does not belong to that subnet
+ ASSERT_TRUE(status);
+ comment_ = parseAnswer(rcode_, status);
+ EXPECT_EQ(2, rcode_);
+}
+
+// Goal of this test is to verify if pools can be defined
+// using prefix/length notation. There is no separate test for min-max
+// notation as it was tested in several previous tests.
+TEST_F(Dhcp6ParserTest, pool_prefix_len) {
+
+ ConstElementPtr x;
+
+ string config = "{ \"interface\": [ \"all\" ],"
+ "\"preferred-lifetime\": 3000,"
+ "\"rebind-timer\": 2000, "
+ "\"renew-timer\": 1000, "
+ "\"subnet6\": [ { "
+ " \"pool\": [ \"2001:db8:1::/80\" ],"
+ " \"subnet\": \"2001:db8:1::/64\" } ],"
+ "\"valid-lifetime\": 4000 }";
+ cout << config << endl;
+
+ ElementPtr json = Element::fromJSON(config);
+
+ EXPECT_NO_THROW(x = configureDhcp6Server(*srv_, json));
+
+ // returned value must be 1 (configuration parse error)
+ ASSERT_TRUE(x);
+ comment_ = parseAnswer(rcode_, x);
+ EXPECT_EQ(0, rcode_);
+
+ Subnet6Ptr subnet = CfgMgr::instance().getSubnet6(IOAddress("2001:db8:1::5"));
+ ASSERT_TRUE(subnet);
+ EXPECT_EQ(1000, subnet->getT1());
+ EXPECT_EQ(2000, subnet->getT2());
+ EXPECT_EQ(3000, subnet->getPreferred());
+ EXPECT_EQ(4000, subnet->getValid());
+}
+
+};
diff --git a/src/bin/host/.gitignore b/src/bin/host/.gitignore
deleted file mode 100644
index 01ef357..0000000
--- a/src/bin/host/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/b10-host
-/b10-host.1
diff --git a/src/bin/host/Makefile.am b/src/bin/host/Makefile.am
deleted file mode 100644
index 42ef954..0000000
--- a/src/bin/host/Makefile.am
+++ /dev/null
@@ -1,37 +0,0 @@
-AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
-AM_CPPFLAGS += -I$(top_srcdir)/src/lib/dns -I$(top_builddir)/src/lib/dns
-AM_CPPFLAGS += $(BOOST_INCLUDES)
-
-AM_CXXFLAGS = $(B10_CXXFLAGS)
-
-if USE_STATIC_LINK
-AM_LDFLAGS = -static
-endif
-
-CLEANFILES = *.gcno *.gcda
-
-bin_PROGRAMS = b10-host
-b10_host_SOURCES = host.cc
-b10_host_LDADD = $(top_builddir)/src/lib/dns/libb10-dns++.la
-b10_host_LDADD += $(top_builddir)/src/lib/util/libb10-util.la
-b10_host_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
-
-man_MANS = b10-host.1
-DISTCLEANFILES = $(man_MANS)
-EXTRA_DIST = $(man_MANS) b10-host.xml
-
-.PHONY: man
-if GENERATE_DOCS
-
-man: b10-host.1
-
-b10-host.1: b10-host.xml
- @XSLTPROC@ --novalid --xinclude --nonet -o $@ http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl $(srcdir)/b10-host.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
diff --git a/src/bin/host/README b/src/bin/host/README
deleted file mode 100644
index 5cc4068..0000000
--- a/src/bin/host/README
+++ /dev/null
@@ -1,4 +0,0 @@
-Rewriting host(1) in C++ from scratch using BIND 10's libdns++.
-
-The bugs and incompatibilities are listed in the manual page
-and in the source code.
diff --git a/src/bin/host/b10-host.xml b/src/bin/host/b10-host.xml
deleted file mode 100644
index a17ef67..0000000
--- a/src/bin/host/b10-host.xml
+++ /dev/null
@@ -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 "—">]>
-<!--
- - 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.
--->
-
-<!-- $Id$ -->
-<refentry>
-
- <refentryinfo>
- <date>May 4, 2011</date>
- </refentryinfo>
-
- <refmeta>
- <refentrytitle>b10-host</refentrytitle>
- <manvolnum>1</manvolnum>
- <refmiscinfo>BIND10</refmiscinfo>
- </refmeta>
-
- <refnamediv>
- <refname>b10-host</refname>
- <refpurpose>DNS lookup utility</refpurpose>
- </refnamediv>
-
- <docinfo>
- <copyright>
- <year>2011</year>
- <holder>Internet Systems Consortium, Inc. ("ISC")</holder>
- </copyright>
- </docinfo>
-
- <refsynopsisdiv>
- <cmdsynopsis>
- <command>b10-host</command>
- <arg><option>-a</option></arg>
- <arg><option>-c <replaceable>class</replaceable></option></arg>
- <arg><option>-d</option></arg>
- <arg><option>-p <replaceable>port</replaceable></option></arg>
- <arg><option>-r</option></arg>
- <arg><option>-t <replaceable>type</replaceable></option></arg>
- <arg><option>-v</option></arg>
- <arg><replaceable>name</replaceable></arg>
- <arg><option><replaceable>server</replaceable></option></arg>
- </cmdsynopsis>
- </refsynopsisdiv>
-
- <refsect1>
- <title>DESCRIPTION</title>
- <para>
- The <command>b10-host</command> utility does DNS lookups.
- Its initial goal is to be a
- <citerefentry><refentrytitle>host</refentrytitle>
- <manvolnum>1</manvolnum></citerefentry>
- clone, but also add a few features useful for BIND 10 development
- testing.
- </para>
-
- <para>
- By default, it looks up the A, AAAA, and MX record sets for the
- <replaceable>name</replaceable>.
- Optionally, you may select a name server to query against by adding
- the <replaceable>server</replaceable> argument.
- </para>
- </refsect1>
-
- <refsect1>
- <title>OPTIONS</title>
-
- <para>The arguments are as follows:</para>
-
- <variablelist>
-
- <varlistentry>
- <term><option>-a</option></term>
- <listitem><para>
- Enable verbose mode and do a query for type ANY.
- (If the <option>-t</option> option is also set, then the
- ANY query is not done, but it still uses verbose mode.)
- </para></listitem>
- </varlistentry>
-
- <varlistentry>
- <term><option>-c <replaceable>class</replaceable></option></term>
- <listitem><para>
- Define the class for the query.
- The default is IN (Internet).
-<!-- TODO: bug if class is unknown causes seg fault and possible core dump -->
- </para></listitem>
- </varlistentry>
-
- <varlistentry>
- <term><option>-d</option></term>
- <listitem><para>
- Enable verbose output mode, including elapsed time in
- milliseconds.
- Verbose mode shows the header, question, answer, authority,
- and additional sections (if provided).
- (Same as <option>-v</option>.)
- </para></listitem>
- </varlistentry>
-
- <varlistentry>
- <term><option>-p <replaceable>port</replaceable></option></term>
- <listitem><para>
- Select an alternative port for the query.
- This may be a number or a service name.
- The default is 53 (domain).
- This is not a standard feature of
- <citerefentry><refentrytitle>host</refentrytitle>
- <manvolnum>1</manvolnum></citerefentry>.
- </para></listitem>
- </varlistentry>
-
- <varlistentry>
- <term><option>-r</option></term>
- <listitem><para>
- Disable recursive processing by not setting the
- Recursion Desired flag in the query.
- </para></listitem>
- </varlistentry>
-
- <varlistentry>
- <term><option>-t <replaceable>type</replaceable></option></term>
- <listitem><para>
- Select a specific resource record type for the query.
- By default, it looks up the A, AAAA, and MX record sets.
-<!-- TODO: bug if class is unknown causes seg fault and possible core dump -->
- (This overrides the <option>-a</option> option.)
- </para></listitem>
- </varlistentry>
-
- <varlistentry>
- <term><option>-v</option></term>
- <listitem><para>
- Same as <option>-d</option> option.
- </para></listitem>
- </varlistentry>
-
- </variablelist>
-
- </refsect1>
-
- <refsect1>
- <title>COMPATIBILITY / BUGS</title>
- <para>
- <command>b10-host</command> does not do reverse lookups by
- default yet (by detecting if name is a IPv4 or IPv6 address).
- </para>
-
- <para>
- Unknown <option>-c</option> class or <option>-t</option> type
- causes <command>b10-host</command> to Abort.
- </para>
-
- <para>
- Not all types are supported yet for formatting.
- Not all switches are supported yet.
- </para>
-
- <para>
- It doesn't use <filename>/etc/resolv.conf</filename> at this time.
- The default name server used is 127.0.0.1.
- </para>
-
- <para>
- <option>-p</option> is not a standard feature.
- </para>
- </refsect1>
-
- <refsect1>
- <title>HISTORY</title>
- <para>
- The C++ version of <command>b10-host</command> was started in
- October 2009 by Jeremy C. Reed of ISC.
- Its usage and output were based on the standard <command>host</command>
- command.
- </para>
- </refsect1>
-</refentry><!--
- - Local variables:
- - mode: sgml
- - End:
--->
diff --git a/src/bin/host/host.cc b/src/bin/host/host.cc
deleted file mode 100644
index a5c6522..0000000
--- a/src/bin/host/host.cc
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright (C) 2010-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.
-
-// host rewritten in C++ using BIND 10 DNS library
-
-#include <arpa/inet.h>
-#include <netdb.h> // for getaddrinfo
-#include <sys/time.h> // for gettimeofday
-#include <sys/socket.h> // networking functions and definitions on FreeBSD
-
-#include <unistd.h>
-
-#include <string>
-#include <iostream>
-
-#include <util/buffer.h>
-
-#include <dns/name.h>
-#include <dns/message.h>
-#include <dns/messagerenderer.h>
-#include <dns/opcode.h>
-#include <dns/rcode.h>
-#include <dns/rrclass.h>
-#include <dns/rrtype.h>
-#include <dns/rrset.h>
-#include <dns/message.h>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::util;
-
-namespace {
-char* dns_type = NULL; // not set, so A, AAAA, MX
-const char* server = "127.0.0.1";
-const char* server_port = "53";
-const char* dns_class = "IN";
-bool verbose = false;
-bool dns_any = false;
-int first_time = 1;
-bool recursive_bit = true;
-struct timeval before_time, after_time;
-
-int
-host_lookup(const char* const name, const char* const dns_class,
- const char* const type, bool any) {
-
- Message msg(Message::RENDER);
-
- msg.setQid(0); // does this matter?
-
- // TODO: add switch for this
- msg.setOpcode(Opcode::QUERY());
- msg.setRcode(Rcode::NOERROR());
- if (recursive_bit) {
- msg.setHeaderFlag(Message::HEADERFLAG_RD); // set recursive bit
- }
-
- msg.addQuestion(Question(Name(name),
- RRClass(dns_class),
- any ? RRType::ANY() : RRType(type))); // if NULL then:
-
- MessageRenderer renderer;
- msg.toWire(renderer);
-
- struct addrinfo hints, *res;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = SOCK_DGRAM;
- hints.ai_flags = 0; // not using AI_NUMERICHOST in case to bootstrap
- if (getaddrinfo(server, server_port, &hints, &res) != 0) {
- cerr << "address/port conversion for " << server << ":"
- << server_port << " failed" << endl;
- return (1);
- }
-
- if (verbose) {
- cout << "Trying \"" << name << "\"\n";
- }
-
- if (verbose && first_time) {
- // this is only output the first time
- first_time = 0;
- cout << "Using domain server:\n";
- cout << "Name: " << server << "\n";
- // TODO: I guess I have to do a lookup to get that address and aliases
- // too
- //cout << "Address: " << address << "\n" ; // "#" << port << "\n";
- //cout << "Aliases: " << server << "\n";
- }
-
- int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
-
- if (s < 0) {
- cerr << "failed to open socket" << endl;
- return (1);
- }
-
- if (verbose) {
- gettimeofday(&before_time, NULL);
- }
-
- sendto(s, renderer.getData(), renderer.getLength(), 0, res->ai_addr,
- res->ai_addrlen);
-
- struct sockaddr_storage ss;
- struct sockaddr* sa;
- socklen_t sa_len;
-
- sa_len = sizeof(ss);
- sa = static_cast<struct sockaddr*>((void*)&ss);
-
- char recvbuf[4096];
- int cc;
- if ((cc = recvfrom(s, recvbuf, sizeof(recvbuf), 0, sa, &sa_len)) > 0) {
- try {
- Message rmsg(Message::PARSE);
- InputBuffer ibuffer(recvbuf, cc);
-
- rmsg.fromWire(ibuffer);
- if (!verbose) {
- string description = "";
- for (RRsetIterator it =
- rmsg.beginSection(Message::SECTION_ANSWER);
- it != rmsg.endSection(Message::SECTION_ANSWER);
- ++it) {
-
- if ((*it)->getType() == RRType::A()) {
- description = "has address";
- }
- else if ((*it)->getType() == RRType::AAAA()) {
- description = "has IPv6 address";
- }
- else if ((*it)->getType() == RRType::MX()) {
- description = "mail is handled by";
- }
- else if ((*it)->getType() == RRType::TXT()) {
- description = "descriptive text";
- }
-
- RdataIteratorPtr rit = (*it)->getRdataIterator();
- for (; !rit->isLast(); rit->next()) {
- // instead of using my name, maybe use returned label?
- cout << name << " " << description << " " <<
- (*rit).getCurrent().toText() << endl;
- }
- }
- } else {
- gettimeofday(&after_time, NULL);
-
- // HEADER and QUESTION, ANSWER, AUTHORITY, and ADDITIONAL
- std::cout << rmsg.toText() << std::endl;
-
- if (before_time.tv_usec > after_time.tv_usec) {
- after_time.tv_usec += 1000000;
- --after_time.tv_sec;
- }
-
- int elapsed_time =
- (after_time.tv_sec - before_time.tv_sec)
- + ((after_time.tv_usec - before_time.tv_usec))/1000;
-
- // TODO: if NXDOMAIN, host(1) doesn't show HEADER
- // Host hsdjkfhksjhdfkj not found: 3(NXDOMAIN)
- // TODO: test if NXDOMAIN
-
- std::cout << "Received " << cc <<
- " bytes in " << elapsed_time << " ms\n";
- // TODO: " bytes from 127.0.0.1#53 in 0 ms
-
- } //verbose
-/*
-TODO: handle InvalidRRClass
-TODO: handle invalid type exception
- } catch (InvalidType ivt) {
- std::cerr << "invalid type:" << ivt.what();
-*/
- } catch (const exception& ex) {
- std::cerr << "parse failed for " <<
- string(name) << "/" << type << ": " << ex.what() << std::endl;
- } catch (...) {
- std::cerr << "parse failed for " << string(name) << "/" << type;
- }
- }
-
- freeaddrinfo(res);
-
- return (0);
-} // host_lookup()
-}
-
-int
-main(int argc, char* argv[]) {
- int c;
-
- while ((c = getopt(argc, argv, "ac:dp:rt:v")) != -1)
- switch (c) {
- case 'a':
- dns_any = true;
- verbose = true;
- break;
- case 'c':
- dns_class = optarg;
- break;
- // p for port is a non-standard switch
- case 'p':
- server_port = optarg;
- break;
- case 'r':
- recursive_bit = false;
- break;
- case 't':
- dns_type = optarg;
- break;
- case 'd':
- // drop through to v, because debug and verbose are equivalent
- case 'v':
- verbose = true;
- break;
- }
- argc -= optind;
- argv += optind;
-
- if (argc < 1) {
- cout << "Usage: host [-adrv] [-c class] [-p port] [-t type] hostname [server]\n";
- exit(1);
- }
-
- if (argc >= 2) {
- server = argv[1];
- }
-
- if (dns_type == NULL) {
- host_lookup(argv[0], dns_class, "A", dns_any);
- // TODO: don't do next if A doesn't exist
- host_lookup(argv[0], dns_class, "AAAA", dns_any);
- host_lookup(argv[0], dns_class, "MX", dns_any);
- } else {
- // -t overrides -a, regardless of order
- host_lookup(argv[0], dns_class, dns_type, false);
- }
- return (0);
-}
diff --git a/src/bin/resolver/resolver.h b/src/bin/resolver/resolver.h
index e91192e..cc0f09f 100644
--- a/src/bin/resolver/resolver.h
+++ b/src/bin/resolver/resolver.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RESOLVER_H
-#define __RESOLVER_H 1
+#ifndef RESOLVER_H
+#define RESOLVER_H 1
#include <string>
#include <vector>
@@ -266,7 +266,7 @@ private:
isc::cache::ResolverCache* cache_;
};
-#endif // __RESOLVER_H
+#endif // RESOLVER_H
// Local Variables:
// mode: c++
diff --git a/src/bin/resolver/resolver_log.h b/src/bin/resolver/resolver_log.h
index e0e3fda..a4b6c44 100644
--- a/src/bin/resolver/resolver_log.h
+++ b/src/bin/resolver/resolver_log.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RESOLVER_LOG__H
-#define __RESOLVER_LOG__H
+#ifndef RESOLVER_LOG_H
+#define RESOLVER_LOG_H
#include <log/macros.h>
#include "resolver_messages.h"
@@ -46,4 +46,4 @@ const int RESOLVER_DBG_DETAIL = DBGLVL_TRACE_DETAIL_DATA;
/// space.
extern isc::log::Logger resolver_logger;
-#endif // __RESOLVER_LOG__H
+#endif // RESOLVER_LOG_H
diff --git a/src/bin/resolver/resolver_messages.mes b/src/bin/resolver/resolver_messages.mes
index 34a97ae..214519b 100644
--- a/src/bin/resolver/resolver_messages.mes
+++ b/src/bin/resolver/resolver_messages.mes
@@ -108,7 +108,7 @@ This error is issued when a resolver configuration update has specified
a negative retry count: only zero or positive values are valid. The
configuration update was abandoned and the parameters were not changed.
-% RESOLVER_NON_IN_PACKET non-IN class request received, returning REFUSED message
+% RESOLVER_NON_IN_PACKET non-IN class (%1) request received, returning REFUSED message
This debug message is issued when resolver has received a DNS packet that
was not IN (Internet) class. The resolver cannot handle such packets,
so is returning a REFUSED response to the sender.
diff --git a/src/bin/resolver/response_scrubber.h b/src/bin/resolver/response_scrubber.h
index c59ac15..cb80b26 100644
--- a/src/bin/resolver/response_scrubber.h
+++ b/src/bin/resolver/response_scrubber.h
@@ -14,8 +14,8 @@
// $Id$
-#ifndef __RESPONSE_SCRUBBER_H
-#define __RESPONSE_SCRUBBER_H
+#ifndef RESPONSE_SCRUBBER_H
+#define RESPONSE_SCRUBBER_H
/// \page DataScrubbing Data Scrubbing
/// \section DataScrubbingIntro Introduction
@@ -419,4 +419,4 @@ public:
}
};
-#endif // __RESPONSE_SCRUBBER_H
+#endif // RESPONSE_SCRUBBER_H
diff --git a/src/bin/sockcreator/sockcreator.h b/src/bin/sockcreator/sockcreator.h
index e5d4783..8e32c48 100644
--- a/src/bin/sockcreator/sockcreator.h
+++ b/src/bin/sockcreator/sockcreator.h
@@ -18,8 +18,8 @@
/// This module holds the functionality of the socket creator. It is a separate
/// module from main to make testing easier.
-#ifndef __SOCKCREATOR_H
-#define __SOCKCREATOR_H 1
+#ifndef SOCKCREATOR_H
+#define SOCKCREATOR_H 1
#include <util/io/fd_share.h>
#include <exceptions/exceptions.h>
@@ -144,4 +144,4 @@ run(const int input_fd, const int output_fd, get_sock_t get_sock_fun,
} // namespace socket_creator
} // NAMESPACE ISC
-#endif // __SOCKCREATOR_H
+#endif // SOCKCREATOR_H
diff --git a/src/bin/sysinfo/.gitignore b/src/bin/sysinfo/.gitignore
index 9194aff..b5c759d 100644
--- a/src/bin/sysinfo/.gitignore
+++ b/src/bin/sysinfo/.gitignore
@@ -1,3 +1,4 @@
/isc-sysinfo
-/sysinfo.py
/isc-sysinfo.1
+/run_sysinfo.sh
+/sysinfo.py
diff --git a/src/bin/sysinfo/Makefile.am b/src/bin/sysinfo/Makefile.am
index 25a3556..1618535 100644
--- a/src/bin/sysinfo/Makefile.am
+++ b/src/bin/sysinfo/Makefile.am
@@ -1,4 +1,5 @@
bin_SCRIPTS = isc-sysinfo
+noinst_SCRIPTS = run_sysinfo.sh
CLEANFILES = isc-sysinfo sysinfo.pyc
diff --git a/src/bin/sysinfo/run_sysinfo.sh.in b/src/bin/sysinfo/run_sysinfo.sh.in
new file mode 100755
index 0000000..268b5a4
--- /dev/null
+++ b/src/bin/sysinfo/run_sysinfo.sh.in
@@ -0,0 +1,38 @@
+#! /bin/sh
+
+# 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.
+
+PYTHON_EXEC=${PYTHON_EXEC:- at PYTHON@}
+export PYTHON_EXEC
+
+SYSINFO_PATH=@abs_top_builddir@/src/bin/sysinfo
+
+# Note: we shouldn't need log_messages except for the seemingly necessary
+# dependency due to the automatic import in the isc package (its __init__.py
+# imports some other modules)
+PYTHONPATH=@abs_top_builddir@/src/lib/python:@abs_top_srcdir@/src/lib/python:@abs_top_builddir@/src/lib/python/isc/log_messages
+export PYTHONPATH
+
+# Likewise, we need only because isc.log requires some loadable modules.
+# sysinfo itself shouldn't need any of them.
+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/acl/.libs:@abs_top_builddir@/src/lib/util/.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
+
+cd ${SYSINFO_PATH}
+exec ${PYTHON_EXEC} -O sysinfo.py "$@"
diff --git a/src/bin/sysinfo/sysinfo.py.in b/src/bin/sysinfo/sysinfo.py.in
index 24cf309..477b9de 100755
--- a/src/bin/sysinfo/sysinfo.py.in
+++ b/src/bin/sysinfo/sysinfo.py.in
@@ -22,11 +22,8 @@ ISC sysinfo program.
import sys; sys.path.append ('@@PYTHONPATH@@')
import getopt
-import isc.util.process
from isc.sysinfo import *
-isc.util.process.rename()
-
def usage():
print("Usage: %s [-h] [-o <output-file>]" % sys.argv[0], \
file=sys.stderr)
@@ -88,7 +85,8 @@ def main():
write_value(f, ' + Machine name: %s\n', s.get_platform_machine)
write_value(f, ' + Hostname: %s\n', s.get_platform_hostname)
- write_value(f, ' + Uptime: %d seconds\n', s.get_uptime)
+ write_value(f, ' + Uptime: %d seconds', s.get_uptime)
+ write_value(f, ' (%s)\n', s.get_uptime_desc)
write_value(f, ' + Loadavg: %f %f %f\n', s.get_loadavg)
diff --git a/src/bin/tests/process_rename_test.py.in b/src/bin/tests/process_rename_test.py.in
index 1156b29..055ebdc 100644
--- a/src/bin/tests/process_rename_test.py.in
+++ b/src/bin/tests/process_rename_test.py.in
@@ -39,6 +39,11 @@ class TestRename(unittest.TestCase):
Then scan them by looking at the source text
(without actually running them)
"""
+
+ # Scripts named in this list are not expected to be renamed and
+ # should be excluded from the scan.
+ EXCLUDED_SCRIPTS = ['isc-sysinfo']
+
# Regexp to find all the *_SCRIPTS = something lines (except for
# noinst_SCRIPTS, which are scripts for tests), including line
# continuations (backslash and newline)
@@ -59,6 +64,8 @@ class TestRename(unittest.TestCase):
for (var, _) in lines.findall(re.sub(excluded_lines, '',
makefile)):
for (script, _) in scripts.findall(var):
+ if script in EXCLUDED_SCRIPTS:
+ continue
self.__scan(d, script, fun)
if __name__ == "__main__":
diff --git a/src/cppcheck-suppress.lst b/src/cppcheck-suppress.lst
index ff4a79a..9dc8d99 100644
--- a/src/cppcheck-suppress.lst
+++ b/src/cppcheck-suppress.lst
@@ -11,3 +11,18 @@ missingInclude
//
// // cppcheck-suppress duplicateExpression
// EXPECT_FALSE(small_name < small_name);
+
+// With cppcheck 1.56, there are a number of false positives, which
+// All of these should be checked and hopefully removed after upgrading
+// cppcheck past 1.56
+
+// eraseDereference: This is a known false positive, which has been
+// fixed in the current development version of cppcheck
+eraseDereference
+
+// Unused functions: there suddenly are a lot of unused function errors
+// We could address those by adding for instance early declarations or
+// (unnecessary) header files, but they were all somewhat false positives
+// When we upgrade past 1.56, we should re-check this, and perhaps enable
+// unused-functions again.
+unusedFunction
diff --git a/src/lib/acl/dns.cc b/src/lib/acl/dns.cc
index d16ec65..5466dad 100644
--- a/src/lib/acl/dns.cc
+++ b/src/lib/acl/dns.cc
@@ -12,12 +12,6 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#include <memory>
-#include <string>
-#include <vector>
-
-#include <boost/shared_ptr.hpp>
-
#include <exceptions/exceptions.h>
#include <dns/name.h>
@@ -31,6 +25,13 @@
#include <acl/loader.h>
#include <acl/logic_check.h>
+#include <boost/shared_ptr.hpp>
+#include <boost/scoped_ptr.hpp>
+
+#include <memory>
+#include <string>
+#include <vector>
+
using namespace std;
using namespace isc::dns;
using namespace isc::data;
@@ -106,10 +107,12 @@ internal::RequestCheckCreator::create(const string& name,
RequestLoader&
getRequestLoader() {
- static RequestLoader* loader(NULL);
- if (loader == NULL) {
+ // To ensure that the singleton gets destroyed at the end of the
+ // program's lifetime, we put it in a static scoped_ptr.
+ static boost::scoped_ptr<RequestLoader> loader(NULL);
+ if (loader.get() == NULL) {
// Creator registration may throw, so we first store the new loader
- // in an auto pointer in order to provide the strong exception
+ // in a second auto pointer in order to provide the strong exception
// guarantee.
auto_ptr<RequestLoader> loader_ptr =
auto_ptr<RequestLoader>(new RequestLoader(REJECT));
@@ -129,7 +132,7 @@ getRequestLoader() {
new LogicCreator<AllOfSpec, RequestContext>("ALL")));
// From this point there shouldn't be any exception thrown
- loader = loader_ptr.release();
+ loader.reset(loader_ptr.release());
}
return (*loader);
diff --git a/src/lib/acl/dnsname_check.h b/src/lib/acl/dnsname_check.h
index 7498d99..7403c16 100644
--- a/src/lib/acl/dnsname_check.h
+++ b/src/lib/acl/dnsname_check.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DNSNAME_CHECK_H
-#define __DNSNAME_CHECK_H 1
+#ifndef DNSNAME_CHECK_H
+#define DNSNAME_CHECK_H 1
#include <dns/name.h>
@@ -76,7 +76,7 @@ private:
} // namespace acl
} // namespace isc
-#endif // __DNSNAME_CHECK_H
+#endif // DNSNAME_CHECK_H
// Local Variables:
// mode: c++
diff --git a/src/lib/acl/ip_check.h b/src/lib/acl/ip_check.h
index 794b943..9d70b0a 100644
--- a/src/lib/acl/ip_check.h
+++ b/src/lib/acl/ip_check.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IP_CHECK_H
-#define __IP_CHECK_H
+#ifndef IP_CHECK_H
+#define IP_CHECK_H
#include <sys/socket.h>
@@ -410,7 +410,7 @@ const size_t IPCheck<Context>::IPV4_SIZE;
} // namespace acl
} // namespace isc
-#endif // __IP_CHECK_H
+#endif // IP_CHECK_H
// Local Variables:
// mode: c++
diff --git a/src/lib/acl/tests/sockaddr.h b/src/lib/acl/tests/sockaddr.h
index bd30451..2a4457a 100644
--- a/src/lib/acl/tests/sockaddr.h
+++ b/src/lib/acl/tests/sockaddr.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ACL_TEST_SOCKADDR_H
-#define __ACL_TEST_SOCKADDR_H 1
+#ifndef ACL_TEST_SOCKADDR_H
+#define ACL_TEST_SOCKADDR_H 1
#include <sys/types.h>
#include <sys/socket.h>
@@ -62,7 +62,7 @@ getSockAddr(const char* const addr) {
} // end of namespace "acl"
} // end of namespace "isc"
-#endif // __ACL_TEST_SOCKADDR_H
+#endif // ACL_TEST_SOCKADDR_H
// Local Variables:
// mode: c++
diff --git a/src/lib/asiodns/asiodns.h b/src/lib/asiodns/asiodns.h
index 8791a72..3032ebd 100644
--- a/src/lib/asiodns/asiodns.h
+++ b/src/lib/asiodns/asiodns.h
@@ -12,12 +12,12 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIODNS_H
-#define __ASIODNS_H 1
+#ifndef ASIODNS_H
+#define ASIODNS_H 1
#include <asiodns/dns_service.h>
#include <asiodns/dns_server.h>
#include <asiodns/dns_lookup.h>
#include <asiodns/dns_answer.h>
-#endif // __ASIODNS_H
+#endif // ASIODNS_H
diff --git a/src/lib/asiodns/dns_answer.h b/src/lib/asiodns/dns_answer.h
index 3654369..4b4576b 100644
--- a/src/lib/asiodns/dns_answer.h
+++ b/src/lib/asiodns/dns_answer.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_DNS_ANSWER_H
-#define __ASIOLINK_DNS_ANSWER_H 1
+#ifndef ASIOLINK_DNS_ANSWER_H
+#define ASIOLINK_DNS_ANSWER_H 1
#include <asiolink/io_message.h>
#include <util/buffer.h>
@@ -74,4 +74,4 @@ public:
} // namespace asiodns
} // namespace isc
-#endif // __ASIOLINK_DNS_ANSWER_H
+#endif // ASIOLINK_DNS_ANSWER_H
diff --git a/src/lib/asiodns/dns_lookup.h b/src/lib/asiodns/dns_lookup.h
index 5dc84ac..309755c 100644
--- a/src/lib/asiodns/dns_lookup.h
+++ b/src/lib/asiodns/dns_lookup.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_DNS_LOOKUP_H
-#define __ASIOLINK_DNS_LOOKUP_H 1
+#ifndef ASIOLINK_DNS_LOOKUP_H
+#define ASIOLINK_DNS_LOOKUP_H 1
#include <asiolink/io_message.h>
#include <asiodns/dns_server.h>
@@ -84,4 +84,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __ASIOLINK_DNS_LOOKUP_H
+#endif // ASIOLINK_DNS_LOOKUP_H
diff --git a/src/lib/asiodns/dns_server.h b/src/lib/asiodns/dns_server.h
index bc39805..3b8758f 100644
--- a/src/lib/asiodns/dns_server.h
+++ b/src/lib/asiodns/dns_server.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_DNS_SERVER_H
-#define __ASIOLINK_DNS_SERVER_H 1
+#ifndef ASIOLINK_DNS_SERVER_H
+#define ASIOLINK_DNS_SERVER_H 1
#include <asiolink/io_message.h>
@@ -152,4 +152,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __ASIOLINK_DNS_SERVER_H
+#endif // ASIOLINK_DNS_SERVER_H
diff --git a/src/lib/asiodns/dns_service.h b/src/lib/asiodns/dns_service.h
index 0b578fb..01b6310 100644
--- a/src/lib/asiodns/dns_service.h
+++ b/src/lib/asiodns/dns_service.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_DNS_SERVICE_H
-#define __ASIOLINK_DNS_SERVICE_H 1
+#ifndef ASIOLINK_DNS_SERVICE_H
+#define ASIOLINK_DNS_SERVICE_H 1
#include <resolve/resolver_interface.h>
@@ -210,7 +210,7 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __ASIOLINK_DNS_SERVICE_H
+#endif // ASIOLINK_DNS_SERVICE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/asiodns/io_fetch.h b/src/lib/asiodns/io_fetch.h
index 78c2da9..c31ee09 100644
--- a/src/lib/asiodns/io_fetch.h
+++ b/src/lib/asiodns/io_fetch.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_FETCH_H
-#define __IO_FETCH_H 1
+#ifndef IO_FETCH_H
+#define IO_FETCH_H 1
#include <config.h>
@@ -229,4 +229,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __IO_FETCH_H
+#endif // IO_FETCH_H
diff --git a/src/lib/asiodns/sync_udp_server.h b/src/lib/asiodns/sync_udp_server.h
index 9718422..ddac1f9 100644
--- a/src/lib/asiodns/sync_udp_server.h
+++ b/src/lib/asiodns/sync_udp_server.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SYNC_UDP_SERVER_H
-#define __SYNC_UDP_SERVER_H 1
+#ifndef SYNC_UDP_SERVER_H
+#define SYNC_UDP_SERVER_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -145,4 +145,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __SYNC_UDP_SERVER_H
+#endif // SYNC_UDP_SERVER_H
diff --git a/src/lib/asiodns/tcp_server.h b/src/lib/asiodns/tcp_server.h
index 7675daf..46f484b 100644
--- a/src/lib/asiodns/tcp_server.h
+++ b/src/lib/asiodns/tcp_server.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TCP_SERVER_H
-#define __TCP_SERVER_H 1
+#ifndef TCP_SERVER_H
+#define TCP_SERVER_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -147,4 +147,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __TCP_SERVER_H
+#endif // TCP_SERVER_H
diff --git a/src/lib/asiodns/udp_server.h b/src/lib/asiodns/udp_server.h
index b32c06c..c2b1b96 100644
--- a/src/lib/asiodns/udp_server.h
+++ b/src/lib/asiodns/udp_server.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UDP_SERVER_H
-#define __UDP_SERVER_H 1
+#ifndef UDP_SERVER_H
+#define UDP_SERVER_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -96,4 +96,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __UDP_SERVER_H
+#endif // UDP_SERVER_H
diff --git a/src/lib/asiolink/asiolink.h b/src/lib/asiolink/asiolink.h
index 51d3a14..708f368 100644
--- a/src/lib/asiolink/asiolink.h
+++ b/src/lib/asiolink/asiolink.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_H
-#define __ASIOLINK_H 1
+#ifndef ASIOLINK_H
+#define ASIOLINK_H 1
// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file. In particular, asio.hpp should never be included here.
@@ -74,4 +74,4 @@
/// the placeholder of callback handlers:
/// http://think-async.com/Asio/asio-1.3.1/doc/asio/reference/asio_handler_allocate.html
-#endif // __ASIOLINK_H
+#endif // ASIOLINK_H
diff --git a/src/lib/asiolink/dummy_io_cb.h b/src/lib/asiolink/dummy_io_cb.h
index bcaefe9..c4644c5 100644
--- a/src/lib/asiolink/dummy_io_cb.h
+++ b/src/lib/asiolink/dummy_io_cb.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DUMMY_IO_CB_H
-#define __DUMMY_IO_CB_H
+#ifndef DUMMY_IO_CB_H
+#define DUMMY_IO_CB_H
#include <iostream>
@@ -59,4 +59,4 @@ public:
} // namespace asiolink
} // namespace isc
-#endif // __DUMMY_IO_CB_H
+#endif // DUMMY_IO_CB_H
diff --git a/src/lib/asiolink/interval_timer.h b/src/lib/asiolink/interval_timer.h
index 57ec1c3..620abfa 100644
--- a/src/lib/asiolink/interval_timer.h
+++ b/src/lib/asiolink/interval_timer.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_INTERVAL_TIMER_H
-#define __ASIOLINK_INTERVAL_TIMER_H 1
+#ifndef ASIOLINK_INTERVAL_TIMER_H
+#define ASIOLINK_INTERVAL_TIMER_H 1
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
@@ -130,4 +130,4 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __ASIOLINK_INTERVAL_TIMER_H
+#endif // ASIOLINK_INTERVAL_TIMER_H
diff --git a/src/lib/asiolink/io_address.h b/src/lib/asiolink/io_address.h
index c40e5b9..6c18a66 100644
--- a/src/lib/asiolink/io_address.h
+++ b/src/lib/asiolink/io_address.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_ADDRESS_H
-#define __IO_ADDRESS_H 1
+#ifndef IO_ADDRESS_H
+#define IO_ADDRESS_H 1
// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file. In particular, asio.hpp should never be included here.
@@ -131,7 +131,7 @@ public:
return equals(other);
}
- // \brief Compare addresses for inequality
+ /// \brief Compare addresses for inequality
///
/// \param other Address to compare against.
///
@@ -140,7 +140,58 @@ public:
return (!equals(other));
}
- // \brief Compare addresses for inequality
+ /// \brief Checks if one address is smaller than the other
+ ///
+ /// \param other Address to compare against.
+ ///
+ /// \return true if this address is smaller than the other address.
+ ///
+ /// It is useful for comparing which address is bigger.
+ /// Operations within one protocol family are obvious.
+ /// Comparisons between v4 and v6 will allways return v4
+ /// being smaller. This follows boost::asio::ip implementation
+ bool lessThan(const IOAddress& other) const {
+ if (this->getFamily() == other.getFamily()) {
+ if (this->getFamily() == AF_INET6) {
+ return (this->asio_address_.to_v6() < other.asio_address_.to_v6());
+ } else {
+ return (this->asio_address_.to_v4() < other.asio_address_.to_v4());
+ }
+ }
+ return (this->getFamily() < other.getFamily());
+ }
+
+ /// \brief Checks if one address is smaller or equal than the other
+ ///
+ /// \param other Address to compare against.
+ ///
+ /// \return true if this address is smaller than the other address.
+ bool smallerEqual(const IOAddress& other) const {
+ if (equals(other)) {
+ return (true);
+ }
+ return (lessThan(other));
+ }
+
+ /// \brief Checks if one address is smaller than the other
+ ///
+ /// \param other Address to compare against.
+ ///
+ /// See \ref smaller_than method for details.
+ bool operator<(const IOAddress& other) const {
+ return (lessThan(other));
+ }
+
+ /// \brief Checks if one address is smaller or equal than the other
+ ///
+ /// \param other Address to compare against.
+ ///
+ /// See \ref smaller_equal method for details.
+ bool operator<=(const IOAddress& other) const {
+ return (smallerEqual(other));
+ }
+
+ /// \brief Compare addresses for inequality
///
/// \param other Address to compare against.
///
@@ -164,4 +215,4 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __IO_ADDRESS_H
+#endif // IO_ADDRESS_H
diff --git a/src/lib/asiolink/io_asio_socket.h b/src/lib/asiolink/io_asio_socket.h
index aeac63d..f6d64a0 100644
--- a/src/lib/asiolink/io_asio_socket.h
+++ b/src/lib/asiolink/io_asio_socket.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_ASIO_SOCKET_H
-#define __IO_ASIO_SOCKET_H 1
+#ifndef IO_ASIO_SOCKET_H
+#define IO_ASIO_SOCKET_H 1
// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file. In particular, asio.hpp should never be included here.
@@ -385,4 +385,4 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __IO_ASIO_SOCKET_H
+#endif // IO_ASIO_SOCKET_H
diff --git a/src/lib/asiolink/io_endpoint.h b/src/lib/asiolink/io_endpoint.h
index 973fc8b..89bc247 100644
--- a/src/lib/asiolink/io_endpoint.h
+++ b/src/lib/asiolink/io_endpoint.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_ENDPOINT_H
-#define __IO_ENDPOINT_H 1
+#ifndef IO_ENDPOINT_H
+#define IO_ENDPOINT_H 1
// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file. In particular, asio.hpp should never be included here.
@@ -184,7 +184,7 @@ public:
std::ostream& operator<<(std::ostream& os, const IOEndpoint& endpoint);
} // namespace asiolink
} // namespace isc
-#endif // __IO_ENDPOINT_H
+#endif // IO_ENDPOINT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/asiolink/io_error.h b/src/lib/asiolink/io_error.h
index c19d91c..2fb2486 100644
--- a/src/lib/asiolink/io_error.h
+++ b/src/lib/asiolink/io_error.h
@@ -13,8 +13,8 @@
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_ERROR_H
-#define __IO_ERROR_H
+#ifndef IO_ERROR_H
+#define IO_ERROR_H
#include <exceptions/exceptions.h>
@@ -34,4 +34,4 @@ public:
} // namespace asiolink
} // namespace isc
-#endif // __IO_ERROR_H
+#endif // IO_ERROR_H
diff --git a/src/lib/asiolink/io_message.h b/src/lib/asiolink/io_message.h
index 81f6da1..7607c72 100644
--- a/src/lib/asiolink/io_message.h
+++ b/src/lib/asiolink/io_message.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_MESSAGE_H
-#define __IO_MESSAGE_H 1
+#ifndef IO_MESSAGE_H
+#define IO_MESSAGE_H 1
// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file. In particular, asio.hpp should never be included here.
@@ -99,4 +99,4 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __IO_MESSAGE_H
+#endif // IO_MESSAGE_H
diff --git a/src/lib/asiolink/io_service.h b/src/lib/asiolink/io_service.h
index 75aaee6..e0198dd 100644
--- a/src/lib/asiolink/io_service.h
+++ b/src/lib/asiolink/io_service.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_IO_SERVICE_H
-#define __ASIOLINK_IO_SERVICE_H 1
+#ifndef ASIOLINK_IO_SERVICE_H
+#define ASIOLINK_IO_SERVICE_H 1
namespace asio {
class io_service;
@@ -76,4 +76,4 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __ASIOLINK_IO_SERVICE_H
+#endif // ASIOLINK_IO_SERVICE_H
diff --git a/src/lib/asiolink/io_socket.h b/src/lib/asiolink/io_socket.h
index ab6479c..6581faf 100644
--- a/src/lib/asiolink/io_socket.h
+++ b/src/lib/asiolink/io_socket.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_SOCKET_H
-#define __IO_SOCKET_H 1
+#ifndef IO_SOCKET_H
+#define IO_SOCKET_H 1
// IMPORTANT NOTE: only very few ASIO headers files can be included in
// this file. In particular, asio.hpp should never be included here.
@@ -123,4 +123,4 @@ public:
} // namespace asiolink
} // namespace isc
-#endif // __IO_SOCKET_H
+#endif // IO_SOCKET_H
diff --git a/src/lib/asiolink/simple_callback.h b/src/lib/asiolink/simple_callback.h
index a297a1d..4301bd1 100644
--- a/src/lib/asiolink/simple_callback.h
+++ b/src/lib/asiolink/simple_callback.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_SIMPLE_CALLBACK_H
-#define __ASIOLINK_SIMPLE_CALLBACK_H 1
+#ifndef ASIOLINK_SIMPLE_CALLBACK_H
+#define ASIOLINK_SIMPLE_CALLBACK_H 1
#include <asiolink/io_message.h>
@@ -72,4 +72,4 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __ASIOLINK_SIMPLE_CALLBACK_H
+#endif // ASIOLINK_SIMPLE_CALLBACK_H
diff --git a/src/lib/asiolink/tcp_endpoint.h b/src/lib/asiolink/tcp_endpoint.h
index a54f6b2..3d6a87a 100644
--- a/src/lib/asiolink/tcp_endpoint.h
+++ b/src/lib/asiolink/tcp_endpoint.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TCP_ENDPOINT_H
-#define __TCP_ENDPOINT_H 1
+#ifndef TCP_ENDPOINT_H
+#define TCP_ENDPOINT_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -116,7 +116,7 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __TCP_ENDPOINT_H
+#endif // TCP_ENDPOINT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/asiolink/tcp_socket.h b/src/lib/asiolink/tcp_socket.h
index 2505d7b..6b0a43c 100644
--- a/src/lib/asiolink/tcp_socket.h
+++ b/src/lib/asiolink/tcp_socket.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TCP_SOCKET_H
-#define __TCP_SOCKET_H 1
+#ifndef TCP_SOCKET_H
+#define TCP_SOCKET_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -415,4 +415,4 @@ TCPSocket<C>::close() {
} // namespace asiolink
} // namespace isc
-#endif // __TCP_SOCKET_H
+#endif // TCP_SOCKET_H
diff --git a/src/lib/asiolink/tests/io_address_unittest.cc b/src/lib/asiolink/tests/io_address_unittest.cc
index 4322283..a1a9076 100644
--- a/src/lib/asiolink/tests/io_address_unittest.cc
+++ b/src/lib/asiolink/tests/io_address_unittest.cc
@@ -99,3 +99,35 @@ TEST(IOAddressTest, uint32) {
EXPECT_EQ(addr3.toText(), "192.0.2.5");
}
+
+TEST(IOAddressTest, lessThanEqual) {
+ IOAddress addr1("192.0.2.5");
+ IOAddress addr2("192.0.2.6");
+ IOAddress addr3("0.0.0.0");
+
+ IOAddress addr4("::");
+ IOAddress addr5("2001:db8::1");
+ IOAddress addr6("2001:db8::1:0");
+ IOAddress addr7("2001:db8::1:0"); // the same as 6
+
+ // v4 comparisons
+ EXPECT_TRUE(addr1 < addr2);
+ EXPECT_FALSE(addr2 < addr1);
+ EXPECT_FALSE(addr2 <= addr1);
+ EXPECT_TRUE(addr3 < addr1);
+ EXPECT_TRUE(addr3 < addr2);
+ EXPECT_TRUE(addr3 <= addr2);
+
+ // v6 comparisons
+ EXPECT_TRUE(addr4 < addr5);
+ EXPECT_TRUE(addr5 < addr6);
+ EXPECT_FALSE(addr6 < addr5);
+ EXPECT_FALSE(addr6 <= addr5);
+
+ // v4 to v6 - v4 should always be smaller
+ EXPECT_TRUE(addr1 < addr4);
+ EXPECT_TRUE(addr3 < addr4);
+ EXPECT_TRUE(addr2 < addr5);
+
+ EXPECT_TRUE(addr6 <= addr7);
+}
diff --git a/src/lib/asiolink/udp_endpoint.h b/src/lib/asiolink/udp_endpoint.h
index c5ba3bd..34701b9 100644
--- a/src/lib/asiolink/udp_endpoint.h
+++ b/src/lib/asiolink/udp_endpoint.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UDP_ENDPOINT_H
-#define __UDP_ENDPOINT_H 1
+#ifndef UDP_ENDPOINT_H
+#define UDP_ENDPOINT_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -116,7 +116,7 @@ private:
} // namespace asiolink
} // namespace isc
-#endif // __UDP_ENDPOINT_H
+#endif // UDP_ENDPOINT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/asiolink/udp_socket.h b/src/lib/asiolink/udp_socket.h
index c061fba..5712957 100644
--- a/src/lib/asiolink/udp_socket.h
+++ b/src/lib/asiolink/udp_socket.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UDP_SOCKET_H
-#define __UDP_SOCKET_H 1
+#ifndef UDP_SOCKET_H
+#define UDP_SOCKET_H 1
#ifndef ASIO_HPP
#error "asio.hpp must be included before including this, see asiolink.h as to why"
@@ -321,4 +321,4 @@ UDPSocket<C>::close() {
} // namespace asiolink
} // namespace isc
-#endif // __UDP_SOCKET_H
+#endif // UDP_SOCKET_H
diff --git a/src/lib/bench/benchmark.h b/src/lib/bench/benchmark.h
index a5c6fd4..3e380dc 100644
--- a/src/lib/bench/benchmark.h
+++ b/src/lib/bench/benchmark.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __BENCHMARK_H
-#define __BENCHMARK_H 1
+#ifndef BENCHMARK_H
+#define BENCHMARK_H 1
#include <sys/time.h>
@@ -402,7 +402,7 @@ private:
}
}
-#endif // __BENCHMARK_H
+#endif // BENCHMARK_H
// Local Variables:
// mode: c++
diff --git a/src/lib/bench/benchmark_util.h b/src/lib/bench/benchmark_util.h
index 3a373f2..2cb6acc 100644
--- a/src/lib/bench/benchmark_util.h
+++ b/src/lib/bench/benchmark_util.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __BENCHMARK_UTIL_H
-#define __BENCHMARK_UTIL_H 1
+#ifndef BENCHMARK_UTIL_H
+#define BENCHMARK_UTIL_H 1
/// \file
/// Utilities to help write benchmark cases.
@@ -140,7 +140,7 @@ void loadQueryData(std::istream& input, BenchQueries& queries,
const isc::dns::RRClass& qclass, const bool strict = false);
}
}
-#endif // __BENCHMARK_UTIL_H
+#endif // BENCHMARK_UTIL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/cache/cache_entry_key.h b/src/lib/cache/cache_entry_key.h
index 674deb0..308a556 100644
--- a/src/lib/cache/cache_entry_key.h
+++ b/src/lib/cache/cache_entry_key.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __CACHE_ENTRY_KEY_H
-#define __CACHE_ENTRY_KEY_H
+#ifndef CACHE_ENTRY_KEY_H
+#define CACHE_ENTRY_KEY_H
#include <string>
#include <dns/name.h>
@@ -50,5 +50,5 @@ genCacheEntryName(const std::string& namestr, const uint16_t type);
} // namespace cache
} // namespace isc
-#endif // __CACHE_ENTRY_KEY_H
+#endif // CACHE_ENTRY_KEY_H
diff --git a/src/lib/cache/local_zone_data.h b/src/lib/cache/local_zone_data.h
index df77f40..4bfdb94 100644
--- a/src/lib/cache/local_zone_data.h
+++ b/src/lib/cache/local_zone_data.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _LOCAL_ZONE_DATA
-#define _LOCAL_ZONE_DATA
+#ifndef LOCAL_ZONE_DATA
+#define LOCAL_ZONE_DATA
#include <map>
#include <string>
@@ -60,5 +60,5 @@ typedef boost::shared_ptr<const LocalZoneData> ConstLocalZoneDataPtr;
} // namespace cache
} // namespace isc
-#endif // _LOCAL_ZONE_DATA
+#endif // LOCAL_ZONE_DATA
diff --git a/src/lib/cache/logger.h b/src/lib/cache/logger.h
index 52c9743..3cadb54 100644
--- a/src/lib/cache/logger.h
+++ b/src/lib/cache/logger.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATASRC_LOGGER_H
-#define __DATASRC_LOGGER_H
+#ifndef DATASRC_LOGGER_H
+#define DATASRC_LOGGER_H
#include <log/macros.h>
#include <cache/cache_messages.h>
diff --git a/src/lib/cache/message_cache.h b/src/lib/cache/message_cache.h
index b418f23..0c19139 100644
--- a/src/lib/cache/message_cache.h
+++ b/src/lib/cache/message_cache.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_CACHE_H
-#define __MESSAGE_CACHE_H
+#ifndef MESSAGE_CACHE_H
+#define MESSAGE_CACHE_H
#include <string>
#include <boost/shared_ptr.hpp>
@@ -90,5 +90,5 @@ typedef boost::shared_ptr<MessageCache> MessageCachePtr;
} // namespace cache
} // namespace isc
-#endif // __MESSAGE_CACHE_H
+#endif // MESSAGE_CACHE_H
diff --git a/src/lib/cache/message_entry.h b/src/lib/cache/message_entry.h
index 6da27cc..206e601 100644
--- a/src/lib/cache/message_entry.h
+++ b/src/lib/cache/message_entry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_ENTRY_H
-#define __MESSAGE_ENTRY_H
+#ifndef MESSAGE_ENTRY_H
+#define MESSAGE_ENTRY_H
#include <vector>
#include <dns/message.h>
@@ -199,5 +199,5 @@ typedef boost::shared_ptr<MessageEntry> MessageEntryPtr;
} // namespace cache
} // namespace isc
-#endif // __MESSAGE_ENTRY_H
+#endif // MESSAGE_ENTRY_H
diff --git a/src/lib/cache/message_utility.h b/src/lib/cache/message_utility.h
index a77af07..1a79480 100644
--- a/src/lib/cache/message_utility.h
+++ b/src/lib/cache/message_utility.h
@@ -14,8 +14,8 @@
// $Id$
-#ifndef __MESSAGE_UTILITY_H
-#define __MESSAGE_UTILITY_H
+#ifndef MESSAGE_UTILITY_H
+#define MESSAGE_UTILITY_H
#include <dns/message.h>
@@ -63,4 +63,4 @@ bool canMessageBeCached(const isc::dns::Message& msg);
} // namespace isc
-#endif//__MESSAGE_UTILITY_H
+#endif//MESSAGE_UTILITY_H
diff --git a/src/lib/cache/resolver_cache.h b/src/lib/cache/resolver_cache.h
index 5630bd7..9813cc2 100644
--- a/src/lib/cache/resolver_cache.h
+++ b/src/lib/cache/resolver_cache.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RESOLVER_CACHE_H
-#define __RESOLVER_CACHE_H
+#ifndef RESOLVER_CACHE_H
+#define RESOLVER_CACHE_H
#include <map>
#include <string>
@@ -319,5 +319,5 @@ private:
} // namespace cache
} // namespace isc
-#endif // __RESOLVER_CACHE_H
+#endif // RESOLVER_CACHE_H
diff --git a/src/lib/cache/rrset_cache.h b/src/lib/cache/rrset_cache.h
index a4ea54e..304c6e8 100644
--- a/src/lib/cache/rrset_cache.h
+++ b/src/lib/cache/rrset_cache.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRSET_CACHE_H
-#define __RRSET_CACHE_H
+#ifndef RRSET_CACHE_H
+#define RRSET_CACHE_H
#include <cache/rrset_entry.h>
#include <nsas/hash_table.h>
@@ -89,5 +89,5 @@ typedef boost::shared_ptr<const RRsetCache> ConstRRsetCachePtr;
} // namespace cache
} // namespace isc
-#endif // __RRSET_CACHE_H
+#endif // RRSET_CACHE_H
diff --git a/src/lib/cache/rrset_copy.h b/src/lib/cache/rrset_copy.h
index e1dc489..6b74bc0 100644
--- a/src/lib/cache/rrset_copy.h
+++ b/src/lib/cache/rrset_copy.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRSET_COPY_
-#define __RRSET_COPY_
+#ifndef RRSET_COPY
+#define RRSET_COPY
#include <dns/rrset.h>
@@ -38,5 +38,5 @@ rrsetCopy(const isc::dns::AbstractRRset& src, isc::dns::AbstractRRset& dst);
} // namespace cache
} // namespace isc
-#endif // __RRSET_COPY_
+#endif // RRSET_COPY
diff --git a/src/lib/cache/rrset_entry.h b/src/lib/cache/rrset_entry.h
index 129300d..0efda36 100644
--- a/src/lib/cache/rrset_entry.h
+++ b/src/lib/cache/rrset_entry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRSET_ENTRY_H
-#define __RRSET_ENTRY_H
+#ifndef RRSET_ENTRY_H
+#define RRSET_ENTRY_H
#include <dns/rrset.h>
#include <dns/message.h>
@@ -132,5 +132,5 @@ typedef boost::shared_ptr<RRsetEntry> RRsetEntryPtr;
} // namespace cache
} // namespace isc
-#endif // __RRSET_ENTRY_H
+#endif // RRSET_ENTRY_H
diff --git a/src/lib/cache/tests/rrset_entry_unittest.cc b/src/lib/cache/tests/rrset_entry_unittest.cc
index c7c3c6e..a6ac27e 100644
--- a/src/lib/cache/tests/rrset_entry_unittest.cc
+++ b/src/lib/cache/tests/rrset_entry_unittest.cc
@@ -50,9 +50,6 @@ class DerivedRRsetEntry: public RRsetEntry {
public:
DerivedRRsetEntry(const isc::dns::RRset& rrset, const RRsetTrustLevel& level) : RRsetEntry(rrset, level) {};
- void updateTTLForTest() {
-
- }
};
#define TEST_TTL 100
diff --git a/src/lib/cc/data.cc b/src/lib/cc/data.cc
index 6ec243a..8d9b87d 100644
--- a/src/lib/cc/data.cc
+++ b/src/lib/cc/data.cc
@@ -57,32 +57,32 @@ Element::toWire(std::ostream& ss) const {
}
bool
-Element::getValue(long int&) {
+Element::getValue(long int&) const {
return (false);
}
bool
-Element::getValue(double&) {
+Element::getValue(double&) const {
return (false);
}
bool
-Element::getValue(bool&) {
+Element::getValue(bool&) const {
return (false);
}
bool
-Element::getValue(std::string&) {
+Element::getValue(std::string&) const {
return (false);
}
bool
-Element::getValue(std::vector<ConstElementPtr>&) {
+Element::getValue(std::vector<ConstElementPtr>&) const {
return (false);
}
bool
-Element::getValue(std::map<std::string, ConstElementPtr>&) {
+Element::getValue(std::map<std::string, ConstElementPtr>&) const {
return (false);
}
@@ -167,7 +167,7 @@ Element::find(const std::string&) const {
}
bool
-Element::find(const std::string&, ConstElementPtr) const {
+Element::find(const std::string&, ConstElementPtr&) const {
return (false);
}
@@ -413,7 +413,7 @@ from_stringstream_number(std::istream &in, int &pos) {
isc_throw(JSONError, std::string("Number overflow: ") + number);
}
}
-
+
if (is_double) {
return (Element::create(d));
} else {
@@ -501,7 +501,7 @@ from_stringstream_map(std::istream &in, const std::string& file, int& line,
ConstElementPtr value = Element::fromJSON(in, file, line, pos);
map->set(key, value);
-
+
skip_to(in, file, line, pos, ",}", WHITESPACE);
c = in.get();
pos++;
@@ -812,7 +812,7 @@ MapElement::set(const std::string& key, ConstElementPtr value) {
}
bool
-MapElement::find(const std::string& id, ConstElementPtr t) const {
+MapElement::find(const std::string& id, ConstElementPtr& t) const {
try {
ConstElementPtr p = find(id);
if (p) {
@@ -942,7 +942,7 @@ removeIdentical(ConstElementPtr a, ConstElementPtr b) {
if (!b) {
return (result);
}
-
+
if (a->getType() != Element::map || b->getType() != Element::map) {
isc_throw(TypeError, "Non-map Elements passed to removeIdentical");
}
@@ -965,7 +965,7 @@ merge(ElementPtr element, ConstElementPtr other) {
other->getType() != Element::map) {
isc_throw(TypeError, "merge arguments not MapElements");
}
-
+
const std::map<std::string, ConstElementPtr>& m = other->mapValue();
for (std::map<std::string, ConstElementPtr>::const_iterator it = m.begin();
it != m.end() ; ++it) {
diff --git a/src/lib/cc/data.h b/src/lib/cc/data.h
index 5c731e6..bb84ae2 100644
--- a/src/lib/cc/data.h
+++ b/src/lib/cc/data.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_DATA_H
-#define _ISC_DATA_H 1
+#ifndef ISC_DATA_H
+#define ISC_DATA_H 1
#include <string>
#include <vector>
@@ -71,7 +71,7 @@ public:
/// the type in question.
///
class Element {
-
+
private:
// technically the type could be omitted; is it useful?
// should we remove it or replace it with a pure virtual
@@ -112,7 +112,7 @@ public:
/// \returns true if the other ElementPtr has the same type and
/// value
virtual bool equals(const Element& other) const = 0;
-
+
/// Converts the Element to JSON format and appends it to
/// the given stringstream.
virtual void toJSON(std::ostream& ss) const = 0;
@@ -152,12 +152,12 @@ public:
/// data to the given reference and returning true
///
//@{
- virtual bool getValue(long int& t);
- virtual bool getValue(double& t);
- virtual bool getValue(bool& t);
- virtual bool getValue(std::string& t);
- virtual bool getValue(std::vector<ConstElementPtr>& t);
- virtual bool getValue(std::map<std::string, ConstElementPtr>& t);
+ virtual bool getValue(long int& t) const;
+ virtual bool getValue(double& t) const;
+ virtual bool getValue(bool& t) const;
+ virtual bool getValue(std::string& t) const;
+ virtual bool getValue(std::vector<ConstElementPtr>& t) const;
+ virtual bool getValue(std::map<std::string, ConstElementPtr>& t) const;
//@}
///
@@ -209,7 +209,7 @@ public:
virtual size_t size() const;
//@}
-
+
/// \name MapElement functions
///
/// \brief If the Element on which these functions are called are not
@@ -253,12 +253,12 @@ public:
/// \param identifier The identifier of the element to find
/// \param t Reference to store the resulting ElementPtr, if found.
/// \return true if the element was found, false if not.
- virtual bool find(const std::string& identifier, ConstElementPtr t) const;
+ virtual bool find(const std::string& identifier, ConstElementPtr& t) const;
//@}
/// \name Factory functions
-
+
// TODO: should we move all factory functions to a different class
// so as not to burden the Element base with too many functions?
// and/or perhaps even to a separate header?
@@ -349,7 +349,7 @@ public:
/// These function pparse the wireformat at the given stringstream
/// (of the given length). If there is a parse error an exception
/// of the type isc::cc::DecodeError is raised.
-
+
//@{
/// Creates an Element from the wire format in the given
/// stringstream of the given length.
@@ -378,7 +378,7 @@ public:
IntElement(long int v) : Element(integer), i(v) { }
long int intValue() const { return (i); }
using Element::getValue;
- bool getValue(long int& t) { t = i; return (true); }
+ bool getValue(long int& t) const { t = i; return (true); }
using Element::setValue;
bool setValue(const long int v) { i = v; return (true); }
void toJSON(std::ostream& ss) const;
@@ -392,7 +392,7 @@ public:
DoubleElement(double v) : Element(real), d(v) {};
double doubleValue() const { return (d); }
using Element::getValue;
- bool getValue(double& t) { t = d; return (true); }
+ bool getValue(double& t) const { t = d; return (true); }
using Element::setValue;
bool setValue(const double v) { d = v; return (true); }
void toJSON(std::ostream& ss) const;
@@ -406,7 +406,7 @@ public:
BoolElement(const bool v) : Element(boolean), b(v) {};
bool boolValue() const { return (b); }
using Element::getValue;
- bool getValue(bool& t) { t = b; return (true); }
+ bool getValue(bool& t) const { t = b; return (true); }
using Element::setValue;
bool setValue(const bool v) { b = v; return (true); }
void toJSON(std::ostream& ss) const;
@@ -427,7 +427,7 @@ public:
StringElement(std::string v) : Element(string), s(v) {};
std::string stringValue() const { return (s); }
using Element::getValue;
- bool getValue(std::string& t) { t = s; return (true); }
+ bool getValue(std::string& t) const { t = s; return (true); }
using Element::setValue;
bool setValue(const std::string& v) { s = v; return (true); }
void toJSON(std::ostream& ss) const;
@@ -441,7 +441,7 @@ public:
ListElement() : Element(list) {}
const std::vector<ConstElementPtr>& listValue() const { return (l); }
using Element::getValue;
- bool getValue(std::vector<ConstElementPtr>& t) {
+ bool getValue(std::vector<ConstElementPtr>& t) const {
t = l;
return (true);
}
@@ -474,7 +474,7 @@ public:
return (m);
}
using Element::getValue;
- bool getValue(std::map<std::string, ConstElementPtr>& t) {
+ bool getValue(std::map<std::string, ConstElementPtr>& t) const {
t = m;
return (true);
}
@@ -495,7 +495,7 @@ public:
return (m.find(s) != m.end());
}
void toJSON(std::ostream& ss) const;
-
+
// we should name the two finds better...
// find the element at id; raises TypeError if one of the
// elements at path except the one we're looking for is not a
@@ -507,7 +507,7 @@ public:
// returns true if found, or false if not found (either because
// it doesnt exist or one of the elements in the path is not
// a MapElement)
- bool find(const std::string& id, ConstElementPtr t) const;
+ bool find(const std::string& id, ConstElementPtr& t) const;
bool equals(const Element& other) const;
};
@@ -567,8 +567,8 @@ std::ostream& operator<<(std::ostream& out, const Element& e);
bool operator==(const Element& a, const Element& b);
bool operator!=(const Element& a, const Element& b);
} }
-#endif // _ISC_DATA_H
+#endif // ISC_DATA_H
-// Local Variables:
+// Local Variables:
// mode: c++
-// End:
+// End:
diff --git a/src/lib/cc/session.h b/src/lib/cc/session.h
index 9b08232..a818291 100644
--- a/src/lib/cc/session.h
+++ b/src/lib/cc/session.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_SESSION_H
-#define _ISC_SESSION_H 1
+#ifndef ISC_SESSION_H
+#define ISC_SESSION_H 1
#include <string>
@@ -161,7 +161,7 @@ namespace isc {
} // namespace cc
} // namespace isc
-#endif // _ISC_SESSION_H
+#endif // ISC_SESSION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/cc/tests/data_unittests.cc b/src/lib/cc/tests/data_unittests.cc
index 87d92f6..1565418 100644
--- a/src/lib/cc/tests/data_unittests.cc
+++ b/src/lib/cc/tests/data_unittests.cc
@@ -112,7 +112,7 @@ TEST(Element, from_and_to_json) {
std::string s = std::string(pe.what());
EXPECT_EQ("String expected in <string>:1:3", s);
}
-
+
sv.clear();
sv.push_back("{1}");
//ElementPtr ep = Element::fromJSON("\"aaa\nbbb\"err");
@@ -172,14 +172,14 @@ TEST(Element, from_and_to_json) {
}
-TEST(Element, create_and_value_throws) {
- // this test checks whether elements throw exceptions if the
- // incorrect type is requested
- ElementPtr el;
+template <typename T>
+void
+testGetValueInt() {
+ T el;
long int i;
double d;
bool b;
- std::string s("asdf");
+ std::string s;
std::vector<ConstElementPtr> v;
std::map<std::string, ConstElementPtr> m;
@@ -196,27 +196,19 @@ TEST(Element, create_and_value_throws) {
EXPECT_FALSE(el->getValue(s));
EXPECT_FALSE(el->getValue(v));
EXPECT_FALSE(el->getValue(m));
- EXPECT_EQ(i, 1);
- i = 2;
- EXPECT_TRUE(el->setValue(i));
- EXPECT_EQ(2, el->intValue());
- EXPECT_FALSE(el->setValue(d));
- EXPECT_FALSE(el->setValue(b));
- EXPECT_FALSE(el->setValue(s));
- EXPECT_FALSE(el->setValue(v));
- EXPECT_FALSE(el->setValue(m));
- EXPECT_THROW(el->get(1), TypeError);
- EXPECT_THROW(el->set(1, el), TypeError);
- EXPECT_THROW(el->add(el), TypeError);
- EXPECT_THROW(el->remove(1), TypeError);
- EXPECT_THROW(el->size(), TypeError);
- EXPECT_THROW(el->get("foo"), TypeError);
- EXPECT_THROW(el->set("foo", el), TypeError);
- EXPECT_THROW(el->remove("foo"), TypeError);
- EXPECT_THROW(el->contains("foo"), TypeError);
- ConstElementPtr tmp;
- EXPECT_FALSE(el->find("foo", tmp));
-
+ EXPECT_EQ(1, i);
+}
+
+template <typename T>
+void
+testGetValueDouble() {
+ T el;
+ long int i;
+ double d;
+ bool b;
+ std::string s;
+ std::vector<ConstElementPtr> v;
+ std::map<std::string, ConstElementPtr> m;
el = Element::create(1.1);
EXPECT_THROW(el->intValue(), TypeError);
@@ -231,15 +223,19 @@ TEST(Element, create_and_value_throws) {
EXPECT_FALSE(el->getValue(s));
EXPECT_FALSE(el->getValue(v));
EXPECT_FALSE(el->getValue(m));
- EXPECT_EQ(d, 1.1);
- d = 2.2;
- EXPECT_TRUE(el->setValue(d));
- EXPECT_EQ(2.2, el->doubleValue());
- EXPECT_FALSE(el->setValue(i));
- EXPECT_FALSE(el->setValue(b));
- EXPECT_FALSE(el->setValue(s));
- EXPECT_FALSE(el->setValue(v));
- EXPECT_FALSE(el->setValue(m));
+ EXPECT_EQ(1.1, d);
+}
+
+template <typename T>
+void
+testGetValueBool() {
+ T el;
+ long int i;
+ double d;
+ bool b;
+ std::string s;
+ std::vector<ConstElementPtr> v;
+ std::map<std::string, ConstElementPtr> m;
el = Element::create(true);
EXPECT_THROW(el->intValue(), TypeError);
@@ -254,10 +250,19 @@ TEST(Element, create_and_value_throws) {
EXPECT_FALSE(el->getValue(s));
EXPECT_FALSE(el->getValue(v));
EXPECT_FALSE(el->getValue(m));
- EXPECT_EQ(b, true);
- b = false;
- EXPECT_TRUE(el->setValue(b));
- EXPECT_FALSE(el->boolValue());
+ EXPECT_EQ(true, b);
+}
+
+template <typename T>
+void
+testGetValueString() {
+ T el;
+ long int i;
+ double d;
+ bool b;
+ std::string s;
+ std::vector<ConstElementPtr> v;
+ std::map<std::string, ConstElementPtr> m;
el = Element::create("foo");
EXPECT_THROW(el->intValue(), TypeError);
@@ -272,10 +277,19 @@ TEST(Element, create_and_value_throws) {
EXPECT_TRUE(el->getValue(s));
EXPECT_FALSE(el->getValue(v));
EXPECT_FALSE(el->getValue(m));
- EXPECT_EQ(s, "foo");
- s = "bar";
- EXPECT_TRUE(el->setValue(s));
- EXPECT_EQ("bar", el->stringValue());
+ EXPECT_EQ("foo", s);
+}
+
+template <typename T>
+void
+testGetValueList() {
+ T el;
+ long int i;
+ double d;
+ bool b;
+ std::string s;
+ std::vector<ConstElementPtr> v;
+ std::map<std::string, ConstElementPtr> m;
el = Element::createList();
EXPECT_THROW(el->intValue(), TypeError);
@@ -291,9 +305,18 @@ TEST(Element, create_and_value_throws) {
EXPECT_TRUE(el->getValue(v));
EXPECT_FALSE(el->getValue(m));
EXPECT_EQ("[ ]", el->str());
- v.push_back(Element::create(1));
- EXPECT_TRUE(el->setValue(v));
- EXPECT_EQ("[ 1 ]", el->str());
+}
+
+template <typename T>
+void
+testGetValueMap() {
+ T el;
+ long int i;
+ double d;
+ bool b;
+ std::string s;
+ std::vector<ConstElementPtr> v;
+ std::map<std::string, ConstElementPtr> m;
el = Element::createMap();
EXPECT_THROW(el->intValue(), TypeError);
@@ -308,7 +331,128 @@ TEST(Element, create_and_value_throws) {
EXPECT_FALSE(el->getValue(s));
EXPECT_FALSE(el->getValue(v));
EXPECT_TRUE(el->getValue(m));
+ EXPECT_EQ("{ }", el->str());
+}
+
+TEST(Element, create_and_value_throws) {
+ // this test checks whether elements throw exceptions if the
+ // incorrect type is requested
+ ElementPtr el;
+ ConstElementPtr cel;
+ long int i = 0;
+ double d = 0.0;
+ bool b = false;
+ std::string s("asdf");
+ std::vector<ConstElementPtr> v;
+ std::map<std::string, ConstElementPtr> m;
+ ConstElementPtr tmp;
+
+ testGetValueInt<ElementPtr>();
+ testGetValueInt<ConstElementPtr>();
+
+ el = Element::create(1);
+ i = 2;
+ EXPECT_TRUE(el->setValue(i));
+ EXPECT_EQ(2, el->intValue());
+ EXPECT_FALSE(el->setValue(d));
+ EXPECT_FALSE(el->setValue(b));
+ EXPECT_FALSE(el->setValue(s));
+ EXPECT_FALSE(el->setValue(v));
+ EXPECT_FALSE(el->setValue(m));
+ EXPECT_THROW(el->get(1), TypeError);
+ EXPECT_THROW(el->set(1, el), TypeError);
+ EXPECT_THROW(el->add(el), TypeError);
+ EXPECT_THROW(el->remove(1), TypeError);
+ EXPECT_THROW(el->size(), TypeError);
+ EXPECT_THROW(el->get("foo"), TypeError);
+ EXPECT_THROW(el->set("foo", el), TypeError);
+ EXPECT_THROW(el->remove("foo"), TypeError);
+ EXPECT_THROW(el->contains("foo"), TypeError);
+ EXPECT_FALSE(el->find("foo", tmp));
+
+ testGetValueDouble<ElementPtr>();
+ testGetValueDouble<ConstElementPtr>();
+
+ el = Element::create(1.1);
+ d = 2.2;
+ EXPECT_TRUE(el->setValue(d));
+ EXPECT_EQ(2.2, el->doubleValue());
+ EXPECT_FALSE(el->setValue(i));
+ EXPECT_FALSE(el->setValue(b));
+ EXPECT_FALSE(el->setValue(s));
+ EXPECT_FALSE(el->setValue(v));
+ EXPECT_FALSE(el->setValue(m));
+ EXPECT_THROW(el->get(1), TypeError);
+ EXPECT_THROW(el->set(1, el), TypeError);
+ EXPECT_THROW(el->add(el), TypeError);
+ EXPECT_THROW(el->remove(1), TypeError);
+ EXPECT_THROW(el->size(), TypeError);
+ EXPECT_THROW(el->get("foo"), TypeError);
+ EXPECT_THROW(el->set("foo", el), TypeError);
+ EXPECT_THROW(el->remove("foo"), TypeError);
+ EXPECT_THROW(el->contains("foo"), TypeError);
+ EXPECT_FALSE(el->find("foo", tmp));
+
+ testGetValueBool<ElementPtr>();
+ testGetValueBool<ConstElementPtr>();
+ el = Element::create(true);
+ b = false;
+ EXPECT_TRUE(el->setValue(b));
+ EXPECT_FALSE(el->boolValue());
+ EXPECT_FALSE(el->setValue(i));
+ EXPECT_FALSE(el->setValue(d));
+ EXPECT_FALSE(el->setValue(s));
+ EXPECT_FALSE(el->setValue(v));
+ EXPECT_FALSE(el->setValue(m));
+ EXPECT_THROW(el->get(1), TypeError);
+ EXPECT_THROW(el->set(1, el), TypeError);
+ EXPECT_THROW(el->add(el), TypeError);
+ EXPECT_THROW(el->remove(1), TypeError);
+ EXPECT_THROW(el->size(), TypeError);
+ EXPECT_THROW(el->get("foo"), TypeError);
+ EXPECT_THROW(el->set("foo", el), TypeError);
+ EXPECT_THROW(el->remove("foo"), TypeError);
+ EXPECT_THROW(el->contains("foo"), TypeError);
+ EXPECT_FALSE(el->find("foo", tmp));
+
+ testGetValueString<ElementPtr>();
+ testGetValueString<ConstElementPtr>();
+
+ el = Element::create("foo");
+ s = "bar";
+ EXPECT_TRUE(el->setValue(s));
+ EXPECT_EQ("bar", el->stringValue());
+ EXPECT_FALSE(el->setValue(i));
+ EXPECT_FALSE(el->setValue(b));
+ EXPECT_FALSE(el->setValue(d));
+ EXPECT_FALSE(el->setValue(v));
+ EXPECT_FALSE(el->setValue(m));
+ EXPECT_THROW(el->get(1), TypeError);
+ EXPECT_THROW(el->set(1, el), TypeError);
+ EXPECT_THROW(el->add(el), TypeError);
+ EXPECT_THROW(el->remove(1), TypeError);
+ EXPECT_THROW(el->size(), TypeError);
+ EXPECT_THROW(el->get("foo"), TypeError);
+ EXPECT_THROW(el->set("foo", el), TypeError);
+ EXPECT_THROW(el->remove("foo"), TypeError);
+ EXPECT_THROW(el->contains("foo"), TypeError);
+ EXPECT_FALSE(el->find("foo", tmp));
+
+ testGetValueList<ElementPtr>();
+ testGetValueList<ConstElementPtr>();
+
+ el = Element::createList();
+ v.push_back(Element::create(1));
+ EXPECT_TRUE(el->setValue(v));
+ EXPECT_EQ("[ 1 ]", el->str());
+
+ testGetValueMap<ElementPtr>();
+ testGetValueMap<ConstElementPtr>();
+
+ el = Element::createMap();
+ EXPECT_NO_THROW(el->set("foo", Element::create("bar")));
+ EXPECT_EQ("{ \"foo\": \"bar\" }", el->str());
}
// Helper for escape check; it puts the given string in a StringElement,
@@ -382,7 +526,7 @@ TEST(Element, MapElement) {
// this function checks the specific functions for ListElements
ElementPtr el = Element::fromJSON("{ \"name\": \"foo\", \"value1\": \"bar\", \"value2\": { \"number\": 42 } }");
ConstElementPtr el2;
-
+
EXPECT_EQ(el->get("name")->stringValue(), "foo");
EXPECT_EQ(el->get("value2")->getType(), Element::map);
@@ -396,11 +540,12 @@ TEST(Element, MapElement) {
EXPECT_EQ(el->find("value2/number")->intValue(), 42);
EXPECT_TRUE(isNull(el->find("value2/nothing/")));
-
+
EXPECT_EQ(el->find("value1")->stringValue(), "bar");
EXPECT_EQ(el->find("value1/")->stringValue(), "bar");
-
+
EXPECT_TRUE(el->find("value1", el2));
+ EXPECT_EQ("bar", el2->stringValue());
EXPECT_FALSE(el->find("name/error", el2));
// A map element whose (only) element has the maximum length of tag.
@@ -410,7 +555,7 @@ TEST(Element, MapElement) {
"9123456789abcdefa123456789abcdefb123456789abcdef"
"c123456789abcdefd123456789abcdefe123456789abcdef"
"f123456789abcde");
-
+
EXPECT_EQ(255, long_maptag.length()); // check prerequisite
el = Element::fromJSON("{ \"" + long_maptag + "\": \"bar\"}");
EXPECT_EQ("bar", el->find(long_maptag)->stringValue());
@@ -689,7 +834,7 @@ TEST(Element, merge) {
c = Element::fromJSON("{ \"a\": { \"b\": \"c\" } }");
merge(b, a);
EXPECT_EQ(*b, *c);
-
+
// And some tests with multiple values
a = Element::fromJSON("{ \"a\": 1, \"b\": true, \"c\": null }");
b = Element::fromJSON("{ \"a\": 1, \"b\": null, \"c\": \"a string\" }");
diff --git a/src/lib/config/ccsession.cc b/src/lib/config/ccsession.cc
index daec005..8516d6c 100644
--- a/src/lib/config/ccsession.cc
+++ b/src/lib/config/ccsession.cc
@@ -338,7 +338,7 @@ getRelatedLoggers(ConstElementPtr loggers) {
// Now find the wildcard names (the one that start with "*").
BOOST_FOREACH(ConstElementPtr cur_logger, loggers->listValue()) {
- std::string cur_name = cur_logger->get("name")->stringValue();
+ const std::string cur_name = cur_logger->get("name")->stringValue();
// If name is '*', or starts with '*.', replace * with root
// logger name.
if (cur_name == "*" || cur_name.length() > 1 &&
@@ -671,9 +671,7 @@ ModuleCCSession::fetchRemoteSpec(const std::string& module, bool is_filename) {
std::string
ModuleCCSession::addRemoteConfig(const std::string& spec_name,
- void (*handler)(const std::string& module,
- ConstElementPtr,
- const ConfigData&),
+ RemoteHandler handler,
bool spec_is_filename)
{
// First get the module name, specification and default config
diff --git a/src/lib/config/ccsession.h b/src/lib/config/ccsession.h
index e96a33d..b4a44d0 100644
--- a/src/lib/config/ccsession.h
+++ b/src/lib/config/ccsession.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __CCSESSION_H
-#define __CCSESSION_H 1
+#ifndef CCSESSION_H
+#define CCSESSION_H 1
#include <config/config_data.h>
#include <config/module_spec.h>
@@ -283,7 +283,7 @@ public:
* the configuration manager must know it). If
* spec_is_filename is true (the default), then a
* filename is assumed, otherwise a module name.
- * \param handler The handler function called whenever there's a change.
+ * \param handler The handler functor called whenever there's a change.
* Called once initally from this function. May be NULL
* if you don't want any handler to be called and you're
* fine with requesting the data through
@@ -296,11 +296,11 @@ public:
* \return The name of the module specified in the given specification
* file
*/
+ typedef boost::function<void(const std::string&,
+ isc::data::ConstElementPtr,
+ const ConfigData&)> RemoteHandler;
std::string addRemoteConfig(const std::string& spec_name,
- void (*handler)(const std::string& module_name,
- isc::data::ConstElementPtr
- update,
- const ConfigData& config_data) = NULL,
+ RemoteHandler handler = RemoteHandler(),
bool spec_is_filename = true);
/**
@@ -513,9 +513,6 @@ private:
const std::string& command,
isc::data::ConstElementPtr args);
- typedef void (*RemoteHandler)(const std::string&,
- isc::data::ConstElementPtr,
- const ConfigData&);
std::map<std::string, ConfigData> remote_module_configs_;
std::map<std::string, RemoteHandler> remote_module_handlers_;
@@ -579,7 +576,7 @@ getRelatedLoggers(isc::data::ConstElementPtr loggers);
} // namespace config
} // namespace isc
-#endif // __CCSESSION_H
+#endif // CCSESSION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/config/config_data.h b/src/lib/config/config_data.h
index 3fdbc25..0bb1bfd 100644
--- a/src/lib/config/config_data.h
+++ b/src/lib/config/config_data.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __CONFIG_DATA_H
-#define __CONFIG_DATA_H 1
+#ifndef CONFIG_DATA_H
+#define CONFIG_DATA_H 1
#include <string>
#include <vector>
diff --git a/src/lib/config/config_log.h b/src/lib/config/config_log.h
index 21709fd..14f681e 100644
--- a/src/lib/config/config_log.h
+++ b/src/lib/config/config_log.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __CONFIG_LOG__H
-#define __CONFIG_LOG__H
+#ifndef CONFIG_LOG_H
+#define CONFIG_LOG_H
#include <log/macros.h>
#include "config_messages.h"
@@ -38,4 +38,4 @@ const int DBG_CONFIG_PROCESS = DBGLVL_TRACE_BASIC;
} // namespace config
} // namespace isc
-#endif // __CONFIG_LOG__H
+#endif // CONFIG_LOG_H
diff --git a/src/lib/config/module_spec.h b/src/lib/config/module_spec.h
index 27dcfe3..d755125 100644
--- a/src/lib/config/module_spec.h
+++ b/src/lib/config/module_spec.h
@@ -13,8 +13,8 @@
// NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
// WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-#ifndef _MODULE_SPEC_H
-#define _MODULE_SPEC_H 1
+#ifndef MODULE_SPEC_H
+#define MODULE_SPEC_H 1
#include <cc/data.h>
diff --git a/src/lib/config/tests/fake_session.h b/src/lib/config/tests/fake_session.h
index c91b519..7d3cfde 100644
--- a/src/lib/config/tests/fake_session.h
+++ b/src/lib/config/tests/fake_session.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_FAKESESSION_H
-#define _ISC_FAKESESSION_H 1
+#ifndef ISC_FAKESESSION_H
+#define ISC_FAKESESSION_H 1
#include <string>
@@ -111,7 +111,7 @@ private:
} // namespace cc
} // namespace isc
-#endif // _ISC_FAKESESSION_H
+#endif // ISC_FAKESESSION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/config/tests/testdata/Makefile.am b/src/lib/config/tests/testdata/Makefile.am
index fce74d0..9b383d6 100644
--- a/src/lib/config/tests/testdata/Makefile.am
+++ b/src/lib/config/tests/testdata/Makefile.am
@@ -70,3 +70,4 @@ EXTRA_DIST += spec38.spec
EXTRA_DIST += spec39.spec
EXTRA_DIST += spec40.spec
EXTRA_DIST += spec41.spec
+EXTRA_DIST += spec42.spec
diff --git a/src/lib/config/tests/testdata/spec32.spec b/src/lib/config/tests/testdata/spec32.spec
index 854d967..2baf1c1 100644
--- a/src/lib/config/tests/testdata/spec32.spec
+++ b/src/lib/config/tests/testdata/spec32.spec
@@ -49,6 +49,22 @@
"item_optional": true
}
}
+ },
+ { "item_name": "named_set_item4",
+ "item_type": "named_set",
+ "item_optional": true,
+ "item_default": {},
+ "named_set_item_spec": {
+ "item_name": "named_set_element",
+ "item_type": "named_set",
+ "item_optional": false,
+ "item_default": { "a": 1, "b": 2 },
+ "named_set_item_spec":
+ { "item_name": "named_set_element",
+ "item_type": "integer",
+ "item_optional": true
+ }
+ }
}
]
}
diff --git a/src/lib/config/tests/testdata/spec42.spec b/src/lib/config/tests/testdata/spec42.spec
new file mode 100644
index 0000000..d822465
--- /dev/null
+++ b/src/lib/config/tests/testdata/spec42.spec
@@ -0,0 +1,17 @@
+{
+ "module_spec": {
+ "module_name": "Spec42",
+ "config_data": [
+ { "item_name": "list_item",
+ "item_type": "list",
+ "item_optional": true,
+ "list_item_spec": {
+ "item_name": "list_element",
+ "item_type": "string",
+ "item_optional": false,
+ "item_default": ""
+ }
+ }
+ ]
+ }
+}
diff --git a/src/lib/cryptolink/crypto_hmac.h b/src/lib/cryptolink/crypto_hmac.h
index 2eb0d0e..ac82785 100644
--- a/src/lib/cryptolink/crypto_hmac.h
+++ b/src/lib/cryptolink/crypto_hmac.h
@@ -18,8 +18,8 @@
#include <cryptolink/cryptolink.h>
-#ifndef _ISC_CRYPTO_HMAC_H
-#define _ISC_CRYPTO_HMAC_H
+#ifndef ISC_CRYPTO_HMAC_H
+#define ISC_CRYPTO_HMAC_H
namespace isc {
namespace cryptolink {
@@ -205,5 +205,5 @@ void deleteHMAC(HMAC* hmac);
} // namespace cryptolink
} // namespace isc
-#endif // __ISC_CRYPTO_HMAC
+#endif // ISC_CRYPTO_HMAC_H
diff --git a/src/lib/cryptolink/cryptolink.h b/src/lib/cryptolink/cryptolink.h
index d0f7d38..859065b 100644
--- a/src/lib/cryptolink/cryptolink.h
+++ b/src/lib/cryptolink/cryptolink.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_CRYPTO_H
-#define _ISC_CRYPTO_H
+#ifndef ISC_CRYPTO_H
+#define ISC_CRYPTO_H
#include <string>
#include <util/buffer.h>
@@ -205,4 +205,4 @@ private:
} // namespace cryptolink
} // namespace isc
-#endif // _ISC_CRYPTO_H
+#endif // ISC_CRYPTO_H
diff --git a/src/lib/datasrc/Makefile.am b/src/lib/datasrc/Makefile.am
index 862de8a..eccc147 100644
--- a/src/lib/datasrc/Makefile.am
+++ b/src/lib/datasrc/Makefile.am
@@ -12,7 +12,9 @@ pkglibdir = $(libexecdir)/@PACKAGE@/backends
datasrc_config.h: datasrc_config.h.pre
$(SED) -e "s|@@PKGLIBDIR@@|$(pkglibdir)|" datasrc_config.h.pre >$@
-static.zone: static.zone.pre
+# The top config.h defines "PACKAGE_STRING". When it's changed we neeed to
+# regenerate this zone file.
+static.zone: static.zone.pre $(top_builddir)/config.h $(top_srcdir)/AUTHORS
$(SED) -e "s|@@VERSION_STRING@@|$(PACKAGE_STRING)|" $(srcdir)/static.zone.pre >$@
$(SED) -e 's/\(.*\)/AUTHORS.BIND. 0 CH TXT "\1"/' $(top_srcdir)/AUTHORS >>$@
diff --git a/src/lib/datasrc/client.h b/src/lib/datasrc/client.h
index dab081f..3756a68 100644
--- a/src/lib/datasrc/client.h
+++ b/src/lib/datasrc/client.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATA_SOURCE_CLIENT_H
-#define __DATA_SOURCE_CLIENT_H 1
+#ifndef DATA_SOURCE_CLIENT_H
+#define DATA_SOURCE_CLIENT_H 1
#include <utility>
diff --git a/src/lib/datasrc/client_list.cc b/src/lib/datasrc/client_list.cc
index 865a1ce..e7fb63b 100644
--- a/src/lib/datasrc/client_list.cc
+++ b/src/lib/datasrc/client_list.cc
@@ -12,17 +12,21 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#include <util/memory_segment_local.h>
#include "client_list.h"
#include "client.h"
#include "factory.h"
#include "memory/memory_client.h"
+#include "memory/zone_table_segment.h"
+#include "memory/zone_writer.h"
+#include "memory/zone_data_loader.h"
#include "logger.h"
#include <dns/masterload.h>
+#include <util/memory_segment_local.h>
#include <memory>
#include <boost/foreach.hpp>
+#include <boost/bind.hpp>
using namespace isc::data;
using namespace isc::dns;
@@ -32,6 +36,7 @@ using boost::lexical_cast;
using boost::shared_ptr;
using boost::dynamic_pointer_cast;
using isc::datasrc::memory::InMemoryClient;
+using isc::datasrc::memory::ZoneTableSegment;
namespace isc {
namespace datasrc {
@@ -39,21 +44,24 @@ namespace datasrc {
ConfigurableClientList::DataSourceInfo::DataSourceInfo(
DataSourceClient* data_src_client,
const DataSourceClientContainerPtr& container, bool has_cache,
- const RRClass& rrclass, MemorySegment& mem_sgmt) :
+ const RRClass& rrclass, const shared_ptr<ZoneTableSegment>& segment) :
data_src_client_(data_src_client),
container_(container)
{
if (has_cache) {
- cache_.reset(new InMemoryClient(mem_sgmt, rrclass));
+ cache_.reset(new InMemoryClient(segment, rrclass));
+ ztable_segment_ = segment;
}
}
ConfigurableClientList::DataSourceInfo::DataSourceInfo(
- const RRClass& rrclass, MemorySegment& mem_sgmt, bool has_cache) :
+ const RRClass& rrclass, const shared_ptr<ZoneTableSegment>& segment,
+ bool has_cache) :
data_src_client_(NULL)
{
if (has_cache) {
- cache_.reset(new InMemoryClient(mem_sgmt, rrclass));
+ cache_.reset(new InMemoryClient(segment, rrclass));
+ ztable_segment_ = segment;
}
}
@@ -64,21 +72,10 @@ ConfigurableClientList::DataSourceInfo::getCacheClient() const {
ConfigurableClientList::ConfigurableClientList(const RRClass& rrclass) :
rrclass_(rrclass),
- mem_sgmt_(new util::MemorySegmentLocal),
configuration_(new isc::data::ListElement),
allow_cache_(false)
{}
-ConfigurableClientList::~ConfigurableClientList() {
- // Explicitly clear the contained data source clients, and check memory
- // leak. assert() (with abort on failure) may be too harsh, but
- // it's probably better to find more leaks initially. Once it's stabilized
- // we should probably revisit it.
-
- data_sources_.clear();
- assert(mem_sgmt_->allMemoryDeallocated());
-}
-
void
ConfigurableClientList::configure(const ConstElementPtr& config,
bool allow_cache)
@@ -90,6 +87,8 @@ ConfigurableClientList::configure(const ConstElementPtr& config,
size_t i(0); // Outside of the try to be able to access it in the catch
try {
vector<DataSourceInfo> new_data_sources;
+ shared_ptr<ZoneTableSegment> ztable_segment(
+ ZoneTableSegment::create(*config, rrclass_));
for (; i < config->size(); ++i) {
// Extract the parameters
const ConstElementPtr dconf(config->get(i));
@@ -126,7 +125,8 @@ ConfigurableClientList::configure(const ConstElementPtr& config,
isc_throw(ConfigurationError, "The cache must be enabled "
"for the MasterFiles type");
}
- new_data_sources.push_back(DataSourceInfo(rrclass_, *mem_sgmt_,
+ new_data_sources.push_back(DataSourceInfo(rrclass_,
+ ztable_segment,
true));
} else {
// Ask the factory to create the data source for us
@@ -135,7 +135,7 @@ ConfigurableClientList::configure(const ConstElementPtr& config,
// And put it into the vector
new_data_sources.push_back(DataSourceInfo(ds.first, ds.second,
want_cache, rrclass_,
- *mem_sgmt_));
+ ztable_segment));
}
if (want_cache) {
@@ -337,33 +337,93 @@ ConfigurableClientList::findInternal(MutableResult& candidate,
// and the need_updater parameter is true, get the zone there.
}
+// We still provide this method for backward compatibility. But to not have
+// duplicate code, it is a thin wrapper around getCachedZoneWriter only.
ConfigurableClientList::ReloadResult
ConfigurableClientList::reload(const Name& name) {
+ const ZoneWriterPair result(getCachedZoneWriter(name));
+ if (result.first != ZONE_SUCCESS) {
+ return (result.first);
+ }
+
+ assert(result.second);
+ result.second->load();
+ result.second->install();
+ result.second->cleanup();
+
+ return (ZONE_SUCCESS);
+}
+
+namespace {
+
+// We would like to use boost::bind for this. However, the loadZoneData takes
+// a reference, while we have a shared pointer to the iterator -- and we need
+// to keep it alive as long as the ZoneWriter is alive. Therefore we can't
+// really just dereference it and pass it, since it would get destroyed once
+// the getCachedZoneWriter would end. This class holds the shared pointer
+// alive, otherwise is mostly simple.
+//
+// It might be doable with nested boost::bind, but it would probably look
+// more awkward and complicated than this.
+class IteratorLoader {
+public:
+ IteratorLoader(const RRClass& rrclass, const Name& name,
+ const ZoneIteratorPtr& iterator) :
+ rrclass_(rrclass),
+ name_(name),
+ iterator_(iterator)
+ {}
+ memory::ZoneData* operator()(util::MemorySegment& segment) {
+ return (memory::loadZoneData(segment, rrclass_, name_, *iterator_));
+ }
+private:
+ const RRClass rrclass_;
+ const Name name_;
+ ZoneIteratorPtr iterator_;
+};
+
+// We can't use the loadZoneData function directly in boost::bind, since
+// it is overloaded and the compiler can't choose the correct version
+// reliably and fails. So we simply wrap it into an unique name.
+memory::ZoneData*
+loadZoneDataFromFile(util::MemorySegment& segment, const RRClass& rrclass,
+ const Name& name, const string& filename)
+{
+ return (memory::loadZoneData(segment, rrclass, name, filename));
+}
+
+}
+
+ConfigurableClientList::ZoneWriterPair
+ConfigurableClientList::getCachedZoneWriter(const Name& name) {
if (!allow_cache_) {
- return (CACHE_DISABLED);
+ return (ZoneWriterPair(CACHE_DISABLED, ZoneWriterPtr()));
}
// Try to find the correct zone.
MutableResult result;
findInternal(result, name, true, true);
if (!result.finder) {
- return (ZONE_NOT_FOUND);
+ return (ZoneWriterPair(ZONE_NOT_FOUND, ZoneWriterPtr()));
}
- // Try to convert the finder to in-memory one. If it is the cache,
- // it should work.
- // It is of a different type or there's no cache.
+ // Try to get the in-memory cache for the zone. If there's none,
+ // we can't provide the result.
if (!result.info->cache_) {
- return (ZONE_NOT_CACHED);
+ return (ZoneWriterPair(ZONE_NOT_CACHED, ZoneWriterPtr()));
}
+ memory::LoadAction load_action;
DataSourceClient* client(result.info->data_src_client_);
- if (client) {
- // Now do the final reload. If it does not exist in client,
+ if (client != NULL) {
+ // Now finally provide the writer.
+ // If it does not exist in client,
// DataSourceError is thrown, which is exactly the result what we
// want, so no need to handle it.
ZoneIteratorPtr iterator(client->getIterator(name));
if (!iterator) {
isc_throw(isc::Unexpected, "Null iterator from " << name);
}
- result.info->cache_->load(name, *iterator);
+ // And wrap the iterator into the correct functor (which
+ // keeps it alive as long as it is needed).
+ load_action = IteratorLoader(rrclass_, name, iterator);
} else {
// The MasterFiles special case
const string filename(result.info->cache_->getFileName(name));
@@ -371,9 +431,14 @@ ConfigurableClientList::reload(const Name& name) {
isc_throw(isc::Unexpected, "Confused about missing both filename "
"and data source");
}
- result.info->cache_->load(name, filename);
+ // boost::bind is enough here.
+ load_action = boost::bind(loadZoneDataFromFile, _1, rrclass_, name,
+ filename);
}
- return (ZONE_RELOADED);
+ return (ZoneWriterPair(ZONE_SUCCESS,
+ ZoneWriterPtr(
+ result.info->ztable_segment_->
+ getZoneWriter(load_action, name, rrclass_))));
}
// NOTE: This function is not tested, it would be complicated. However, the
diff --git a/src/lib/datasrc/client_list.h b/src/lib/datasrc/client_list.h
index 61544ef..d1a35b5 100644
--- a/src/lib/datasrc/client_list.h
+++ b/src/lib/datasrc/client_list.h
@@ -21,6 +21,7 @@
#include <dns/rrclass.h>
#include <cc/data.h>
#include <exceptions/exceptions.h>
+#include "memory/zone_table_segment.h"
#include <vector>
#include <boost/shared_ptr.hpp>
@@ -37,12 +38,12 @@ typedef boost::shared_ptr<DataSourceClient> DataSourceClientPtr;
class DataSourceClientContainer;
typedef boost::shared_ptr<DataSourceClientContainer>
DataSourceClientContainerPtr;
-
// XXX: it's better to even hide the existence of the "memory" namespace.
// We should probably consider pimpl for details of ConfigurableClientList
// and hide real definitions except for itself and tests.
namespace memory {
class InMemoryClient;
+class ZoneWriter;
}
/// \brief The list of data source clients.
@@ -220,9 +221,6 @@ public:
/// \param rrclass For which class the list should work.
ConfigurableClientList(const isc::dns::RRClass& rrclass);
- /// \brief Destructor
- virtual ~ConfigurableClientList();
-
/// \brief Exception thrown when there's an error in configuration.
class ConfigurationError : public Exception {
public:
@@ -272,7 +270,8 @@ public:
CACHE_DISABLED, ///< The cache is not enabled in this list.
ZONE_NOT_CACHED, ///< Zone is served directly, not from cache.
ZONE_NOT_FOUND, ///< Zone does not exist or not cached.
- ZONE_RELOADED ///< The zone was successfully reloaded.
+ ZONE_SUCCESS ///< The zone was successfully reloaded or
+ /// the writer provided.
};
/// \brief Reloads a cached zone.
@@ -289,6 +288,36 @@ public:
/// the original data source no longer contains the cached zone.
ReloadResult reload(const dns::Name& zone);
+private:
+ /// \brief Convenience type shortcut
+ typedef boost::shared_ptr<memory::ZoneWriter> ZoneWriterPtr;
+public:
+
+ /// \brief Return value of getCachedZoneWriter()
+ ///
+ /// A pair containing status and the zone writer, for the
+ /// getCachedZoneWriter() method.
+ typedef std::pair<ReloadResult, ZoneWriterPtr> ZoneWriterPair;
+
+ /// \brief Return a zone writer that can be used to reload a zone.
+ ///
+ /// This looks up a cached copy of zone and returns the ZoneWriter
+ /// that can be used to reload the content of the zone. This can
+ /// be used instead of reload() -- reload() works synchronously, which
+ /// is not what is needed every time.
+ ///
+ /// \param zone The origin of the zone to reload.
+ /// \return The result has two parts. The first one is a status describing
+ /// if it worked or not (and in case it didn't, also why). If the
+ /// status is ZONE_SUCCESS, the second part contains a shared pointer
+ /// to the writer. If the status is anything else, the second part is
+ /// NULL.
+ /// \throw DataSourceError or anything else that the data source
+ /// containing the zone might throw is propagated.
+ /// \throw DataSourceError if something unexpected happens, like when
+ /// the original data source no longer contains the cached zone.
+ ZoneWriterPair getCachedZoneWriter(const dns::Name& zone);
+
/// \brief Implementation of the ClientList::find.
virtual FindResult find(const dns::Name& zone,
bool want_exact_match = false,
@@ -300,12 +329,16 @@ public:
struct DataSourceInfo {
// Plays a role of default constructor too (for vector)
DataSourceInfo(const dns::RRClass& rrclass,
- util::MemorySegment& mem_sgmt,
+ const boost::shared_ptr
+ <isc::datasrc::memory::ZoneTableSegment>&
+ ztable_segment,
bool has_cache = false);
DataSourceInfo(DataSourceClient* data_src_client,
const DataSourceClientContainerPtr& container,
bool has_cache, const dns::RRClass& rrclass,
- util::MemorySegment& mem_sgmt);
+ const boost::shared_ptr
+ <isc::datasrc::memory::ZoneTableSegment>&
+ ztable_segment);
DataSourceClient* data_src_client_;
DataSourceClientContainerPtr container_;
@@ -316,6 +349,7 @@ public:
// No other applications or tests may use it.
const DataSourceClient* getCacheClient() const;
boost::shared_ptr<memory::InMemoryClient> cache_;
+ boost::shared_ptr<memory::ZoneTableSegment> ztable_segment_;
};
/// \brief The collection of data sources.
@@ -370,12 +404,6 @@ private:
bool want_exact_match, bool want_finder) const;
const isc::dns::RRClass rrclass_;
- /// \brief Memory segment for in-memory cache.
- ///
- /// Note that this must be placed before data_sources_ so it won't be
- /// destroyed before the built objects in the destructor.
- boost::scoped_ptr<util::MemorySegment> mem_sgmt_;
-
/// \brief Currently active configuration.
isc::data::ConstElementPtr configuration_;
@@ -391,6 +419,11 @@ protected:
DataSources data_sources_;
};
+/// \brief Shortcut typedef for maps of client_lists.
+typedef boost::shared_ptr<std::map<
+ isc::dns::RRClass, boost::shared_ptr<ConfigurableClientList> > >
+ ClientListMapPtr;
+
} // namespace datasrc
} // namespace isc
diff --git a/src/lib/datasrc/data_source.h b/src/lib/datasrc/data_source.h
index 37c536e..bf5a7d7 100644
--- a/src/lib/datasrc/data_source.h
+++ b/src/lib/datasrc/data_source.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATA_SOURCE_H
-#define __DATA_SOURCE_H
+#ifndef DATA_SOURCE_H
+#define DATA_SOURCE_H
#include <stdint.h>
diff --git a/src/lib/datasrc/database.cc b/src/lib/datasrc/database.cc
index ede7aa3..fbada44 100644
--- a/src/lib/datasrc/database.cc
+++ b/src/lib/datasrc/database.cc
@@ -386,10 +386,11 @@ DatabaseClient::Finder::findAll(const isc::dns::Name& name,
std::vector<isc::dns::ConstRRsetPtr>& target,
const FindOptions options)
{
- return (ZoneFinderContextPtr(new Context(*this, options,
- findInternal(name, RRType::ANY(),
- &target, options),
- target)));
+ return (ZoneFinderContextPtr(new GenericContext(
+ *this, options,
+ findInternal(name, RRType::ANY(),
+ &target, options),
+ target)));
}
ZoneFinderContextPtr
@@ -400,9 +401,10 @@ DatabaseClient::Finder::find(const isc::dns::Name& name,
if (type == RRType::ANY()) {
isc_throw(isc::Unexpected, "Use findAll to answer ANY");
}
- return (ZoneFinderContextPtr(new Context(*this, options,
- findInternal(name, type, NULL,
- options))));
+ return (ZoneFinderContextPtr(new GenericContext(
+ *this, options,
+ findInternal(name, type, NULL,
+ options))));
}
DatabaseClient::Finder::DelegationSearchResult
diff --git a/src/lib/datasrc/database.h b/src/lib/datasrc/database.h
index 6895509..320f327 100644
--- a/src/lib/datasrc/database.h
+++ b/src/lib/datasrc/database.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATABASE_DATASRC_H
-#define __DATABASE_DATASRC_H
+#ifndef DATABASE_DATASRC_H
+#define DATABASE_DATASRC_H
#include <string>
@@ -1425,7 +1425,7 @@ private:
}
}
-#endif // __DATABASE_DATASRC_H
+#endif // DATABASE_DATASRC_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/datasrc_config.h.pre.in b/src/lib/datasrc/datasrc_config.h.pre.in
index 9074df6..221cab0 100644
--- a/src/lib/datasrc/datasrc_config.h.pre.in
+++ b/src/lib/datasrc/datasrc_config.h.pre.in
@@ -11,8 +11,9 @@
// 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_CONFIG_H
-#define __DATASRC_CONFIG_H 1
+
+#ifndef DATASRC_CONFIG_H
+#define DATASRC_CONFIG_H 1
namespace isc {
namespace datasrc {
@@ -28,4 +29,4 @@ const char* const BACKEND_LIBRARY_PATH = "@@PKGLIBDIR@@/";
} // end namespace datasrc
} // end namespace isc
-#endif // __DATASRC_CONFIG_H
+#endif // DATASRC_CONFIG_H
diff --git a/src/lib/datasrc/factory.h b/src/lib/datasrc/factory.h
index 2731f58..45e4f9b 100644
--- a/src/lib/datasrc/factory.h
+++ b/src/lib/datasrc/factory.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATA_SOURCE_FACTORY_H
-#define __DATA_SOURCE_FACTORY_H 1
+#ifndef DATA_SOURCE_FACTORY_H
+#define DATA_SOURCE_FACTORY_H 1
#include <datasrc/data_source.h>
#include <datasrc/client.h>
diff --git a/src/lib/datasrc/iterator.h b/src/lib/datasrc/iterator.h
index 99d3331..e1c6929 100644
--- a/src/lib/datasrc/iterator.h
+++ b/src/lib/datasrc/iterator.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATASRC_ZONE_ITERATOR_H
-#define __DATASRC_ZONE_ITERATOR_H 1
+#ifndef DATASRC_ZONE_ITERATOR_H
+#define DATASRC_ZONE_ITERATOR_H 1
#include <dns/rrset.h>
@@ -98,7 +98,7 @@ public:
}
}
-#endif // __DATASRC_ZONE_ITERATOR_H
+#endif // DATASRC_ZONE_ITERATOR_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/logger.h b/src/lib/datasrc/logger.h
index db4e5cb..a270082 100644
--- a/src/lib/datasrc/logger.h
+++ b/src/lib/datasrc/logger.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATASRC_LOGGER_H
-#define __DATASRC_LOGGER_H
+#ifndef DATASRC_LOGGER_H
+#define DATASRC_LOGGER_H
#include <log/macros.h>
#include <datasrc/datasrc_messages.h>
diff --git a/src/lib/datasrc/memory/Makefile.am b/src/lib/datasrc/memory/Makefile.am
index 3bdec0d..7b82269 100644
--- a/src/lib/datasrc/memory/Makefile.am
+++ b/src/lib/datasrc/memory/Makefile.am
@@ -16,10 +16,18 @@ libdatasrc_memory_la_SOURCES += treenode_rrset.h treenode_rrset.cc
libdatasrc_memory_la_SOURCES += rdata_serialization.h rdata_serialization.cc
libdatasrc_memory_la_SOURCES += zone_data.h zone_data.cc
libdatasrc_memory_la_SOURCES += segment_object_holder.h
-libdatasrc_memory_la_SOURCES += memory_client.h memory_client.cc
libdatasrc_memory_la_SOURCES += logger.h logger.cc
libdatasrc_memory_la_SOURCES += zone_table.h zone_table.cc
libdatasrc_memory_la_SOURCES += zone_finder.h zone_finder.cc
+libdatasrc_memory_la_SOURCES += zone_table_segment.h zone_table_segment.cc
+libdatasrc_memory_la_SOURCES += zone_table_segment_local.h zone_table_segment_local.cc
+libdatasrc_memory_la_SOURCES += zone_data_updater.h zone_data_updater.cc
+libdatasrc_memory_la_SOURCES += zone_data_loader.h zone_data_loader.cc
+libdatasrc_memory_la_SOURCES += memory_client.h memory_client.cc
+libdatasrc_memory_la_SOURCES += zone_writer.h
+libdatasrc_memory_la_SOURCES += zone_writer_local.h zone_writer_local.cc
+libdatasrc_memory_la_SOURCES += load_action.h
+
nodist_libdatasrc_memory_la_SOURCES = memory_messages.h memory_messages.cc
EXTRA_DIST = rdata_serialization_priv.cc
diff --git a/src/lib/datasrc/memory/domaintree.h b/src/lib/datasrc/memory/domaintree.h
index 20f4693..4816452 100644
--- a/src/lib/datasrc/memory/domaintree.h
+++ b/src/lib/datasrc/memory/domaintree.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _DOMAINTREE_H
-#define _DOMAINTREE_H 1
+#ifndef DOMAINTREE_H
+#define DOMAINTREE_H 1
//! \file datasrc/memory/domaintree.h
///
@@ -947,7 +947,7 @@ public:
PARTIALMATCH, ///< A superdomain node was found
NOTFOUND, ///< Not even any superdomain was found
/// \brief Returned by insert() if a node of the name already exists
- ALREADYEXISTS,
+ ALREADYEXISTS
};
/// \brief Allocate and construct \c DomainTree
@@ -1080,55 +1080,25 @@ public:
/// of it. In that case, node parameter is left intact.
//@{
- /// \brief Simple find.
+ /// \brief Simple find
///
/// Acts as described in the \ref find section.
Result find(const isc::dns::Name& name,
- DomainTreeNode<T>** node) const {
- DomainTreeNodeChain<T> node_path;
- const isc::dns::LabelSequence ls(name);
- return (find<void*>(ls, node, node_path, NULL, NULL));
- }
-
- /// \brief Simple find returning immutable node.
- ///
- /// Acts as described in the \ref find section, but returns immutable node
- /// pointer.
- Result find(const isc::dns::Name& name,
const DomainTreeNode<T>** node) const {
DomainTreeNodeChain<T> node_path;
- DomainTreeNode<T> *target_node = NULL;
const isc::dns::LabelSequence ls(name);
- Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
- if (ret != NOTFOUND) {
- *node = target_node;
- }
+ Result ret = (find<void*>(ls, node, node_path, NULL, NULL));
return (ret);
}
/// \brief Simple find, with node_path tracking
///
/// Acts as described in the \ref find section.
- Result find(const isc::dns::Name& name, DomainTreeNode<T>** node,
- DomainTreeNodeChain<T>& node_path) const
- {
- const isc::dns::LabelSequence ls(name);
- return (find<void*>(ls, node, node_path, NULL, NULL));
- }
-
- /// \brief Simple find returning immutable node, with node_path tracking
- ///
- /// Acts as described in the \ref find section, but returns immutable node
- /// pointer.
Result find(const isc::dns::Name& name, const DomainTreeNode<T>** node,
DomainTreeNodeChain<T>& node_path) const
{
- DomainTreeNode<T> *target_node = NULL;
const isc::dns::LabelSequence ls(name);
- Result ret = (find<void*>(ls, &target_node, node_path, NULL, NULL));
- if (ret != NOTFOUND) {
- *node = target_node;
- }
+ Result ret = (find<void*>(ls, node, node_path, NULL, NULL));
return (ret);
}
@@ -1143,13 +1113,9 @@ public:
bool (*callback)(const DomainTreeNode<T>&, CBARG),
CBARG callback_arg) const
{
- DomainTreeNode<T>* target_node = NULL;
const isc::dns::LabelSequence ls(name);
- Result ret = find(ls, &target_node, node_path, callback,
+ Result ret = find(ls, node, node_path, callback,
callback_arg);
- if (ret != NOTFOUND) {
- *node = target_node;
- }
return (ret);
}
@@ -1229,30 +1195,10 @@ public:
/// \c true, it returns immediately with the current node.
template <typename CBARG>
Result find(const isc::dns::LabelSequence& target_labels_orig,
- DomainTreeNode<T>** node,
- DomainTreeNodeChain<T>& node_path,
- bool (*callback)(const DomainTreeNode<T>&, CBARG),
- CBARG callback_arg) const;
-
- /// \brief Simple find returning immutable node.
- ///
- /// Acts as described in the \ref find section, but returns immutable
- /// node pointer.
- template <typename CBARG>
- Result find(const isc::dns::LabelSequence& target_labels,
const DomainTreeNode<T>** node,
DomainTreeNodeChain<T>& node_path,
bool (*callback)(const DomainTreeNode<T>&, CBARG),
- CBARG callback_arg) const
- {
- DomainTreeNode<T>* target_node = NULL;
- Result ret = find(target_labels, &target_node, node_path,
- callback, callback_arg);
- if (ret != NOTFOUND) {
- *node = target_node;
- }
- return (ret);
- }
+ CBARG callback_arg) const;
//@}
/// \brief return the next bigger node in DNSSEC order from a given node
@@ -1515,7 +1461,7 @@ template <typename T>
template <typename CBARG>
typename DomainTree<T>::Result
DomainTree<T>::find(const isc::dns::LabelSequence& target_labels_orig,
- DomainTreeNode<T>** target,
+ const DomainTreeNode<T>** target,
DomainTreeNodeChain<T>& node_path,
bool (*callback)(const DomainTreeNode<T>&, CBARG),
CBARG callback_arg) const
@@ -1526,11 +1472,11 @@ DomainTree<T>::find(const isc::dns::LabelSequence& target_labels_orig,
" and label sequence");
}
- DomainTreeNode<T>* node;
+ const DomainTreeNode<T>* node;
if (!node_path.isEmpty()) {
// Get the top node in the node chain
- node = const_cast<DomainTreeNode<T>*>(node_path.top());
+ node = node_path.top();
// Start searching from its down pointer
node = node->getDown();
} else {
@@ -2180,7 +2126,7 @@ DomainTree<T>::dumpDotHelper(std::ostream& os,
} // namespace datasrc
} // namespace isc
-#endif // _DOMAINTREE_H
+#endif // DOMAINTREE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/memory/load_action.h b/src/lib/datasrc/memory/load_action.h
new file mode 100644
index 0000000..f9625af
--- /dev/null
+++ b/src/lib/datasrc/memory/load_action.h
@@ -0,0 +1,47 @@
+// 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 LOAD_ACTION_H
+#define LOAD_ACTION_H
+
+#include <boost/function.hpp>
+
+namespace isc {
+// Forward declarations
+namespace util{
+class MemorySegment;
+}
+namespace datasrc {
+namespace memory {
+class ZoneData;
+
+/// \brief Callback to load data into the memory
+///
+/// This is called from the ZoneWriter whenever there's need to load the
+/// zone data. The callback should allocate new ZoneData and fill it with
+/// the zone content. It is up to the callback to know where or how to
+/// load the data, or even the origin and class of the zone (it is assumed
+/// the callback will be some kind of functor).
+///
+/// All data should be allocated from the passed MemorySegment. The ownership
+/// is passed onto the caller.
+///
+/// It must not return NULL.
+typedef boost::function<ZoneData*(util::MemorySegment&)> LoadAction;
+
+}
+}
+}
+
+#endif
diff --git a/src/lib/datasrc/memory/memory_client.cc b/src/lib/datasrc/memory/memory_client.cc
index a51a1a0..65e1e3b 100644
--- a/src/lib/datasrc/memory/memory_client.cc
+++ b/src/lib/datasrc/memory/memory_client.cc
@@ -17,12 +17,12 @@
#include <datasrc/memory/memory_client.h>
#include <datasrc/memory/logger.h>
#include <datasrc/memory/zone_data.h>
-#include <datasrc/memory/rdata_serialization.h>
#include <datasrc/memory/rdataset.h>
-#include <datasrc/memory/domaintree.h>
#include <datasrc/memory/segment_object_holder.h>
#include <datasrc/memory/treenode_rrset.h>
#include <datasrc/memory/zone_finder.h>
+#include <datasrc/memory/zone_data_loader.h>
+#include <datasrc/memory/zone_table_segment.h>
#include <util/memory_segment_local.h>
@@ -31,21 +31,10 @@
#include <datasrc/result.h>
#include <dns/name.h>
-#include <dns/nsec3hash.h>
#include <dns/rdataclass.h>
#include <dns/rrclass.h>
-#include <dns/rrsetlist.h>
-#include <dns/masterload.h>
-
-#include <boost/function.hpp>
-#include <boost/shared_ptr.hpp>
-#include <boost/scoped_ptr.hpp>
-#include <boost/bind.hpp>
-#include <boost/foreach.hpp>
-#include <boost/noncopyable.hpp>
#include <algorithm>
-#include <map>
#include <utility>
#include <cctype>
#include <cassert>
@@ -54,560 +43,53 @@ using namespace std;
using namespace isc::dns;
using namespace isc::dns::rdata;
using namespace isc::datasrc::memory;
-using boost::scoped_ptr;
+using namespace isc::util;
namespace isc {
namespace datasrc {
namespace memory {
using detail::SegmentObjectHolder;
+using boost::shared_ptr;
-namespace {
-// Some type aliases
-typedef DomainTree<std::string> FileNameTree;
-typedef DomainTreeNode<std::string> FileNameNode;
-
-// A functor type used for loading.
-typedef boost::function<void(ConstRRsetPtr)> LoadCallback;
-
-} // end of anonymous namespace
-
-/// Implementation details for \c InMemoryClient hidden from the public
-/// interface.
-///
-/// For now, \c InMemoryClient only contains a \c ZoneTable object, which
-/// consists of (pointers to) \c InMemoryZoneFinder objects, we may add more
-/// member variables later for new features.
-class InMemoryClient::InMemoryClientImpl {
-private:
- // The deleter for the filenames stored in the tree.
- struct FileNameDeleter {
- FileNameDeleter() {}
- void operator()(std::string* filename) const {
- delete filename;
- }
- };
+namespace { // unnamed namespace
+// A helper internal class used by the memory client, used for deleting
+// filenames stored in an internal tree.
+class FileNameDeleter {
public:
- InMemoryClientImpl(util::MemorySegment& mem_sgmt, RRClass rrclass) :
- mem_sgmt_(mem_sgmt),
- rrclass_(rrclass),
- zone_count_(0),
- zone_table_(ZoneTable::create(mem_sgmt_, rrclass)),
- file_name_tree_(FileNameTree::create(mem_sgmt_, false))
- {}
- ~InMemoryClientImpl() {
- FileNameDeleter deleter;
- FileNameTree::destroy(mem_sgmt_, file_name_tree_, deleter);
-
- ZoneTable::destroy(mem_sgmt_, zone_table_, rrclass_);
- }
-
- util::MemorySegment& mem_sgmt_;
- const RRClass rrclass_;
- unsigned int zone_count_;
- ZoneTable* zone_table_;
- FileNameTree* file_name_tree_;
-
- // Common process for zone load.
- // rrset_installer is a functor that takes another functor as an argument,
- // and expected to call the latter for each RRset of the zone. How the
- // sequence of the RRsets is generated depends on the internal
- // details of the loader: either from a textual master file or from
- // another data source.
- // filename is the file name of the master file or empty if the zone is
- // loaded from another data source.
- result::Result load(const Name& zone_name, const string& filename,
- boost::function<void(LoadCallback)> rrset_installer);
-
- // Add the necessary magic for any wildcard contained in 'name'
- // (including itself) to be found in the zone.
- //
- // In order for wildcard matching to work correctly in the zone finder,
- // we must ensure that a node for the wildcarding level exists in the
- // backend RBTree.
- // E.g. if the wildcard name is "*.sub.example." then we must ensure
- // that "sub.example." exists and is marked as a wildcard level.
- // Note: the "wildcarding level" is for the parent name of the wildcard
- // name (such as "sub.example.").
- //
- // We also perform the same trick for empty wild card names possibly
- // contained in 'name' (e.g., '*.foo.example' in 'bar.*.foo.example').
- void addWildcards(const Name& zone_name, ZoneData& zone_data,
- const Name& name)
- {
- Name wname(name);
- const unsigned int labels(wname.getLabelCount());
- const unsigned int origin_labels(zone_name.getLabelCount());
- for (unsigned int l = labels;
- l > origin_labels;
- --l, wname = wname.split(1)) {
- if (wname.isWildcard()) {
- LOG_DEBUG(logger, DBG_TRACE_DATA,
- DATASRC_MEMORY_MEM_ADD_WILDCARD).arg(name);
-
- // Ensure a separate level exists for the "wildcarding" name,
- // and mark the node as "wild".
- ZoneNode* node;
- zone_data.insertName(mem_sgmt_, wname.split(1), &node);
- node->setFlag(ZoneData::WILDCARD_NODE);
-
- // Ensure a separate level exists for the wildcard name.
- // Note: for 'name' itself we do this later anyway, but the
- // overhead should be marginal because wildcard names should
- // be rare.
- zone_data.insertName(mem_sgmt_, wname, &node);
- }
- }
- }
-
- /*
- * Does some checks in context of the data that are already in the zone.
- * Currently checks for forbidden combinations of RRsets in the same
- * domain (CNAME+anything, DNAME+NS).
- *
- * If such condition is found, it throws AddError.
- */
- void contextCheck(const Name& zone_name, const AbstractRRset& rrset,
- const RdataSet* set) const
- {
- // Ensure CNAME and other type of RR don't coexist for the same
- // owner name except with NSEC, which is the only RR that can coexist
- // with CNAME (and also RRSIG, which is handled separately)
- if (rrset.getType() == RRType::CNAME()) {
- for (const RdataSet* sp = set; sp != NULL; sp = sp->getNext()) {
- if (sp->type != RRType::NSEC()) {
- LOG_ERROR(logger, DATASRC_MEMORY_MEM_CNAME_TO_NONEMPTY).
- arg(rrset.getName());
- isc_throw(AddError, "CNAME can't be added with "
- << sp->type << " RRType for "
- << rrset.getName());
- }
- }
- } else if ((rrset.getType() != RRType::NSEC()) &&
- (RdataSet::find(set, RRType::CNAME()) != NULL)) {
- LOG_ERROR(logger,
- DATASRC_MEMORY_MEM_CNAME_COEXIST).arg(rrset.getName());
- isc_throw(AddError, "CNAME and " << rrset.getType() <<
- " can't coexist for " << rrset.getName());
- }
-
- /*
- * Similar with DNAME, but it must not coexist only with NS and only in
- * non-apex domains.
- * RFC 2672 section 3 mentions that it is implied from it and RFC 2181
- */
- if (rrset.getName() != zone_name &&
- // Adding DNAME, NS already there
- ((rrset.getType() == RRType::DNAME() &&
- RdataSet::find(set, RRType::NS()) != NULL) ||
- // Adding NS, DNAME already there
- (rrset.getType() == RRType::NS() &&
- RdataSet::find(set, RRType::DNAME()) != NULL)))
- {
- LOG_ERROR(logger, DATASRC_MEMORY_MEM_DNAME_NS).arg(rrset.getName());
- isc_throw(AddError, "DNAME can't coexist with NS in non-apex "
- "domain " << rrset.getName());
- }
- }
-
- // Validate rrset before adding it to the zone. If something is wrong
- // it throws an exception. It doesn't modify the zone, and provides
- // the strong exception guarantee.
- void addValidation(const Name& zone_name, const ConstRRsetPtr rrset) {
- if (!rrset) {
- isc_throw(NullRRset, "The rrset provided is NULL");
- }
- if (rrset->getRdataCount() == 0) {
- isc_throw(AddError, "The rrset provided is empty: " <<
- rrset->getName() << "/" << rrset->getType());
- }
- // Check for singleton RRs. It should probably handled at a different
- // layer in future.
- if ((rrset->getType() == RRType::CNAME() ||
- rrset->getType() == RRType::DNAME()) &&
- rrset->getRdataCount() > 1)
- {
- // XXX: this is not only for CNAME or DNAME. We should generalize
- // this code for all other "singleton RR types" (such as SOA) in a
- // separate task.
- LOG_ERROR(logger,
- DATASRC_MEMORY_MEM_SINGLETON).arg(rrset->getName()).
- arg(rrset->getType());
- isc_throw(AddError, "multiple RRs of singleton type for "
- << rrset->getName());
- }
- // NSEC3/NSEC3PARAM is not a "singleton" per protocol, but this
- // implementation requests it be so at the moment.
- if ((rrset->getType() == RRType::NSEC3() ||
- rrset->getType() == RRType::NSEC3PARAM()) &&
- rrset->getRdataCount() > 1) {
- isc_throw(AddError, "Multiple NSEC3/NSEC3PARAM RDATA is given for "
- << rrset->getName() << " which isn't supported");
- }
-
- // For RRSIGs, check consistency of the type covered.
- // We know the RRset isn't empty, so the following check is safe.
- if (rrset->getType() == RRType::RRSIG()) {
- RdataIteratorPtr rit = rrset->getRdataIterator();
- const RRType covered = dynamic_cast<const generic::RRSIG&>(
- rit->getCurrent()).typeCovered();
- for (rit->next(); !rit->isLast(); rit->next()) {
- if (dynamic_cast<const generic::RRSIG&>(
- rit->getCurrent()).typeCovered() != covered) {
- isc_throw(AddError, "RRSIG contains mixed covered types: "
- << rrset->toText());
- }
- }
- }
-
- const NameComparisonResult compare =
- zone_name.compare(rrset->getName());
- if (compare.getRelation() != NameComparisonResult::SUPERDOMAIN &&
- compare.getRelation() != NameComparisonResult::EQUAL)
- {
- LOG_ERROR(logger,
- DATASRC_MEMORY_MEM_OUT_OF_ZONE).arg(rrset->getName()).
- arg(zone_name);
- isc_throw(OutOfZone, "The name " << rrset->getName() <<
- " is not contained in zone " << zone_name);
- }
-
- // Some RR types do not really work well with a wildcard.
- // Even though the protocol specifically doesn't completely ban such
- // usage, we refuse to load a zone containing such RR in order to
- // keep the lookup logic simpler and more predictable.
- // See RFC4592 and (for DNAME) RFC6672 for more technical background.
- // Note also that BIND 9 refuses NS at a wildcard, so in that sense
- // we simply provide compatible behavior.
- if (rrset->getName().isWildcard()) {
- if (rrset->getType() == RRType::NS()) {
- LOG_ERROR(logger, DATASRC_MEMORY_MEM_WILDCARD_NS).
- arg(rrset->getName());
- isc_throw(AddError, "Invalid NS owner name (wildcard): " <<
- rrset->getName());
- }
- if (rrset->getType() == RRType::DNAME()) {
- LOG_ERROR(logger, DATASRC_MEMORY_MEM_WILDCARD_DNAME).
- arg(rrset->getName());
- isc_throw(AddError, "Invalid DNAME owner name (wildcard): " <<
- rrset->getName());
- }
- }
-
- // Owner names of NSEC3 have special format as defined in RFC5155,
- // and cannot be a wildcard name or must be one label longer than
- // the zone origin. While the RFC doesn't prohibit other forms of
- // names, no sane zone would have such names for NSEC3.
- // BIND 9 also refuses NSEC3 at wildcard.
- if (rrset->getType() == RRType::NSEC3() &&
- (rrset->getName().isWildcard() ||
- rrset->getName().getLabelCount() !=
- zone_name.getLabelCount() + 1)) {
- LOG_ERROR(logger, DATASRC_MEMORY_BAD_NSEC3_NAME).
- arg(rrset->getName());
- isc_throw(AddError, "Invalid NSEC3 owner name: " <<
- rrset->getName());
- }
- }
-
- void addNSEC3(const ConstRRsetPtr rrset,
- const ConstRRsetPtr rrsig,
- ZoneData& zone_data)
- {
- // We know rrset has exactly one RDATA
- const generic::NSEC3& nsec3_rdata =
- dynamic_cast<const generic::NSEC3&>(
- rrset->getRdataIterator()->getCurrent());
-
- NSEC3Data* nsec3_data = zone_data.getNSEC3Data();
- if (nsec3_data == NULL) {
- nsec3_data = NSEC3Data::create(mem_sgmt_, nsec3_rdata);
- zone_data.setNSEC3Data(nsec3_data);
- zone_data.setSigned(true);
- } else {
- size_t salt_len = nsec3_data->getSaltLen();
- const uint8_t* salt_data = nsec3_data->getSaltData();
- const vector<uint8_t>& salt_data_2 = nsec3_rdata.getSalt();
-
- if ((nsec3_rdata.getHashalg() != nsec3_data->hashalg) ||
- (nsec3_rdata.getIterations() != nsec3_data->iterations) ||
- (salt_data_2.size() != salt_len)) {
- isc_throw(AddError,
- "NSEC3 with inconsistent parameters: " <<
- rrset->toText());
- }
- if ((salt_len > 0) &&
- (std::memcmp(&salt_data_2[0], salt_data, salt_len) != 0)) {
- isc_throw(AddError,
- "NSEC3 with inconsistent parameters: " <<
- rrset->toText());
- }
- }
-
- ZoneNode* node;
- nsec3_data->insertName(mem_sgmt_, rrset->getName(), &node);
+ FileNameDeleter() {}
- RdataEncoder encoder;
- RdataSet* set = RdataSet::create(mem_sgmt_, encoder, rrset, rrsig);
- RdataSet* old_set = node->setData(set);
- if (old_set != NULL) {
- RdataSet::destroy(mem_sgmt_, rrclass_, old_set);
- }
- }
-
- void addRdataSet(const Name& zone_name, ZoneData& zone_data,
- const ConstRRsetPtr rrset, const ConstRRsetPtr rrsig)
- {
- if (rrset->getType() == RRType::NSEC3()) {
- addNSEC3(rrset, rrsig, zone_data);
- } else {
- ZoneNode* node;
- zone_data.insertName(mem_sgmt_, rrset->getName(), &node);
-
- RdataSet* rdataset_head = node->getData();
-
- // Checks related to the surrounding data.
- // Note: when the check fails and the exception is thrown,
- // it may break strong exception guarantee. At the moment
- // we prefer code simplicity and don't bother to introduce
- // complicated recovery code.
- contextCheck(zone_name, *rrset, rdataset_head);
-
- if (RdataSet::find(rdataset_head, rrset->getType()) != NULL) {
- isc_throw(AddError,
- "RRset of the type already exists: "
- << rrset->getName() << " (type: "
- << rrset->getType() << ")");
- }
-
- RdataEncoder encoder;
- RdataSet* rdataset = RdataSet::create(mem_sgmt_, encoder, rrset,
- rrsig);
- rdataset->next = rdataset_head;
- node->setData(rdataset);
-
- // Ok, we just put it in
-
- // If this RRset creates a zone cut at this node, mark the
- // node indicating the need for callback in find().
- if (rrset->getType() == RRType::NS() &&
- rrset->getName() != zone_name) {
- node->setFlag(ZoneNode::FLAG_CALLBACK);
- // If it is DNAME, we have a callback as well here
- } else if (rrset->getType() == RRType::DNAME()) {
- node->setFlag(ZoneNode::FLAG_CALLBACK);
- }
-
- // If we've added NSEC3PARAM at zone origin, set up NSEC3
- // specific data or check consistency with already set up
- // parameters.
- if (rrset->getType() == RRType::NSEC3PARAM() &&
- rrset->getName() == zone_name) {
- // We know rrset has exactly one RDATA
- const generic::NSEC3PARAM& param =
- dynamic_cast<const generic::NSEC3PARAM&>
- (rrset->getRdataIterator()->getCurrent());
-
- NSEC3Data* nsec3_data = zone_data.getNSEC3Data();
- if (nsec3_data == NULL) {
- nsec3_data = NSEC3Data::create(mem_sgmt_, param);
- zone_data.setNSEC3Data(nsec3_data);
- zone_data.setSigned(true);
- } else {
- size_t salt_len = nsec3_data->getSaltLen();
- const uint8_t* salt_data = nsec3_data->getSaltData();
- const vector<uint8_t>& salt_data_2 = param.getSalt();
-
- if ((param.getHashalg() != nsec3_data->hashalg) ||
- (param.getIterations() != nsec3_data->iterations) ||
- (salt_data_2.size() != salt_len)) {
- isc_throw(AddError,
- "NSEC3PARAM with inconsistent parameters: "
- << rrset->toText());
- }
-
- if ((salt_len > 0) &&
- (std::memcmp(&salt_data_2[0],
- salt_data, salt_len) != 0)) {
- isc_throw(AddError,
- "NSEC3PARAM with inconsistent parameters: "
- << rrset->toText());
- }
- }
- } else if (rrset->getType() == RRType::NSEC()) {
- // If it is NSEC signed zone, we mark the zone as signed
- // (conceptually "signed" is a broader notion but our current
- // zone finder implementation regards "signed" as "NSEC
- // signed")
- zone_data.setSigned(true);
- }
- }
- }
-
- // Implementation of InMemoryClient::add()
- void add(const ConstRRsetPtr& rrset, const ConstRRsetPtr& sig_rrset,
- const Name& zone_name, ZoneData& zone_data)
- {
- // Sanitize input. This will cause an exception to be thrown
- // if the input RRset is empty.
- addValidation(zone_name, rrset);
- if (sig_rrset) {
- addValidation(zone_name, sig_rrset);
- }
-
- // OK, can add the RRset.
- LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEMORY_MEM_ADD_RRSET).
- arg(rrset->getName()).arg(rrset->getType()).arg(zone_name);
-
- // Add wildcards possibly contained in the owner name to the domain
- // tree. This can only happen for the normal (non-NSEC3) tree.
- // Note: this can throw an exception, breaking strong exception
- // guarantee. (see also the note for the call to contextCheck()
- // above).
- if (rrset->getType() != RRType::NSEC3()) {
- addWildcards(zone_name, zone_data, rrset->getName());
- }
-
- addRdataSet(zone_name, zone_data, rrset, sig_rrset);
+ void operator()(std::string* filename) const {
+ delete filename;
}
};
-// A helper internal class for load(). make it non-copyable to avoid
-// accidental copy.
-//
-// The current internal implementation expects that both a normal
-// (non RRSIG) RRset and (when signed) its RRSIG are added at once.
-// Also in the current implementation, the input sequence of RRsets
-// are grouped with their owner name (so once a new owner name is encountered,
-// no subsequent RRset has the previous owner name), but the ordering
-// in the same group is not fixed. So we hold all RRsets of the same
-// owner name in node_rrsets_ and node_rrsigsets_, and add the matching
-// pairs of RRsets to the zone when we see a new owner name.
-//
-// The caller is responsible for adding the RRsets of the last group
-// in the input sequence by explicitly calling flushNodeRRsets() at the
-// end. It's cleaner and more robust if we let the destructor of this class
-// do it, but since we cannot guarantee the adding operation is exception free,
-// we don't choose that option to maintain the common expectation for
-// destructors.
-class InMemoryClient::Loader : boost::noncopyable {
- typedef std::map<RRType, ConstRRsetPtr> NodeRRsets;
- typedef NodeRRsets::value_type NodeRRsetsVal;
-public:
- Loader(InMemoryClientImpl* client_impl, const Name& zone_name,
- ZoneData& zone_data) :
- client_impl_(client_impl), zone_name_(zone_name), zone_data_(zone_data)
- {}
- void addFromLoad(const ConstRRsetPtr& rrset) {
- // If we see a new name, flush the temporary holders, adding the
- // pairs of RRsets and RRSIGs of the previous name to the zone.
- if ((!node_rrsets_.empty() || !node_rrsigsets_.empty()) &&
- getCurrentName() != rrset->getName()) {
- flushNodeRRsets();
- }
-
- // Store this RRset until it can be added to the zone. The current
- // implementation requires RRs of the same RRset should be added at
- // once, so we check the "duplicate" here.
- const bool is_rrsig = rrset->getType() == RRType::RRSIG();
- NodeRRsets& node_rrsets = is_rrsig ? node_rrsigsets_ : node_rrsets_;
- const RRType& rrtype = is_rrsig ?
- getCoveredType(rrset) : rrset->getType();
- if (!node_rrsets.insert(NodeRRsetsVal(rrtype, rrset)).second) {
- isc_throw(AddError,
- "Duplicate add of the same type of"
- << (is_rrsig ? " RRSIG" : "") << " RRset: "
- << rrset->getName() << "/" << rrtype);
- }
- }
- void flushNodeRRsets() {
- BOOST_FOREACH(NodeRRsetsVal val, node_rrsets_) {
- // Identify the corresponding RRSIG for the RRset, if any.
- // If found add both the RRset and its RRSIG at once.
- ConstRRsetPtr sig_rrset;
- NodeRRsets::iterator sig_it =
- node_rrsigsets_.find(val.first);
- if (sig_it != node_rrsigsets_.end()) {
- sig_rrset = sig_it->second;
- node_rrsigsets_.erase(sig_it);
- }
- client_impl_->add(val.second, sig_rrset, zone_name_, zone_data_);
- }
-
- // Right now, we don't accept RRSIG without covered RRsets (this
- // should eventually allowed, but to do so we'll need to update the
- // finder).
- if (!node_rrsigsets_.empty()) {
- isc_throw(AddError, "RRSIG is added without covered RRset for "
- << getCurrentName());
- }
+} // end of unnamed namespace
- node_rrsets_.clear();
- node_rrsigsets_.clear();
- }
-private:
- // A helper to identify the covered type of an RRSIG.
- static RRType getCoveredType(const ConstRRsetPtr& sig_rrset) {
- RdataIteratorPtr it = sig_rrset->getRdataIterator();
- // Empty RRSIG shouldn't be passed either via a master file or another
- // data source iterator, but it could still happen if the iterator
- // has a bug. We catch and reject such cases.
- if (it->isLast()) {
- isc_throw(isc::Unexpected,
- "Empty RRset is passed in-memory loader, name: "
- << sig_rrset->getName());
- }
- return (dynamic_cast<const generic::RRSIG&>(it->getCurrent()).
- typeCovered());
- }
- const Name& getCurrentName() const {
- if (!node_rrsets_.empty()) {
- return (node_rrsets_.begin()->second->getName());
- }
- assert(!node_rrsigsets_.empty());
- return (node_rrsigsets_.begin()->second->getName());
- }
+InMemoryClient::InMemoryClient(shared_ptr<ZoneTableSegment> ztable_segment,
+ RRClass rrclass) :
+ ztable_segment_(ztable_segment),
+ rrclass_(rrclass),
+ zone_count_(0),
+ file_name_tree_(FileNameTree::create(
+ ztable_segment_->getMemorySegment(), false))
+{}
-private:
- InMemoryClientImpl* client_impl_;
- const Name& zone_name_;
- ZoneData& zone_data_;
- NodeRRsets node_rrsets_;
- NodeRRsets node_rrsigsets_;
-};
+InMemoryClient::~InMemoryClient() {
+ MemorySegment& mem_sgmt = ztable_segment_->getMemorySegment();
+ FileNameDeleter deleter;
+ FileNameTree::destroy(mem_sgmt, file_name_tree_, deleter);
+}
result::Result
-InMemoryClient::InMemoryClientImpl::load(
- const Name& zone_name,
- const string& filename,
- boost::function<void(LoadCallback)> rrset_installer)
+InMemoryClient::loadInternal(const isc::dns::Name& zone_name,
+ const std::string& filename,
+ ZoneData* zone_data)
{
+ MemorySegment& mem_sgmt = ztable_segment_->getMemorySegment();
SegmentObjectHolder<ZoneData, RRClass> holder(
- mem_sgmt_, ZoneData::create(mem_sgmt_, zone_name), rrclass_);
-
- Loader loader(this, zone_name, *holder.get());
- rrset_installer(boost::bind(&Loader::addFromLoad, &loader, _1));
- // Add any last RRsets that were left
- loader.flushNodeRRsets();
-
- const ZoneNode* origin_node = holder.get()->getOriginNode();
- const RdataSet* set = origin_node->getData();
- // If the zone is NSEC3-signed, check if it has NSEC3PARAM
- if (holder.get()->isNSEC3Signed()) {
- if (RdataSet::find(set, RRType::NSEC3PARAM()) == NULL) {
- LOG_WARN(logger, DATASRC_MEMORY_MEM_NO_NSEC3PARAM).
- arg(zone_name).arg(rrclass_);
- }
- }
-
- // When an empty zone file is loaded, the origin doesn't even have
- // an SOA RR. This condition should be avoided, and hence load()
- // should throw when an empty zone is loaded.
- if (RdataSet::find(set, RRType::SOA()) == NULL) {
- isc_throw(EmptyZone,
- "Won't create an empty zone for: " << zone_name);
- }
+ mem_sgmt, zone_data, rrclass_);
LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEMORY_MEM_ADD_ZONE).
arg(zone_name).arg(rrclass_);
@@ -615,7 +97,7 @@ InMemoryClient::InMemoryClientImpl::load(
// Set the filename in file_name_tree_ now, so that getFileName()
// can use it (during zone reloading).
FileNameNode* node(NULL);
- switch (file_name_tree_->insert(mem_sgmt_, zone_name, &node)) {
+ switch (file_name_tree_->insert(mem_sgmt, zone_name, &node)) {
case FileNameTree::SUCCESS:
case FileNameTree::ALREADYEXISTS:
// These are OK
@@ -627,67 +109,34 @@ InMemoryClient::InMemoryClientImpl::load(
// node must point to a valid node now
assert(node != NULL);
- std::string* tstr = node->setData(new std::string(filename));
+ const std::string* tstr = node->setData(new std::string(filename));
delete tstr;
- ZoneTable::AddResult result(zone_table_->addZone(mem_sgmt_, rrclass_,
- zone_name));
+ ZoneTable* zone_table = ztable_segment_->getHeader().getTable();
+ const ZoneTable::AddResult result(zone_table->addZone(mem_sgmt, rrclass_,
+ zone_name,
+ holder.release()));
if (result.code == result::SUCCESS) {
// Only increment the zone count if the zone doesn't already
// exist.
++zone_count_;
}
-
- ZoneTable::FindResult fr(zone_table_->setZoneData(zone_name,
- holder.release()));
- assert(fr.code == result::SUCCESS);
- if (fr.zone_data != NULL) {
- ZoneData::destroy(mem_sgmt_, fr.zone_data, rrclass_);
+ // Destroy the old instance of the zone if there was any
+ if (result.zone_data != NULL) {
+ ZoneData::destroy(mem_sgmt, result.zone_data, rrclass_);
}
return (result.code);
}
-namespace {
-// A wrapper for dns::masterLoad used by load() below. Essentially it
-// converts the two callback types. Note the mostly redundant wrapper of
-// boost::bind. It converts function<void(ConstRRsetPtr)> to
-// function<void(RRsetPtr)> (masterLoad() expects the latter). SunStudio
-// doesn't seem to do this conversion if we just pass 'callback'.
-void
-masterLoadWrapper(const char* const filename, const Name& origin,
- const RRClass& zone_class, LoadCallback callback)
-{
- masterLoad(filename, origin, zone_class, boost::bind(callback, _1));
-}
-
-// The installer called from Impl::load() for the iterator version of load().
-void
-generateRRsetFromIterator(ZoneIterator* iterator, LoadCallback callback) {
- ConstRRsetPtr rrset;
- while ((rrset = iterator->getNextRRset()) != NULL) {
- callback(rrset);
- }
-}
-}
-
-InMemoryClient::InMemoryClient(util::MemorySegment& mem_sgmt,
- RRClass rrclass) :
- impl_(new InMemoryClientImpl(mem_sgmt, rrclass))
-{}
-
-InMemoryClient::~InMemoryClient() {
- delete impl_;
-}
-
RRClass
InMemoryClient::getClass() const {
- return (impl_->rrclass_);
+ return (rrclass_);
}
unsigned int
InMemoryClient::getZoneCount() const {
- return (impl_->zone_count_);
+ return (zone_count_);
}
isc::datasrc::DataSourceClient::FindResult
@@ -695,7 +144,8 @@ InMemoryClient::findZone(const isc::dns::Name& zone_name) const {
LOG_DEBUG(logger, DBG_TRACE_DATA,
DATASRC_MEMORY_MEM_FIND_ZONE).arg(zone_name);
- ZoneTable::FindResult result(impl_->zone_table_->findZone(zone_name));
+ const ZoneTable* zone_table = ztable_segment_->getHeader().getTable();
+ const ZoneTable::FindResult result(zone_table->findZone(zone_name));
ZoneFinderPtr finder;
if (result.code != result::NOTFOUND) {
@@ -707,34 +157,37 @@ InMemoryClient::findZone(const isc::dns::Name& zone_name) const {
const ZoneData*
InMemoryClient::findZoneData(const isc::dns::Name& zone_name) {
- ZoneTable::FindResult result(impl_->zone_table_->findZone(zone_name));
+ const ZoneTable* zone_table = ztable_segment_->getHeader().getTable();
+ const ZoneTable::FindResult result(zone_table->findZone(zone_name));
return (result.zone_data);
}
result::Result
InMemoryClient::load(const isc::dns::Name& zone_name,
- const std::string& filename) {
+ const std::string& filename)
+{
LOG_DEBUG(logger, DBG_TRACE_BASIC, DATASRC_MEMORY_MEM_LOAD).arg(zone_name).
arg(filename);
- return (impl_->load(zone_name, filename,
- boost::bind(masterLoadWrapper, filename.c_str(),
- zone_name, getClass(), _1)));
+ MemorySegment& mem_sgmt = ztable_segment_->getMemorySegment();
+ ZoneData* zone_data = loadZoneData(mem_sgmt, rrclass_, zone_name,
+ filename);
+ return (loadInternal(zone_name, filename, zone_data));
}
result::Result
-InMemoryClient::load(const isc::dns::Name& zone_name,
- ZoneIterator& iterator) {
- return (impl_->load(zone_name, string(),
- boost::bind(generateRRsetFromIterator,
- &iterator, _1)));
+InMemoryClient::load(const isc::dns::Name& zone_name, ZoneIterator& iterator) {
+ MemorySegment& mem_sgmt = ztable_segment_->getMemorySegment();
+ ZoneData* zone_data = loadZoneData(mem_sgmt, rrclass_, zone_name,
+ iterator);
+ return (loadInternal(zone_name, string(), zone_data));
}
const std::string
InMemoryClient::getFileName(const isc::dns::Name& zone_name) const {
- FileNameNode* node(NULL);
- FileNameTree::Result result = impl_->file_name_tree_->find(zone_name,
- &node);
+ const FileNameNode* node(NULL);
+ const FileNameTree::Result result = file_name_tree_->find(zone_name,
+ &node);
if (result == FileNameTree::EXACTMATCH) {
return (*node->getData());
} else {
@@ -742,24 +195,6 @@ InMemoryClient::getFileName(const isc::dns::Name& zone_name) const {
}
}
-result::Result
-InMemoryClient::add(const isc::dns::Name& zone_name,
- const ConstRRsetPtr& rrset)
-{
- const ZoneTable::FindResult result =
- impl_->zone_table_->findZone(zone_name);
- if (result.code != result::SUCCESS) {
- isc_throw(DataSourceError, "No such zone: " + zone_name.toText());
- }
-
- const ConstRRsetPtr sig_rrset =
- rrset ? rrset->getRRsig() : ConstRRsetPtr();
- impl_->add(rrset, sig_rrset, zone_name, *result.zone_data);
-
- // add() doesn't allow duplicate add, so we always return SUCCESS.
- return (result::SUCCESS);
-}
-
namespace {
class MemoryIterator : public ZoneIterator {
@@ -775,7 +210,7 @@ private:
bool separate_rrs_;
bool ready_;
public:
- MemoryIterator(const RRClass rrclass,
+ MemoryIterator(const RRClass& rrclass,
const ZoneTree& tree, const Name& origin,
bool separate_rrs) :
rrclass_(rrclass),
@@ -874,7 +309,8 @@ public:
ZoneIteratorPtr
InMemoryClient::getIterator(const Name& name, bool separate_rrs) const {
- ZoneTable::FindResult result(impl_->zone_table_->findZone(name));
+ const ZoneTable* zone_table = ztable_segment_->getHeader().getTable();
+ const ZoneTable::FindResult result(zone_table->findZone(name));
if (result.code != result::SUCCESS) {
isc_throw(DataSourceError, "No such zone: " + name.toText());
}
diff --git a/src/lib/datasrc/memory/memory_client.h b/src/lib/datasrc/memory/memory_client.h
index 330d62e..3218c75 100644
--- a/src/lib/datasrc/memory/memory_client.h
+++ b/src/lib/datasrc/memory/memory_client.h
@@ -22,6 +22,8 @@
#include <datasrc/memory/zone_table.h>
#include <datasrc/memory/zone_data.h>
+#include <boost/shared_ptr.hpp>
+
#include <string>
namespace isc {
@@ -34,6 +36,8 @@ class RRsetList;
namespace datasrc {
namespace memory {
+class ZoneTableSegment;
+
/// \brief A data source client that holds all necessary data in memory.
///
/// The \c InMemoryClient class provides an access to a conceptual data
@@ -60,7 +64,7 @@ public:
/// This constructor internally involves resource allocation, and if
/// it fails, a corresponding standard exception will be thrown.
/// It never throws an exception otherwise.
- InMemoryClient(util::MemorySegment& mem_sgmt,
+ InMemoryClient(boost::shared_ptr<ZoneTableSegment> ztable_segment,
isc::dns::RRClass rrclass);
/// The destructor.
@@ -139,69 +143,6 @@ public:
/// zone from a file before.
const std::string getFileName(const isc::dns::Name& zone_name) const;
- /// \brief Inserts an rrset into the zone.
- ///
- /// It puts another RRset into the zone.
- ///
- /// In the current implementation, this method doesn't allow an existing
- /// RRset to be updated or overridden. So the caller must make sure that
- /// all RRs of the same type and name must be given in the form of a
- /// single RRset. The current implementation will also require that
- /// when an RRSIG is added, the RRset to be covered has already been
- /// added. These restrictions are probably too strict when this data
- /// source accepts various forms of input, so they should be revisited
- /// later.
- ///
- /// Except for NullRRset and OutOfZone, this method does not guarantee
- /// strong exception safety (it is currently not needed, if it is needed
- /// in future, it should be implemented).
- ///
- /// \throw NullRRset \c rrset is a NULL pointer.
- /// \throw OutOfZone The owner name of \c rrset is outside of the
- /// origin of the zone.
- /// \throw AddError Other general errors.
- /// \throw Others This method might throw standard allocation exceptions.
- ///
- /// \param rrset The set to add.
- /// \return SUCCESS or EXIST (if an rrset for given name and type already
- /// exists).
- result::Result add(const isc::dns::Name& zone_name,
- const isc::dns::ConstRRsetPtr& rrset);
-
- /// \brief RRset is NULL exception.
- ///
- /// This is thrown if the provided RRset parameter is NULL.
- struct NullRRset : public InvalidParameter {
- NullRRset(const char* file, size_t line, const char* what) :
- InvalidParameter(file, line, what)
- { }
- };
-
- /// \brief Zone is empty exception.
- ///
- /// This is thrown if we have an empty zone created as a result of
- /// load().
- struct EmptyZone : public InvalidParameter {
- EmptyZone(const char* file, size_t line, const char* what) :
- InvalidParameter(file, line, what)
- { }
- };
-
- /// \brief General failure exception for \c add().
- ///
- /// This is thrown against general error cases in adding an RRset
- /// to the zone.
- ///
- /// Note: this exception would cover cases for \c OutOfZone or
- /// \c NullRRset. We'll need to clarify and unify the granularity
- /// of exceptions eventually. For now, exceptions are added as
- /// developers see the need for it.
- struct AddError : public InvalidParameter {
- AddError(const char* file, size_t line, const char* what) :
- InvalidParameter(file, line, what)
- { }
- };
-
/// Returns a \c ZoneFinder result that best matches the given name.
///
/// This derived version of the method never throws an exception.
@@ -239,14 +180,20 @@ public:
uint32_t end_serial) const;
private:
- // TODO: Do we still need the PImpl if nobody should manipulate this class
- // directly any more (it should be handled through DataSourceClient)?
- class InMemoryClientImpl;
- InMemoryClientImpl* impl_;
-
- // A helper internal class used by load(). It maintains some intermediate
- // states while loading RRs of the zone.
- class Loader;
+ // Some type aliases
+ typedef DomainTree<std::string> FileNameTree;
+ typedef DomainTreeNode<std::string> FileNameNode;
+
+ // Common process for zone load. Registers filename internally and
+ // adds the ZoneData to the ZoneTable.
+ result::Result loadInternal(const isc::dns::Name& zone_name,
+ const std::string& filename,
+ ZoneData* zone_data);
+
+ boost::shared_ptr<ZoneTableSegment> ztable_segment_;
+ const isc::dns::RRClass rrclass_;
+ unsigned int zone_count_;
+ FileNameTree* file_name_tree_;
};
} // namespace memory
diff --git a/src/lib/datasrc/memory/treenode_rrset.cc b/src/lib/datasrc/memory/treenode_rrset.cc
index f51b2f9..e7ed20c 100644
--- a/src/lib/datasrc/memory/treenode_rrset.cc
+++ b/src/lib/datasrc/memory/treenode_rrset.cc
@@ -342,7 +342,7 @@ TreeNodeRRset::isSameKind(const AbstractRRset& abs_other) const {
// Same for the owner name. Comparing the nodes also detect
// the case where RR classes are different (see the method description
// of the header for details).
- if (node_ != other->node_ ) {
+ if (node_ != other->node_) {
return (false);
}
// If one is constructed with a "real name" and the other isn't
diff --git a/src/lib/datasrc/memory/zone_data_loader.cc b/src/lib/datasrc/memory/zone_data_loader.cc
new file mode 100644
index 0000000..d759901
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_data_loader.cc
@@ -0,0 +1,250 @@
+// 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 <datasrc/memory/zone_data_loader.h>
+#include <datasrc/memory/zone_data_updater.h>
+#include <datasrc/memory/logger.h>
+#include <datasrc/memory/segment_object_holder.h>
+
+#include <dns/rdataclass.h>
+#include <dns/rrset.h>
+#include <dns/masterload.h>
+
+#include <boost/foreach.hpp>
+#include <boost/bind.hpp>
+#include <boost/noncopyable.hpp>
+
+#include <map>
+
+using namespace isc::dns;
+using namespace isc::dns::rdata;
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+using detail::SegmentObjectHolder;
+
+namespace { // unnamed namespace
+
+// A functor type used for loading.
+typedef boost::function<void(isc::dns::ConstRRsetPtr)> LoadCallback;
+
+// A helper internal class for \c loadZoneData(). make it non-copyable
+// to avoid accidental copy.
+//
+// The current internal implementation expects that both a normal
+// (non RRSIG) RRset and (when signed) its RRSIG are added at once.
+// Also in the current implementation, the input sequence of RRsets
+// are grouped with their owner name (so once a new owner name is encountered,
+// no subsequent RRset has the previous owner name), but the ordering
+// in the same group is not fixed. So we hold all RRsets of the same
+// owner name in node_rrsets_ and node_rrsigsets_, and add the matching
+// pairs of RRsets to the zone when we see a new owner name.
+//
+// The caller is responsible for adding the RRsets of the last group
+// in the input sequence by explicitly calling flushNodeRRsets() at the
+// end. It's cleaner and more robust if we let the destructor of this class
+// do it, but since we cannot guarantee the adding operation is exception free,
+// we don't choose that option to maintain the common expectation for
+// destructors.
+class ZoneDataLoader : boost::noncopyable {
+public:
+ ZoneDataLoader(util::MemorySegment& mem_sgmt,
+ const isc::dns::RRClass rrclass,
+ const isc::dns::Name& zone_name, ZoneData& zone_data) :
+ updater_(mem_sgmt, rrclass, zone_name, zone_data)
+ {}
+
+ void addFromLoad(const isc::dns::ConstRRsetPtr& rrset);
+ void flushNodeRRsets();
+
+private:
+ typedef std::map<isc::dns::RRType, isc::dns::ConstRRsetPtr> NodeRRsets;
+ typedef NodeRRsets::value_type NodeRRsetsVal;
+
+ // A helper to identify the covered type of an RRSIG.
+ static isc::dns::RRType getCoveredType
+ (const isc::dns::ConstRRsetPtr& sig_rrset);
+ const isc::dns::Name& getCurrentName() const;
+
+private:
+ NodeRRsets node_rrsets_;
+ NodeRRsets node_rrsigsets_;
+ ZoneDataUpdater updater_;
+};
+
+void
+ZoneDataLoader::addFromLoad(const ConstRRsetPtr& rrset) {
+ // If we see a new name, flush the temporary holders, adding the
+ // pairs of RRsets and RRSIGs of the previous name to the zone.
+ if ((!node_rrsets_.empty() || !node_rrsigsets_.empty()) &&
+ (getCurrentName() != rrset->getName())) {
+ flushNodeRRsets();
+ }
+
+ // Store this RRset until it can be added to the zone. The current
+ // implementation requires RRs of the same RRset should be added at
+ // once, so we check the "duplicate" here.
+ const bool is_rrsig = rrset->getType() == RRType::RRSIG();
+ NodeRRsets& node_rrsets = is_rrsig ? node_rrsigsets_ : node_rrsets_;
+ const RRType& rrtype = is_rrsig ? getCoveredType(rrset) : rrset->getType();
+ if (!node_rrsets.insert(NodeRRsetsVal(rrtype, rrset)).second) {
+ isc_throw(ZoneDataUpdater::AddError,
+ "Duplicate add of the same type of"
+ << (is_rrsig ? " RRSIG" : "") << " RRset: "
+ << rrset->getName() << "/" << rrtype);
+ }
+
+ if (rrset->getRRsig()) {
+ addFromLoad(rrset->getRRsig());
+ }
+}
+
+void
+ZoneDataLoader::flushNodeRRsets() {
+ BOOST_FOREACH(NodeRRsetsVal val, node_rrsets_) {
+ // Identify the corresponding RRSIG for the RRset, if any. If
+ // found add both the RRset and its RRSIG at once.
+ ConstRRsetPtr sig_rrset;
+ NodeRRsets::iterator sig_it = node_rrsigsets_.find(val.first);
+ if (sig_it != node_rrsigsets_.end()) {
+ sig_rrset = sig_it->second;
+ node_rrsigsets_.erase(sig_it);
+ }
+ updater_.add(val.second, sig_rrset);
+ }
+
+ // Right now, we don't accept RRSIG without covered RRsets (this
+ // should eventually allowed, but to do so we'll need to update the
+ // finder).
+ if (!node_rrsigsets_.empty()) {
+ isc_throw(ZoneDataUpdater::AddError,
+ "RRSIG is added without covered RRset for "
+ << getCurrentName());
+ }
+
+ node_rrsets_.clear();
+ node_rrsigsets_.clear();
+}
+
+RRType
+ZoneDataLoader::getCoveredType(const ConstRRsetPtr& sig_rrset) {
+ RdataIteratorPtr it = sig_rrset->getRdataIterator();
+ // Empty RRSIG shouldn't be passed either via a master file or
+ // another data source iterator, but it could still happen if the
+ // iterator has a bug. We catch and reject such cases.
+ if (it->isLast()) {
+ isc_throw(isc::Unexpected,
+ "Empty RRset is passed in-memory loader, name: "
+ << sig_rrset->getName());
+ }
+ return (dynamic_cast<const generic::RRSIG&>(it->getCurrent()).
+ typeCovered());
+}
+
+const Name&
+ZoneDataLoader::getCurrentName() const {
+ if (!node_rrsets_.empty()) {
+ return (node_rrsets_.begin()->second->getName());
+ }
+ assert(!node_rrsigsets_.empty());
+ return (node_rrsigsets_.begin()->second->getName());
+}
+
+ZoneData*
+loadZoneDataInternal(util::MemorySegment& mem_sgmt,
+ const isc::dns::RRClass& rrclass,
+ const Name& zone_name,
+ boost::function<void(LoadCallback)> rrset_installer)
+{
+ SegmentObjectHolder<ZoneData, RRClass> holder(
+ mem_sgmt, ZoneData::create(mem_sgmt, zone_name), rrclass);
+
+ ZoneDataLoader loader(mem_sgmt, rrclass, zone_name, *holder.get());
+ rrset_installer(boost::bind(&ZoneDataLoader::addFromLoad, &loader, _1));
+ // Add any last RRsets that were left
+ loader.flushNodeRRsets();
+
+ const ZoneNode* origin_node = holder.get()->getOriginNode();
+ const RdataSet* rdataset = origin_node->getData();
+ // If the zone is NSEC3-signed, check if it has NSEC3PARAM
+ if (holder.get()->isNSEC3Signed()) {
+ if (RdataSet::find(rdataset, RRType::NSEC3PARAM()) == NULL) {
+ LOG_WARN(logger, DATASRC_MEMORY_MEM_NO_NSEC3PARAM).
+ arg(zone_name).arg(rrclass);
+ }
+ }
+
+ // When an empty zone file is loaded, the origin doesn't even have
+ // an SOA RR. This condition should be avoided, and hence load()
+ // should throw when an empty zone is loaded.
+ if (RdataSet::find(rdataset, RRType::SOA()) == NULL) {
+ isc_throw(EmptyZone,
+ "Won't create an empty zone for: " << zone_name);
+ }
+
+ return (holder.release());
+}
+
+// A wrapper for dns::masterLoad used by loadZoneData() below. Essentially it
+// converts the two callback types. Note the mostly redundant wrapper of
+// boost::bind. It converts function<void(ConstRRsetPtr)> to
+// function<void(RRsetPtr)> (masterLoad() expects the latter). SunStudio
+// doesn't seem to do this conversion if we just pass 'callback'.
+void
+masterLoadWrapper(const char* const filename, const Name& origin,
+ const RRClass& zone_class, LoadCallback callback)
+{
+ masterLoad(filename, origin, zone_class, boost::bind(callback, _1));
+}
+
+// The installer called from the iterator version of loadZoneData().
+void
+generateRRsetFromIterator(ZoneIterator* iterator, LoadCallback callback) {
+ ConstRRsetPtr rrset;
+ while ((rrset = iterator->getNextRRset()) != NULL) {
+ callback(rrset);
+ }
+}
+
+} // end of unnamed namespace
+
+ZoneData*
+loadZoneData(util::MemorySegment& mem_sgmt,
+ const isc::dns::RRClass& rrclass,
+ const isc::dns::Name& zone_name,
+ const std::string& zone_file)
+{
+ return (loadZoneDataInternal(mem_sgmt, rrclass, zone_name,
+ boost::bind(masterLoadWrapper,
+ zone_file.c_str(),
+ zone_name, rrclass,
+ _1)));
+}
+
+ZoneData*
+loadZoneData(util::MemorySegment& mem_sgmt,
+ const isc::dns::RRClass& rrclass,
+ const isc::dns::Name& zone_name,
+ ZoneIterator& iterator)
+{
+ return (loadZoneDataInternal(mem_sgmt, rrclass, zone_name,
+ boost::bind(generateRRsetFromIterator,
+ &iterator, _1)));
+}
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
diff --git a/src/lib/datasrc/memory/zone_data_loader.h b/src/lib/datasrc/memory/zone_data_loader.h
new file mode 100644
index 0000000..6f02fcb
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_data_loader.h
@@ -0,0 +1,80 @@
+// 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_ZONE_DATA_LOADER_H
+#define DATASRC_ZONE_DATA_LOADER_H 1
+
+#include <datasrc/memory/zone_data.h>
+#include <datasrc/iterator.h>
+#include <dns/name.h>
+#include <dns/rrclass.h>
+#include <util/memory_segment.h>
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+/// \brief Zone is empty exception.
+///
+/// This is thrown if an empty zone would be created during
+/// \c loadZoneData().
+struct EmptyZone : public InvalidParameter {
+ EmptyZone(const char* file, size_t line, const char* what) :
+ InvalidParameter(file, line, what)
+ {}
+};
+
+/// \brief Create and return a ZoneData instance populated from the
+/// \c zone_file.
+///
+/// Throws \c ZoneDataUpdater::AddError if invalid or inconsistent data
+/// is present in the \c zone_file. Throws \c isc::Unexpected if empty
+/// RRsets are passed by the master loader. Throws \c EmptyZone if an
+/// empty zone would be created due to the \c loadZoneData().
+///
+/// \param mem_sgmt The memory segment.
+/// \param rrclass The RRClass.
+/// \param zone_name The name of the zone that is being loaded.
+/// \param zone_file Filename which contains the zone data for \c zone_name.
+ZoneData* loadZoneData(util::MemorySegment& mem_sgmt,
+ const isc::dns::RRClass& rrclass,
+ const isc::dns::Name& zone_name,
+ const std::string& zone_file);
+
+/// \brief Create and return a ZoneData instance populated from the
+/// \c iterator.
+///
+/// Throws \c ZoneDataUpdater::AddError if invalid or inconsistent data
+/// is present in the \c zone_file. Throws \c isc::Unexpected if empty
+/// RRsets are passed by the zone iterator. Throws \c EmptyZone if an
+/// empty zone would be created due to the \c loadZoneData().
+///
+/// \param mem_sgmt The memory segment.
+/// \param rrclass The RRClass.
+/// \param zone_name The name of the zone that is being loaded.
+/// \param iterator Iterator that returns RRsets to load into the zone.
+ZoneData* loadZoneData(util::MemorySegment& mem_sgmt,
+ const isc::dns::RRClass& rrclass,
+ const isc::dns::Name& zone_name,
+ ZoneIterator& iterator);
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
+
+#endif // DATASRC_ZONE_DATA_LOADER_H
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/lib/datasrc/memory/zone_data_updater.cc b/src/lib/datasrc/memory/zone_data_updater.cc
new file mode 100644
index 0000000..037eeb4
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_data_updater.cc
@@ -0,0 +1,347 @@
+// 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 <datasrc/memory/zone_data_updater.h>
+#include <datasrc/memory/logger.h>
+#include <datasrc/zone.h>
+
+#include <dns/rdataclass.h>
+
+using namespace isc::dns;
+using namespace isc::dns::rdata;
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+void
+ZoneDataUpdater::addWildcards(const Name& name) {
+ Name wname(name);
+ const unsigned int labels(wname.getLabelCount());
+ const unsigned int origin_labels(zone_name_.getLabelCount());
+ for (unsigned int l = labels;
+ l > origin_labels;
+ --l, wname = wname.split(1))
+ {
+ if (wname.isWildcard()) {
+ LOG_DEBUG(logger, DBG_TRACE_DATA,
+ DATASRC_MEMORY_MEM_ADD_WILDCARD).arg(name);
+
+ // Ensure a separate level exists for the "wildcarding"
+ // name, and mark the node as "wild".
+ ZoneNode* node;
+ zone_data_.insertName(mem_sgmt_, wname.split(1), &node);
+ node->setFlag(ZoneData::WILDCARD_NODE);
+
+ // Ensure a separate level exists for the wildcard name.
+ // Note: for 'name' itself we do this later anyway, but the
+ // overhead should be marginal because wildcard names should
+ // be rare.
+ zone_data_.insertName(mem_sgmt_, wname, &node);
+ }
+ }
+}
+
+void
+ZoneDataUpdater::contextCheck(const AbstractRRset& rrset,
+ const RdataSet* rdataset) const
+{
+ // Ensure CNAME and other type of RR don't coexist for the same
+ // owner name except with NSEC, which is the only RR that can
+ // coexist with CNAME (and also RRSIG, which is handled separately)
+ if (rrset.getType() == RRType::CNAME()) {
+ for (const RdataSet* sp = rdataset; sp != NULL; sp = sp->getNext()) {
+ if (sp->type != RRType::NSEC()) {
+ LOG_ERROR(logger, DATASRC_MEMORY_MEM_CNAME_TO_NONEMPTY).
+ arg(rrset.getName());
+ isc_throw(AddError,
+ "CNAME can't be added with " << sp->type
+ << " RRType for " << rrset.getName());
+ }
+ }
+ } else if ((rrset.getType() != RRType::NSEC()) &&
+ (RdataSet::find(rdataset, RRType::CNAME()) != NULL))
+ {
+ LOG_ERROR(logger,
+ DATASRC_MEMORY_MEM_CNAME_COEXIST).arg(rrset.getName());
+ isc_throw(AddError,
+ "CNAME and " << rrset.getType() <<
+ " can't coexist for " << rrset.getName());
+ }
+
+ // Similar with DNAME, but it must not coexist only with NS and only
+ // in non-apex domains. RFC 2672 section 3 mentions that it is
+ // implied from it and RFC 2181.
+ if (rrset.getName() != zone_name_ &&
+ // Adding DNAME, NS already there
+ ((rrset.getType() == RRType::DNAME() &&
+ RdataSet::find(rdataset, RRType::NS()) != NULL) ||
+ // Adding NS, DNAME already there
+ (rrset.getType() == RRType::NS() &&
+ RdataSet::find(rdataset, RRType::DNAME()) != NULL)))
+ {
+ LOG_ERROR(logger, DATASRC_MEMORY_MEM_DNAME_NS).arg(rrset.getName());
+ isc_throw(AddError, "DNAME can't coexist with NS in non-apex domain: "
+ << rrset.getName());
+ }
+}
+
+void
+ZoneDataUpdater::validate(const isc::dns::ConstRRsetPtr rrset) const {
+ if (!rrset) {
+ isc_throw(NullRRset, "The rrset provided is NULL");
+ }
+
+ if (rrset->getRdataCount() == 0) {
+ isc_throw(AddError,
+ "The rrset provided is empty: "
+ << rrset->getName() << "/" << rrset->getType());
+ }
+
+ // Check for singleton RRs. It should probably handled at a different
+ // layer in future.
+ if ((rrset->getType() == RRType::CNAME() ||
+ rrset->getType() == RRType::DNAME()) &&
+ rrset->getRdataCount() > 1)
+ {
+ // XXX: this is not only for CNAME or DNAME. We should
+ // generalize this code for all other "singleton RR types" (such
+ // as SOA) in a separate task.
+ LOG_ERROR(logger,
+ DATASRC_MEMORY_MEM_SINGLETON).arg(rrset->getName()).
+ arg(rrset->getType());
+ isc_throw(AddError, "multiple RRs of singleton type for "
+ << rrset->getName());
+ }
+
+ // NSEC3/NSEC3PARAM is not a "singleton" per protocol, but this
+ // implementation requests it be so at the moment.
+ if ((rrset->getType() == RRType::NSEC3() ||
+ rrset->getType() == RRType::NSEC3PARAM()) &&
+ (rrset->getRdataCount() > 1))
+ {
+ isc_throw(AddError, "Multiple NSEC3/NSEC3PARAM RDATA is given for "
+ << rrset->getName() << " which isn't supported");
+ }
+
+ // For RRSIGs, check consistency of the type covered. We know the
+ // RRset isn't empty, so the following check is safe.
+ if (rrset->getType() == RRType::RRSIG()) {
+ RdataIteratorPtr rit = rrset->getRdataIterator();
+ const RRType covered = dynamic_cast<const generic::RRSIG&>(
+ rit->getCurrent()).typeCovered();
+ for (rit->next(); !rit->isLast(); rit->next()) {
+ if (dynamic_cast<const generic::RRSIG&>(
+ rit->getCurrent()).typeCovered() != covered)
+ {
+ isc_throw(AddError, "RRSIG contains mixed covered types: "
+ << rrset->toText());
+ }
+ }
+ }
+
+ const NameComparisonResult compare = zone_name_.compare(rrset->getName());
+ if (compare.getRelation() != NameComparisonResult::SUPERDOMAIN &&
+ compare.getRelation() != NameComparisonResult::EQUAL)
+ {
+ LOG_ERROR(logger,
+ DATASRC_MEMORY_MEM_OUT_OF_ZONE).arg(rrset->getName()).
+ arg(zone_name_);
+ isc_throw(OutOfZone,
+ "The name " << rrset->getName() <<
+ " is not contained in zone " << zone_name_);
+ }
+
+ // Some RR types do not really work well with a wildcard. Even
+ // though the protocol specifically doesn't completely ban such
+ // usage, we refuse to load a zone containing such RR in order to
+ // keep the lookup logic simpler and more predictable. See RFC4592
+ // and (for DNAME) RFC6672 for more technical background. Note also
+ // that BIND 9 refuses NS at a wildcard, so in that sense we simply
+ // provide compatible behavior.
+ if (rrset->getName().isWildcard()) {
+ if (rrset->getType() == RRType::NS()) {
+ LOG_ERROR(logger, DATASRC_MEMORY_MEM_WILDCARD_NS).
+ arg(rrset->getName());
+ isc_throw(AddError, "Invalid NS owner name (wildcard): "
+ << rrset->getName());
+ }
+
+ if (rrset->getType() == RRType::DNAME()) {
+ LOG_ERROR(logger, DATASRC_MEMORY_MEM_WILDCARD_DNAME).
+ arg(rrset->getName());
+ isc_throw(AddError, "Invalid DNAME owner name (wildcard): "
+ << rrset->getName());
+ }
+ }
+
+ // Owner names of NSEC3 have special format as defined in RFC5155,
+ // and cannot be a wildcard name or must be one label longer than
+ // the zone origin. While the RFC doesn't prohibit other forms of
+ // names, no sane zone would have such names for NSEC3. BIND 9 also
+ // refuses NSEC3 at wildcard.
+ if (rrset->getType() == RRType::NSEC3() &&
+ (rrset->getName().isWildcard() ||
+ rrset->getName().getLabelCount() != zone_name_.getLabelCount() + 1))
+ {
+ LOG_ERROR(logger, DATASRC_MEMORY_BAD_NSEC3_NAME).arg(rrset->getName());
+ isc_throw(AddError, "Invalid NSEC3 owner name: " <<
+ rrset->getName() << "; zone: " << zone_name_);
+ }
+}
+
+const NSEC3Hash*
+ZoneDataUpdater::getNSEC3Hash() {
+ if (hash_ == NULL) {
+ NSEC3Data* nsec3_data = zone_data_.getNSEC3Data();
+ // This should never be NULL in this codepath.
+ assert(nsec3_data != NULL);
+
+ hash_ = NSEC3Hash::create(nsec3_data->hashalg,
+ nsec3_data->iterations,
+ nsec3_data->getSaltData(),
+ nsec3_data->getSaltLen());
+ }
+
+ return (hash_);
+}
+
+template <typename T>
+void
+ZoneDataUpdater::setupNSEC3(const ConstRRsetPtr rrset) {
+ // We know rrset has exactly one RDATA
+ const T& nsec3_rdata =
+ dynamic_cast<const T&>(
+ rrset->getRdataIterator()->getCurrent());
+
+ NSEC3Data* nsec3_data = zone_data_.getNSEC3Data();
+ if (nsec3_data == NULL) {
+ nsec3_data = NSEC3Data::create(mem_sgmt_, nsec3_rdata);
+ zone_data_.setNSEC3Data(nsec3_data);
+ zone_data_.setSigned(true);
+ } else {
+ const NSEC3Hash* hash = getNSEC3Hash();
+ if (!hash->match(nsec3_rdata)) {
+ isc_throw(AddError,
+ rrset->getType() << " with inconsistent parameters: "
+ << rrset->toText());
+ }
+ }
+}
+
+void
+ZoneDataUpdater::addNSEC3(const ConstRRsetPtr rrset, const ConstRRsetPtr rrsig)
+{
+ setupNSEC3<generic::NSEC3>(rrset);
+
+ NSEC3Data* nsec3_data = zone_data_.getNSEC3Data();
+
+ ZoneNode* node;
+ nsec3_data->insertName(mem_sgmt_, rrset->getName(), &node);
+
+ RdataSet* rdataset = RdataSet::create(mem_sgmt_, encoder_, rrset, rrsig);
+ RdataSet* old_rdataset = node->setData(rdataset);
+ if (old_rdataset != NULL) {
+ RdataSet::destroy(mem_sgmt_, rrclass_, old_rdataset);
+ }
+}
+
+void
+ZoneDataUpdater::addRdataSet(const ConstRRsetPtr rrset,
+ const ConstRRsetPtr rrsig)
+{
+ if (rrset->getType() == RRType::NSEC3()) {
+ addNSEC3(rrset, rrsig);
+ } else {
+ ZoneNode* node;
+ zone_data_.insertName(mem_sgmt_, rrset->getName(), &node);
+
+ RdataSet* rdataset_head = node->getData();
+
+ // Checks related to the surrounding data. Note: when the check
+ // fails and the exception is thrown, it may break strong
+ // exception guarantee. At the moment we prefer code simplicity
+ // and don't bother to introduce complicated recovery code.
+ contextCheck(*rrset, rdataset_head);
+
+ if (RdataSet::find(rdataset_head, rrset->getType()) != NULL) {
+ isc_throw(AddError,
+ "RRset of the type already exists: "
+ << rrset->getName() << " (type: "
+ << rrset->getType() << ")");
+ }
+
+ RdataSet* rdataset_new = RdataSet::create(mem_sgmt_, encoder_,
+ rrset, rrsig);
+ rdataset_new->next = rdataset_head;
+ node->setData(rdataset_new);
+
+ // Ok, we just put it in.
+
+ // If this RRset creates a zone cut at this node, mark the node
+ // indicating the need for callback in find().
+ if (rrset->getType() == RRType::NS() &&
+ rrset->getName() != zone_name_) {
+ node->setFlag(ZoneNode::FLAG_CALLBACK);
+ // If it is DNAME, we have a callback as well here
+ } else if (rrset->getType() == RRType::DNAME()) {
+ node->setFlag(ZoneNode::FLAG_CALLBACK);
+ }
+
+ // If we've added NSEC3PARAM at zone origin, set up NSEC3
+ // specific data or check consistency with already set up
+ // parameters.
+ if (rrset->getType() == RRType::NSEC3PARAM() &&
+ rrset->getName() == zone_name_) {
+ setupNSEC3<generic::NSEC3PARAM>(rrset);
+ } else if (rrset->getType() == RRType::NSEC()) {
+ // If it is NSEC signed zone, we mark the zone as signed
+ // (conceptually "signed" is a broader notion but our
+ // current zone finder implementation regards "signed" as
+ // "NSEC signed")
+ zone_data_.setSigned(true);
+ }
+ }
+}
+
+void
+ZoneDataUpdater::add(const ConstRRsetPtr& rrset,
+ const ConstRRsetPtr& sig_rrset)
+{
+ // Validate input. This will cause an exception to be thrown if the
+ // input RRset is empty.
+ validate(rrset);
+ if (sig_rrset) {
+ validate(sig_rrset);
+ }
+
+ // OK, can add the RRset.
+ LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEMORY_MEM_ADD_RRSET).
+ arg(rrset->getName()).arg(rrset->getType()).arg(zone_name_);
+
+ // Add wildcards possibly contained in the owner name to the domain
+ // tree. This can only happen for the normal (non-NSEC3) tree.
+ // Note: this can throw an exception, breaking strong exception
+ // guarantee. (see also the note for the call to contextCheck()
+ // above).
+ if (rrset->getType() != RRType::NSEC3()) {
+ addWildcards(rrset->getName());
+ }
+
+ addRdataSet(rrset, sig_rrset);
+}
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
diff --git a/src/lib/datasrc/memory/zone_data_updater.h b/src/lib/datasrc/memory/zone_data_updater.h
new file mode 100644
index 0000000..341d8ae
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_data_updater.h
@@ -0,0 +1,180 @@
+// 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_ZONE_DATA_UPDATER_H
+#define DATASRC_ZONE_DATA_UPDATER_H 1
+
+#include <datasrc/memory/zone_data.h>
+#include <datasrc/memory/rdata_serialization.h>
+#include <dns/name.h>
+#include <dns/rrclass.h>
+#include <dns/rrset.h>
+#include <dns/nsec3hash.h>
+#include <util/memory_segment.h>
+
+#include <boost/noncopyable.hpp>
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+/// \brief A helper class to add records to a zone.
+///
+/// This class provides an \c add() method that can be used to add
+/// RRsets to a ZoneData instance. The RRsets are first validated for
+/// correctness and consistency, and their data is made into RdataSets
+/// which are added to the ZoneData for the zone.
+///
+/// The way to use this is to make a ZoneDataUpdater instance, and call
+/// add() on it as follows:
+///
+/// \code
+/// ZoneDataUpdater updater(mem_sgmt, rrclass, zone_origin_name, zone_data);
+/// ConstRRsetPtr rrset;
+/// updater.add(rrset, ConstRRsetPtr());
+/// \endcode
+///
+/// We enforce that instances are non-copyable as it's pointless to make
+/// copies.
+class ZoneDataUpdater : boost::noncopyable {
+public:
+ ///
+ /// \name Constructors and Destructor.
+ ///
+ //@{
+
+ /// The constructor.
+ ///
+ /// \throw none
+ ///
+ /// \param mem_sgmt The memory segment used for the zone data.
+ /// \param rrclass The RRclass of the zone data.
+ /// \param zone_name The Name of the zone under which records will be
+ /// added.
+ // \param zone_data The ZoneData object which is populated with
+ // record data.
+ ZoneDataUpdater(util::MemorySegment& mem_sgmt,
+ isc::dns::RRClass rrclass,
+ const isc::dns::Name& zone_name,
+ ZoneData& zone_data) :
+ mem_sgmt_(mem_sgmt),
+ rrclass_(rrclass),
+ zone_name_(zone_name),
+ zone_data_(zone_data),
+ hash_(NULL)
+ {}
+
+ /// The destructor.
+ ~ZoneDataUpdater() {
+ delete hash_;
+ }
+
+ //@}
+
+ /// This is thrown if the provided RRset parameter passed to \c
+ /// add() is NULL.
+ struct NullRRset : public InvalidParameter {
+ NullRRset(const char* file, size_t line, const char* what) :
+ InvalidParameter(file, line, what)
+ {}
+ };
+
+ /// \brief General failure exception for \c add().
+ ///
+ /// This is thrown against general error cases in adding an RRset
+ /// to the zone.
+ ///
+ /// Note: this exception would cover cases for \c OutOfZone or
+ /// \c NullRRset. We'll need to clarify and unify the granularity
+ /// of exceptions eventually. For now, exceptions are added as
+ /// developers see the need for it.
+ struct AddError : public InvalidParameter {
+ AddError(const char* file, size_t line, const char* what) :
+ InvalidParameter(file, line, what)
+ {}
+ };
+
+ /// \brief Add an RRset to the zone.
+ ///
+ /// This is the core method of this class. It is used to add an
+ /// RRset to the ZoneData associated with this object. The RRset is
+ /// first validated for correctness and consistency with the rest of
+ /// the records in the zone, and then an RdataSet is created and
+ /// populated with the record data and added to the ZoneData for the
+ /// name in the RRset.
+ ///
+ /// This method throws an \c NullRRset exception (see above) if
+ /// \c rrset is empty. It throws \c AddError if any of a variety of
+ /// validation checks fail for the \c rrset and its associated
+ /// \c sig_rrset.
+ ///
+ /// \param rrset The RRset to be added.
+ /// \param sig_rrset An associated RRSIG RRset for the \c rrset. It
+ /// can be empty if there is no RRSIG for the \c rrset.
+ void add(const isc::dns::ConstRRsetPtr& rrset,
+ const isc::dns::ConstRRsetPtr& sig_rrset);
+
+private:
+ // Add the necessary magic for any wildcard contained in 'name'
+ // (including itself) to be found in the zone.
+ //
+ // In order for wildcard matching to work correctly in the zone finder,
+ // we must ensure that a node for the wildcarding level exists in the
+ // backend ZoneTree.
+ // E.g. if the wildcard name is "*.sub.example." then we must ensure
+ // that "sub.example." exists and is marked as a wildcard level.
+ // Note: the "wildcarding level" is for the parent name of the wildcard
+ // name (such as "sub.example.").
+ //
+ // We also perform the same trick for empty wild card names possibly
+ // contained in 'name' (e.g., '*.foo.example' in 'bar.*.foo.example').
+ void addWildcards(const isc::dns::Name& name);
+
+ // Does some checks in context of the data that are already in the
+ // zone. Currently checks for forbidden combinations of RRsets in
+ // the same domain (CNAME+anything, DNAME+NS). If such condition is
+ // found, it throws AddError.
+ void contextCheck(const isc::dns::AbstractRRset& rrset,
+ const RdataSet* set) const;
+
+ // Validate rrset before adding it to the zone. If something is wrong
+ // it throws an exception. It doesn't modify the zone, and provides
+ // the strong exception guarantee.
+ void validate(const isc::dns::ConstRRsetPtr rrset) const;
+
+ const isc::dns::NSEC3Hash* getNSEC3Hash();
+ template <typename T>
+ void setupNSEC3(const isc::dns::ConstRRsetPtr rrset);
+ void addNSEC3(const isc::dns::ConstRRsetPtr rrset,
+ const isc::dns::ConstRRsetPtr rrsig);
+ void addRdataSet(const isc::dns::ConstRRsetPtr rrset,
+ const isc::dns::ConstRRsetPtr rrsig);
+
+ util::MemorySegment& mem_sgmt_;
+ const isc::dns::RRClass rrclass_;
+ const isc::dns::Name& zone_name_;
+ ZoneData& zone_data_;
+ RdataEncoder encoder_;
+ const isc::dns::NSEC3Hash* hash_;
+};
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
+
+#endif // DATASRC_ZONE_DATA_UPDATER_H
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/lib/datasrc/memory/zone_finder.cc b/src/lib/datasrc/memory/zone_finder.cc
index 4dddc2c..11188a0 100644
--- a/src/lib/datasrc/memory/zone_finder.cc
+++ b/src/lib/datasrc/memory/zone_finder.cc
@@ -33,6 +33,8 @@
#include <algorithm>
#include <vector>
+#include <utility>
+
using namespace isc::dns;
using namespace isc::datasrc::memory;
using namespace isc::datasrc;
@@ -73,6 +75,17 @@ public:
using internal::ZoneFinderResultContext;
namespace {
+/// Conceptual RRset in the form of a pair of zone node and RdataSet.
+///
+/// In this implementation, the owner name of an RRset is derived from the
+/// corresponding zone node, and the rest of the attributes come from
+/// an RdataSet. This shortcut type can be used when we want to refer to
+/// the conceptual RRset without knowing these details.
+///
+/// This is a read-only version of the pair (and at the moment we don't need
+/// a mutable version).
+typedef std::pair<const ZoneNode*, const RdataSet*> ConstNodeRRset;
+
/// Creates a TreeNodeRRsetPtr for the given RdataSet at the given Node, for
/// the given RRClass
///
@@ -117,7 +130,7 @@ struct FindState {
FindState(bool glue_ok) :
zonecut_node_(NULL),
dname_node_(NULL),
- rrset_(NULL),
+ rdataset_(NULL),
glue_ok_(glue_ok)
{}
@@ -129,7 +142,7 @@ struct FindState {
const ZoneNode* dname_node_;
// Delegation RRset (NS or DNAME), if found.
- const RdataSet* rrset_;
+ const RdataSet* rdataset_;
// Whether to continue search below a delegation point.
// Set at construction time.
@@ -137,7 +150,7 @@ struct FindState {
};
// A callback called from possible zone cut nodes and nodes with DNAME.
-// This will be passed from findNode() to \c RBTree::find().
+// This will be passed from findNode() to \c ZoneTree::find().
bool cutCallback(const ZoneNode& node, FindState* state) {
// We need to look for DNAME first, there's allowed case where
// DNAME and NS coexist in the apex. DNAME is the one to notice,
@@ -149,7 +162,7 @@ bool cutCallback(const ZoneNode& node, FindState* state) {
if (found_dname != NULL) {
LOG_DEBUG(logger, DBG_TRACE_DETAILED, DATASRC_MEM_DNAME_ENCOUNTERED);
state->dname_node_ = &node;
- state->rrset_ = found_dname;
+ state->rdataset_ = found_dname;
return (true);
}
@@ -171,7 +184,7 @@ bool cutCallback(const ZoneNode& node, FindState* state) {
// It cannot happen for us (at least for now), so we don't do
// that check.
state->zonecut_node_ = &node;
- state->rrset_ = found_ns;
+ state->rdataset_ = found_ns;
// Unless glue is allowed the search stops here, so we return
// false; otherwise return true to continue the search.
@@ -225,8 +238,8 @@ ZoneFinderResultContext
createFindResult(const RRClass& rrclass,
const ZoneData& zone_data,
ZoneFinder::Result code,
- const RdataSet* rdset,
const ZoneNode* node,
+ const RdataSet* rdataset,
ZoneFinder::FindOptions options,
bool wild = false,
const Name* qname = NULL)
@@ -247,10 +260,10 @@ createFindResult(const RRClass& rrclass,
}
}
- return (ZoneFinderResultContext(code, createTreeNodeRRset(node, rdset,
+ return (ZoneFinderResultContext(code, createTreeNodeRRset(node, rdataset,
rrclass, options,
rename),
- flags, zone_data, node, rdset));
+ flags, zone_data, node, rdataset));
}
// A helper function for NSEC-signed zones. It searches the zone for
@@ -264,7 +277,7 @@ createFindResult(const RRClass& rrclass,
// it should always succeed.
//
// node_path must store valid search context (in practice, it's expected
-// to be set by findNode()); otherwise the underlying RBTree implementation
+// to be set by findNode()); otherwise the underlying ZoneTree implementation
// throws.
//
// If the zone is not considered NSEC-signed or DNSSEC records were not
@@ -272,16 +285,15 @@ createFindResult(const RRClass& rrclass,
// method doesn't bother to find NSEC, and simply returns NULL. So, by
// definition of "NSEC-signed", when it really tries to find an NSEC it
// should succeed; there should be one at least at the zone origin.
-const RdataSet*
+ConstNodeRRset
getClosestNSEC(const ZoneData& zone_data,
ZoneChain& node_path,
- const ZoneNode** nsec_node,
ZoneFinder::FindOptions options)
{
if (!zone_data.isSigned() ||
(options & ZoneFinder::FIND_DNSSEC) == 0 ||
zone_data.isNSEC3Signed()) {
- return (NULL);
+ return (ConstNodeRRset(NULL, NULL));
}
const ZoneNode* prev_node;
@@ -291,8 +303,7 @@ getClosestNSEC(const ZoneData& zone_data,
const RdataSet* found =
RdataSet::find(prev_node->getData(), RRType::NSEC());
if (found != NULL) {
- *nsec_node = prev_node;
- return (found);
+ return (ConstNodeRRset(prev_node, found));
}
}
}
@@ -301,7 +312,7 @@ getClosestNSEC(const ZoneData& zone_data,
assert(false);
// Even though there is an assert here, strict compilers
// will still need some return value.
- return (NULL);
+ return (ConstNodeRRset(NULL, NULL));
}
// A helper function for the NXRRSET case in find(). If the zone is
@@ -338,16 +349,16 @@ public:
FindNodeResult(ZoneFinder::Result code_param,
const ZoneNode* node_param,
- const RdataSet* rrset_param,
+ const RdataSet* rdataset_param,
unsigned int flags_param = 0) :
code(code_param),
node(node_param),
- rrset(rrset_param),
+ rdataset(rdataset_param),
flags(flags_param)
{}
const ZoneFinder::Result code;
const ZoneNode* node;
- const RdataSet* rrset;
+ const RdataSet* rdataset;
const unsigned int flags;
};
@@ -417,7 +428,7 @@ FindNodeResult findNode(const ZoneData& zone_data,
ZoneFinder::FindOptions options,
bool out_of_zone_ok = false)
{
- ZoneNode* node = NULL;
+ const ZoneNode* node = NULL;
FindState state((options & ZoneFinder::FIND_GLUE_OK) != 0);
const ZoneTree& tree(zone_data.getZoneTree());
@@ -426,7 +437,7 @@ FindNodeResult findNode(const ZoneData& zone_data,
const unsigned int zonecut_flag =
(state.zonecut_node_ != NULL) ? FindNodeResult::FIND_ZONECUT : 0;
if (result == ZoneTree::EXACTMATCH) {
- return (FindNodeResult(ZoneFinder::SUCCESS, node, state.rrset_,
+ return (FindNodeResult(ZoneFinder::SUCCESS, node, state.rdataset_,
zonecut_flag));
} else if (result == ZoneTree::PARTIALMATCH) {
assert(node != NULL);
@@ -434,26 +445,23 @@ FindNodeResult findNode(const ZoneData& zone_data,
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DNAME_FOUND).
arg(state.dname_node_->getName());
return (FindNodeResult(ZoneFinder::DNAME, state.dname_node_,
- state.rrset_));
+ state.rdataset_));
}
if (state.zonecut_node_ != NULL) { // DELEGATION due to NS
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DELEG_FOUND).
arg(state.zonecut_node_->getName());
return (FindNodeResult(ZoneFinder::DELEGATION,
state.zonecut_node_,
- state.rrset_));
+ state.rdataset_));
}
if (node_path.getLastComparisonResult().getRelation() ==
NameComparisonResult::SUPERDOMAIN) { // empty node, so NXRRSET
LOG_DEBUG(logger, DBG_TRACE_DATA,
DATASRC_MEM_SUPER_STOP).arg(name_labels);
- const ZoneNode* nsec_node;
- const RdataSet* nsec_rds = getClosestNSEC(zone_data,
- node_path,
- &nsec_node,
- options);
- return (FindNodeResult(ZoneFinder::NXRRSET, nsec_node,
- nsec_rds));
+ ConstNodeRRset nsec_rrset = getClosestNSEC(zone_data, node_path,
+ options);
+ return (FindNodeResult(ZoneFinder::NXRRSET, nsec_rrset.first,
+ nsec_rrset.second));
}
// Nothing really matched.
@@ -468,13 +476,11 @@ FindNodeResult findNode(const ZoneData& zone_data,
// should cancel wildcard. Treat it as NXDOMAIN.
LOG_DEBUG(logger, DBG_TRACE_DATA,
DATASRC_MEM_WILDCARD_CANCEL).arg(name_labels);
- const ZoneNode* nsec_node;
- const RdataSet* nsec_rds = getClosestNSEC(zone_data,
- node_path,
- &nsec_node,
- options);
- return (FindNodeResult(ZoneFinder::NXDOMAIN, nsec_node,
- nsec_rds));
+ ConstNodeRRset nsec_rrset = getClosestNSEC(zone_data,
+ node_path,
+ options);
+ return (FindNodeResult(ZoneFinder::NXDOMAIN, nsec_rrset.first,
+ nsec_rrset.second));
}
uint8_t ls_buf[LabelSequence::MAX_SERIALIZED_LENGTH];
@@ -490,22 +496,21 @@ FindNodeResult findNode(const ZoneData& zone_data,
// Clear the node_path so that we don't keep incorrect (NSEC)
// context
node_path.clear();
- ZoneTree::Result result = tree.find(LabelSequence(wildcard_ls),
- &node, node_path, cutCallback,
- &state);
+ ZoneTree::Result result = tree.find(wildcard_ls, &node, node_path,
+ cutCallback, &state);
// Otherwise, why would the domain_flag::WILD be there if
// there was no wildcard under it?
assert(result == ZoneTree::EXACTMATCH);
- return (FindNodeResult(ZoneFinder::SUCCESS, node, state.rrset_,
+ return (FindNodeResult(ZoneFinder::SUCCESS, node, state.rdataset_,
FindNodeResult::FIND_WILDCARD | zonecut_flag));
}
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_NOT_FOUND).
arg(name_labels);
- const ZoneNode* nsec_node;
- const RdataSet* nsec_rds = getClosestNSEC(zone_data, node_path,
- &nsec_node, options);
- return (FindNodeResult(ZoneFinder::NXDOMAIN, nsec_node, nsec_rds));
+ ConstNodeRRset nsec_rrset = getClosestNSEC(zone_data, node_path,
+ options);
+ return (FindNodeResult(ZoneFinder::NXDOMAIN, nsec_rrset.first,
+ nsec_rrset.second));
} else {
// If the name is neither an exact or partial match, it is
// out of bailiwick, which is considered an error, unless the caller
@@ -529,17 +534,26 @@ FindNodeResult findNode(const ZoneData& zone_data,
/// context.
class InMemoryZoneFinder::Context : public ZoneFinder::Context {
public:
- Context(ZoneFinder& finder, ZoneFinder::FindOptions options,
+ Context(InMemoryZoneFinder& finder, ZoneFinder::FindOptions options,
const RRClass& rrclass, const ZoneFinderResultContext& result) :
- ZoneFinder::Context(finder, options,
- ResultContext(result.code, result.rrset,
- result.flags)),
+ ZoneFinder::Context(options, ResultContext(result.code, result.rrset,
+ result.flags)),
+ finder_(finder), // NOTE: when entire #2283 is done we won't need this
rrclass_(rrclass), zone_data_(result.zone_data),
found_node_(result.found_node),
found_rdset_(result.found_rdset)
{}
protected:
+ // When all tickets in #2283 are done this can simply return NULL.
+ virtual ZoneFinder* getFinder() { return (&finder_); }
+
+ // We don't use the default protected methods that rely on this method,
+ // so we can simply return NULL.
+ virtual const std::vector<isc::dns::ConstRRsetPtr>* getAllRRsets() const {
+ return (NULL);
+ }
+
virtual void getAdditionalImpl(const std::vector<RRType>& requested_types,
std::vector<ConstRRsetPtr>& result)
{
@@ -621,6 +635,7 @@ private:
}
private:
+ InMemoryZoneFinder& finder_;
const RRClass rrclass_;
const ZoneData* const zone_data_;
const ZoneNode* const found_node_;
@@ -690,8 +705,8 @@ InMemoryZoneFinder::find(const isc::dns::Name& name,
const FindOptions options)
{
return (ZoneFinderContextPtr(new Context(*this, options, rrclass_,
- find_internal(name, type,
- NULL, options))));
+ findInternal(name, type,
+ NULL, options))));
}
boost::shared_ptr<ZoneFinder::Context>
@@ -700,17 +715,17 @@ InMemoryZoneFinder::findAll(const isc::dns::Name& name,
const FindOptions options)
{
return (ZoneFinderContextPtr(new Context(*this, options, rrclass_,
- find_internal(name,
- RRType::ANY(),
- &target,
- options))));
+ findInternal(name,
+ RRType::ANY(),
+ &target,
+ options))));
}
ZoneFinderResultContext
-InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
- const isc::dns::RRType& type,
- std::vector<ConstRRsetPtr>* target,
- const FindOptions options)
+InMemoryZoneFinder::findInternal(const isc::dns::Name& name,
+ const isc::dns::RRType& type,
+ std::vector<ConstRRsetPtr>* target,
+ const FindOptions options)
{
// Get the node. All other cases than an exact match are handled
// in findNode(). We simply construct a result structure and return.
@@ -719,7 +734,7 @@ InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
findNode(zone_data_, LabelSequence(name), node_path, options);
if (node_result.code != SUCCESS) {
return (createFindResult(rrclass_, zone_data_, node_result.code,
- node_result.rrset, node_result.node,
+ node_result.node, node_result.rdataset,
options));
}
@@ -735,11 +750,11 @@ InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
if (node->isEmpty()) {
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_DOMAIN_EMPTY).
arg(name);
- const ZoneNode* nsec_node;
- const RdataSet* nsec_rds = getClosestNSEC(zone_data_, node_path,
- &nsec_node, options);
+ ConstNodeRRset nsec_rrset = getClosestNSEC(zone_data_, node_path,
+ options);
return (createFindResult(rrclass_, zone_data_, NXRRSET,
- nsec_rds, nsec_node, options, wild));
+ nsec_rrset.first, nsec_rrset.second,
+ options, wild));
}
const RdataSet* found;
@@ -758,7 +773,7 @@ InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
LOG_DEBUG(logger, DBG_TRACE_DATA,
DATASRC_MEM_EXACT_DELEGATION).arg(name);
return (createFindResult(rrclass_, zone_data_, DELEGATION,
- found, node, options, wild, &name));
+ node, found, options, wild, &name));
}
}
@@ -773,7 +788,7 @@ InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
}
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_ANY_SUCCESS).
arg(name);
- return (createFindResult(rrclass_, zone_data_, SUCCESS, NULL, node,
+ return (createFindResult(rrclass_, zone_data_, SUCCESS, node, NULL,
options, wild, &name));
}
@@ -782,7 +797,7 @@ InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
// Good, it is here
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_SUCCESS).arg(name).
arg(type);
- return (createFindResult(rrclass_, zone_data_, SUCCESS, found, node,
+ return (createFindResult(rrclass_, zone_data_, SUCCESS, node, found,
options, wild, &name));
} else {
// Next, try CNAME.
@@ -790,14 +805,14 @@ InMemoryZoneFinder::find_internal(const isc::dns::Name& name,
if (found != NULL) {
LOG_DEBUG(logger, DBG_TRACE_DATA, DATASRC_MEM_CNAME).arg(name);
- return (createFindResult(rrclass_, zone_data_, CNAME, found, node,
+ return (createFindResult(rrclass_, zone_data_, CNAME, node, found,
options, wild, &name));
}
}
// No exact match or CNAME. Get NSEC if necessary and return NXRRSET.
- return (createFindResult(rrclass_, zone_data_, NXRRSET,
+ return (createFindResult(rrclass_, zone_data_, NXRRSET, node,
getNSECForNXRRSET(zone_data_, options, node),
- node, options, wild, &name));
+ options, wild, &name));
}
isc::datasrc::ZoneFinder::FindNSEC3Result
diff --git a/src/lib/datasrc/memory/zone_finder.h b/src/lib/datasrc/memory/zone_finder.h
index 85e21c3..c95b5bc 100644
--- a/src/lib/datasrc/memory/zone_finder.h
+++ b/src/lib/datasrc/memory/zone_finder.h
@@ -92,7 +92,7 @@ private:
class Context;
/// Actual implementation for both find() and findAll()
- internal::ZoneFinderResultContext find_internal(
+ internal::ZoneFinderResultContext findInternal(
const isc::dns::Name& name,
const isc::dns::RRType& type,
std::vector<isc::dns::ConstRRsetPtr>* target,
diff --git a/src/lib/datasrc/memory/zone_table.cc b/src/lib/datasrc/memory/zone_table.cc
index a74a61d..c0237f5 100644
--- a/src/lib/datasrc/memory/zone_table.cc
+++ b/src/lib/datasrc/memory/zone_table.cc
@@ -47,39 +47,34 @@ typedef boost::function<void(ZoneData*)> ZoneDataDeleterType;
}
ZoneTable*
-ZoneTable::create(util::MemorySegment& mem_sgmt, RRClass zone_class) {
+ZoneTable::create(util::MemorySegment& mem_sgmt, const RRClass& zone_class) {
SegmentObjectHolder<ZoneTableTree, ZoneDataDeleterType> holder(
mem_sgmt, ZoneTableTree::create(mem_sgmt),
boost::bind(deleteZoneData, &mem_sgmt, _1, zone_class));
void* p = mem_sgmt.allocate(sizeof(ZoneTable));
- ZoneTable* zone_table = new(p) ZoneTable(holder.get());
+ ZoneTable* zone_table = new(p) ZoneTable(zone_class, holder.get());
holder.release();
return (zone_table);
}
void
-ZoneTable::destroy(util::MemorySegment& mem_sgmt, ZoneTable* ztable,
- RRClass zone_class)
+ZoneTable::destroy(util::MemorySegment& mem_sgmt, ZoneTable* ztable)
{
ZoneTableTree::destroy(mem_sgmt, ztable->zones_.get(),
boost::bind(deleteZoneData, &mem_sgmt, _1,
- zone_class));
+ ztable->rrclass_));
mem_sgmt.deallocate(ztable, sizeof(ZoneTable));
}
ZoneTable::AddResult
ZoneTable::addZone(util::MemorySegment& mem_sgmt, RRClass zone_class,
- const Name& zone_name)
+ const Name& zone_name, ZoneData* content)
{
- // Create a new ZoneData instance first. If the specified name already
- // exists in the table, the new data will soon be destroyed, but we want
- // to make sure if this allocation fails the tree won't be changed to
- // provide as strong guarantee as possible. In practice, we generally
- // expect the caller tries to add a zone only when it's a new one, so
- // this should be a minor concern.
- SegmentObjectHolder<ZoneData, RRClass> holder(
- mem_sgmt, ZoneData::create(mem_sgmt, zone_name), zone_class);
-
+ if (content == NULL) {
+ isc_throw(isc::BadValue, "Zone content must not be NULL");
+ }
+ SegmentObjectHolder<ZoneData, RRClass> holder(mem_sgmt, content,
+ zone_class);
// Get the node where we put the zone
ZoneTableNode* node(NULL);
switch (zones_->insert(mem_sgmt, zone_name, &node)) {
@@ -94,18 +89,18 @@ ZoneTable::addZone(util::MemorySegment& mem_sgmt, RRClass zone_class,
// Can Not Happen
assert(node != NULL);
- // Is it empty? We either just created it or it might be nonterminal
- if (node->isEmpty()) {
- node->setData(holder.get());
- return (AddResult(result::SUCCESS, holder.release()));
- } else { // There's something there already
- return (AddResult(result::EXIST, node->getData()));
+ // We can release now, setData never throws
+ ZoneData* old = node->setData(holder.release());
+ if (old != NULL) {
+ return (AddResult(result::EXIST, old));
+ } else {
+ return (AddResult(result::SUCCESS, NULL));
}
}
ZoneTable::FindResult
ZoneTable::findZone(const Name& name) const {
- ZoneTableNode* node(NULL);
+ const ZoneTableNode* node(NULL);
result::Result my_result;
// Translate the return codes
@@ -132,20 +127,6 @@ ZoneTable::findZone(const Name& name) const {
return (FindResult(my_result, node->getData()));
}
-ZoneTable::FindResult
-ZoneTable::setZoneData(const Name& name, ZoneData* data)
-{
- ZoneTableNode* node(NULL);
-
- ZoneTableTree::Result result(zones_->find(name, &node));
-
- if (result != ZoneTableTree::EXACTMATCH) {
- return (FindResult(result::NOTFOUND, NULL));
- } else {
- return (FindResult(result::SUCCESS, node->setData(data)));
- }
-}
-
} // end of namespace memory
} // end of namespace datasrc
} // end of namespace isc
diff --git a/src/lib/datasrc/memory/zone_table.h b/src/lib/datasrc/memory/zone_table.h
index 8ad6213..1b369b9 100644
--- a/src/lib/datasrc/memory/zone_table.h
+++ b/src/lib/datasrc/memory/zone_table.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATASRC_MEMORY_ZONE_TABLE_H
-#define __DATASRC_MEMORY_ZONE_TABLE_H 1
+#ifndef DATASRC_MEMORY_ZONE_TABLE_H
+#define DATASRC_MEMORY_ZONE_TABLE_H 1
#include <util/memory_segment.h>
@@ -74,23 +74,23 @@ private:
typedef DomainTreeNode<ZoneData> ZoneTableNode;
public:
- /// \brief Result data of addZone() method.
- struct AddResult {
- AddResult(result::Result param_code, ZoneData* param_zone_data) :
- code(param_code), zone_data(param_zone_data)
- {}
- const result::Result code;
- ZoneData* const zone_data;
- };
+ /// \brief Result data of addZone() method.
+ struct AddResult {
+ AddResult(result::Result param_code, ZoneData* param_zone_data) :
+ code(param_code), zone_data(param_zone_data)
+ {}
+ const result::Result code;
+ ZoneData* const zone_data;
+ };
/// \brief Result data of findZone() method.
struct FindResult {
FindResult(result::Result param_code,
- ZoneData* param_zone_data) :
+ const ZoneData* param_zone_data) :
code(param_code), zone_data(param_zone_data)
{}
const result::Result code;
- ZoneData* const zone_data;
+ const ZoneData* const zone_data;
};
private:
@@ -102,7 +102,9 @@ private:
/// This constructor internally involves resource allocation, and if
/// it fails, a corresponding standard exception will be thrown.
/// It never throws an exception otherwise.
- ZoneTable(ZoneTableTree* zones) : zones_(zones)
+ ZoneTable(const dns::RRClass& rrclass, ZoneTableTree* zones) :
+ rrclass_(rrclass),
+ zones_(zones)
{}
public:
@@ -119,7 +121,7 @@ public:
/// \param zone_class The RR class of the zone. It must be the RR class
/// that is supposed to be associated to the zone table.
static ZoneTable* create(util::MemorySegment& mem_sgmt,
- dns::RRClass zone_class);
+ const dns::RRClass& zone_class);
/// \brief Destruct and deallocate \c ZoneTable
///
@@ -135,35 +137,33 @@ public:
/// \param ztable A non NULL pointer to a valid \c ZoneTable object
/// that was originally created by the \c create() method (the behavior
/// is undefined if this condition isn't met).
- static void destroy(util::MemorySegment& mem_sgmt, ZoneTable* ztable,
- dns::RRClass zone_class);
+ static void destroy(util::MemorySegment& mem_sgmt, ZoneTable* ztable);
/// Add a new zone to the \c ZoneTable.
///
- /// This method creates a new \c ZoneData for the given zone name and
- /// holds it in the internal table. The newly created zone data will be
- /// returned via the \c zone_data member of the return value. If the given
- /// zone name already exists in the table, a new data object won't be
- /// created; instead, the existing corresponding data will be returned.
- ///
- /// The zone table keeps the ownership of the created zone data; the
- /// caller must not try to destroy it directly. (We'll eventually
- /// add an interface to delete specific zone data from the table).
+ /// This method adds a given zone data to the internal table.
///
/// \throw std::bad_alloc Internal resource allocation fails.
///
/// \param mem_sgmt The \c MemorySegment to allocate zone data to be
- /// created. It must be the same segment that was used to create
- /// the zone table at the time of create().
+ /// created. It must be the same segment that was used to create
+ /// the zone table at the time of create().
/// \param zone_name The name of the zone to be added.
/// \param zone_class The RR class of the zone. It must be the RR class
- /// that is supposed to be associated to the zone table.
+ /// that is supposed to be associated to the zone table.
+ /// \param content This one should hold the zone content (the ZoneData).
+ /// The ownership is passed onto the zone table. Must not be null.
+ /// Must correspond to the name and class and must be allocated from
+ /// mem_sgmt.
/// \return \c result::SUCCESS If the zone is successfully
- /// added to the zone table.
- /// \return \c result::EXIST The zone table already contains
- /// zone of the same origin.
- AddResult addZone(util::MemorySegment& mem_sgmt, dns::RRClass zone_class,
- const dns::Name& zone_name);
+ /// added to the zone table.
+ /// \return \c result::EXIST The zone table already contained
+ /// zone of the same origin. The old data is replaced and returned
+ /// inside the result.
+ AddResult addZone(util::MemorySegment& mem_sgmt,
+ dns::RRClass zone_class,
+ const dns::Name& zone_name,
+ ZoneData* content);
/// Find a zone that best matches the given name in the \c ZoneTable.
///
@@ -185,23 +185,14 @@ public:
/// \return A \c FindResult object enclosing the search result (see above).
FindResult findZone(const isc::dns::Name& name) const;
- /// Override the ZoneData for a node (zone) in the zone tree.
- ///
- /// \throw none
- ///
- /// \param name A domain name for which the zone data is set.
- /// \param data The new zone data to set.
- /// \return A \c FindResult object containing the old data if the
- /// zone was found.
- FindResult setZoneData(const isc::dns::Name& name, ZoneData* data);
-
private:
+ const dns::RRClass rrclass_;
boost::interprocess::offset_ptr<ZoneTableTree> zones_;
};
}
}
}
-#endif // __DATASRC_MEMORY_ZONE_TABLE_H
+#endif // DATASRC_MEMORY_ZONE_TABLE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/memory/zone_table_segment.cc b/src/lib/datasrc/memory/zone_table_segment.cc
new file mode 100644
index 0000000..50587c4
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_table_segment.cc
@@ -0,0 +1,41 @@
+// 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 <datasrc/memory/zone_table_segment.h>
+#include <datasrc/memory/zone_table_segment_local.h>
+
+using namespace isc::dns;
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+ZoneTableSegment*
+ZoneTableSegment::create(const isc::data::Element&, const RRClass& rrclass) {
+ /// FIXME: For now, we always return ZoneTableSegmentLocal. This
+ /// should be updated eventually to parse the passed Element
+ /// argument and construct a corresponding ZoneTableSegment
+ /// implementation.
+
+ return (new ZoneTableSegmentLocal(rrclass));
+}
+
+void
+ZoneTableSegment::destroy(ZoneTableSegment *segment) {
+ delete segment;
+}
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
diff --git a/src/lib/datasrc/memory/zone_table_segment.h b/src/lib/datasrc/memory/zone_table_segment.h
new file mode 100644
index 0000000..88e69f6
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_table_segment.h
@@ -0,0 +1,149 @@
+// 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 ZONE_TABLE_SEGMENT_H
+#define ZONE_TABLE_SEGMENT_H
+
+#include <dns/rrclass.h>
+#include <datasrc/memory/zone_table.h>
+#include "load_action.h"
+#include <cc/data.h>
+#include <util/memory_segment.h>
+
+#include <boost/interprocess/offset_ptr.hpp>
+
+#include <stdlib.h>
+
+namespace isc {
+// Some forward declarations
+namespace dns {
+class Name;
+class RRClass;
+}
+namespace datasrc {
+namespace memory {
+class ZoneWriter;
+
+/// \brief Memory-management independent entry point that contains a
+/// pointer to a zone table in memory.
+///
+/// An instance of this type lives inside a ZoneTableSegment
+/// implementation. It contains an offset pointer to the zone table (a
+/// map from domain names to zone locators) in memory.
+struct ZoneTableHeader {
+public:
+ ZoneTableHeader(ZoneTable* zone_table) :
+ table_(zone_table)
+ {}
+
+ /// \brief Returns a pointer to the underlying zone table.
+ ZoneTable* getTable() {
+ return (table_.get());
+ }
+
+ /// \brief const version of \c getTable().
+ const ZoneTable* getTable() const {
+ return (table_.get());
+ }
+private:
+ boost::interprocess::offset_ptr<ZoneTable> table_;
+};
+
+/// \brief Manages a ZoneTableHeader, an entry point into a table of
+/// zones
+///
+/// This class specifies an interface for derived implementations which
+/// return a pointer to an object of type ZoneTableHeader, an entry
+/// point into a table of zones regardless of the underlying memory
+/// management implementation. Derived classes would implement the
+/// interface for specific memory-implementation behavior.
+class ZoneTableSegment {
+protected:
+ /// \brief Protected constructor
+ ///
+ /// An instance implementing this interface is expected to be
+ /// created by the factory method (\c create()), so this constructor
+ /// is protected.
+ ZoneTableSegment(isc::dns::RRClass)
+ {}
+public:
+ /// \brief Destructor
+ virtual ~ZoneTableSegment() {}
+
+ /// \brief Return the ZoneTableHeader for the zone table segment.
+ virtual ZoneTableHeader& getHeader() = 0;
+
+ /// \brief const version of \c getHeader().
+ virtual const ZoneTableHeader& getHeader() const = 0;
+
+ /// \brief Return the MemorySegment for the zone table segment.
+ virtual isc::util::MemorySegment& getMemorySegment() = 0;
+
+ /// \brief Create an instance depending on the memory segment model
+ ///
+ /// This is a factory method to create a derived ZoneTableSegment
+ /// object based on the \c config passed. The method returns a
+ /// dynamically-allocated object. The caller is responsible for
+ /// destroying it with \c ZoneTableSegment::destroy().
+ ///
+ /// FIXME: For now, we always return ZoneTableSegmentLocal
+ /// regardless of the passed \c config.
+ ///
+ /// \param config The configuration based on which a derived object
+ /// is returned.
+ /// \return Returns a ZoneTableSegment object
+ static ZoneTableSegment* create(const isc::data::Element& config,
+ const isc::dns::RRClass& rrclass);
+
+ /// \brief Temporary/Testing version of create.
+ ///
+ /// This exists as a temporary solution during the migration phase
+ /// towards using the ZoneTableSegment. It doesn't take a config,
+ /// but a memory segment instead. If you can, you should use the
+ /// other version, this one will be gone soon.
+ ///
+ /// \param segment The memory segment to use.
+ /// \return Returns a new ZoneTableSegment object.
+ /// \todo Remove this method.
+ static ZoneTableSegment* create(isc::util::MemorySegment& segment);
+
+ /// \brief Destroy a ZoneTableSegment
+ ///
+ /// This method destroys the passed ZoneTableSegment. It must be
+ /// passed a segment previously created by \c ZoneTableSegment::create().
+ ///
+ /// \param segment The segment to destroy.
+ static void destroy(ZoneTableSegment* segment);
+
+ /// \brief Create a zone write corresponding to this segment
+ ///
+ /// This creates a new write that can be used to update zones
+ /// inside this zone table segment.
+ ///
+ /// \param loadAction Callback to provide the actual data.
+ /// \param origin The origin of the zone to reload.
+ /// \param rrclass The class of the zone to reload.
+ /// \return New instance of a zone writer. The ownership is passed
+ /// onto the caller and the caller needs to \c delete it when
+ /// it's done with the writer.
+ virtual ZoneWriter* getZoneWriter(const LoadAction& load_action,
+ const dns::Name& origin,
+ const dns::RRClass& rrclass) = 0;
+};
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
+
+#endif // ZONE_TABLE_SEGMENT_H
diff --git a/src/lib/datasrc/memory/zone_table_segment_local.cc b/src/lib/datasrc/memory/zone_table_segment_local.cc
new file mode 100644
index 0000000..fdaf678
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_table_segment_local.cc
@@ -0,0 +1,69 @@
+// 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 <datasrc/memory/zone_table_segment_local.h>
+#include "zone_writer_local.h"
+
+using namespace isc::dns;
+using namespace isc::util;
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+ZoneTableSegmentLocal::ZoneTableSegmentLocal(const RRClass& rrclass) :
+ ZoneTableSegment(rrclass),
+ header_(ZoneTable::create(mem_sgmt_, rrclass))
+{
+}
+
+ZoneTableSegmentLocal::~ZoneTableSegmentLocal() {
+ // Explicitly clear the contained data, and check memory
+ // leak. assert() (with abort on failure) may be too harsh, but
+ // it's probably better to find more leaks initially. Once it's stabilized
+ // we should probably revisit it.
+
+ ZoneTable::destroy(mem_sgmt_, header_.getTable());
+ assert(mem_sgmt_.allMemoryDeallocated());
+}
+
+// After more methods' definitions are added here, it would be a good
+// idea to move getHeader() and getMemorySegment() definitions to the
+// header file.
+ZoneTableHeader&
+ZoneTableSegmentLocal::getHeader() {
+ return (header_);
+}
+
+const ZoneTableHeader&
+ZoneTableSegmentLocal::getHeader() const {
+ return (header_);
+}
+
+MemorySegment&
+ZoneTableSegmentLocal::getMemorySegment() {
+ return (mem_sgmt_);
+}
+
+ZoneWriter*
+ZoneTableSegmentLocal::getZoneWriter(const LoadAction& load_action,
+ const dns::Name& name,
+ const dns::RRClass& rrclass)
+{
+ return (new ZoneWriterLocal(this, load_action, name, rrclass));
+}
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
diff --git a/src/lib/datasrc/memory/zone_table_segment_local.h b/src/lib/datasrc/memory/zone_table_segment_local.h
new file mode 100644
index 0000000..e08ca39
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_table_segment_local.h
@@ -0,0 +1,69 @@
+// 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 ZONE_TABLE_SEGMENT_LOCAL_H
+#define ZONE_TABLE_SEGMENT_LOCAL_H
+
+#include <datasrc/memory/zone_table_segment.h>
+#include <util/memory_segment_local.h>
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+/// \brief Local implementation of ZoneTableSegment class
+///
+/// This class specifies a concrete implementation for a
+/// MemorySegmentLocal based ZoneTableSegment. Please see the
+/// ZoneTableSegment class documentation for usage.
+class ZoneTableSegmentLocal : public ZoneTableSegment {
+ // This is so that ZoneTableSegmentLocal can be instantiated from
+ // ZoneTableSegment::create().
+ friend class ZoneTableSegment;
+protected:
+ /// \brief Protected constructor
+ ///
+ /// Instances are expected to be created by the factory method
+ /// (\c ZoneTableSegment::create()), so this constructor is
+ /// protected.
+ ZoneTableSegmentLocal(const isc::dns::RRClass& rrclass);
+public:
+ /// \brief Destructor
+ virtual ~ZoneTableSegmentLocal();
+
+ /// \brief Return the ZoneTableHeader for the local zone table
+ /// segment implementation.
+ virtual ZoneTableHeader& getHeader();
+
+ /// \brief const version of \c getHeader().
+ virtual const ZoneTableHeader& getHeader() const;
+
+ /// \brief Return the MemorySegment for the local zone table segment
+ /// implementation (a MemorySegmentLocal instance).
+ virtual isc::util::MemorySegment& getMemorySegment();
+
+ /// \brief Concrete implementation of ZoneTableSegment::getZoneWriter
+ virtual ZoneWriter* getZoneWriter(const LoadAction& load_action,
+ const dns::Name& origin,
+ const dns::RRClass& rrclass);
+private:
+ isc::util::MemorySegmentLocal mem_sgmt_;
+ ZoneTableHeader header_;
+};
+
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
+
+#endif // ZONE_TABLE_SEGMENT_LOCAL_H
diff --git a/src/lib/datasrc/memory/zone_writer.h b/src/lib/datasrc/memory/zone_writer.h
new file mode 100644
index 0000000..0e8f285
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_writer.h
@@ -0,0 +1,92 @@
+// 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 MEM_ZONE_WRITER_H
+#define MEM_ZONE_WRITER_H
+
+#include "load_action.h"
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+/// \brief Does an update to a zone.
+///
+/// This abstract base class represents the work of a reload of a zone.
+/// The work is divided into three stages -- load(), install() and cleanup().
+/// They should be called in this order for the effect to take place.
+///
+/// We divide them so the update of zone data can be done asynchronously,
+/// in a different thread. The install() operation is the only one that needs
+/// to be done in a critical section.
+///
+/// Each derived class implementation must provide the strong exception
+/// guarantee for each public method. That is, when any of the methods
+/// throws, the entire state should stay the same as before the call
+/// (how to achieve that may be implementation dependant).
+class ZoneWriter {
+public:
+ /// \brief Virtual destructor.
+ virtual ~ZoneWriter() {};
+
+ /// \brief Get the zone data into memory.
+ ///
+ /// This is the part that does the time-consuming loading into the memory.
+ /// This can be run in a separate thread, for example. It has no effect on
+ /// the data actually served, it only prepares them for future use.
+ ///
+ /// This is the first method you should call on the object. Never call it
+ /// multiple times.
+ ///
+ /// \note As this contains reading of files or other data sources, or with
+ /// some other source of the data to load, it may throw quite anything.
+ /// If it throws, do not call any other methods on the object and
+ /// discard it.
+ /// \note After successful load(), you have to call cleanup() some time
+ /// later.
+ /// \throw isc::InvalidOperation if called second time.
+ virtual void load() = 0;
+
+ /// \brief Put the changes to effect.
+ ///
+ /// This replaces the old version of zone with the one previously prepared
+ /// by load(). It takes ownership of the old zone data, if any.
+ ///
+ /// You may call it only after successful load() and at most once.
+ ///
+ /// The operation is expected to be fast and is meant to be used inside
+ /// a critical section.
+ ///
+ /// This may throw in rare cases, depending on the concrete implementation.
+ /// If it throws, you still need to call cleanup().
+ ///
+ /// \throw isc::InvalidOperation if called without previous load() or for
+ /// the second time or cleanup() was called already.
+ virtual void install() = 0;
+
+ /// \brief Clean up resources.
+ ///
+ /// This releases all resources held by owned zone data. That means the
+ /// one loaded by load() in case install() was not called or was not
+ /// successful, or the one replaced in install().
+ ///
+ /// Generally, this should never throw.
+ virtual void cleanup() = 0;
+};
+
+}
+}
+}
+
+#endif
diff --git a/src/lib/datasrc/memory/zone_writer_local.cc b/src/lib/datasrc/memory/zone_writer_local.cc
new file mode 100644
index 0000000..0cd9587
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_writer_local.cc
@@ -0,0 +1,93 @@
+// 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 "zone_writer_local.h"
+#include "zone_data.h"
+#include "zone_table_segment_local.h"
+
+#include <memory>
+
+using std::auto_ptr;
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+ZoneWriterLocal::ZoneWriterLocal(ZoneTableSegmentLocal* segment,
+ const LoadAction& load_action,
+ const dns::Name& origin,
+ const dns::RRClass& rrclass) :
+ segment_(segment),
+ load_action_(load_action),
+ origin_(origin),
+ rrclass_(rrclass),
+ zone_data_(NULL),
+ state_(ZW_UNUSED)
+{}
+
+ZoneWriterLocal::~ZoneWriterLocal() {
+ // Clean up everything there might be left if someone forgot, just
+ // in case.
+ cleanup();
+}
+
+void
+ZoneWriterLocal::load() {
+ if (state_ != ZW_UNUSED) {
+ isc_throw(isc::InvalidOperation, "Trying to load twice");
+ }
+
+ zone_data_ = load_action_(segment_->getMemorySegment());
+
+ if (zone_data_ == NULL) {
+ // Bug inside load_action_.
+ isc_throw(isc::InvalidOperation, "No data returned from load action");
+ }
+
+ state_ = ZW_LOADED;
+}
+
+void
+ZoneWriterLocal::install() {
+ if (state_ != ZW_LOADED) {
+ isc_throw(isc::InvalidOperation, "No data to install");
+ }
+
+
+ ZoneTable* table(segment_->getHeader().getTable());
+ if (table == NULL) {
+ isc_throw(isc::Unexpected, "No zone table present");
+ }
+ const ZoneTable::AddResult result(table->addZone(
+ segment_->getMemorySegment(),
+ rrclass_, origin_, zone_data_));
+
+ state_ = ZW_INSTALLED;
+ zone_data_ = result.zone_data;
+}
+
+void
+ZoneWriterLocal::cleanup() {
+ // We eat the data (if any) now.
+
+ if (zone_data_ != NULL) {
+ ZoneData::destroy(segment_->getMemorySegment(), zone_data_, rrclass_);
+ zone_data_ = NULL;
+ state_ = ZW_CLEANED;
+ }
+}
+
+}
+}
+}
diff --git a/src/lib/datasrc/memory/zone_writer_local.h b/src/lib/datasrc/memory/zone_writer_local.h
new file mode 100644
index 0000000..7231a57
--- /dev/null
+++ b/src/lib/datasrc/memory/zone_writer_local.h
@@ -0,0 +1,95 @@
+// 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 MEM_ZONE_WRITER_LOCAL_H
+#define MEM_ZONE_WRITER_LOCAL_H
+
+#include "zone_writer.h"
+
+#include <dns/rrclass.h>
+#include <dns/name.h>
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+
+class ZoneData;
+class ZoneTableSegmentLocal;
+
+/// \brief Writer implementation which loads data locally.
+///
+/// This implementation prepares a clean zone data and lets one callback
+/// to fill it and another to install it somewhere. The class does mostly
+/// nothing (and delegates the work to the callbacks), just stores little bit
+/// of state between the calls.
+class ZoneWriterLocal : public ZoneWriter {
+public:
+ /// \brief Constructor
+ ///
+ /// \param segment The zone table segment to store the zone into.
+ /// \param load_action The callback used to load data.
+ /// \param install_action The callback used to install the loaded zone.
+ /// \param rrclass The class of the zone.
+ ZoneWriterLocal(ZoneTableSegmentLocal* segment,
+ const LoadAction& load_action, const dns::Name& name,
+ const dns::RRClass& rrclass);
+
+ /// \brief Destructor
+ ~ZoneWriterLocal();
+
+ /// \brief Loads the data.
+ ///
+ /// This calls the load_action (passed to constructor) and stores the
+ /// data for future use.
+ ///
+ /// \throw isc::InvalidOperation if it is called the second time in
+ /// lifetime of the object.
+ /// \throw Whatever the load_action throws, it is propagated up.
+ virtual void load();
+
+ /// \brief Installs the zone.
+ ///
+ /// It modifies the zone table accessible through the segment (passed to
+ /// constructor).
+ ///
+ /// \throw isc::InvalidOperation if it is called the second time in
+ /// lifetime of the object or if load() was not called previously or if
+ /// cleanup() was already called.
+ virtual void install();
+
+ /// \brief Clean up memory.
+ ///
+ /// Cleans up the memory used by load()ed zone if not yet installed, or
+ /// the old zone replaced by install().
+ virtual void cleanup();
+private:
+ ZoneTableSegmentLocal* segment_;
+ LoadAction load_action_;
+ dns::Name origin_;
+ dns::RRClass rrclass_;
+ ZoneData* zone_data_;
+ enum State {
+ ZW_UNUSED,
+ ZW_LOADED,
+ ZW_INSTALLED,
+ ZW_CLEANED
+ };
+ State state_;
+};
+
+}
+}
+}
+
+#endif
diff --git a/src/lib/datasrc/memory_datasrc.cc b/src/lib/datasrc/memory_datasrc.cc
index e38a487..686dd94 100644
--- a/src/lib/datasrc/memory_datasrc.cc
+++ b/src/lib/datasrc/memory_datasrc.cc
@@ -20,7 +20,6 @@
#include <dns/nsec3hash.h>
#include <dns/rdataclass.h>
#include <dns/rrclass.h>
-#include <dns/rrsetlist.h>
#include <dns/masterload.h>
#include <datasrc/memory_datasrc.h>
@@ -792,13 +791,19 @@ public:
/// context.
Context(ZoneFinder& finder, ZoneFinder::FindOptions options,
const RBNodeResultContext& result) :
- ZoneFinder::Context(finder, options,
+ ZoneFinder::Context(options,
ResultContext(result.code, result.rrset,
result.flags)),
- rrset_(result.rrset), found_node_(result.found_node)
+ finder_(finder), rrset_(result.rrset), found_node_(result.found_node)
{}
protected:
+ virtual ZoneFinder* getFinder() { return (&finder_); }
+
+ virtual const std::vector<isc::dns::ConstRRsetPtr>* getAllRRsets() const {
+ return (NULL);
+ }
+
virtual void getAdditionalImpl(const vector<RRType>& requested_types,
vector<ConstRRsetPtr>& result)
{
@@ -866,6 +871,7 @@ private:
}
}
+ ZoneFinder& finder_;
const ConstRBNodeRRsetPtr rrset_;
const DomainNode* const found_node_;
};
diff --git a/src/lib/datasrc/memory_datasrc.h b/src/lib/datasrc/memory_datasrc.h
index be545d4..4e277e0 100644
--- a/src/lib/datasrc/memory_datasrc.h
+++ b/src/lib/datasrc/memory_datasrc.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MEMORY_DATA_SOURCE_H
-#define __MEMORY_DATA_SOURCE_H 1
+#ifndef MEMORY_DATA_SOURCE_H
+#define MEMORY_DATA_SOURCE_H 1
#include <string>
@@ -360,7 +360,7 @@ extern "C" void destroyInstance(DataSourceClient* instance);
}
}
-#endif // __DATA_SOURCE_MEMORY_H
+#endif // MEMORY_DATA_SOURCE_H
// Local Variables:
// mode: c++
// End:
diff --git a/src/lib/datasrc/memory_datasrc_link.cc b/src/lib/datasrc/memory_datasrc_link.cc
index cbbc6db..857223f 100644
--- a/src/lib/datasrc/memory_datasrc_link.cc
+++ b/src/lib/datasrc/memory_datasrc_link.cc
@@ -129,7 +129,7 @@ checkConfig(ConstElementPtr config, ElementPtr errors) {
result = false;
} else {
try {
- RRClass rrc(config->get("class")->stringValue());
+ RRClass(config->get("class")->stringValue());
} catch (const isc::Exception& rrce) {
addError(errors,
"Error parsing class config for memory backend: " +
diff --git a/src/lib/datasrc/rbnode_rrset.h b/src/lib/datasrc/rbnode_rrset.h
index 1c23e05..cbb1b71 100644
--- a/src/lib/datasrc/rbnode_rrset.h
+++ b/src/lib/datasrc/rbnode_rrset.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RBNODE_RRSET_H
-#define __RBNODE_RRSET_H
+#ifndef RBNODE_RRSET_H
+#define RBNODE_RRSET_H
#include <dns/messagerenderer.h>
#include <dns/name.h>
@@ -227,4 +227,4 @@ private:
} // namespace datasrc
} // namespace isc
-#endif // __RBNODE_RRSET_H
+#endif // RBNODE_RRSET_H
diff --git a/src/lib/datasrc/rbtree.h b/src/lib/datasrc/rbtree.h
index eb971e8..d0efa0a 100644
--- a/src/lib/datasrc/rbtree.h
+++ b/src/lib/datasrc/rbtree.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _RBTREE_H
-#define _RBTREE_H 1
+#ifndef RBTREE_H
+#define RBTREE_H 1
//! \file datasrc/rbtree.h
///
@@ -1986,7 +1986,7 @@ RBTree<T>::dumpDotHelper(std::ostream& os, const RBNode<T>* node,
}
}
-#endif // _RBTREE_H
+#endif // RBTREE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/result.h b/src/lib/datasrc/result.h
index f7ca363..5a28d08 100644
--- a/src/lib/datasrc/result.h
+++ b/src/lib/datasrc/result.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATASRC_RESULT_H
-#define __DATASRC_RESULT_H 1
+#ifndef DATASRC_RESULT_H
+#define DATASRC_RESULT_H 1
namespace isc {
namespace datasrc {
diff --git a/src/lib/datasrc/sqlite3_accessor.cc b/src/lib/datasrc/sqlite3_accessor.cc
index 24d7b3f..68d6554 100644
--- a/src/lib/datasrc/sqlite3_accessor.cc
+++ b/src/lib/datasrc/sqlite3_accessor.cc
@@ -20,6 +20,8 @@
#include <exceptions/exceptions.h>
+#include <dns/name.h>
+
#include <datasrc/sqlite3_accessor.h>
#include <datasrc/logger.h>
#include <datasrc/data_source.h>
@@ -42,7 +44,7 @@ namespace {
// program may not be taking advantage of features (possibly performance
// improvements) added to the database.
const int SQLITE_SCHEMA_MAJOR_VERSION = 2;
-const int SQLITE_SCHEMA_MINOR_VERSION = 0;
+const int SQLITE_SCHEMA_MINOR_VERSION = 1;
}
namespace isc {
@@ -63,19 +65,20 @@ enum StatementID {
DEL_ZONE_RECORDS = 6,
ADD_RECORD = 7,
DEL_RECORD = 8,
- ITERATE = 9,
- FIND_PREVIOUS = 10,
- ADD_RECORD_DIFF = 11,
- LOW_DIFF_ID = 12,
- HIGH_DIFF_ID = 13,
- DIFF_RECS = 14,
- NSEC3 = 15,
- NSEC3_PREVIOUS = 16,
- NSEC3_LAST = 17,
- ADD_NSEC3_RECORD = 18,
- DEL_ZONE_NSEC3_RECORDS = 19,
- DEL_NSEC3_RECORD = 20,
- NUM_STATEMENTS = 21
+ ITERATE_RECORDS = 9,
+ ITERATE_NSEC3 = 10,
+ FIND_PREVIOUS = 11,
+ ADD_RECORD_DIFF = 12,
+ LOW_DIFF_ID = 13,
+ HIGH_DIFF_ID = 14,
+ DIFF_RECS = 15,
+ NSEC3 = 16,
+ NSEC3_PREVIOUS = 17,
+ NSEC3_LAST = 18,
+ ADD_NSEC3_RECORD = 19,
+ DEL_ZONE_NSEC3_RECORDS = 20,
+ DEL_NSEC3_RECORD = 21,
+ NUM_STATEMENTS = 22
};
const char* const text_statements[NUM_STATEMENTS] = {
@@ -84,8 +87,13 @@ const char* const text_statements[NUM_STATEMENTS] = {
"SELECT id FROM zones WHERE name=?1 AND rdclass = ?2", // ZONE
"SELECT rdtype, ttl, sigtype, rdata FROM records " // ANY
"WHERE zone_id=?1 AND name=?2",
- "SELECT rdtype, ttl, sigtype, rdata " // ANY_SUB
- "FROM records WHERE zone_id=?1 AND name LIKE (\"%.\" || ?2)",
+
+ // ANY_SUB:
+ // This query returns records in the specified zone for the domain
+ // matching the passed name, and its sub-domains.
+ "SELECT rdtype, ttl, sigtype, rdata "
+ "FROM records WHERE zone_id=?1 AND rname LIKE ?2",
+
"BEGIN", // BEGIN
"COMMIT", // COMMIT
"ROLLBACK", // ROLLBACK
@@ -95,19 +103,17 @@ const char* const text_statements[NUM_STATEMENTS] = {
"VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
"DELETE FROM records WHERE zone_id=?1 AND name=?2 " // DEL_RECORD
"AND rdtype=?3 AND rdata=?4",
- // The following iterates the whole zone. As the NSEC3 records
- // (and corresponding RRSIGs) live in separate table, we need to
- // take both of them. As the RRSIGs are for NSEC3s in the other
- // table, we can easily hardcode the sigtype.
- //
- // The extra column is so we can order it by rname. This is to
- // preserve the previous order, mostly for tests.
- // TODO: Is it possible to get rid of the ordering?
- "SELECT rdtype, ttl, sigtype, rdata, name, rname FROM records " // ITERATE
- "WHERE zone_id = ?1 "
- "UNION "
- "SELECT rdtype, ttl, \"NSEC3\", rdata, owner, owner FROM nsec3 "
- "WHERE zone_id = ?1 ORDER by rname, rdtype",
+
+ // ITERATE_RECORDS:
+ // The following iterates the whole zone in the records table.
+ "SELECT rdtype, ttl, sigtype, rdata, name FROM records "
+ "WHERE zone_id = ?1 ORDER BY rname, rdtype",
+
+ // ITERATE_NSEC3:
+ // The following iterates the whole zone in the nsec3 table. As the
+ // RRSIGs are for NSEC3s, we can hardcode the sigtype.
+ "SELECT rdtype, ttl, \"NSEC3\", rdata, owner FROM nsec3 "
+ "WHERE zone_id = ?1 ORDER BY hash, rdtype",
/*
* This one looks for previous name with NSEC record. It is done by
* using the reversed name. The NSEC is checked because we need to
@@ -325,7 +331,7 @@ public:
const char* const SCHEMA_LIST[] = {
"CREATE TABLE schema_version (version INTEGER NOT NULL, "
"minor INTEGER NOT NULL DEFAULT 0)",
- "INSERT INTO schema_version VALUES (2, 0)",
+ "INSERT INTO schema_version VALUES (2, 1)",
"CREATE TABLE zones (id INTEGER PRIMARY KEY, "
"name TEXT NOT NULL COLLATE NOCASE, "
"rdclass TEXT NOT NULL COLLATE NOCASE DEFAULT 'IN', "
@@ -351,6 +357,7 @@ const char* const SCHEMA_LIST[] = {
"ttl INTEGER NOT NULL, rdtype TEXT NOT NULL COLLATE NOCASE, "
"rdata TEXT NOT NULL)",
"CREATE INDEX nsec3_byhash ON nsec3 (hash)",
+ "CREATE INDEX nsec3_byhash_and_rdtype ON nsec3 (hash, rdtype)",
"CREATE TABLE diffs (id INTEGER PRIMARY KEY, "
"zone_id INTEGER NOT NULL, "
"version INTEGER NOT NULL, "
@@ -635,11 +642,21 @@ public:
iterator_type_(ITT_ALL),
accessor_(accessor),
statement_(NULL),
+ statement2_(NULL),
+ rc_(SQLITE_OK),
+ rc2_(SQLITE_OK),
name_("")
{
- // We create the statement now and then just keep getting data from it
+ // We create the statements now and then just keep getting data
+ // from them.
statement_ = prepare(accessor->dbparameters_->db_,
- text_statements[ITERATE]);
+ text_statements[ITERATE_NSEC3]);
+ bindZoneId(id);
+
+ std::swap(statement_, statement2_);
+
+ statement_ = prepare(accessor->dbparameters_->db_,
+ text_statements[ITERATE_RECORDS]);
bindZoneId(id);
}
@@ -658,19 +675,32 @@ public:
iterator_type_(qtype == QT_NSEC3 ? ITT_NSEC3 : ITT_NAME),
accessor_(accessor),
statement_(NULL),
+ statement2_(NULL),
+ rc_(SQLITE_OK),
+ rc2_(SQLITE_OK),
name_(name)
{
- // Choose the statement text depending on the query type
- const char* statement(NULL);
+ // Choose the statement text depending on the query type, and
+ // prepare a statement to get data from it.
switch (qtype) {
case QT_ANY:
- statement = text_statements[ANY];
+ statement_ = prepare(accessor->dbparameters_->db_,
+ text_statements[ANY]);
+ bindZoneId(id);
+ bindName(name_);
break;
case QT_SUBDOMAINS:
- statement = text_statements[ANY_SUB];
+ statement_ = prepare(accessor->dbparameters_->db_,
+ text_statements[ANY_SUB]);
+ bindZoneId(id);
+ // Done once, this should not be very inefficient.
+ bindName(isc::dns::Name(name_).reverse().toText() + "%");
break;
case QT_NSEC3:
- statement = text_statements[NSEC3];
+ statement_ = prepare(accessor->dbparameters_->db_,
+ text_statements[NSEC3]);
+ bindZoneId(id);
+ bindName(name_);
break;
default:
// Can Not Happen - there isn't any other type of query
@@ -680,40 +710,41 @@ public:
"Invalid qtype passed - unreachable code branch "
"reached");
}
-
- // We create the statement now and then just keep getting data from it
- statement_ = prepare(accessor->dbparameters_->db_, statement);
- bindZoneId(id);
- bindName(name_);
}
bool getNext(std::string (&data)[COLUMN_COUNT]) {
// If there's another row, get it
// If finalize has been called (e.g. when previous getNext() got
// SQLITE_DONE), directly return false
- if (statement_ == NULL) {
- return false;
- }
- const int rc(sqlite3_step(statement_));
- if (rc == SQLITE_ROW) {
- // For both types, we copy the first four columns
- copyColumn(data, TYPE_COLUMN);
- copyColumn(data, TTL_COLUMN);
- // The NSEC3 lookup does not provide the SIGTYPE, it is not
- // necessary and not contained in the table.
- if (iterator_type_ != ITT_NSEC3) {
- copyColumn(data, SIGTYPE_COLUMN);
+ while (statement_ != NULL) {
+ rc_ = sqlite3_step(statement_);
+ if (rc_ == SQLITE_ROW) {
+ // For both types, we copy the first four columns
+ copyColumn(data, TYPE_COLUMN);
+ copyColumn(data, TTL_COLUMN);
+ // The NSEC3 lookup does not provide the SIGTYPE, it is not
+ // necessary and not contained in the table.
+ if (iterator_type_ != ITT_NSEC3) {
+ copyColumn(data, SIGTYPE_COLUMN);
+ }
+ copyColumn(data, RDATA_COLUMN);
+ // Only copy Name if we are iterating over every record
+ if (iterator_type_ == ITT_ALL) {
+ copyColumn(data, NAME_COLUMN);
+ }
+ return (true);
+ } else if (rc_ != SQLITE_DONE) {
+ isc_throw(DataSourceError,
+ "Unexpected failure in sqlite3_step: " <<
+ sqlite3_errmsg(accessor_->dbparameters_->db_));
}
- copyColumn(data, RDATA_COLUMN);
- // Only copy Name if we are iterating over every record
- if (iterator_type_ == ITT_ALL) {
- copyColumn(data, NAME_COLUMN);
+ // We are done with statement_. If statement2_ has not been
+ // used yet, try that one now.
+ if ((statement2_ == NULL) || (rc2_ != SQLITE_OK)) {
+ break;
}
- return (true);
- } else if (rc != SQLITE_DONE) {
- isc_throw(DataSourceError,
- "Unexpected failure in sqlite3_step: " <<
- sqlite3_errmsg(accessor_->dbparameters_->db_));
+ std::swap(statement_, statement2_);
+ std::swap(rc_, rc2_);
}
finalize();
return (false);
@@ -759,13 +790,22 @@ private:
}
void finalize() {
- sqlite3_finalize(statement_);
- statement_ = NULL;
+ if (statement_ != NULL) {
+ sqlite3_finalize(statement_);
+ statement_ = NULL;
+ }
+ if (statement2_ != NULL) {
+ sqlite3_finalize(statement2_);
+ statement2_ = NULL;
+ }
}
const IteratorType iterator_type_;
boost::shared_ptr<const SQLite3Accessor> accessor_;
sqlite3_stmt* statement_;
+ sqlite3_stmt* statement2_;
+ int rc_;
+ int rc2_;
const std::string name_;
};
diff --git a/src/lib/datasrc/sqlite3_accessor.h b/src/lib/datasrc/sqlite3_accessor.h
index 3e44d5b..a8112d4 100644
--- a/src/lib/datasrc/sqlite3_accessor.h
+++ b/src/lib/datasrc/sqlite3_accessor.h
@@ -13,8 +13,8 @@
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DATASRC_SQLITE3_ACCESSOR_H
-#define __DATASRC_SQLITE3_ACCESSOR_H
+#ifndef DATASRC_SQLITE3_ACCESSOR_H
+#define DATASRC_SQLITE3_ACCESSOR_H
#include <datasrc/database.h>
#include <datasrc/data_source.h>
@@ -291,7 +291,7 @@ extern "C" void destroyInstance(DataSourceClient* instance);
}
}
-#endif // __DATASRC_SQLITE3_CONNECTION_H
+#endif // DATASRC_SQLITE3_ACCESSOR_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/tests/client_list_unittest.cc b/src/lib/datasrc/tests/client_list_unittest.cc
index d995d5c..d1ff852 100644
--- a/src/lib/datasrc/tests/client_list_unittest.cc
+++ b/src/lib/datasrc/tests/client_list_unittest.cc
@@ -12,14 +12,14 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#include <util/memory_segment_local.h>
-
#include <datasrc/client_list.h>
#include <datasrc/client.h>
#include <datasrc/iterator.h>
#include <datasrc/data_source.h>
#include <datasrc/memory/memory_client.h>
+#include <datasrc/memory/zone_table_segment.h>
#include <datasrc/memory/zone_finder.h>
+#include <datasrc/memory/zone_writer.h>
#include <dns/rrclass.h>
#include <dns/rrttl.h>
@@ -27,15 +27,20 @@
#include <gtest/gtest.h>
+#include <boost/shared_ptr.hpp>
+
#include <set>
#include <fstream>
using namespace isc::datasrc;
using isc::datasrc::memory::InMemoryClient;
+using isc::datasrc::memory::ZoneTableSegment;
using isc::datasrc::memory::InMemoryZoneFinder;
using namespace isc::data;
using namespace isc::dns;
-using namespace boost;
+// don't import the entire boost namespace. It will unexpectedly hide uintXX_t
+// for some systems.
+using boost::shared_ptr;
using namespace std;
namespace {
@@ -255,7 +260,9 @@ public:
" \"type\": \"test_type\","
" \"params\": [\"example.org\", \"example.com\", "
" \"noiter.org\", \"null.org\"]"
- "}]"))
+ "}]")),
+ config_(Element::fromJSON("{}")),
+ ztable_segment_(ZoneTableSegment::create(*config_, rrclass_))
{
for (size_t i(0); i < ds_count; ++ i) {
shared_ptr<MockDataSourceClient>
@@ -263,7 +270,7 @@ public:
ds_.push_back(ds);
ds_info_.push_back(ConfigurableClientList::DataSourceInfo(
ds.get(), DataSourceClientContainerPtr(),
- false, rrclass_, mem_sgmt_));
+ false, rrclass_, ztable_segment_));
}
}
@@ -283,13 +290,14 @@ public:
// Create cache from the temporary data source, and push it to the
// client list.
- const shared_ptr<InMemoryClient> cache(new InMemoryClient(mem_sgmt_,
- rrclass_));
+ const shared_ptr<InMemoryClient> cache(
+ new InMemoryClient(ztable_segment_, rrclass_));
cache->load(zone, *mock_client.getIterator(zone, false));
ConfigurableClientList::DataSourceInfo& dsrc_info =
list_->getDataSources()[index];
dsrc_info.cache_ = cache;
+ dsrc_info.ztable_segment_ = ztable_segment_;
}
// Check the positive result is as we expect it.
void positiveResult(const ClientList::FindResult& result,
@@ -309,7 +317,7 @@ public:
result.life_keeper_);
if (from_cache) {
EXPECT_NE(shared_ptr<InMemoryZoneFinder>(),
- dynamic_pointer_cast<InMemoryZoneFinder>(
+ boost::dynamic_pointer_cast<InMemoryZoneFinder>(
result.finder_)) << "Finder is not from cache";
EXPECT_TRUE(NULL !=
dynamic_cast<InMemoryClient*>(result.dsrc_client_));
@@ -362,12 +370,12 @@ public:
shared_ptr<InMemoryClient>());
}
const RRClass rrclass_;
- isc::util::MemorySegmentLocal mem_sgmt_;
shared_ptr<TestedList> list_;
const ClientList::FindResult negative_result_;
vector<shared_ptr<MockDataSourceClient> > ds_;
vector<ConfigurableClientList::DataSourceInfo> ds_info_;
- const ConstElementPtr config_elem_, config_elem_zones_;
+ const ConstElementPtr config_elem_, config_elem_zones_, config_;
+ shared_ptr<ZoneTableSegment> ztable_segment_;
};
// Test the test itself
@@ -844,116 +852,169 @@ TEST_F(ListTest, BadMasterFile) {
true);
}
+// This allows us to test two versions of the reloading code
+// (One by calling reload(), one by obtaining a ZoneWriter and
+// playing with that). Once we deprecate reload(), we should revert this
+// change and not use typed tests any more.
+template<class UpdateType>
+class ReloadTest : public ListTest {
+public:
+ ConfigurableClientList::ReloadResult doReload(const Name& origin);
+};
+
+// Version with calling reload()
+class ReloadUpdateType {};
+template<>
+ConfigurableClientList::ReloadResult
+ReloadTest<ReloadUpdateType>::doReload(const Name& origin) {
+ return (list_->reload(origin));
+};
+
+// Version with the ZoneWriter
+class WriterUpdateType {};
+template<>
+ConfigurableClientList::ReloadResult
+ReloadTest<WriterUpdateType>::doReload(const Name& origin) {
+ ConfigurableClientList::ZoneWriterPair
+ result(list_->getCachedZoneWriter(origin));
+ if (result.first == ConfigurableClientList::ZONE_SUCCESS) {
+ // Can't use ASSERT_NE here, it would want to return(), which
+ // it can't in non-void function.
+ if (result.second) {
+ result.second->load();
+ result.second->install();
+ result.second->cleanup();
+ } else {
+ ADD_FAILURE() << "getCachedZoneWriter returned ZONE_SUCCESS, "
+ "but the writer is NULL";
+ }
+ } else {
+ EXPECT_EQ(static_cast<memory::ZoneWriter*>(NULL),
+ result.second.get());
+ }
+ return (result.first);
+}
+
+// Typedefs for the GTEST guts to make it work
+typedef ::testing::Types<ReloadUpdateType, WriterUpdateType> UpdateTypes;
+TYPED_TEST_CASE(ReloadTest, UpdateTypes);
+
// Test we can reload a zone
-TEST_F(ListTest, reloadSuccess) {
- list_->configure(config_elem_zones_, true);
+TYPED_TEST(ReloadTest, reloadSuccess) {
+ this->list_->configure(this->config_elem_zones_, true);
const Name name("example.org");
- prepareCache(0, name);
+ this->prepareCache(0, name);
// The cache currently contains a tweaked version of zone, which doesn't
// have apex NS. So the lookup should result in NXRRSET.
EXPECT_EQ(ZoneFinder::NXRRSET,
- list_->find(name).finder_->find(name, RRType::NS())->code);
+ this->list_->find(name).finder_->find(name, RRType::NS())->code);
// Now reload the full zone. It should be there now.
- EXPECT_EQ(ConfigurableClientList::ZONE_RELOADED, list_->reload(name));
+ EXPECT_EQ(ConfigurableClientList::ZONE_SUCCESS, this->doReload(name));
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::NS())->code);
+ this->list_->find(name).finder_->find(name, RRType::NS())->code);
}
// The cache is not enabled. The load should be rejected.
-TEST_F(ListTest, reloadNotEnabled) {
- list_->configure(config_elem_zones_, false);
+TYPED_TEST(ReloadTest, reloadNotEnabled) {
+ this->list_->configure(this->config_elem_zones_, false);
const Name name("example.org");
// We put the cache in even when not enabled. This won't confuse the thing.
- prepareCache(0, name);
+ this->prepareCache(0, name);
// See the reloadSuccess test. This should result in NXRRSET.
EXPECT_EQ(ZoneFinder::NXRRSET,
- list_->find(name).finder_->find(name, RRType::NS())->code);
+ this->list_->find(name).finder_->find(name, RRType::NS())->code);
// Now reload. It should reject it.
- EXPECT_EQ(ConfigurableClientList::CACHE_DISABLED, list_->reload(name));
+ EXPECT_EQ(ConfigurableClientList::CACHE_DISABLED, this->doReload(name));
// Nothing changed here
EXPECT_EQ(ZoneFinder::NXRRSET,
- list_->find(name).finder_->find(name, RRType::NS())->code);
+ this->list_->find(name).finder_->find(name, RRType::NS())->code);
}
// Test several cases when the zone does not exist
-TEST_F(ListTest, reloadNoSuchZone) {
- list_->configure(config_elem_zones_, true);
+TYPED_TEST(ReloadTest, reloadNoSuchZone) {
+ this->list_->configure(this->config_elem_zones_, true);
const Name name("example.org");
// We put the cache in even when not enabled. This won't confuse the
// reload method, as that one looks at the real state of things, not
// at the configuration.
- prepareCache(0, Name("example.com"));
+ this->prepareCache(0, Name("example.com"));
// Not in the data sources
EXPECT_EQ(ConfigurableClientList::ZONE_NOT_FOUND,
- list_->reload(Name("example.cz")));
+ this->doReload(Name("exmaple.cz")));
// Not cached
- EXPECT_EQ(ConfigurableClientList::ZONE_NOT_FOUND, list_->reload(name));
+ EXPECT_EQ(ConfigurableClientList::ZONE_NOT_FOUND, this->doReload(name));
// Partial match
EXPECT_EQ(ConfigurableClientList::ZONE_NOT_FOUND,
- list_->reload(Name("sub.example.com")));
+ this->doReload(Name("sub.example.com")));
// Nothing changed here - these zones don't exist
EXPECT_EQ(static_cast<isc::datasrc::DataSourceClient*>(NULL),
- list_->find(name).dsrc_client_);
+ this->list_->find(name).dsrc_client_);
EXPECT_EQ(static_cast<isc::datasrc::DataSourceClient*>(NULL),
- list_->find(Name("example.cz")).dsrc_client_);
+ this->list_->find(Name("example.cz")).dsrc_client_);
EXPECT_EQ(static_cast<isc::datasrc::DataSourceClient*>(NULL),
- list_->find(Name("sub.example.com"), true).dsrc_client_);
+ this->list_->find(Name("sub.example.com"), true).dsrc_client_);
// Not reloaded, so NS shouldn't be visible yet.
EXPECT_EQ(ZoneFinder::NXRRSET,
- list_->find(Name("example.com")).finder_->
+ this->list_->find(Name("example.com")).finder_->
find(Name("example.com"), RRType::NS())->code);
}
// Check we gracefuly throw an exception when a zone disappeared in
// the underlying data source when we want to reload it
-TEST_F(ListTest, reloadZoneGone) {
- list_->configure(config_elem_, true);
+TYPED_TEST(ReloadTest, reloadZoneGone) {
+ this->list_->configure(this->config_elem_, true);
const Name name("example.org");
// We put in a cache for non-existant zone. This emulates being loaded
// and then the zone disappearing. We prefill the cache, so we can check
// it.
- prepareCache(0, name);
+ this->prepareCache(0, name);
// The (cached) zone contains zone's SOA
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::SOA())->code);
+ this->list_->find(name).finder_->find(name,
+ RRType::SOA())->code);
// The zone is not there, so abort the reload.
- EXPECT_THROW(list_->reload(name), DataSourceError);
+ EXPECT_THROW(this->doReload(name), DataSourceError);
// The (cached) zone is not hurt.
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::SOA())->code);
+ this->list_->find(name).finder_->find(name,
+ RRType::SOA())->code);
}
// The underlying data source throws. Check we don't modify the state.
-TEST_F(ListTest, reloadZoneThrow) {
- list_->configure(config_elem_zones_, true);
+TYPED_TEST(ReloadTest, reloadZoneThrow) {
+ this->list_->configure(this->config_elem_zones_, true);
const Name name("noiter.org");
- prepareCache(0, name);
+ this->prepareCache(0, name);
// The zone contains stuff now
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::SOA())->code);
+ this->list_->find(name).finder_->find(name,
+ RRType::SOA())->code);
// The iterator throws, so abort the reload.
- EXPECT_THROW(list_->reload(name), isc::NotImplemented);
+ EXPECT_THROW(this->doReload(name), isc::NotImplemented);
// The zone is not hurt.
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::SOA())->code);
+ this->list_->find(name).finder_->find(name,
+ RRType::SOA())->code);
}
-TEST_F(ListTest, reloadNullIterator) {
- list_->configure(config_elem_zones_, true);
+TYPED_TEST(ReloadTest, reloadNullIterator) {
+ this->list_->configure(this->config_elem_zones_, true);
const Name name("null.org");
- prepareCache(0, name);
+ this->prepareCache(0, name);
// The zone contains stuff now
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::SOA())->code);
+ this->list_->find(name).finder_->find(name,
+ RRType::SOA())->code);
// The iterator throws, so abort the reload.
- EXPECT_THROW(list_->reload(name), isc::Unexpected);
+ EXPECT_THROW(this->doReload(name), isc::Unexpected);
// The zone is not hurt.
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(name).finder_->find(name, RRType::SOA())->code);
+ this->list_->find(name).finder_->find(name,
+ RRType::SOA())->code);
}
// Test we can reload the master files too (special-cased)
-TEST_F(ListTest, reloadMasterFile) {
+TYPED_TEST(ReloadTest, reloadMasterFile) {
const char* const install_cmd = INSTALL_PROG " -c " TEST_DATA_DIR
"/root.zone " TEST_DATA_BUILDDIR "/root.zone.copied";
if (system(install_cmd) != 0) {
@@ -971,21 +1032,21 @@ TEST_F(ListTest, reloadMasterFile) {
" \".\": \"" TEST_DATA_BUILDDIR "/root.zone.copied\""
" }"
"}]"));
- list_->configure(elem, true);
+ this->list_->configure(elem, true);
// Add a record that is not in the zone
EXPECT_EQ(ZoneFinder::NXDOMAIN,
- list_->find(Name(".")).finder_->find(Name("nosuchdomain"),
- RRType::TXT())->code);
+ this->list_->find(Name(".")).finder_->find(Name("nosuchdomain"),
+ RRType::TXT())->code);
ofstream f;
f.open(TEST_DATA_BUILDDIR "/root.zone.copied", ios::out | ios::app);
f << "nosuchdomain.\t\t3600\tIN\tTXT\ttest" << std::endl;
f.close();
// Do the reload.
- EXPECT_EQ(ConfigurableClientList::ZONE_RELOADED, list_->reload(Name(".")));
+ EXPECT_EQ(ConfigurableClientList::ZONE_SUCCESS, this->doReload(Name(".")));
// It is here now.
EXPECT_EQ(ZoneFinder::SUCCESS,
- list_->find(Name(".")).finder_->find(Name("nosuchdomain"),
- RRType::TXT())->code);
+ this->list_->find(Name(".")).finder_->find(Name("nosuchdomain"),
+ RRType::TXT())->code);
}
}
diff --git a/src/lib/datasrc/tests/memory/Makefile.am b/src/lib/datasrc/tests/memory/Makefile.am
index 00d5594..67e63b9 100644
--- a/src/lib/datasrc/tests/memory/Makefile.am
+++ b/src/lib/datasrc/tests/memory/Makefile.am
@@ -32,12 +32,16 @@ run_unittests_SOURCES += ../../tests/faked_nsec3.h ../../tests/faked_nsec3.cc
run_unittests_SOURCES += memory_segment_test.h
run_unittests_SOURCES += segment_object_holder_unittest.cc
run_unittests_SOURCES += memory_client_unittest.cc
+run_unittests_SOURCES += zone_table_segment_test.h
+run_unittests_SOURCES += zone_table_segment_unittest.cc
+run_unittests_SOURCES += zone_writer_unittest.cc
run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES)
run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
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/cc/libb10-cc.la
run_unittests_LDADD += $(top_builddir)/src/lib/util/unittests/libutil_unittests.la
run_unittests_LDADD += $(top_builddir)/src/lib/util/libb10-util.la
run_unittests_LDADD += $(top_builddir)/src/lib/testutils/libb10-testutils.la
diff --git a/src/lib/datasrc/tests/memory/domaintree_unittest.cc b/src/lib/datasrc/tests/memory/domaintree_unittest.cc
index cb16e02..45e256a 100644
--- a/src/lib/datasrc/tests/memory/domaintree_unittest.cc
+++ b/src/lib/datasrc/tests/memory/domaintree_unittest.cc
@@ -256,8 +256,8 @@ TEST_F(DomainTreeTest, subTreeRoot) {
// "g.h" is not a subtree root
EXPECT_EQ(TestDomainTree::EXACTMATCH,
- dtree_expose_empty_node.find(Name("g.h"), &dtnode));
- EXPECT_FALSE(dtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
+ dtree_expose_empty_node.find(Name("g.h"), &cdtnode));
+ EXPECT_FALSE(cdtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
// fission the node "g.h"
EXPECT_EQ(TestDomainTree::ALREADYEXISTS,
@@ -270,8 +270,8 @@ TEST_F(DomainTreeTest, subTreeRoot) {
// "g.h" should be a subtree root now.
EXPECT_EQ(TestDomainTree::EXACTMATCH,
- dtree_expose_empty_node.find(Name("g.h"), &dtnode));
- EXPECT_TRUE(dtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
+ dtree_expose_empty_node.find(Name("g.h"), &cdtnode));
+ EXPECT_TRUE(cdtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
}
TEST_F(DomainTreeTest, additionalNodeFission) {
@@ -286,8 +286,8 @@ TEST_F(DomainTreeTest, additionalNodeFission) {
// "t.0" is not a subtree root
EXPECT_EQ(TestDomainTree::EXACTMATCH,
- dtree_expose_empty_node.find(Name("t.0"), &dtnode));
- EXPECT_FALSE(dtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
+ dtree_expose_empty_node.find(Name("t.0"), &cdtnode));
+ EXPECT_FALSE(cdtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
// fission the node "t.0"
EXPECT_EQ(TestDomainTree::ALREADYEXISTS,
@@ -300,8 +300,8 @@ TEST_F(DomainTreeTest, additionalNodeFission) {
// "t.0" should be a subtree root now.
EXPECT_EQ(TestDomainTree::EXACTMATCH,
- dtree_expose_empty_node.find(Name("t.0"), &dtnode));
- EXPECT_TRUE(dtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
+ dtree_expose_empty_node.find(Name("t.0"), &cdtnode));
+ EXPECT_TRUE(cdtnode->getFlag(TestDomainTreeNode::FLAG_SUBTREE_ROOT));
}
TEST_F(DomainTreeTest, findName) {
@@ -328,10 +328,10 @@ TEST_F(DomainTreeTest, findName) {
EXPECT_EQ(TestDomainTree::PARTIALMATCH,
dtree_expose_empty_node.find(Name("m.d.e.f"), &cdtnode));
- // find dtnode
+ // find cdtnode
EXPECT_EQ(TestDomainTree::EXACTMATCH, dtree.find(Name("q.w.y.d.e.f"),
- &dtnode));
- EXPECT_EQ(Name("q"), dtnode->getName());
+ &cdtnode));
+ EXPECT_EQ(Name("q"), cdtnode->getName());
}
TEST_F(DomainTreeTest, findError) {
@@ -411,11 +411,12 @@ performCallbackTest(TestDomainTree& dtree,
Name("example"),
&parentdtnode));
// the child/parent nodes shouldn't "inherit" the callback flag.
- // "dtnode" may be invalid due to the insertion, so we need to re-find
- // it.
+ // "dtnode" should still validly point to "callback.example", but we
+ // explicitly confirm it.
EXPECT_EQ(TestDomainTree::EXACTMATCH, dtree.find(Name("callback.example"),
- &dtnode));
- EXPECT_TRUE(dtnode->getFlag(TestDomainTreeNode::FLAG_CALLBACK));
+ &cdtnode));
+ ASSERT_EQ(dtnode, cdtnode);
+ EXPECT_TRUE(cdtnode->getFlag(TestDomainTreeNode::FLAG_CALLBACK));
EXPECT_FALSE(subdtnode->getFlag(TestDomainTreeNode::FLAG_CALLBACK));
EXPECT_FALSE(parentdtnode->getFlag(TestDomainTreeNode::FLAG_CALLBACK));
diff --git a/src/lib/datasrc/tests/memory/memory_client_unittest.cc b/src/lib/datasrc/tests/memory/memory_client_unittest.cc
index 58979a4..c1d2f30 100644
--- a/src/lib/datasrc/tests/memory/memory_client_unittest.cc
+++ b/src/lib/datasrc/tests/memory/memory_client_unittest.cc
@@ -22,7 +22,6 @@
#include <dns/nsec3hash.h>
#include <dns/rdata.h>
#include <dns/rdataclass.h>
-#include <dns/rrsetlist.h>
#include <dns/rrttl.h>
#include <dns/masterload.h>
@@ -30,21 +29,30 @@
#include <datasrc/data_source.h>
#include <datasrc/memory/zone_data.h>
#include <datasrc/memory/zone_table.h>
+#include <datasrc/memory/zone_data_updater.h>
+#include <datasrc/memory/zone_data_loader.h>
#include <datasrc/memory/memory_client.h>
#include <testutils/dnsmessage_test.h>
#include "memory_segment_test.h"
+#include "zone_table_segment_test.h"
#include <gtest/gtest.h>
+#include <boost/lexical_cast.hpp>
+#include <boost/shared_ptr.hpp>
+
#include <new> // for bad_alloc
+using namespace isc::data;
using namespace isc::dns;
using namespace isc::dns::rdata;
using namespace isc::datasrc;
using namespace isc::datasrc::memory;
using namespace isc::testutils;
+using boost::shared_ptr;
+using std::vector;
namespace {
@@ -87,8 +95,7 @@ private:
MockIterator(const char** rrset_data_ptr, bool pass_empty_rrsig) :
rrset_data_ptr_(rrset_data_ptr),
pass_empty_rrsig_(pass_empty_rrsig)
- {
- }
+ {}
const char** rrset_data_ptr_;
// If true, emulate an unexpected bogus case where an RRSIG RRset is
@@ -124,23 +131,53 @@ public:
}
};
+class MockVectorIterator : public ZoneIterator {
+private:
+ MockVectorIterator(const vector<ConstRRsetPtr>& rrsets) :
+ rrsets_(rrsets),
+ counter_(0)
+ {}
+
+ const vector<ConstRRsetPtr> rrsets_;
+ int counter_;
+
+public:
+ virtual ConstRRsetPtr getNextRRset() {
+ if (counter_ >= rrsets_.size()) {
+ return (ConstRRsetPtr());
+ }
+
+ return (rrsets_[counter_++]);
+ }
+
+ virtual ConstRRsetPtr getSOA() const {
+ isc_throw(isc::NotImplemented, "Not implemented");
+ }
+
+ static ZoneIteratorPtr makeIterator(const vector<ConstRRsetPtr>& rrsets) {
+ return (ZoneIteratorPtr(new MockVectorIterator(rrsets)));
+ }
+};
+
class MemoryClientTest : public ::testing::Test {
protected:
MemoryClientTest() : zclass_(RRClass::IN()),
- client_(new InMemoryClient(mem_sgmt_, zclass_))
+ ztable_segment_(new test::ZoneTableSegmentTest(
+ zclass_, mem_sgmt_)),
+ client_(new InMemoryClient(ztable_segment_, zclass_))
{}
~MemoryClientTest() {
- if (client_ != NULL) {
- delete client_;
- }
+ delete client_;
}
void TearDown() {
delete client_;
client_ = NULL;
+ ztable_segment_.reset();
EXPECT_TRUE(mem_sgmt_.allMemoryDeallocated()); // catch any leak here.
}
const RRClass zclass_;
test::MemorySegmentTest mem_sgmt_;
+ shared_ptr<ZoneTableSegment> ztable_segment_;
InMemoryClient* client_;
};
@@ -188,7 +225,7 @@ TEST_F(MemoryClientTest, loadEmptyZoneFileThrows) {
EXPECT_THROW(client_->load(Name("."),
TEST_DATA_DIR "/empty.zone"),
- InMemoryClient::EmptyZone);
+ EmptyZone);
EXPECT_EQ(0, client_->getZoneCount());
@@ -242,13 +279,13 @@ TEST_F(MemoryClientTest, loadFromIterator) {
EXPECT_THROW(client_->load(Name("example.org"),
*MockIterator::makeIterator(
rrset_data_separated)),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Similar to the previous case, but with separated RRSIGs.
EXPECT_THROW(client_->load(Name("example.org"),
*MockIterator::makeIterator(
rrset_data_sigseparated)),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Emulating bogus iterator implementation that passes empty RRSIGs.
EXPECT_THROW(client_->load(Name("example.org"),
@@ -260,10 +297,22 @@ TEST_F(MemoryClientTest, loadMemoryAllocationFailures) {
// Just to check that things get cleaned up
for (int i = 1; i < 16; i++) {
+ SCOPED_TRACE("For throw count = " +
+ boost::lexical_cast<std::string>(i));
mem_sgmt_.setThrowCount(i);
- EXPECT_THROW(client_->load(Name("example.org"),
- TEST_DATA_DIR "/example.org.zone"),
- std::bad_alloc);
+ EXPECT_THROW({
+ shared_ptr<ZoneTableSegment> ztable_segment(
+ new test::ZoneTableSegmentTest(
+ zclass_, mem_sgmt_));
+
+ // Include the InMemoryClient construction too here. Now,
+ // even allocations done from InMemoryClient constructor
+ // fail (due to MemorySegmentTest throwing) and we check for
+ // leaks when this happens.
+ InMemoryClient client2(ztable_segment, zclass_);
+ client2.load(Name("example.org"),
+ TEST_DATA_DIR "/example.org.zone");
+ }, std::bad_alloc);
}
// Teardown checks for memory segment leaks
}
@@ -384,7 +433,7 @@ TEST_F(MemoryClientTest, loadDuplicateType) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-duplicate-type-bad.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -393,7 +442,7 @@ TEST_F(MemoryClientTest, loadMultipleCNAMEThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-multiple-cname.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -402,7 +451,7 @@ TEST_F(MemoryClientTest, loadMultipleDNAMEThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-multiple-dname.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -411,7 +460,7 @@ TEST_F(MemoryClientTest, loadMultipleNSEC3Throws) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-multiple-nsec3.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -420,7 +469,7 @@ TEST_F(MemoryClientTest, loadMultipleNSEC3PARAMThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-multiple-nsec3param.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -438,7 +487,7 @@ TEST_F(MemoryClientTest, loadWildcardNSThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-wildcard-ns.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -447,7 +496,7 @@ TEST_F(MemoryClientTest, loadWildcardDNAMEThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-wildcard-dname.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -456,7 +505,7 @@ TEST_F(MemoryClientTest, loadWildcardNSEC3Throws) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-wildcard-nsec3.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -465,7 +514,7 @@ TEST_F(MemoryClientTest, loadNSEC3WithFewerLabelsThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-nsec3-fewer-labels.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -474,7 +523,7 @@ TEST_F(MemoryClientTest, loadNSEC3WithMoreLabelsThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-nsec3-more-labels.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -483,12 +532,12 @@ TEST_F(MemoryClientTest, loadCNAMEAndNotNSECThrows) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-cname-and-not-nsec-1.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-cname-and-not-nsec-2.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -514,7 +563,7 @@ TEST_F(MemoryClientTest, loadDNAMEAndNSNonApex1) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-dname-ns-nonapex-1.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -523,7 +572,7 @@ TEST_F(MemoryClientTest, loadDNAMEAndNSNonApex2) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-dname-ns-nonapex-2.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -533,7 +582,7 @@ TEST_F(MemoryClientTest, loadRRSIGFollowsNothing) {
EXPECT_THROW(client_->load(Name("example.org"),
TEST_DATA_DIR
"/example.org-rrsig-follows-nothing.zone"),
- InMemoryClient::AddError);
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -544,25 +593,29 @@ TEST_F(MemoryClientTest, loadRRSIGs) {
}
TEST_F(MemoryClientTest, loadRRSIGsRdataMixedCoveredTypes) {
- client_->load(Name("example.org"),
- TEST_DATA_DIR "/example.org-rrsigs.zone");
-
- RRsetPtr rrset(new RRset(Name("example.org"),
- RRClass::IN(), RRType::A(), RRTTL(3600)));
- rrset->addRdata(in::A("192.0.2.1"));
- rrset->addRdata(in::A("192.0.2.2"));
-
- RRsetPtr rrsig(new RRset(Name("example.org"), zclass_,
- RRType::RRSIG(), RRTTL(300)));
- rrsig->addRdata(generic::RRSIG("A 5 3 3600 20000101000000 20000201000000 "
- "12345 example.org. FAKEFAKEFAKE"));
+ vector<ConstRRsetPtr> rrsets_vec;
+
+ rrsets_vec.push_back(textToRRset("example.org. 3600 IN SOA "
+ "ns1.example.org. bugs.x.w.example.org. "
+ "2010012601 3600 300 3600000 1200",
+ zclass_, Name("example.org")));
+ RRsetPtr rrset(textToRRset("example.org. 3600 IN A 192.0.2.1\n"
+ "example.org. 3600 IN A 192.0.2.2\n"));
+ RRsetPtr rrsig(textToRRset("example.org. 300 IN RRSIG "
+ "A 5 3 3600 20000101000000 20000201000000 "
+ "12345 example.org. FAKEFAKEFAKE"));
+ // textToRRset (correctly) consider this RDATA belongs to a different
+ // RRSIG, so we need to manually add it.
rrsig->addRdata(generic::RRSIG("NS 5 3 3600 20000101000000 20000201000000 "
"54321 example.org. FAKEFAKEFAKEFAKE"));
rrset->addRRsig(rrsig);
- EXPECT_THROW(client_->add(Name("example.org"), rrset),
- InMemoryClient::AddError);
+ rrsets_vec.push_back(rrset);
+ EXPECT_THROW(
+ client_->load(Name("example.org"),
+ *MockVectorIterator::makeIterator(rrsets_vec)),
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
@@ -655,75 +708,22 @@ TEST_F(MemoryClientTest, getIteratorGetSOAThrowsNotImplemented) {
EXPECT_THROW(iterator->getSOA(), isc::NotImplemented);
}
-TEST_F(MemoryClientTest, addRRsetToNonExistentZoneThrows) {
- // The zone "example.org" doesn't exist, so we can't add an RRset to
- // it.
- RRsetPtr rrset_a(new RRset(Name("example.org"), RRClass::IN(), RRType::A(),
- RRTTL(300)));
- rrset_a->addRdata(rdata::in::A("192.0.2.1"));
- EXPECT_THROW(client_->add(Name("example.org"), rrset_a), DataSourceError);
-}
-
-TEST_F(MemoryClientTest, addOutOfZoneThrows) {
- // Out of zone names should throw.
- client_->load(Name("example.org"),
- TEST_DATA_DIR "/example.org-empty.zone");
-
- RRsetPtr rrset_a(new RRset(Name("a.example.com"),
- RRClass::IN(), RRType::A(), RRTTL(300)));
- rrset_a->addRdata(rdata::in::A("192.0.2.1"));
-
- EXPECT_THROW(client_->add(Name("example.org"), rrset_a),
- OutOfZone);
- // Teardown checks for memory segment leaks
-}
-
-TEST_F(MemoryClientTest, addNullRRsetThrows) {
- client_->load(Name("example.org"),
- TEST_DATA_DIR "/example.org-rrsigs.zone");
-
- EXPECT_THROW(client_->add(Name("example.org"), ConstRRsetPtr()),
- InMemoryClient::NullRRset);
-
- // Teardown checks for memory segment leaks
-}
-
TEST_F(MemoryClientTest, addEmptyRRsetThrows) {
- client_->load(Name("example.org"),
- TEST_DATA_DIR "/example.org-rrsigs.zone");
-
- RRsetPtr rrset_a(new RRset(Name("example.org"), RRClass::IN(), RRType::A(),
- RRTTL(300)));
- EXPECT_THROW(client_->add(Name("example.org"), rrset_a),
- InMemoryClient::AddError);
-
+ vector<ConstRRsetPtr> rrsets_vec;
+ rrsets_vec.push_back(textToRRset("example.org. 3600 IN SOA "
+ "ns1.example.org. bugs.x.w.example.org. "
+ "2010012601 3600 300 3600000 1200",
+ zclass_, Name("example.org")));
+ rrsets_vec.push_back(RRsetPtr(new RRset(Name("example.org"), zclass_,
+ RRType::A(), RRTTL(3600))));
+
+ EXPECT_THROW(
+ client_->load(Name("example.org"),
+ *MockVectorIterator::makeIterator(rrsets_vec)),
+ ZoneDataUpdater::AddError);
// Teardown checks for memory segment leaks
}
-TEST_F(MemoryClientTest, add) {
- client_->load(Name("example.org"), TEST_DATA_DIR "/example.org-empty.zone");
-
- // Add another RRset
- RRsetPtr rrset_a(new RRset(Name("example.org"), RRClass::IN(), RRType::A(),
- RRTTL(300)));
- rrset_a->addRdata(rdata::in::A("192.0.2.1"));
- client_->add(Name("example.org"), rrset_a);
-
- ZoneIteratorPtr iterator(client_->getIterator(Name("example.org")));
-
- // First we have the SOA
- ConstRRsetPtr rrset(iterator->getNextRRset());
- EXPECT_TRUE(rrset);
- EXPECT_EQ(RRType::A(), rrset->getType());
-
- rrset = iterator->getNextRRset();
- EXPECT_TRUE(rrset);
- EXPECT_EQ(RRType::SOA(), rrset->getType());
-
- // There's nothing else in this zone
- EXPECT_EQ(ConstRRsetPtr(), iterator->getNextRRset());
-}
-
TEST_F(MemoryClientTest, findZoneData) {
client_->load(Name("example.org"),
TEST_DATA_DIR "/example.org-rrsigs.zone");
@@ -774,4 +774,5 @@ TEST_F(MemoryClientTest, getJournalReaderNotImplemented) {
EXPECT_THROW(client_->getJournalReader(Name("."), 0, 0),
isc::NotImplemented);
}
+
}
diff --git a/src/lib/datasrc/tests/memory/zone_data_unittest.cc b/src/lib/datasrc/tests/memory/zone_data_unittest.cc
index d15fe8b..3c28cec 100644
--- a/src/lib/datasrc/tests/memory/zone_data_unittest.cc
+++ b/src/lib/datasrc/tests/memory/zone_data_unittest.cc
@@ -108,7 +108,7 @@ void
checkFindRdataSet(const ZoneTree& tree, const Name& name, RRType type,
const RdataSet* expected_set)
{
- ZoneNode* node = NULL;
+ const ZoneNode* node = NULL;
tree.find(name, &node);
ASSERT_NE(static_cast<ZoneNode*>(NULL), node);
EXPECT_EQ(expected_set, RdataSet::find(node->getData(), type));
diff --git a/src/lib/datasrc/tests/memory/zone_finder_unittest.cc b/src/lib/datasrc/tests/memory/zone_finder_unittest.cc
index 494f19d..4cd08c0 100644
--- a/src/lib/datasrc/tests/memory/zone_finder_unittest.cc
+++ b/src/lib/datasrc/tests/memory/zone_finder_unittest.cc
@@ -23,6 +23,7 @@
#include "../../tests/faked_nsec3.h"
#include <datasrc/memory/zone_finder.h>
+#include <datasrc/memory/zone_data_updater.h>
#include <datasrc/memory/rdata_serialization.h>
#include <datasrc/data_source.h>
#include <testutils/dnsmessage_test.h>
@@ -105,7 +106,8 @@ public:
class_(RRClass::IN()),
origin_("example.org"),
zone_data_(ZoneData::create(mem_sgmt_, origin_)),
- zone_finder_(*zone_data_, class_)
+ zone_finder_(*zone_data_, class_),
+ updater_(mem_sgmt_, class_, origin_, *zone_data_)
{
// Build test RRsets. Below, we construct an RRset for
// each textual RR(s) of zone_data, and assign it to the corresponding
@@ -190,130 +192,8 @@ public:
ZoneData::destroy(mem_sgmt_, zone_data_, RRClass::IN());
}
- // NSEC3-specific call for 'loading' data
- void addZoneDataNSEC3(const ConstRRsetPtr rrset) {
- assert(rrset->getType() == RRType::NSEC3());
-
- const generic::NSEC3& nsec3_rdata =
- dynamic_cast<const generic::NSEC3&>(
- rrset->getRdataIterator()->getCurrent());
-
- NSEC3Data* nsec3_data = zone_data_->getNSEC3Data();
- if (nsec3_data == NULL) {
- nsec3_data = NSEC3Data::create(mem_sgmt_, nsec3_rdata);
- zone_data_->setNSEC3Data(nsec3_data);
- } else {
- const size_t salt_len = nsec3_data->getSaltLen();
- const uint8_t* salt_data = nsec3_data->getSaltData();
- const vector<uint8_t>& salt_data_2 = nsec3_rdata.getSalt();
-
- if ((nsec3_rdata.getHashalg() != nsec3_data->hashalg) ||
- (nsec3_rdata.getIterations() != nsec3_data->iterations) ||
- (salt_data_2.size() != salt_len)) {
- isc_throw(isc::Unexpected,
- "NSEC3 with inconsistent parameters: " <<
- rrset->toText());
- }
-
- if ((salt_len > 0) &&
- (std::memcmp(&salt_data_2[0], salt_data, salt_len) != 0)) {
- isc_throw(isc::Unexpected,
- "NSEC3 with inconsistent parameters: " <<
- rrset->toText());
- }
- }
-
- ZoneNode* node;
- nsec3_data->insertName(mem_sgmt_, rrset->getName(), &node);
-
- RdataSet* rdset = RdataSet::create(mem_sgmt_, encoder_,
- rrset, ConstRRsetPtr());
- RdataSet* old_rdset = node->setData(rdset);
- if (old_rdset != NULL) {
- RdataSet::destroy(mem_sgmt_, class_, old_rdset);
- }
- zone_data_->setSigned(true);
- }
-
- // simplified version of 'loading' data
- void addZoneData(const ConstRRsetPtr rrset) {
- ZoneNode* node = NULL;
-
- if (rrset->getType() == RRType::NSEC3()) {
- return (addZoneDataNSEC3(rrset));
- } else if (rrset->getType() == RRType::NSEC()) {
- zone_data_->setSigned(true);
- }
-
- zone_data_->insertName(mem_sgmt_, rrset->getName(), &node);
-
- if (rrset->getType() == RRType::NS() &&
- rrset->getName() != zone_data_->getOriginNode()->getName()) {
- node->setFlag(DomainTreeNode<RdataSet>::FLAG_CALLBACK);
- } else if (rrset->getType() == RRType::DNAME()) {
- node->setFlag(DomainTreeNode<RdataSet>::FLAG_CALLBACK);
- }
-
- RdataSet* next_rds = node->getData();
- RdataSet* rdataset =
- RdataSet::create(mem_sgmt_, encoder_, rrset, rrset->getRRsig());
- rdataset->next = next_rds;
- node->setData(rdataset);
-
- // find wildcard nodes in name (go through all of them in case there
- // is a nonterminal one)
- // Note that this method is pretty much equal to the 'real' loader;
- // but less efficient
- Name name(rrset->getName());
- while (name.getLabelCount() > 1) {
- if (name.isWildcard()) {
- ZoneNode* wnode = NULL;
- // add Wild node
- zone_data_->insertName(mem_sgmt_, name.split(1), &wnode);
- wnode->setFlag(ZoneData::WILDCARD_NODE);
- // add wildcard name itself too
- zone_data_->insertName(mem_sgmt_, name, &wnode);
- }
- name = name.split(1);
- }
-
- // If we've added NSEC3PARAM at zone origin, set up NSEC3
- // specific data or check consistency with already set up
- // parameters.
- if (rrset->getType() == RRType::NSEC3PARAM() &&
- rrset->getName() == origin_) {
- // We know rrset has exactly one RDATA
- const generic::NSEC3PARAM& param =
- dynamic_cast<const generic::NSEC3PARAM&>
- (rrset->getRdataIterator()->getCurrent());
-
- NSEC3Data* nsec3_data = zone_data_->getNSEC3Data();
- if (nsec3_data == NULL) {
- nsec3_data = NSEC3Data::create(mem_sgmt_, param);
- zone_data_->setNSEC3Data(nsec3_data);
- zone_data_->setSigned(true);
- } else {
- size_t salt_len = nsec3_data->getSaltLen();
- const uint8_t* salt_data = nsec3_data->getSaltData();
- const vector<uint8_t>& salt_data_2 = param.getSalt();
-
- if ((param.getHashalg() != nsec3_data->hashalg) ||
- (param.getIterations() != nsec3_data->iterations) ||
- (salt_data_2.size() != salt_len)) {
- isc_throw(isc::Unexpected,
- "NSEC3PARAM with inconsistent parameters: "
- << rrset->toText());
- }
-
- if ((salt_len > 0) &&
- (std::memcmp(&salt_data_2[0],
- salt_data, salt_len) != 0)) {
- isc_throw(isc::Unexpected,
- "NSEC3PARAM with inconsistent parameters: "
- << rrset->toText());
- }
- }
- }
+ void addToZoneData(const ConstRRsetPtr rrset) {
+ updater_.add(rrset, rrset->getRRsig());
}
// Some data to test with
@@ -323,7 +203,7 @@ public:
MemorySegmentTest mem_sgmt_;
memory::ZoneData* zone_data_;
memory::InMemoryZoneFinder zone_finder_;
- isc::datasrc::memory::RdataEncoder encoder_;
+ ZoneDataUpdater updater_;
// Placeholder for storing RRsets to be checked with rrsetsCheck()
vector<ConstRRsetPtr> actual_rrsets_;
@@ -538,7 +418,7 @@ TEST_F(InMemoryZoneFinderTest, constructor) {
TEST_F(InMemoryZoneFinderTest, findCNAME) {
// install CNAME RR
- addZoneData(rr_cname_);
+ addToZoneData(rr_cname_);
// Find A RR of the same. Should match the CNAME
findTest(rr_cname_->getName(), RRType::NS(), ZoneFinder::CNAME, true,
@@ -553,10 +433,10 @@ TEST_F(InMemoryZoneFinderTest, findCNAMEUnderZoneCut) {
// There's nothing special when we find a CNAME under a zone cut
// (with FIND_GLUE_OK). The behavior is different from BIND 9,
// so we test this case explicitly.
- addZoneData(rr_child_ns_);
+ addToZoneData(rr_child_ns_);
ConstRRsetPtr rr_cname_under_cut_ = textToRRset(
"cname.child.example.org. 300 IN CNAME target.child.example.org.");
- addZoneData(rr_cname_under_cut_);
+ addToZoneData(rr_cname_under_cut_);
findTest(Name("cname.child.example.org"), RRType::AAAA(),
ZoneFinder::CNAME, true, rr_cname_under_cut_,
ZoneFinder::RESULT_DEFAULT, NULL, ZoneFinder::FIND_GLUE_OK);
@@ -564,7 +444,7 @@ TEST_F(InMemoryZoneFinderTest, findCNAMEUnderZoneCut) {
// Search under a DNAME record. It should return the DNAME
TEST_F(InMemoryZoneFinderTest, findBelowDNAME) {
- EXPECT_NO_THROW(addZoneData(rr_dname_));
+ EXPECT_NO_THROW(addToZoneData(rr_dname_));
findTest(Name("below.dname.example.org"), RRType::A(), ZoneFinder::DNAME,
true, rr_dname_);
}
@@ -572,8 +452,8 @@ TEST_F(InMemoryZoneFinderTest, findBelowDNAME) {
// Search at the domain with DNAME. It should act as DNAME isn't there, DNAME
// influences only the data below (see RFC 2672, section 3)
TEST_F(InMemoryZoneFinderTest, findAtDNAME) {
- EXPECT_NO_THROW(addZoneData(rr_dname_));
- EXPECT_NO_THROW(addZoneData(rr_dname_a_));
+ EXPECT_NO_THROW(addToZoneData(rr_dname_));
+ EXPECT_NO_THROW(addToZoneData(rr_dname_a_));
const Name dname_name(rr_dname_->getName());
findTest(dname_name, RRType::A(), ZoneFinder::SUCCESS, true, rr_dname_a_);
@@ -585,8 +465,8 @@ TEST_F(InMemoryZoneFinderTest, findAtDNAME) {
// Try searching something that is both under NS and DNAME, without and with
// GLUE_OK mode (it should stop at the NS and DNAME respectively).
TEST_F(InMemoryZoneFinderTest, DNAMEUnderNS) {
- addZoneData(rr_child_ns_);
- addZoneData(rr_child_dname_);
+ addToZoneData(rr_child_ns_);
+ addToZoneData(rr_child_dname_);
Name lowName("below.dname.child.example.org.");
@@ -598,10 +478,10 @@ TEST_F(InMemoryZoneFinderTest, DNAMEUnderNS) {
// Test adding child zones and zone cut handling
TEST_F(InMemoryZoneFinderTest, delegationNS) {
// add in-zone data
- EXPECT_NO_THROW(addZoneData(rr_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_));
// install a zone cut
- EXPECT_NO_THROW(addZoneData(rr_child_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_child_ns_));
// below the zone cut
findTest(Name("www.child.example.org"), RRType::A(),
@@ -618,7 +498,7 @@ TEST_F(InMemoryZoneFinderTest, delegationNS) {
findTest(origin_, RRType::NS(), ZoneFinder::SUCCESS, true, rr_ns_);
// unusual case of "nested delegation": the highest cut should be used.
- EXPECT_NO_THROW(addZoneData(rr_grandchild_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_grandchild_ns_));
findTest(Name("www.grand.child.example.org"), RRType::A(),
// note: !rr_grandchild_ns_
ZoneFinder::DELEGATION, true, rr_child_ns_);
@@ -627,9 +507,9 @@ TEST_F(InMemoryZoneFinderTest, delegationNS) {
TEST_F(InMemoryZoneFinderTest, delegationWithDS) {
// Similar setup to the previous one, but with DS RR at the delegation
// point.
- addZoneData(rr_ns_);
- addZoneData(rr_child_ns_);
- addZoneData(rr_child_ds_);
+ addToZoneData(rr_ns_);
+ addToZoneData(rr_child_ns_);
+ addToZoneData(rr_child_ds_);
// Normal types of query should result in delegation, but DS query
// should be considered in-zone (but only exactly at the delegation point).
@@ -647,9 +527,9 @@ TEST_F(InMemoryZoneFinderTest, delegationWithDS) {
}
TEST_F(InMemoryZoneFinderTest, findAny) {
- EXPECT_NO_THROW(addZoneData(rr_a_));
- EXPECT_NO_THROW(addZoneData(rr_ns_));
- EXPECT_NO_THROW(addZoneData(rr_child_glue_));
+ EXPECT_NO_THROW(addToZoneData(rr_a_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_child_glue_));
vector<ConstRRsetPtr> expected_sets;
@@ -668,7 +548,7 @@ TEST_F(InMemoryZoneFinderTest, findAny) {
findAllTest(rr_child_glue_->getName(), ZoneFinder::SUCCESS, expected_sets);
// add zone cut
- EXPECT_NO_THROW(addZoneData(rr_child_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_child_ns_));
// zone cut
findAllTest(rr_child_ns_->getName(), ZoneFinder::DELEGATION,
@@ -684,16 +564,16 @@ TEST_F(InMemoryZoneFinderTest, findAny) {
TEST_F(InMemoryZoneFinderTest, glue) {
// install zone data:
// a zone cut
- EXPECT_NO_THROW(addZoneData(rr_child_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_child_ns_));
// glue for this cut
- EXPECT_NO_THROW(addZoneData(rr_child_glue_));
+ EXPECT_NO_THROW(addToZoneData(rr_child_glue_));
// a nested zone cut (unusual)
- EXPECT_NO_THROW(addZoneData(rr_grandchild_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_grandchild_ns_));
// glue under the deeper zone cut
- EXPECT_NO_THROW(addZoneData(rr_grandchild_glue_));
+ EXPECT_NO_THROW(addToZoneData(rr_grandchild_glue_));
// glue 'at the' zone cut
- EXPECT_NO_THROW(addZoneData(rr_ns_a_));
- EXPECT_NO_THROW(addZoneData(rr_ns_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_a_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_ns_));
// by default glue is hidden due to the zone cut
findTest(rr_child_glue_->getName(), RRType::A(), ZoneFinder::DELEGATION,
@@ -749,16 +629,16 @@ InMemoryZoneFinderTest::findCheck(ZoneFinder::FindResultFlags expected_flags,
rr_a_->addRRsig(createRdata(RRType::RRSIG(), RRClass::IN(),
"A 5 3 3600 20120814220826 20120715220826 "
"1234 example.com. FAKE"));
- EXPECT_NO_THROW(addZoneData(rr_ns_));
- EXPECT_NO_THROW(addZoneData(rr_ns_a_));
- EXPECT_NO_THROW(addZoneData(rr_ns_aaaa_));
- EXPECT_NO_THROW(addZoneData(rr_a_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_a_));
+ EXPECT_NO_THROW(addToZoneData(rr_ns_aaaa_));
+ EXPECT_NO_THROW(addToZoneData(rr_a_));
if ((expected_flags & ZoneFinder::RESULT_NSEC3_SIGNED) != 0) {
- addZoneData(rr_nsec3_);
+ addToZoneData(rr_nsec3_);
zone_data_->setSigned(true);
}
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_nsec_);
+ addToZoneData(rr_nsec_);
zone_data_->setSigned(true);
}
@@ -805,7 +685,7 @@ InMemoryZoneFinderTest::findCheck(ZoneFinder::FindResultFlags expected_flags,
expected_nsec, expected_flags, NULL, find_options);
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_ns_nsec_);
+ addToZoneData(rr_ns_nsec_);
zone_data_->setSigned(true);
if ((find_options & ZoneFinder::FIND_DNSSEC) != 0) {
expected_nsec = rr_ns_nsec_;
@@ -841,8 +721,8 @@ InMemoryZoneFinderTest::findNSECENTCheck(const Name& ent_name,
ConstRRsetPtr expected_nsec,
ZoneFinder::FindResultFlags expected_flags)
{
- addZoneData(rr_emptywild_);
- addZoneData(rr_under_wild_);
+ addToZoneData(rr_emptywild_);
+ addToZoneData(rr_under_wild_);
// Sanity check: Should result in NXRRSET
findTest(ent_name, RRType::A(), ZoneFinder::NXRRSET, true,
@@ -854,10 +734,10 @@ InMemoryZoneFinderTest::findNSECENTCheck(const Name& ent_name,
// Now add the NSEC rrs making it a 'complete' zone (in terms of NSEC,
// there are no sigs)
- addZoneData(rr_nsec_);
- addZoneData(rr_ent_nsec2_);
- addZoneData(rr_ent_nsec3_);
- addZoneData(rr_ent_nsec4_);
+ addToZoneData(rr_nsec_);
+ addToZoneData(rr_ent_nsec2_);
+ addToZoneData(rr_ent_nsec3_);
+ addToZoneData(rr_ent_nsec4_);
zone_data_->setSigned(true);
// Should result in NXRRSET, and RESULT_NSEC_SIGNED
@@ -897,7 +777,7 @@ InMemoryZoneFinderTest::emptyNodeCheck(
ZoneFinder::FindResultFlags expected_flags)
{
/*
- * The backend RBTree for this test should look like as follows:
+ * The backend ZoneTree for this test should look like as follows:
* example.org
* |
* baz (empty; easy case)
@@ -915,14 +795,14 @@ InMemoryZoneFinderTest::emptyNodeCheck(
for (int i = 0; names[i] != NULL; ++i) {
ConstRRsetPtr rrset = textToRRset(string(names[i]) +
" 300 IN A 192.0.2.1");
- addZoneData(rrset);
+ addToZoneData(rrset);
}
if ((expected_flags & ZoneFinder::RESULT_NSEC3_SIGNED) != 0) {
- addZoneData(rr_nsec3_);
+ addToZoneData(rr_nsec3_);
zone_data_->setSigned(true);
}
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_nsec_);
+ addToZoneData(rr_nsec_);
zone_data_->setSigned(true);
}
@@ -989,15 +869,15 @@ InMemoryZoneFinderTest::wildcardCheck(
"RRSIG CNAME " +
string(rrsig_common)));
}
- addZoneData(rr_wild_);
- addZoneData(rr_cnamewild_);
+ addToZoneData(rr_wild_);
+ addToZoneData(rr_cnamewild_);
// If the zone is expected to be "signed" with NSEC3, add an NSEC3.
// (the content of the NSEC3 shouldn't matter)
if ((expected_flags & ZoneFinder::RESULT_NSEC3_SIGNED) != 0) {
- addZoneData(rr_nsec3_);
+ addToZoneData(rr_nsec3_);
}
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_nsec_);
+ addToZoneData(rr_nsec_);
}
// Search at the parent. The parent will not have the A, but it will
@@ -1073,7 +953,7 @@ InMemoryZoneFinderTest::wildcardCheck(
wild_expected_flags, NULL, find_options, wild_ok);
}
- addZoneData(rr_under_wild_);
+ addToZoneData(rr_under_wild_);
{
SCOPED_TRACE("Search under non-wildcard");
findTest(Name("bar.foo.wild.example.org"), RRType::A(),
@@ -1090,7 +970,7 @@ InMemoryZoneFinderTest::wildcardCheck(
// NO_WILDCARD effect itself can be checked by the result code (NXDOMAIN).
ConstRRsetPtr expected_wild_nsec; // by default it's NULL
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_wild_nsec_);
+ addToZoneData(rr_wild_nsec_);
expected_wild_nsec = rr_wild_nsec_;
}
{
@@ -1127,8 +1007,8 @@ TEST_F(InMemoryZoneFinderTest, wildcardDisabledWithoutNSEC) {
* the wildcard defaults."
*/
TEST_F(InMemoryZoneFinderTest, delegatedWildcard) {
- addZoneData(rr_child_wild_);
- addZoneData(rr_child_ns_);
+ addToZoneData(rr_child_wild_);
+ addToZoneData(rr_child_ns_);
{
SCOPED_TRACE("Looking under delegation point");
@@ -1149,12 +1029,12 @@ void
InMemoryZoneFinderTest::anyWildcardCheck(
ZoneFinder::FindResultFlags expected_flags)
{
- addZoneData(rr_wild_);
+ addToZoneData(rr_wild_);
if ((expected_flags & ZoneFinder::RESULT_NSEC3_SIGNED) != 0) {
- addZoneData(rr_nsec3_);
+ addToZoneData(rr_nsec3_);
}
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_nsec_);
+ addToZoneData(rr_nsec_);
}
vector<ConstRRsetPtr> expected_sets;
@@ -1206,12 +1086,12 @@ InMemoryZoneFinderTest::emptyWildcardCheck(
* *
* wild
*/
- addZoneData(rr_emptywild_);
+ addToZoneData(rr_emptywild_);
if ((expected_flags & ZoneFinder::RESULT_NSEC3_SIGNED) != 0) {
- addZoneData(rr_nsec3_);
+ addToZoneData(rr_nsec3_);
}
if ((expected_flags & ZoneFinder::RESULT_NSEC_SIGNED) != 0) {
- addZoneData(rr_nsec_);
+ addToZoneData(rr_nsec_);
}
{
@@ -1263,7 +1143,7 @@ TEST_F(InMemoryZoneFinderTest, emptyWildcardNSEC) {
// Same as emptyWildcard, but with multiple * in the path.
TEST_F(InMemoryZoneFinderTest, nestedEmptyWildcard) {
- addZoneData(rr_nested_emptywild_);
+ addToZoneData(rr_nested_emptywild_);
{
SCOPED_TRACE("Asking for the original record under wildcards");
@@ -1394,8 +1274,8 @@ InMemoryZoneFinderTest::doCancelWildcardCheck(
* shouldn't be canceled isn't.
*/
TEST_F(InMemoryZoneFinderTest, cancelWildcard) {
- addZoneData(rr_wild_);
- addZoneData(rr_not_wild_);
+ addToZoneData(rr_wild_);
+ addToZoneData(rr_not_wild_);
{
SCOPED_TRACE("Runnig with single entry under foo.wild.example.org");
@@ -1405,7 +1285,7 @@ TEST_F(InMemoryZoneFinderTest, cancelWildcard) {
// Try putting another one under foo.wild....
// The result should be the same but it will be done in another way in the
// code, because the foo.wild.example.org will exist in the tree.
- addZoneData(rr_not_wild_another_);
+ addToZoneData(rr_not_wild_another_);
{
SCOPED_TRACE("Runnig with two entries under foo.wild.example.org");
doCancelWildcardCheck();
@@ -1414,15 +1294,15 @@ TEST_F(InMemoryZoneFinderTest, cancelWildcard) {
// Same tests as cancelWildcard for NSEC3-signed zone
TEST_F(InMemoryZoneFinderTest, cancelWildcardNSEC3) {
- addZoneData(rr_wild_);
- addZoneData(rr_not_wild_);
- addZoneData(rr_nsec3_);
+ addToZoneData(rr_wild_);
+ addToZoneData(rr_not_wild_);
+ addToZoneData(rr_nsec3_);
{
SCOPED_TRACE("Runnig with single entry under foo.wild.example.org");
doCancelWildcardCheck(ZoneFinder::RESULT_NSEC3_SIGNED);
}
- addZoneData(rr_not_wild_another_);
+ addToZoneData(rr_not_wild_another_);
{
SCOPED_TRACE("Runnig with two entries under foo.wild.example.org");
doCancelWildcardCheck(ZoneFinder::RESULT_NSEC3_SIGNED);
@@ -1433,9 +1313,9 @@ TEST_F(InMemoryZoneFinderTest, cancelWildcardNSEC3) {
// or without FIND_DNSSEC option. NSEC should be returned only when the option
// is given.
TEST_F(InMemoryZoneFinderTest, cancelWildcardNSEC) {
- addZoneData(rr_wild_);
- addZoneData(rr_not_wild_);
- addZoneData(rr_nsec_);
+ addToZoneData(rr_wild_);
+ addToZoneData(rr_not_wild_);
+ addToZoneData(rr_nsec_);
{
SCOPED_TRACE("Runnig with single entry under foo.wild.example.org");
@@ -1443,7 +1323,7 @@ TEST_F(InMemoryZoneFinderTest, cancelWildcardNSEC) {
ZoneFinder::FIND_DNSSEC);
doCancelWildcardCheck(ZoneFinder::RESULT_NSEC_SIGNED);
}
- addZoneData(rr_not_wild_another_);
+ addToZoneData(rr_not_wild_another_);
{
SCOPED_TRACE("Runnig with two entries under foo.wild.example.org");
doCancelWildcardCheck(ZoneFinder::RESULT_NSEC_SIGNED,
@@ -1464,7 +1344,7 @@ TEST_F(InMemoryZoneFinderTest, findNSEC3ForBadZone) {
DataSourceError);
// Only having NSEC3PARAM isn't enough
- addZoneData(textToRRset("example.org. 300 IN NSEC3PARAM "
+ addToZoneData(textToRRset("example.org. 300 IN NSEC3PARAM "
"1 0 12 aabbccdd"));
EXPECT_THROW(zone_finder_.findNSEC3(Name("www.example.org"), true),
DataSourceError);
@@ -1473,7 +1353,7 @@ TEST_F(InMemoryZoneFinderTest, findNSEC3ForBadZone) {
// is guaranteed.
const string ns1_nsec3_text = string(ns1_hash) + ".example.org." +
string(nsec3_common);
- addZoneData(textToRRset(ns1_nsec3_text));
+ addToZoneData(textToRRset(ns1_nsec3_text));
EXPECT_THROW(zone_finder_.findNSEC3(Name("www.example.org"), true),
DataSourceError);
}
@@ -1492,16 +1372,16 @@ public:
// zzz.example.org: hash=R5..
const string apex_nsec3_text = string(apex_hash) + ".example.org." +
string(nsec3_common);
- addZoneData(textToRRset(apex_nsec3_text));
+ addToZoneData(textToRRset(apex_nsec3_text));
const string ns1_nsec3_text = string(ns1_hash) + ".example.org." +
string(nsec3_common);
- addZoneData(textToRRset(ns1_nsec3_text));
+ addToZoneData(textToRRset(ns1_nsec3_text));
const string w_nsec3_text = string(w_hash) + ".example.org." +
string(nsec3_common);
- addZoneData(textToRRset(w_nsec3_text));
+ addToZoneData(textToRRset(w_nsec3_text));
const string zzz_nsec3_text = string(zzz_hash) + ".example.org." +
string(nsec3_common);
- addZoneData(textToRRset(zzz_nsec3_text));
+ addToZoneData(textToRRset(zzz_nsec3_text));
}
private:
diff --git a/src/lib/datasrc/tests/memory/zone_table_segment_test.h b/src/lib/datasrc/tests/memory/zone_table_segment_test.h
new file mode 100644
index 0000000..2078036
--- /dev/null
+++ b/src/lib/datasrc/tests/memory/zone_table_segment_test.h
@@ -0,0 +1,116 @@
+// 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_MEMORY_ZONE_TABLE_SEGMENT_TEST_H
+#define DATASRC_MEMORY_ZONE_TABLE_SEGMENT_TEST_H 1
+
+#include <datasrc/memory/zone_table_segment.h>
+#include <datasrc/memory/zone_table.h>
+#include <datasrc/memory/zone_data.h>
+#include <datasrc/memory/zone_writer_local.h>
+
+namespace isc {
+namespace datasrc {
+namespace memory {
+namespace test {
+
+// A special ZoneTableSegment that can be used for tests. It can be
+// passed a MemorySegment that can be used later to test if all memory
+// was de-allocated on it.
+class ZoneTableSegmentTest : public ZoneTableSegment {
+public:
+ ZoneTableSegmentTest(isc::dns::RRClass rrclass,
+ isc::util::MemorySegment& mem_sgmt) :
+ ZoneTableSegment(rrclass),
+ mem_sgmt_(mem_sgmt),
+ header_(ZoneTable::create(mem_sgmt_, rrclass))
+ {}
+
+ virtual ~ZoneTableSegmentTest() {
+ ZoneTable::destroy(mem_sgmt_, header_.getTable());
+ }
+
+ virtual ZoneTableHeader& getHeader() {
+ return (header_);
+ }
+
+ virtual const ZoneTableHeader& getHeader() const {
+ return (header_);
+ }
+
+ virtual isc::util::MemorySegment& getMemorySegment() {
+ return (mem_sgmt_);
+ }
+
+ virtual ZoneWriter* getZoneWriter(const LoadAction& load_action,
+ const dns::Name& name,
+ const dns::RRClass& rrclass)
+ {
+ return (new Writer(this, load_action, name, rrclass));
+ }
+
+private:
+ isc::util::MemorySegment& mem_sgmt_;
+ ZoneTableHeader header_;
+
+ // A writer for this segment. The implementation is similar
+ // to ZoneWriterLocal, but all the error handling is stripped
+ // for simplicity. Also, we do everything inside the
+ // install(), for the same reason. We just need something
+ // inside the tests, not a full-blown implementation
+ // for background loading.
+ class Writer : public ZoneWriter {
+ public:
+ Writer(ZoneTableSegmentTest* segment, const LoadAction& load_action,
+ const dns::Name& name, const dns::RRClass& rrclass) :
+ segment_(segment),
+ load_action_(load_action),
+ name_(name),
+ rrclass_(rrclass)
+ {}
+
+ void load() {}
+
+ void install() {
+ ZoneTable* table(segment_->getHeader().getTable());
+ const ZoneTable::AddResult
+ result(table->addZone(segment_->getMemorySegment(), rrclass_,
+ name_,
+ load_action_(segment_->
+ getMemorySegment())));
+ if (result.zone_data != NULL) {
+ ZoneData::destroy(segment_->getMemorySegment(),
+ result.zone_data, rrclass_);
+ }
+ }
+
+ virtual void cleanup() {}
+ private:
+ ZoneTableSegmentTest* segment_;
+ LoadAction load_action_;
+ dns::Name name_;
+ dns::RRClass rrclass_;
+ };
+};
+
+} // namespace test
+} // namespace memory
+} // namespace datasrc
+} // namespace isc
+
+#endif // DATASRC_MEMORY_ZONE_TABLE_SEGMENT_TEST_H
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/lib/datasrc/tests/memory/zone_table_segment_unittest.cc b/src/lib/datasrc/tests/memory/zone_table_segment_unittest.cc
new file mode 100644
index 0000000..ac114e2
--- /dev/null
+++ b/src/lib/datasrc/tests/memory/zone_table_segment_unittest.cc
@@ -0,0 +1,97 @@
+// 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 <datasrc/memory/zone_writer_local.h>
+#include <datasrc/memory/zone_table_segment_local.h>
+#include <util/memory_segment_local.h>
+
+#include <gtest/gtest.h>
+#include <boost/scoped_ptr.hpp>
+
+using namespace isc::dns;
+using namespace isc::datasrc::memory;
+using namespace isc::data;
+using namespace isc::util;
+using namespace std;
+using boost::scoped_ptr;
+
+namespace {
+
+class ZoneTableSegmentTest : public ::testing::Test {
+protected:
+ ZoneTableSegmentTest() :
+ ztable_segment_(ZoneTableSegment::create(isc::data::NullElement(),
+ RRClass::IN()))
+ {}
+
+ void TearDown() {
+ ZoneTableSegment::destroy(ztable_segment_);
+ ztable_segment_ = NULL;
+ }
+
+ ZoneTableSegment* ztable_segment_;
+};
+
+
+TEST_F(ZoneTableSegmentTest, create) {
+ // By default, a local zone table segment is created.
+ EXPECT_NE(static_cast<void*>(NULL), ztable_segment_);
+}
+
+// Helper function to check const and non-const methods.
+template <typename TS, typename TH, typename TT>
+void
+testGetHeader(ZoneTableSegment* ztable_segment) {
+ TH& header = static_cast<TS*>(ztable_segment)->getHeader();
+
+ // The zone table must be set.
+ TT* table = header.getTable();
+ EXPECT_NE(static_cast<void*>(NULL), table);
+}
+
+TEST_F(ZoneTableSegmentTest, getHeader) {
+ // non-const version.
+ testGetHeader<ZoneTableSegment, ZoneTableHeader, ZoneTable>
+ (ztable_segment_);
+
+ // const version.
+ testGetHeader<const ZoneTableSegment, const ZoneTableHeader,
+ const ZoneTable>(ztable_segment_);
+}
+
+TEST_F(ZoneTableSegmentTest, getMemorySegment) {
+ // This doesn't do anything fun except test the API.
+ MemorySegment& mem_sgmt = ztable_segment_->getMemorySegment();
+ mem_sgmt.allMemoryDeallocated(); // use mem_sgmt
+}
+
+ZoneData*
+loadAction(MemorySegment&) {
+ // The function won't be called, so this is OK
+ return (NULL);
+}
+
+// Test we can get a writer.
+TEST_F(ZoneTableSegmentTest, getZoneWriter) {
+ scoped_ptr<ZoneWriter>
+ writer(ztable_segment_->getZoneWriter(loadAction, Name("example.org"),
+ RRClass::IN()));
+ // We have to get something
+ EXPECT_NE(static_cast<void*>(NULL), writer.get());
+ // And for now, it should be the local writer
+ EXPECT_NE(static_cast<void*>(NULL),
+ dynamic_cast<ZoneWriterLocal*>(writer.get()));
+}
+
+} // anonymous namespace
diff --git a/src/lib/datasrc/tests/memory/zone_table_unittest.cc b/src/lib/datasrc/tests/memory/zone_table_unittest.cc
index 359df49..3c53a59 100644
--- a/src/lib/datasrc/tests/memory/zone_table_unittest.cc
+++ b/src/lib/datasrc/tests/memory/zone_table_unittest.cc
@@ -12,6 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
+#include "memory_segment_test.h"
+
#include <exceptions/exceptions.h>
#include <util/memory_segment_local.h>
@@ -22,6 +24,7 @@
#include <datasrc/result.h>
#include <datasrc/memory/zone_data.h>
#include <datasrc/memory/zone_table.h>
+#include <datasrc/memory/segment_object_holder.h>
#include <gtest/gtest.h>
@@ -30,29 +33,9 @@
using namespace isc::dns;
using namespace isc::datasrc;
using namespace isc::datasrc::memory;
+using namespace isc::datasrc::memory::detail;
namespace {
-// Memory segment specified for tests. It normally behaves like a "local"
-// memory segment. If "throw count" is set to non 0 via setThrowCount(),
-// it continues the normal behavior up to the specified number of calls to
-// allocate(), and throws an exception at the next call.
-class TestMemorySegment : public isc::util::MemorySegmentLocal {
-public:
- TestMemorySegment() : throw_count_(0) {}
- virtual void* allocate(size_t size) {
- if (throw_count_ > 0) {
- if (--throw_count_ == 0) {
- throw std::bad_alloc();
- }
- }
- return (isc::util::MemorySegmentLocal::allocate(size));
- }
- void setThrowCount(size_t count) { throw_count_ = count; }
-
-private:
- size_t throw_count_;
-};
-
class ZoneTableTest : public ::testing::Test {
protected:
ZoneTableTest() : zclass_(RRClass::IN()),
@@ -63,17 +46,17 @@ protected:
{}
~ZoneTableTest() {
if (zone_table != NULL) {
- ZoneTable::destroy(mem_sgmt_, zone_table, zclass_);
+ ZoneTable::destroy(mem_sgmt_, zone_table);
}
}
void TearDown() {
- ZoneTable::destroy(mem_sgmt_, zone_table, zclass_);
+ ZoneTable::destroy(mem_sgmt_, zone_table);
zone_table = NULL;
EXPECT_TRUE(mem_sgmt_.allMemoryDeallocated()); // catch any leak here.
}
const RRClass zclass_;
const Name zname1, zname2, zname3;
- TestMemorySegment mem_sgmt_;
+ test::MemorySegmentTest mem_sgmt_;
ZoneTable* zone_table;
};
@@ -87,46 +70,89 @@ TEST_F(ZoneTableTest, create) {
}
TEST_F(ZoneTableTest, addZone) {
+ // It doesn't accept empty (NULL) zones
+ EXPECT_THROW(zone_table->addZone(mem_sgmt_, zclass_, zname1, NULL),
+ isc::BadValue);
+
+ SegmentObjectHolder<ZoneData, RRClass> holder1(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname1), zclass_);
+ const ZoneData* data1(holder1.get());
// Normal successful case.
- const ZoneTable::AddResult result1 =
- zone_table->addZone(mem_sgmt_, zclass_, zname1);
+ const ZoneTable::AddResult result1(zone_table->addZone(mem_sgmt_, zclass_,
+ zname1,
+ holder1.release()));
EXPECT_EQ(result::SUCCESS, result1.code);
+ EXPECT_EQ(static_cast<const ZoneData*>(NULL), result1.zone_data);
+ // It got released by it
+ EXPECT_EQ(static_cast<const ZoneData*>(NULL), holder1.get());
// Duplicate add doesn't replace the existing data.
- EXPECT_EQ(result::EXIST, zone_table->addZone(mem_sgmt_, zclass_,
- zname1).code);
- EXPECT_EQ(result1.zone_data,
- zone_table->addZone(mem_sgmt_, zclass_, zname1).zone_data);
+ SegmentObjectHolder<ZoneData, RRClass> holder2(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname1), zclass_);
+ const ZoneTable::AddResult result2(zone_table->addZone(mem_sgmt_, zclass_,
+ zname1,
+ holder2.release()));
+ EXPECT_EQ(result::EXIST, result2.code);
+ // The old one gets out
+ EXPECT_EQ(data1, result2.zone_data);
+ // It releases this one even when we replace the old zone
+ EXPECT_EQ(static_cast<const ZoneData*>(NULL), holder2.get());
+ // We need to release the old one manually
+ ZoneData::destroy(mem_sgmt_, result2.zone_data, zclass_);
+
+ SegmentObjectHolder<ZoneData, RRClass> holder3(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, Name("EXAMPLE.COM")),
+ zclass_);
// names are compared in a case insensitive manner.
- EXPECT_EQ(result::EXIST, zone_table->addZone(mem_sgmt_, zclass_,
- Name("EXAMPLE.COM")).code);
+ const ZoneTable::AddResult result3(zone_table->addZone(mem_sgmt_, zclass_,
+ Name("EXAMPLE.COM"),
+ holder3.release()));
+ EXPECT_EQ(result::EXIST, result3.code);
+ ZoneData::destroy(mem_sgmt_, result3.zone_data, zclass_);
// Add some more different ones. Should just succeed.
+ SegmentObjectHolder<ZoneData, RRClass> holder4(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname2), zclass_);
EXPECT_EQ(result::SUCCESS,
- zone_table->addZone(mem_sgmt_, zclass_, zname2).code);
+ zone_table->addZone(mem_sgmt_, zclass_, zname2,
+ holder4.release()).code);
+ SegmentObjectHolder<ZoneData, RRClass> holder5(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname3), zclass_);
EXPECT_EQ(result::SUCCESS,
- zone_table->addZone(mem_sgmt_, zclass_, zname3).code);
+ zone_table->addZone(mem_sgmt_, zclass_, zname3,
+ holder5.release()).code);
// Have the memory segment throw an exception in extending the internal
// tree. It still shouldn't cause memory leak (which would be detected
// in TearDown()).
- mem_sgmt_.setThrowCount(2);
- EXPECT_THROW(zone_table->addZone(mem_sgmt_, zclass_, Name("example.org")),
+ SegmentObjectHolder<ZoneData, RRClass> holder6(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, Name("example.org")), zclass_);
+ mem_sgmt_.setThrowCount(1);
+ EXPECT_THROW(zone_table->addZone(mem_sgmt_, zclass_, Name("example.org"),
+ holder6.release()),
std::bad_alloc);
}
TEST_F(ZoneTableTest, findZone) {
- const ZoneTable::AddResult add_result1 =
- zone_table->addZone(mem_sgmt_, zclass_, zname1);
- EXPECT_EQ(result::SUCCESS, add_result1.code);
+ SegmentObjectHolder<ZoneData, RRClass> holder1(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname1), zclass_);
+ ZoneData* zone_data = holder1.get();
+ EXPECT_EQ(result::SUCCESS, zone_table->addZone(mem_sgmt_, zclass_, zname1,
+ holder1.release()).code);
+ SegmentObjectHolder<ZoneData, RRClass> holder2(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname2), zclass_);
EXPECT_EQ(result::SUCCESS,
- zone_table->addZone(mem_sgmt_, zclass_, zname2).code);
+ zone_table->addZone(mem_sgmt_, zclass_, zname2,
+ holder2.release()).code);
+ SegmentObjectHolder<ZoneData, RRClass> holder3(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, zname3), zclass_);
EXPECT_EQ(result::SUCCESS,
- zone_table->addZone(mem_sgmt_, zclass_, zname3).code);
+ zone_table->addZone(mem_sgmt_, zclass_, zname3,
+ holder3.release()).code);
const ZoneTable::FindResult find_result1 =
zone_table->findZone(Name("example.com"));
EXPECT_EQ(result::SUCCESS, find_result1.code);
- EXPECT_EQ(add_result1.zone_data, find_result1.zone_data);
+ EXPECT_EQ(zone_data, find_result1.zone_data);
EXPECT_EQ(result::NOTFOUND,
zone_table->findZone(Name("example.org")).code);
@@ -137,14 +163,17 @@ TEST_F(ZoneTableTest, findZone) {
// and the code should be PARTIALMATCH.
EXPECT_EQ(result::PARTIALMATCH,
zone_table->findZone(Name("www.example.com")).code);
- EXPECT_EQ(add_result1.zone_data,
+ EXPECT_EQ(zone_data,
zone_table->findZone(Name("www.example.com")).zone_data);
// make sure the partial match is indeed the longest match by adding
// a zone with a shorter origin and query again.
+ SegmentObjectHolder<ZoneData, RRClass> holder4(
+ mem_sgmt_, ZoneData::create(mem_sgmt_, Name("com")), zclass_);
EXPECT_EQ(result::SUCCESS, zone_table->addZone(mem_sgmt_, zclass_,
- Name("com")).code);
- EXPECT_EQ(add_result1.zone_data,
+ Name("com"),
+ holder4.release()).code);
+ EXPECT_EQ(zone_data,
zone_table->findZone(Name("www.example.com")).zone_data);
}
}
diff --git a/src/lib/datasrc/tests/memory/zone_writer_unittest.cc b/src/lib/datasrc/tests/memory/zone_writer_unittest.cc
new file mode 100644
index 0000000..13bcc3b
--- /dev/null
+++ b/src/lib/datasrc/tests/memory/zone_writer_unittest.cc
@@ -0,0 +1,240 @@
+// 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 <datasrc/memory/zone_writer_local.h>
+#include <datasrc/memory/zone_table_segment_local.h>
+#include <datasrc/memory/zone_data.h>
+
+#include <cc/data.h>
+#include <dns/rrclass.h>
+#include <dns/name.h>
+
+#include <gtest/gtest.h>
+
+#include <boost/scoped_ptr.hpp>
+#include <boost/bind.hpp>
+
+using boost::scoped_ptr;
+using boost::bind;
+using isc::dns::RRClass;
+using isc::dns::Name;
+using namespace isc::datasrc::memory;
+
+namespace {
+
+class TestException {};
+
+class ZoneWriterLocalTest : public ::testing::Test {
+public:
+ ZoneWriterLocalTest() :
+ // FIXME: The NullElement probably isn't the best one, but we don't
+ // know how the config will look, so it just fills the argument
+ // (which is currently ignored)
+ segment_(ZoneTableSegment::create(isc::data::NullElement(),
+ RRClass::IN())),
+ writer_(new
+ ZoneWriterLocal(dynamic_cast<ZoneTableSegmentLocal*>(segment_.
+ get()),
+ bind(&ZoneWriterLocalTest::loadAction, this, _1),
+ Name("example.org"), RRClass::IN())),
+ load_called_(false),
+ load_throw_(false),
+ load_null_(false),
+ load_data_(false)
+ {}
+ void TearDown() {
+ // Release the writer
+ writer_.reset();
+ }
+protected:
+ scoped_ptr<ZoneTableSegment> segment_;
+ scoped_ptr<ZoneWriterLocal> writer_;
+ bool load_called_;
+ bool load_throw_;
+ bool load_null_;
+ bool load_data_;
+private:
+ ZoneData* loadAction(isc::util::MemorySegment& segment) {
+ // Make sure it is the correct segment passed. We know the
+ // exact instance, can compare pointers to them.
+ EXPECT_EQ(&segment_->getMemorySegment(), &segment);
+ // We got called
+ load_called_ = true;
+ if (load_throw_) {
+ throw TestException();
+ }
+
+ if (load_null_) {
+ // Be nasty to the caller and return NULL, which is forbidden
+ return (NULL);
+ }
+ ZoneData* data = ZoneData::create(segment, Name("example.org"));
+ if (load_data_) {
+ // Put something inside. The node itself should be enough for
+ // the tests.
+ ZoneNode* node(NULL);
+ data->insertName(segment, Name("subdomain.example.org"), &node);
+ EXPECT_NE(static_cast<ZoneNode*>(NULL), node);
+ }
+ return (data);
+ }
+};
+
+// We call it the way we are supposed to, check every callback is called in the
+// right moment.
+TEST_F(ZoneWriterLocalTest, correctCall) {
+ // Nothing called before we call it
+ EXPECT_FALSE(load_called_);
+
+ // Just the load gets called now
+ EXPECT_NO_THROW(writer_->load());
+ EXPECT_TRUE(load_called_);
+ load_called_ = false;
+
+ EXPECT_NO_THROW(writer_->install());
+ EXPECT_FALSE(load_called_);
+
+ // We don't check explicitly how this works, but call it to free memory. If
+ // everything is freed should be checked inside the TearDown.
+ EXPECT_NO_THROW(writer_->cleanup());
+}
+
+TEST_F(ZoneWriterLocalTest, loadTwice) {
+ // Load it the first time
+ EXPECT_NO_THROW(writer_->load());
+ EXPECT_TRUE(load_called_);
+ load_called_ = false;
+
+ // The second time, it should not be possible
+ EXPECT_THROW(writer_->load(), isc::InvalidOperation);
+ EXPECT_FALSE(load_called_);
+
+ // The object should not be damaged, try installing and clearing now
+ EXPECT_NO_THROW(writer_->install());
+ EXPECT_FALSE(load_called_);
+
+ // We don't check explicitly how this works, but call it to free memory. If
+ // everything is freed should be checked inside the TearDown.
+ EXPECT_NO_THROW(writer_->cleanup());
+}
+
+// Try loading after call to install and call to cleanup. Both is
+// forbidden.
+TEST_F(ZoneWriterLocalTest, loadLater) {
+ // Load first, so we can install
+ EXPECT_NO_THROW(writer_->load());
+ EXPECT_NO_THROW(writer_->install());
+ // Reset so we see nothing is called now
+ load_called_ = false;
+
+ EXPECT_THROW(writer_->load(), isc::InvalidOperation);
+ EXPECT_FALSE(load_called_);
+
+ // Cleanup and try loading again. Still shouldn't work.
+ EXPECT_NO_THROW(writer_->cleanup());
+
+ EXPECT_THROW(writer_->load(), isc::InvalidOperation);
+ EXPECT_FALSE(load_called_);
+}
+
+// Try calling install at various bad times
+TEST_F(ZoneWriterLocalTest, invalidInstall) {
+ // Nothing loaded yet
+ EXPECT_THROW(writer_->install(), isc::InvalidOperation);
+ EXPECT_FALSE(load_called_);
+
+ EXPECT_NO_THROW(writer_->load());
+ load_called_ = false;
+ // This install is OK
+ EXPECT_NO_THROW(writer_->install());
+ // But we can't call it second time now
+ EXPECT_THROW(writer_->install(), isc::InvalidOperation);
+ EXPECT_FALSE(load_called_);
+}
+
+// We check we can clean without installing first and nothing bad
+// happens. We also misuse the testcase to check we can't install
+// after cleanup.
+TEST_F(ZoneWriterLocalTest, cleanWithoutInstall) {
+ EXPECT_NO_THROW(writer_->load());
+ EXPECT_NO_THROW(writer_->cleanup());
+
+ EXPECT_TRUE(load_called_);
+
+ // We cleaned up, no way to install now
+ EXPECT_THROW(writer_->install(), isc::InvalidOperation);
+}
+
+// Test the case when load callback throws
+TEST_F(ZoneWriterLocalTest, loadThrows) {
+ load_throw_ = true;
+ EXPECT_THROW(writer_->load(), TestException);
+
+ // We can't install now
+ EXPECT_THROW(writer_->install(), isc::InvalidOperation);
+ EXPECT_TRUE(load_called_);
+
+ // But we can cleanup
+ EXPECT_NO_THROW(writer_->cleanup());
+}
+
+// Check the strong exception guarantee - if it throws, nothing happened
+// to the content.
+TEST_F(ZoneWriterLocalTest, retry) {
+ // First attempt fails due to some exception.
+ load_throw_ = true;
+ EXPECT_THROW(writer_->load(), TestException);
+ // This one shall succeed.
+ load_called_ = load_throw_ = false;
+ // We want some data inside.
+ load_data_ = true;
+ EXPECT_NO_THROW(writer_->load());
+ // And this one will fail again. But the old data will survive.
+ load_data_ = false;
+ EXPECT_THROW(writer_->load(), isc::InvalidOperation);
+
+ // The rest still works correctly
+ EXPECT_NO_THROW(writer_->install());
+ ZoneTable* const table(segment_->getHeader().getTable());
+ const ZoneTable::FindResult found(table->findZone(Name("example.org")));
+ ASSERT_EQ(isc::datasrc::result::SUCCESS, found.code);
+ // For some reason it doesn't seem to work by the ZoneNode typedef, using
+ // the full definition instead. At least on some compilers.
+ const isc::datasrc::memory::DomainTreeNode<RdataSet>* node;
+ EXPECT_EQ(isc::datasrc::memory::DomainTree<RdataSet>::EXACTMATCH,
+ found.zone_data->getZoneTree().
+ find(Name("subdomain.example.org"), &node));
+ EXPECT_NO_THROW(writer_->cleanup());
+}
+
+// Check the writer defends itsefl when load action returns NULL
+TEST_F(ZoneWriterLocalTest, loadNull) {
+ load_null_ = true;
+ EXPECT_THROW(writer_->load(), isc::InvalidOperation);
+
+ // We can't install that
+ EXPECT_THROW(writer_->install(), isc::InvalidOperation);
+
+ // It should be possible to clean up safely
+ EXPECT_NO_THROW(writer_->cleanup());
+}
+
+// Check the object cleans up in case we forget it.
+TEST_F(ZoneWriterLocalTest, autoCleanUp) {
+ // Load data and forget about it. It should get released
+ // when the writer itself is destroyed.
+ EXPECT_NO_THROW(writer_->load());
+}
+
+}
diff --git a/src/lib/datasrc/tests/memory_datasrc_unittest.cc b/src/lib/datasrc/tests/memory_datasrc_unittest.cc
index 958c9e1..5223d83 100644
--- a/src/lib/datasrc/tests/memory_datasrc_unittest.cc
+++ b/src/lib/datasrc/tests/memory_datasrc_unittest.cc
@@ -22,7 +22,6 @@
#include <dns/rdata.h>
#include <dns/rdataclass.h>
#include <dns/rrclass.h>
-#include <dns/rrsetlist.h>
#include <dns/rrttl.h>
#include <dns/masterload.h>
diff --git a/src/lib/datasrc/tests/sqlite3_accessor_unittest.cc b/src/lib/datasrc/tests/sqlite3_accessor_unittest.cc
index 718d29b..100a0dd 100644
--- a/src/lib/datasrc/tests/sqlite3_accessor_unittest.cc
+++ b/src/lib/datasrc/tests/sqlite3_accessor_unittest.cc
@@ -191,6 +191,11 @@ TEST_F(SQLite3AccessorTest, iterator) {
checkRR(context, "sub.example.org.", "3600", "NS", "ns.sub.example.org.");
checkRR(context, "ns.sub.example.org.", "3600", "A", "192.0.2.101");
checkRR(context, "www.example.org.", "3600", "A", "192.0.2.1");
+ checkRR(context, "ns3.example.org.", "3600", "NSEC3",
+ "1 1 12 aabbccdd 2T7B4G4VSA5SMI47K61MV5BV1A22BOJR A RRSIG");
+ checkRR(context, "ns3.example.org.", "3600", "RRSIG",
+ "NSEC3 5 3 3600 20000101000000 20000201000000 "
+ "12345 ns3.example.org. FAKEFAKEFAKE");
// Check there's no other
EXPECT_FALSE(context->getNext(data));
@@ -665,16 +670,16 @@ TEST_F(SQLite3Create, creationtest) {
TEST_F(SQLite3Create, emptytest) {
ASSERT_FALSE(isReadable(SQLITE_NEW_DBFILE));
- // open one manualle
+ // open one manually
sqlite3* db;
ASSERT_EQ(SQLITE_OK, sqlite3_open(SQLITE_NEW_DBFILE, &db));
- // empty, but not locked, so creating it now should work
+ // empty, but not locked, so creating another accessor should work
SQLite3Accessor accessor2(SQLITE_NEW_DBFILE, "IN");
sqlite3_close(db);
- // should work now that we closed it
+ // should still work now that we closed it
SQLite3Accessor accessor3(SQLITE_NEW_DBFILE, "IN");
}
@@ -692,8 +697,10 @@ TEST_F(SQLite3Create, lockedtest) {
sqlite3_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, NULL);
- // should work now that we closed it
+ // should work now that the transaction has been rolled back
SQLite3Accessor accessor3(SQLITE_NEW_DBFILE, "IN");
+
+ ASSERT_EQ(SQLITE_OK, sqlite3_close(db));
}
TEST_F(SQLite3AccessorTest, clone) {
diff --git a/src/lib/datasrc/tests/test_client.h b/src/lib/datasrc/tests/test_client.h
index 2c692d3..1e35cd3 100644
--- a/src/lib/datasrc/tests/test_client.h
+++ b/src/lib/datasrc/tests/test_client.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TEST_DATA_SOURCE_CLIENT_H
-#define __TEST_DATA_SOURCE_CLIENT_H 1
+#ifndef TEST_DATA_SOURCE_CLIENT_H
+#define TEST_DATA_SOURCE_CLIENT_H 1
#include <dns/name.h>
#include <dns/rrclass.h>
@@ -64,7 +64,7 @@ createSQLite3Client(dns::RRClass zclass, const dns::Name& zname,
} // end of datasrc
} // end of isc
-#endif // __TEST_DATA_SOURCE_CLIENT_H
+#endif // TEST_DATA_SOURCE_CLIENT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/tests/testdata/contexttest.zone b/src/lib/datasrc/tests/testdata/contexttest.zone
index a39649d..0c1393c 100644
--- a/src/lib/datasrc/tests/testdata/contexttest.zone
+++ b/src/lib/datasrc/tests/testdata/contexttest.zone
@@ -1,9 +1,10 @@
;; test zone file used for ZoneFinderContext tests.
;; RRSIGs are (obviouslly) faked ones for testing.
-example.org. 3600 IN SOA ns1.example.org. bugs.x.w.example.org. 71 3600 300 3600000 3600
+example.org. 3600 IN SOA ns1.example.org. bugs.x.w.example.org. 74 3600 300 3600000 3600
example.org. 3600 IN NS ns1.example.org.
example.org. 3600 IN NS ns2.example.org.
+example.org. 3600 IN RRSIG NS 7 3 3600 20150420235959 20051021000000 40430 example.org. FAKEFAKEFAKE
example.org. 3600 IN MX 1 mx1.example.org.
example.org. 3600 IN MX 2 mx2.example.org.
example.org. 3600 IN MX 3 mx.a.example.org.
diff --git a/src/lib/datasrc/tests/testdata/example.org.sqlite3 b/src/lib/datasrc/tests/testdata/example.org.sqlite3
index c7388ff..c799d2e 100644
Binary files a/src/lib/datasrc/tests/testdata/example.org.sqlite3 and b/src/lib/datasrc/tests/testdata/example.org.sqlite3 differ
diff --git a/src/lib/datasrc/tests/zone_finder_context_unittest.cc b/src/lib/datasrc/tests/zone_finder_context_unittest.cc
index 14429ae..1a4cae2 100644
--- a/src/lib/datasrc/tests/zone_finder_context_unittest.cc
+++ b/src/lib/datasrc/tests/zone_finder_context_unittest.cc
@@ -14,14 +14,13 @@
#include <exceptions/exceptions.h>
-#include <util/memory_segment_local.h>
-
#include <dns/masterload.h>
#include <dns/name.h>
#include <dns/rrclass.h>
#include <datasrc/zone.h>
#include <datasrc/memory/memory_client.h>
+#include <datasrc/memory/zone_table_segment.h>
#include <datasrc/database.h>
#include <datasrc/sqlite3_accessor.h>
@@ -41,10 +40,12 @@
using namespace std;
using boost::shared_ptr;
+using namespace isc::data;
using namespace isc::util;
using namespace isc::dns;
using namespace isc::datasrc;
using isc::datasrc::memory::InMemoryClient;
+using isc::datasrc::memory::ZoneTableSegment;
using namespace isc::testutils;
namespace {
@@ -58,15 +59,17 @@ typedef shared_ptr<DataSourceClient> DataSourceClientPtr;
// This is the type used as the test parameter. Note that this is
// intentionally a plain old type (i.e. a function pointer), not a class;
// otherwise it could cause initialization fiasco at the instantiation time.
-typedef DataSourceClientPtr (*ClientCreator)(MemorySegment&, RRClass,
- const Name&);
+typedef DataSourceClientPtr (*ClientCreator)(RRClass, const Name&);
// Creator for the in-memory client to be tested
DataSourceClientPtr
-createInMemoryClient(MemorySegment& mem_sgmt, RRClass zclass,
- const Name& zname)
+createInMemoryClient(RRClass zclass, const Name& zname)
{
- shared_ptr<InMemoryClient> client(new InMemoryClient(mem_sgmt, zclass));
+ const ElementPtr config(Element::fromJSON("{}"));
+ shared_ptr<ZoneTableSegment> ztable_segment(
+ ZoneTableSegment::create(*config, zclass));
+ shared_ptr<InMemoryClient> client(new InMemoryClient(ztable_segment,
+ zclass));
client->load(zname, TEST_ZONE_FILE);
return (client);
@@ -78,7 +81,7 @@ addRRset(ZoneUpdaterPtr updater, ConstRRsetPtr rrset) {
}
DataSourceClientPtr
-createSQLite3Client(MemorySegment&, RRClass zclass, const Name& zname) {
+createSQLite3Client(RRClass zclass, const Name& zname) {
// We always begin with an empty template SQLite3 DB file and install
// the zone data from the zone file to ensure both cases have the
// same test data.
@@ -105,7 +108,7 @@ class ZoneFinderContextTest :
{
protected:
ZoneFinderContextTest() : qclass_(RRClass::IN()), qzone_("example.org") {
- client_ = (*GetParam())(mem_sgmt_, qclass_, qzone_);
+ client_ = (*GetParam())(qclass_, qzone_);
REQUESTED_A.push_back(RRType::A());
REQUESTED_AAAA.push_back(RRType::AAAA());
REQUESTED_BOTH.push_back(RRType::A());
@@ -116,7 +119,6 @@ protected:
ASSERT_TRUE(finder_);
}
- MemorySegmentLocal mem_sgmt_;
const RRClass qclass_;
const Name qzone_;
DataSourceClientPtr client_;
diff --git a/src/lib/datasrc/zone.h b/src/lib/datasrc/zone.h
index 2330412..9572ed0 100644
--- a/src/lib/datasrc/zone.h
+++ b/src/lib/datasrc/zone.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ZONE_H
-#define __ZONE_H 1
+#ifndef ZONE_H
+#define ZONE_H 1
#include <dns/name.h>
#include <dns/rrset.h>
@@ -168,48 +168,25 @@ public:
/// can define a derived class of the base Context and override the
/// specific virtual method.
///
+ /// This base class defines these common protected methods along with
+ /// some helper pure virtual methods that would be necessary for the
+ /// common methods. If a derived class wants to use the common version
+ /// of the protected method, it needs to provide expected result through
+ /// their implementation of the pure virtual methods.
+ ///
/// This class object is generally expected to be associated with the
/// ZoneFinder that originally performed the \c find() call, and expects
/// the finder is valid throughout the lifetime of this object. It's
/// caller's responsibility to ensure that assumption.
class Context {
public:
- /// \brief The constructor for the normal find call.
- ///
- /// This constructor is expected to be called from the \c find()
- /// method when it constructs the return value.
+ /// \brief The constructor.
///
- /// \param finder The ZoneFinder on which find() is called.
/// \param options The find options specified for the find() call.
/// \param result The result of the find() call.
- Context(ZoneFinder& finder, FindOptions options,
- const ResultContext& result) :
- code(result.code), rrset(result.rrset),
- finder_(finder), flags_(result.flags), options_(options)
- {}
-
- /// \brief The constructor for the normal findAll call.
- ///
- /// This constructor is expected to be called from the \c findAll()
- /// method when it constructs the return value.
- ///
- /// It copies the vector that is to be returned to the caller of
- /// \c findAll() for possible subsequent use. Note that it cannot
- /// simply hold a reference to the vector because the caller may
- /// alter it after the \c findAll() call.
- ///
- /// \param finder The ZoneFinder on which findAll() is called.
- /// \param options The find options specified for the findAll() call.
- /// \param result The result of the findAll() call (whose rrset is
- /// expected to be NULL).
- /// \param all_set Reference to the vector given by the caller of
- /// \c findAll(), storing the RRsets to be returned.
- Context(ZoneFinder& finder, FindOptions options,
- const ResultContext& result,
- const std::vector<isc::dns::ConstRRsetPtr> &all_set) :
+ Context(FindOptions options, const ResultContext& result) :
code(result.code), rrset(result.rrset),
- finder_(finder), flags_(result.flags), options_(options),
- all_set_(all_set)
+ flags_(result.flags), options_(options)
{}
/// \brief The destructor.
@@ -292,21 +269,108 @@ public:
}
protected:
+ /// \brief Return the \c ZoneFinder that created this \c Context.
+ ///
+ /// A derived class implementation can return NULL if it defines
+ /// other protected methods that require a non NULL result from
+ /// this method. Otherwise it must return a valid, non NULL pointer
+ /// to the \c ZoneFinder object.
+ ///
+ /// When returning non NULL, the ownership of the pointed object
+ /// was not transferred to the caller; it cannot be assumed to be
+ /// valid after the originating \c Context object is destroyed.
+ /// Also, the caller must not try to delete the returned object.
+ virtual ZoneFinder* getFinder() = 0;
+
+ /// \brief Return a vector of RRsets corresponding to findAll() result.
+ ///
+ /// This method returns a set of RRsets that correspond to the
+ /// returned RRsets to a prior \c findAll() call.
+ ///
+ /// A derived class implementation can return NULL if it defines
+ /// other protected methods that require a non NULL result from
+ /// this method. Otherwise it must return a valid, non NULL pointer
+ /// to a vector that correspond to the expected set of RRsets.
+ ///
+ /// When returning non NULL, the ownership of the pointed object
+ /// was not transferred to the caller; it cannot be assumed to be
+ /// valid after the originating \c Context object is destroyed.
+ /// Also, the caller must not try to delete the returned object.
+ virtual const std::vector<isc::dns::ConstRRsetPtr>*
+ getAllRRsets() const = 0;
+
/// \brief Actual implementation of getAdditional().
///
/// This base class defines a default implementation that can be
/// used for any type of data sources. A data source implementation
/// can override it.
+ ///
+ /// The default version of this implementation requires both
+ /// \c getFinder() and \c getAllRRsets() return valid results.
virtual void getAdditionalImpl(
const std::vector<isc::dns::RRType>& requested_types,
std::vector<isc::dns::ConstRRsetPtr>& result);
private:
- ZoneFinder& finder_;
const FindResultFlags flags_;
protected:
const FindOptions options_;
+ };
+
+ /// \brief Generic ZoneFinder context that works for all implementations.
+ ///
+ /// This is a concrete derived class of \c ZoneFinder::Context that
+ /// only use the generic (default) versions of the protected methods
+ /// and therefore work for any data source implementation.
+ ///
+ /// A data source implementation can use this class to create a
+ /// \c Context object as a return value of \c find() or \c findAll()
+ /// method if it doesn't have to optimize specific protected methods.
+ class GenericContext : public Context {
+ public:
+ /// \brief The constructor for the normal find call.
+ ///
+ /// This constructor is expected to be called from the \c find()
+ /// method when it constructs the return value.
+ ///
+ /// \param finder The ZoneFinder on which find() is called.
+ /// \param options See the \c Context class.
+ /// \param result See the \c Context class.
+ GenericContext(ZoneFinder& finder, FindOptions options,
+ const ResultContext& result) :
+ Context(options, result), finder_(finder)
+ {}
+
+ /// \brief The constructor for the normal findAll call.
+ ///
+ /// This constructor is expected to be called from the \c findAll()
+ /// method when it constructs the return value.
+ ///
+ /// It copies the vector that is to be returned to the caller of
+ /// \c findAll() for possible subsequent use. Note that it cannot
+ /// simply hold a reference to the vector because the caller may
+ /// alter it after the \c findAll() call.
+ ///
+ /// \param finder The ZoneFinder on which findAll() is called.
+ /// \param options See the \c Context class.
+ /// \param result See the \c Context class.
+ /// \param all_set Reference to the vector given by the caller of
+ /// \c findAll(), storing the RRsets to be returned.
+ GenericContext(ZoneFinder& finder, FindOptions options,
+ const ResultContext& result,
+ const std::vector<isc::dns::ConstRRsetPtr>& all_set) :
+ Context(options, result), finder_(finder), all_set_(all_set)
+ {}
+
+ protected:
+ virtual ZoneFinder* getFinder() { return (&finder_); }
+ virtual const std::vector<isc::dns::ConstRRsetPtr>*
+ getAllRRsets() const {
+ return (&all_set_);
+ }
+
private:
+ ZoneFinder& finder_;
std::vector<isc::dns::ConstRRsetPtr> all_set_;
};
@@ -1001,7 +1065,7 @@ typedef boost::shared_ptr<ZoneJournalReader> ZoneJournalReaderPtr;
} // end of datasrc
} // end of isc
-#endif // __ZONE_H
+#endif // ZONE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/datasrc/zone_finder_context.cc b/src/lib/datasrc/zone_finder_context.cc
index 7913d71..482eb65 100644
--- a/src/lib/datasrc/zone_finder_context.cc
+++ b/src/lib/datasrc/zone_finder_context.cc
@@ -12,6 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
+#include <exceptions/exceptions.h>
+
#include <dns/rdata.h>
#include <dns/rrset.h>
#include <dns/rrtype.h>
@@ -87,13 +89,22 @@ ZoneFinder::Context::getAdditionalImpl(const vector<RRType>& requested_types,
{
// If rrset is non NULL, it should have been SUCCESS/DELEGATION; otherwise
// we should have responded to type ANY query.
+ ZoneFinder* finder = getFinder();
+ if (finder == NULL) {
+ // This is a bug of the derived class implementation.
+ isc_throw(isc::Unexpected, "NULL ZoneFinder in finder Context");
+ }
if (rrset) {
- getAdditionalForRRset(finder_, *rrset, requested_types, result,
+ getAdditionalForRRset(*finder, *rrset, requested_types, result,
options_);
return;
}
- BOOST_FOREACH(ConstRRsetPtr rrset_in_set, all_set_) {
- getAdditionalForRRset(finder_, *rrset_in_set, requested_types, result,
+ const vector<ConstRRsetPtr>* all_sets = getAllRRsets();
+ if (all_sets == NULL) { // bug of the derived class implementation.
+ isc_throw(isc::Unexpected, "All RRsets is NULL in finder Context");
+ }
+ BOOST_FOREACH(ConstRRsetPtr rrset_in_set, *getAllRRsets()) {
+ getAdditionalForRRset(*finder, *rrset_in_set, requested_types, result,
options_);
}
}
diff --git a/src/lib/datasrc/zonetable.h b/src/lib/datasrc/zonetable.h
index 93a021c..911391c 100644
--- a/src/lib/datasrc/zonetable.h
+++ b/src/lib/datasrc/zonetable.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ZONETABLE_H
-#define __ZONETABLE_H 1
+#ifndef ZONETABLE_H
+#define ZONETABLE_H 1
#include <util/memory_segment.h>
@@ -153,7 +153,7 @@ private:
};
}
}
-#endif // __ZONETABLE_H
+#endif // ZONETABLE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dhcp/Makefile.am b/src/lib/dhcp/Makefile.am
index fbd4eb5..43a1b04 100644
--- a/src/lib/dhcp/Makefile.am
+++ b/src/lib/dhcp/Makefile.am
@@ -13,7 +13,7 @@ AM_CXXFLAGS += $(WARNING_NO_MISSING_FIELD_INITIALIZERS_CFLAG)
CLEANFILES = *.gcno *.gcda
-lib_LTLIBRARIES = libb10-dhcp++.la
+lib_LTLIBRARIES = libb10-dhcp++.la libb10-dhcpsrv.la
libb10_dhcp___la_SOURCES =
libb10_dhcp___la_SOURCES += libdhcp++.cc libdhcp++.h
libb10_dhcp___la_SOURCES += iface_mgr.cc iface_mgr.h
@@ -21,16 +21,33 @@ libb10_dhcp___la_SOURCES += iface_mgr_linux.cc
libb10_dhcp___la_SOURCES += iface_mgr_bsd.cc
libb10_dhcp___la_SOURCES += iface_mgr_sun.cc
libb10_dhcp___la_SOURCES += option.cc option.h
+libb10_dhcp___la_SOURCES += option_data_types.h
+libb10_dhcp___la_SOURCES += option_definition.cc option_definition.h
libb10_dhcp___la_SOURCES += option6_ia.cc option6_ia.h
libb10_dhcp___la_SOURCES += option6_iaaddr.cc option6_iaaddr.h
libb10_dhcp___la_SOURCES += option6_addrlst.cc option6_addrlst.h
libb10_dhcp___la_SOURCES += option4_addrlst.cc option4_addrlst.h
+libb10_dhcp___la_SOURCES += option6_int.h
+libb10_dhcp___la_SOURCES += option6_int_array.h
libb10_dhcp___la_SOURCES += dhcp6.h dhcp4.h
libb10_dhcp___la_SOURCES += pkt6.cc pkt6.h
libb10_dhcp___la_SOURCES += pkt4.cc pkt4.h
+libb10_dhcp___la_SOURCES += duid.cc duid.h
+
+libb10_dhcpsrv_la_SOURCES = cfgmgr.cc cfgmgr.h
+libb10_dhcpsrv_la_SOURCES += pool.cc pool.h
+libb10_dhcpsrv_la_SOURCES += subnet.cc subnet.h
+libb10_dhcpsrv_la_SOURCES += triplet.h
+libb10_dhcpsrv_la_SOURCES += lease_mgr.cc lease_mgr.h
+libb10_dhcpsrv_la_SOURCES += addr_utilities.cc addr_utilities.h
+libb10_dhcpsrv_la_SOURCES += alloc_engine.cc alloc_engine.h
+libb10_dhcpsrv_la_CXXFLAGS = $(AM_CXXFLAGS)
+libb10_dhcpsrv_la_CPPFLAGS = $(AM_CPPFLAGS) $(LOG4CPLUS_INCLUDES)
+libb10_dhcpsrv_la_LIBADD = $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
+libb10_dhcpsrv_la_LIBADD += $(top_builddir)/src/lib/util/libb10-util.la
+libb10_dhcpsrv_la_LDFLAGS = -no-undefined -version-info 2:0:0
EXTRA_DIST = README
-#EXTRA_DIST += log_messages.mes
libb10_dhcp___la_CXXFLAGS = $(AM_CXXFLAGS)
libb10_dhcp___la_CPPFLAGS = $(AM_CPPFLAGS) $(LOG4CPLUS_INCLUDES)
diff --git a/src/lib/dhcp/README b/src/lib/dhcp/README
index 6bd6384..c5e70f2 100644
--- a/src/lib/dhcp/README
+++ b/src/lib/dhcp/README
@@ -1,11 +1,9 @@
-This directory holds implementation for libdhcp++.
+This directory holds implementation for DHCP libraries:
+libdhcp++ - this is a generic purpose DHCP library. Please be careful
+what is put here. It is going to be shared by various servers (the "regular"
+one and the embedded as well), clients, relays and performance tools.
-Basic Ideas
-===========
+libdhcpsrv - Server specific code goes in here. It will be used by
+dhcp4 and dhcp6 server.
-
-Notes
-=====
-This work just begun. Don't expect to see much useful code here.
-We are working on it.
diff --git a/src/lib/dhcp/addr_utilities.cc b/src/lib/dhcp/addr_utilities.cc
new file mode 100644
index 0000000..de1e8b4
--- /dev/null
+++ b/src/lib/dhcp/addr_utilities.cc
@@ -0,0 +1,181 @@
+// 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 <string.h>
+#include <exceptions/exceptions.h>
+#include <dhcp/addr_utilities.h>
+
+using namespace isc::asiolink;
+
+namespace {
+
+/// @brief mask used for first/last address calculation in a IPv4 prefix
+///
+/// Using a static mask is faster than calculating it dynamically every time.
+const uint32_t bitMask4[] = { 0xffffffff, 0x7fffffff, 0x3fffffff, 0x1fffffff,
+ 0x0fffffff, 0x07ffffff, 0x03ffffff, 0x01ffffff,
+ 0x00ffffff, 0x007fffff, 0x003fffff, 0x001fffff,
+ 0x000fffff, 0x0007ffff, 0x0003ffff, 0x0001ffff,
+ 0x0000ffff, 0x00007fff, 0x00003fff, 0x00001fff,
+ 0x00000fff, 0x000007ff, 0x000003ff, 0x000001ff,
+ 0x000000ff, 0x0000007f, 0x0000003f, 0x0000001f,
+ 0x0000000f, 0x00000007, 0x00000003, 0x00000001,
+ 0x00000000 };
+
+/// @brief mask used for first/last address calculation in a IPv6 prefix
+const uint8_t bitMask6[]= { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
+
+/// @brief calculates the first IPv6 address in a IPv6 prefix
+///
+/// Note: This is a private function. Do not use it directly.
+/// Please use firstAddrInPrefix() instead.
+///
+/// @param prefix IPv6 prefix
+/// @param len prefix length
+isc::asiolink::IOAddress firstAddrInPrefix6(const isc::asiolink::IOAddress& prefix,
+ uint8_t len) {
+
+ uint8_t packed[V6ADDRESS_LEN];
+
+ // First we copy the whole address as 16 bytes.
+ memcpy(packed, prefix.getAddress().to_v6().to_bytes().data(), 16);
+
+ // If the length is divisible by 8, it is simple. We just zero out the host
+ // part. Otherwise we need to handle the byte that has to be partially
+ // zeroed.
+ if (len % 8 != 0) {
+
+ // Get the appropriate mask. It has relevant bits (those that should
+ // stay) set and irrelevant (those that should be wiped) cleared.
+ uint8_t mask = bitMask6[len % 8];
+
+ // Let's leave only whatever the mask says should not be cleared.
+ packed[len / 8] = packed[len / 8] & mask;
+
+ // Since we have just dealt with this byte, let's move the prefix length
+ // to the beginning of the next byte (len is expressed in bits).
+ len = (len / 8 + 1) * 8;
+ }
+
+ // Clear out the remaining bits.
+ for (int i = len / 8; i < sizeof(packed); ++i) {
+ packed[i] = 0x0;
+ }
+
+ // Finally, let's wrap this into nice and easy IOAddress object.
+ return (isc::asiolink::IOAddress::from_bytes(AF_INET6, packed));
+}
+
+/// @brief calculates the first IPv4 address in a IPv4 prefix
+///
+/// Note: This is a private function. Do not use it directly.
+/// Please use firstAddrInPrefix() instead.
+///
+/// @param prefix IPv4 prefix
+/// @param len netmask length (0-32)
+isc::asiolink::IOAddress firstAddrInPrefix4(const isc::asiolink::IOAddress& prefix,
+ uint8_t len) {
+ uint32_t addr = prefix;
+ if (len > 32) {
+ isc_throw(isc::BadValue, "Too large netmask. 0..32 is allowed in IPv4");
+ }
+
+ return (IOAddress(addr & (~bitMask4[len])));
+}
+
+/// @brief calculates the last IPv4 address in a IPv4 prefix
+///
+/// Note: This is a private function. Do not use it directly.
+/// Please use firstAddrInPrefix() instead.
+///
+/// @param prefix IPv4 prefix that we calculate first address for
+/// @param len netmask length (0-32)
+isc::asiolink::IOAddress lastAddrInPrefix4(const isc::asiolink::IOAddress& prefix,
+ uint8_t len) {
+ uint32_t addr = prefix;
+ if (len>32) {
+ isc_throw(isc::BadValue, "Too large netmask. 0..32 is allowed in IPv4");
+ }
+
+ return (IOAddress(addr | bitMask4[len]));
+}
+
+/// @brief calculates the last IPv6 address in a IPv6 prefix
+///
+/// Note: This is a private function. Do not use it directly.
+/// Please use lastAddrInPrefix() instead.
+///
+/// @param prefix IPv6 prefix that we calculate first address for
+/// @param len netmask length (0-128)
+isc::asiolink::IOAddress lastAddrInPrefix6(const isc::asiolink::IOAddress& prefix,
+ uint8_t len) {
+
+ uint8_t packed[V6ADDRESS_LEN];
+
+ // First we copy the whole address as 16 bytes.
+ memcpy(packed, prefix.getAddress().to_v6().to_bytes().data(), 16);
+
+ // if the length is divisible by 8, it is simple. We just fill the host part
+ // with ones. Otherwise we need to handle the byte that has to be partially
+ // zeroed.
+ if (len % 8 != 0) {
+ // Get the appropriate mask. It has relevant bits (those that should
+ // stay) set and irrelevant (those that should be set to 1) cleared.
+ uint8_t mask = bitMask6[len % 8];
+
+ // Let's set those irrelevant bits with 1. It would be perhaps
+ // easier to not use negation here and invert bitMask6 content. However,
+ // with this approach, we can use the same mask in first and last
+ // address calculations.
+ packed[len / 8] = packed[len / 8] | ~mask;
+
+ // Since we have just dealt with this byte, let's move the prefix length
+ // to the beginning of the next byte (len is expressed in bits).
+ len = (len / 8 + 1) * 8;
+ }
+
+ // Finally set remaining bits to 1.
+ for (int i = len / 8; i < sizeof(packed); ++i) {
+ packed[i] = 0xff;
+ }
+
+ // Finally, let's wrap this into nice and easy IOAddress object.
+ return (isc::asiolink::IOAddress::from_bytes(AF_INET6, packed));
+}
+
+}; // end of anonymous namespace
+
+namespace isc {
+namespace dhcp {
+
+isc::asiolink::IOAddress firstAddrInPrefix(const isc::asiolink::IOAddress& prefix,
+ uint8_t len) {
+ if (prefix.getFamily() == AF_INET) {
+ return firstAddrInPrefix4(prefix, len);
+ } else {
+ return firstAddrInPrefix6(prefix, len);
+ }
+}
+
+isc::asiolink::IOAddress lastAddrInPrefix(const isc::asiolink::IOAddress& prefix,
+ uint8_t len) {
+ if (prefix.getFamily() == AF_INET) {
+ return lastAddrInPrefix4(prefix, len);
+ } else {
+ return lastAddrInPrefix6(prefix, len);
+ }
+}
+
+};
+};
diff --git a/src/lib/dhcp/addr_utilities.h b/src/lib/dhcp/addr_utilities.h
new file mode 100644
index 0000000..15532d0
--- /dev/null
+++ b/src/lib/dhcp/addr_utilities.h
@@ -0,0 +1,53 @@
+// 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 <asiolink/io_address.h>
+
+namespace isc {
+namespace dhcp {
+
+/// This code is based on similar code from the Dibbler project. I, Tomasz Mrugalski,
+/// as a sole creator of that code hereby release it under BSD license for the benefit
+/// of the BIND10 project.
+
+/// @brief returns a first address in a given prefix
+///
+/// Example: For 2001:db8:1::deaf:beef and length /120 the function will return
+/// 2001:db8:1::dead:be00. See also @ref lastAddrInPrefix.
+///
+/// @todo It currently works for v6 only and will throw if v4 address is passed.
+///
+/// @param prefix and address that belongs to a prefix
+/// @param len prefix length
+///
+/// @return first address from a prefix
+isc::asiolink::IOAddress firstAddrInPrefix(const isc::asiolink::IOAddress& prefix,
+ uint8_t len);
+
+/// @brief returns a last address in a given prefix
+///
+/// Example: For 2001:db8:1::deaf:beef and length /112 the function will return
+/// 2001:db8:1::dead:ffff. See also @ref firstAddrInPrefix.
+///
+/// @todo It currently works for v6 only and will throw if v4 address is passed.
+///
+/// @param prefix and address that belongs to a prefix
+/// @param len prefix length
+///
+/// @return first address from a prefix
+isc::asiolink::IOAddress lastAddrInPrefix(const isc::asiolink::IOAddress& prefix,
+ uint8_t len);
+
+};
+};
diff --git a/src/lib/dhcp/alloc_engine.cc b/src/lib/dhcp/alloc_engine.cc
new file mode 100644
index 0000000..8ebefdc
--- /dev/null
+++ b/src/lib/dhcp/alloc_engine.cc
@@ -0,0 +1,274 @@
+// 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 <alloc_engine.h>
+
+#include <cstring>
+
+using namespace isc::asiolink;
+
+namespace isc {
+namespace dhcp {
+
+AllocEngine::IterativeAllocator::IterativeAllocator()
+ :Allocator() {
+}
+
+isc::asiolink::IOAddress
+AllocEngine::IterativeAllocator::increaseAddress(const isc::asiolink::IOAddress& addr) {
+ uint8_t packed[V6ADDRESS_LEN];
+ int len;
+
+ // First we copy the whole address as 16 bytes.
+ if (addr.getFamily()==AF_INET) {
+ // IPv4
+ std::memcpy(packed, addr.getAddress().to_v4().to_bytes().data(), 4);
+ len = 4;
+ } else {
+ // IPv6
+ std::memcpy(packed, addr.getAddress().to_v6().to_bytes().data(), 16);
+ len = 16;
+ }
+
+ for (int i = len - 1; i >= 0; --i) {
+ ++packed[i];
+ if (packed[i] != 0) {
+ break;
+ }
+ }
+
+ return (IOAddress::from_bytes(addr.getFamily(), packed));
+}
+
+
+isc::asiolink::IOAddress
+AllocEngine::IterativeAllocator::pickAddress(const Subnet6Ptr& subnet,
+ const DuidPtr&,
+ const IOAddress&) {
+
+ // Let's get the last allocated address. It is usually set correctly,
+ // but there are times when it won't be (like after removing a pool or
+ // perhaps restaring the server).
+ IOAddress last = subnet->getLastAllocated();
+
+ const Pool6Collection& pools = subnet->getPools();
+
+ if (pools.size() == 0) {
+ isc_throw(AllocFailed, "No pools defined in selected subnet");
+ }
+
+ // first we need to find a pool the last address belongs to.
+ Pool6Collection::const_iterator it;
+ for (it = pools.begin(); it != pools.end(); ++it) {
+ if ((*it)->inRange(last)) {
+ break;
+ }
+ }
+
+ // last one was bogus for one of several reasons:
+ // - we just booted up and that's the first address we're allocating
+ // - a subnet was removed or other reconfiguration just completed
+ // - perhaps allocation algorithm was changed
+ if (it == pools.end()) {
+ // ok to access first element directly. We checked that pools is non-empty
+ IOAddress next = pools[0]->getFirstAddress();
+ subnet->setLastAllocated(next);
+ return (next);
+ }
+
+ // Ok, we have a pool that the last address belonged to, let's use it.
+
+ IOAddress next = increaseAddress(last); // basically addr++
+ if ((*it)->inRange(next)) {
+ // the next one is in the pool as well, so we haven't hit pool boundary yet
+ subnet->setLastAllocated(next);
+ return (next);
+ }
+
+ // We hit pool boundary, let's try to jump to the next pool and try again
+ ++it;
+ if (it == pools.end()) {
+ // Really out of luck today. That was the last pool. Let's rewind
+ // to the beginning.
+ next = pools[0]->getFirstAddress();
+ subnet->setLastAllocated(next);
+ return (next);
+ }
+
+ // there is a next pool, let's try first adddress from it
+ next = (*it)->getFirstAddress();
+ subnet->setLastAllocated(next);
+ return (next);
+}
+
+AllocEngine::HashedAllocator::HashedAllocator()
+ :Allocator() {
+ isc_throw(NotImplemented, "Hashed allocator is not implemented");
+}
+
+
+isc::asiolink::IOAddress
+AllocEngine::HashedAllocator::pickAddress(const Subnet6Ptr&,
+ const DuidPtr&,
+ const IOAddress&) {
+ isc_throw(NotImplemented, "Hashed allocator is not implemented");
+}
+
+AllocEngine::RandomAllocator::RandomAllocator()
+ :Allocator() {
+ isc_throw(NotImplemented, "Random allocator is not implemented");
+}
+
+
+isc::asiolink::IOAddress
+AllocEngine::RandomAllocator::pickAddress(const Subnet6Ptr&,
+ const DuidPtr&,
+ const IOAddress&) {
+ isc_throw(NotImplemented, "Random allocator is not implemented");
+}
+
+
+AllocEngine::AllocEngine(AllocType engine_type, unsigned int attempts)
+ :attempts_(attempts) {
+ switch (engine_type) {
+ case ALLOC_ITERATIVE:
+ allocator_ = boost::shared_ptr<Allocator>(new IterativeAllocator());
+ break;
+ case ALLOC_HASHED:
+ allocator_ = boost::shared_ptr<Allocator>(new HashedAllocator());
+ break;
+ case ALLOC_RANDOM:
+ allocator_ = boost::shared_ptr<Allocator>(new RandomAllocator());
+ break;
+
+ default:
+ isc_throw(BadValue, "Invalid/unsupported allocation algorithm");
+ }
+}
+
+Lease6Ptr
+AllocEngine::allocateAddress6(const Subnet6Ptr& subnet,
+ const DuidPtr& duid,
+ uint32_t iaid,
+ const IOAddress& hint,
+ bool fake_allocation /* = false */ ) {
+
+ // That check is not necessary. We create allocator in AllocEngine
+ // constructor
+ if (!allocator_) {
+ isc_throw(InvalidOperation, "No allocator selected");
+ }
+
+ // check if there's existing lease for that subnet/duid/iaid combination.
+ Lease6Ptr existing = LeaseMgr::instance().getLease6(*duid, iaid, subnet->getID());
+ if (existing) {
+ // we have a lease already. This is a returning client, probably after
+ // his reboot.
+ return (existing);
+ }
+
+ // check if the hint is in pool and is available
+ if (subnet->inPool(hint)) {
+ existing = LeaseMgr::instance().getLease6(hint);
+ if (!existing) {
+ /// @todo: check if the hint is reserved once we have host support
+ /// implemented
+
+ // the hint is valid and not currently used, let's create a lease for it
+ Lease6Ptr lease = createLease(subnet, duid, iaid, hint, fake_allocation);
+
+ // It can happen that the lease allocation failed (we could have lost
+ // the race condition. That means that the hint is lo longer usable and
+ // we need to continue the regular allocation path.
+ if (lease) {
+ return (lease);
+ }
+ }
+ }
+
+ unsigned int i = attempts_;
+ do {
+ IOAddress candidate = allocator_->pickAddress(subnet, duid, hint);
+
+ /// @todo: check if the address is reserved once we have host support
+ /// implemented
+
+ Lease6Ptr existing = LeaseMgr::instance().getLease6(candidate);
+ // there's no existing lease for selected candidate, so it is
+ // free. Let's allocate it.
+ if (!existing) {
+ Lease6Ptr lease = createLease(subnet, duid, iaid, candidate,
+ fake_allocation);
+ if (lease) {
+ return (lease);
+ }
+
+ // Although the address was free just microseconds ago, it may have
+ // been taken just now. If the lease insertion fails, we continue
+ // allocation attempts.
+ }
+
+ // continue trying allocation until we run out of attempts
+ // (or attempts are set to 0, which means infinite)
+ --i;
+ } while ( i || !attempts_);
+
+ isc_throw(AllocFailed, "Failed to allocate address after " << attempts_
+ << " tries");
+}
+
+Lease6Ptr AllocEngine::createLease(const Subnet6Ptr& subnet,
+ const DuidPtr& duid,
+ uint32_t iaid,
+ const IOAddress& addr,
+ bool fake_allocation /*= false */ ) {
+
+ Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr, duid, iaid,
+ subnet->getPreferred(), subnet->getValid(),
+ subnet->getT1(), subnet->getT2(), subnet->getID()));
+
+ if (!fake_allocation) {
+ // That is a real (REQUEST) allocation
+ bool status = LeaseMgr::instance().addLease(lease);
+
+ if (status) {
+
+ return (lease);
+ } else {
+ // One of many failures with LeaseMgr (e.g. lost connection to the
+ // database, database failed etc.). One notable case for that
+ // is that we are working in multi-process mode and we lost a race
+ // (some other process got that address first)
+ return (Lease6Ptr());
+ }
+ } else {
+ // That is only fake (SOLICIT without rapid-commit) allocation
+
+ // It is for advertise only. We should not insert the lease into LeaseMgr,
+ // but rather check that we could have inserted it.
+ Lease6Ptr existing = LeaseMgr::instance().getLease6(addr);
+ if (!existing) {
+ return (lease);
+ } else {
+ return (Lease6Ptr());
+ }
+ }
+}
+
+AllocEngine::~AllocEngine() {
+ // no need to delete allocator. smart_ptr will do the trick for us
+}
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
diff --git a/src/lib/dhcp/alloc_engine.h b/src/lib/dhcp/alloc_engine.h
new file mode 100644
index 0000000..496703a
--- /dev/null
+++ b/src/lib/dhcp/alloc_engine.h
@@ -0,0 +1,228 @@
+// 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 ALLOC_ENGINE_H
+#define ALLOC_ENGINE_H
+
+#include <boost/shared_ptr.hpp>
+#include <boost/noncopyable.hpp>
+#include <dhcp/duid.h>
+#include <dhcp/subnet.h>
+#include <asiolink/io_address.h>
+#include <dhcp/lease_mgr.h>
+
+namespace isc {
+namespace dhcp {
+
+/// An exception that is thrown when allocation module fails (e.g. due to
+/// lack of available addresses)
+class AllocFailed : public isc::Exception {
+public:
+
+ /// @brief constructor
+ ///
+ /// @param file name of the file, where exception occurred
+ /// @param line line of the file, where exception occurred
+ /// @param what text description of the issue that caused exception
+ AllocFailed(const char* file, size_t line, const char* what)
+ : isc::Exception(file, line, what) {}
+};
+
+/// @brief DHCPv4 and DHCPv6 allocation engine
+///
+/// This class represents DHCP allocation engine. It is responsible
+/// for picking subnets, choosing and allocating a lease, extending,
+/// renewing, releasing and possibly expiring leases.
+///
+/// @todo: Does not handle out of leases well
+/// @todo: Does not handle out of allocation attempts well
+class AllocEngine : public boost::noncopyable {
+protected:
+
+ /// @brief base class for all address/prefix allocation algorithms
+ ///
+ /// This is an abstract class that should not be used directly, but rather
+ /// specialized implementations should be used instead.
+ class Allocator {
+ public:
+
+ /// @brief picks one address out of available pools in a given subnet
+ ///
+ /// This method returns one address from the available pools in the
+ /// specified subnet. It should not check if the address is used or
+ /// reserved - AllocEngine will check that and will call pickAddress
+ /// again if necessary. The number of times this method is called will
+ /// increase as the number of available leases will decrease.
+ virtual isc::asiolink::IOAddress
+ pickAddress(const Subnet6Ptr& subnet, const DuidPtr& duid,
+ const isc::asiolink::IOAddress& hint) = 0;
+
+ /// @brief virtual destructor
+ virtual ~Allocator() {
+ }
+ protected:
+ };
+
+ /// @brief Address/prefix allocator that iterates over all addresses
+ ///
+ /// This class implements iterative algorithm that returns all addresses in
+ /// a pool iteratively, one after another. Once the last address is reached,
+ /// it starts allocating from the beginning of the first pool (i.e. it loops
+ /// over).
+ class IterativeAllocator : public Allocator {
+ public:
+
+ /// @brief default constructor
+ ///
+ /// Does not do anything
+ IterativeAllocator();
+
+ /// @brief returns the next address from pools in a subnet
+ ///
+ /// @param subnet next address will be returned from pool of that subnet
+ /// @param duid Client's DUID (ignored)
+ /// @param hint client's hint (ignored)
+ /// @return the next address
+ virtual isc::asiolink::IOAddress
+ pickAddress(const Subnet6Ptr& subnet,
+ const DuidPtr& duid,
+ const isc::asiolink::IOAddress& hint);
+ private:
+
+ /// @brief returns an address by one
+ /// @param addr address to be increased
+ /// @return address increased by one
+ isc::asiolink::IOAddress increaseAddress(const isc::asiolink::IOAddress& addr);
+
+ };
+
+ /// @brief Address/prefix allocator that gets an address based on a hash
+ ///
+ /// @todo: This is a skeleton class for now and is missing implementation.
+ class HashedAllocator : public Allocator {
+ public:
+
+ /// @brief default constructor (does nothing)
+ HashedAllocator();
+
+ /// @brief returns an address based on hash calculated from client's DUID.
+ ///
+ /// @todo: Implement this method
+ ///
+ /// @param subnet an address will be picked from pool of that subnet
+ /// @param duid Client's DUID
+ /// @param hint a hint (last address that was picked)
+ /// @return selected address
+ virtual isc::asiolink::IOAddress pickAddress(const Subnet6Ptr& subnet,
+ const DuidPtr& duid,
+ const isc::asiolink::IOAddress& hint);
+ };
+
+ /// @brief Random allocator that picks address randomly
+ ///
+ /// @todo: This is a skeleton class for now and is missing implementation.
+ class RandomAllocator : public Allocator {
+ public:
+
+ /// @brief default constructor (does nothing)
+ RandomAllocator();
+
+ /// @brief returns an random address from pool of specified subnet
+ ///
+ /// @todo: Implement this method
+ ///
+ /// @param subnet an address will be picked from pool of that subnet
+ /// @param duid Client's DUID (ignored)
+ /// @param hint the last address that was picked (ignored)
+ /// @return a random address from the pool
+ virtual isc::asiolink::IOAddress
+ pickAddress(const Subnet6Ptr& subnet, const DuidPtr& duid,
+ const isc::asiolink::IOAddress& hint);
+ };
+
+ public:
+
+ /// @brief specifies allocation type
+ typedef enum {
+ ALLOC_ITERATIVE, // iterative - one address after another
+ ALLOC_HASHED, // hashed - client's DUID/client-id is hashed
+ ALLOC_RANDOM // random - an address is randomly selected
+ } AllocType;
+
+
+ /// @brief Default constructor.
+ ///
+ /// Instantiates necessary services, required to run DHCPv6 server.
+ /// In particular, creates IfaceMgr that will be responsible for
+ /// network interaction. Will instantiate lease manager, and load
+ /// old or create new DUID.
+ ///
+ /// @param engine_type selects allocation algorithm
+ /// @param attempts number of attempts for each lease allocation before
+ /// we give up (0 means unlimited)
+ AllocEngine(AllocType engine_type, unsigned int attempts);
+
+ /// @brief Allocates an IPv6 lease
+ ///
+ /// This method uses currently selected allocator to pick an address from
+ /// specified subnet, creates a lease for that address and then inserts
+ /// it into LeaseMgr (if this allocation is not fake).
+ ///
+ /// @param subnet subnet the allocation should come from
+ /// @param duid Client'd DUID
+ /// @param iaid iaid field from the IA_NA container that client sent
+ /// @param hint a hint that the client provided
+ /// @param fake_allocation is this real i.e. REQUEST (false) or just picking
+ /// an address for SOLICIT that is not really allocated (true)
+ /// @return Allocated IPv6 lease (or NULL if allocation failed)
+ Lease6Ptr
+ allocateAddress6(const Subnet6Ptr& subnet,
+ const DuidPtr& duid,
+ uint32_t iaid,
+ const isc::asiolink::IOAddress& hint,
+ bool fake_allocation);
+
+ /// @brief Destructor. Used during DHCPv6 service shutdown.
+ virtual ~AllocEngine();
+private:
+
+ /// @brief creates a lease and inserts it in LeaseMgr if necessary
+ ///
+ /// Creates a lease based on specified parameters and tries to insert it
+ /// into the database. That may fail in some cases, i.e. when there is another
+ /// allocation process and we lost a race to a specific lease.
+ ///
+ /// @param subnet subnet the lease is allocated from
+ /// @param duid client's DUID
+ /// @param iaid IAID from the IA_NA container the client sent to us
+ /// @param addr an address that was selected and is confirmed to be available
+ /// @param fake_allocation is this real i.e. REQUEST (false) or just picking
+ /// an address for SOLICIT that is not really allocated (true)
+ /// @return allocated lease (or NULL in the unlikely case of the lease just
+ /// becomed unavailable)
+ Lease6Ptr createLease(const Subnet6Ptr& subnet, const DuidPtr& duid,
+ uint32_t iaid, const isc::asiolink::IOAddress& addr,
+ bool fake_allocation = false);
+
+ /// @brief a pointer to currently used allocator
+ boost::shared_ptr<Allocator> allocator_;
+
+ /// @brief number of attempts before we give up lease allocation (0=unlimited)
+ unsigned int attempts_;
+};
+
+}; // namespace isc::dhcp
+}; // namespace isc
+
+#endif // ALLOC_ENGINE_H
diff --git a/src/lib/dhcp/cfgmgr.cc b/src/lib/dhcp/cfgmgr.cc
new file mode 100644
index 0000000..d06544c
--- /dev/null
+++ b/src/lib/dhcp/cfgmgr.cc
@@ -0,0 +1,111 @@
+// 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 <asiolink/io_address.h>
+#include <dhcp/cfgmgr.h>
+
+using namespace isc::asiolink;
+using namespace isc::util;
+
+namespace isc {
+namespace dhcp {
+
+
+
+
+CfgMgr&
+CfgMgr::instance() {
+ static CfgMgr cfg_mgr;
+ return (cfg_mgr);
+}
+
+Subnet6Ptr
+CfgMgr::getSubnet6(const isc::asiolink::IOAddress& hint) {
+
+ // If there's only one subnet configured, let's just use it
+ // The idea is to keep small deployments easy. In a small network - one
+ // router that also runs DHCPv6 server. Users specifies a single pool and
+ // expects it to just work. Without this, the server would complain that it
+ // doesn't have IP address on its interfaces that matches that
+ // configuration. Such requirement makes sense in IPv4, but not in IPv6.
+ // The server does not need to have a global address (using just link-local
+ // is ok for DHCPv6 server) from the pool it serves.
+ if (subnets6_.size() == 1) {
+ return (subnets6_[0]);
+ }
+
+ // If there is more than one, we need to choose the proper one
+ for (Subnet6Collection::iterator subnet = subnets6_.begin();
+ subnet != subnets6_.end(); ++subnet) {
+ if ((*subnet)->inRange(hint)) {
+ return (*subnet);
+ }
+ }
+
+ // sorry, we don't support that subnet
+ return (Subnet6Ptr());
+}
+
+Subnet6Ptr CfgMgr::getSubnet6(OptionPtr /*interfaceId*/) {
+ /// @todo: Implement get subnet6 by interface-id (for relayed traffic)
+ isc_throw(NotImplemented, "Relayed DHCPv6 traffic is not supported yet.");
+}
+
+void CfgMgr::addSubnet6(const Subnet6Ptr& subnet) {
+ /// @todo: Check that this new subnet does not cross boundaries of any
+ /// other already defined subnet.
+ subnets6_.push_back(subnet);
+}
+
+Subnet4Ptr
+CfgMgr::getSubnet4(const isc::asiolink::IOAddress& hint) {
+
+ // If there's only one subnet configured, let's just use it
+ // The idea is to keep small deployments easy. In a small network - one
+ // router that also runs DHCPv6 server. Users specifies a single pool and
+ // expects it to just work. Without this, the server would complain that it
+ // doesn't have IP address on its interfaces that matches that
+ // configuration. Such requirement makes sense in IPv4, but not in IPv6.
+ // The server does not need to have a global address (using just link-local
+ // is ok for DHCPv6 server) from the pool it serves.
+ if (subnets4_.size() == 1) {
+ return (subnets4_[0]);
+ }
+
+ // If there is more than one, we need to choose the proper one
+ for (Subnet4Collection::iterator subnet = subnets4_.begin();
+ subnet != subnets4_.end(); ++subnet) {
+ if ((*subnet)->inRange(hint)) {
+ return (*subnet);
+ }
+ }
+
+ // sorry, we don't support that subnet
+ return (Subnet4Ptr());
+}
+
+void CfgMgr::addSubnet4(const Subnet4Ptr& subnet) {
+ /// @todo: Check that this new subnet does not cross boundaries of any
+ /// other already defined subnet.
+ subnets4_.push_back(subnet);
+}
+
+CfgMgr::CfgMgr() {
+}
+
+CfgMgr::~CfgMgr() {
+}
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
diff --git a/src/lib/dhcp/cfgmgr.h b/src/lib/dhcp/cfgmgr.h
new file mode 100644
index 0000000..2911d05
--- /dev/null
+++ b/src/lib/dhcp/cfgmgr.h
@@ -0,0 +1,165 @@
+// 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 CFGMGR_H
+#define CFGMGR_H
+
+#include <string>
+#include <map>
+#include <vector>
+#include <boost/shared_ptr.hpp>
+#include <boost/noncopyable.hpp>
+#include <asiolink/io_address.h>
+#include <util/buffer.h>
+#include <dhcp/option.h>
+#include <dhcp/pool.h>
+#include <dhcp/subnet.h>
+
+namespace isc {
+namespace dhcp {
+
+
+/// @brief Configuration Manager
+///
+/// This singleton class holds the whole configuration for DHCPv4 and DHCPv6
+/// servers. It currently holds information about zero or more subnets6.
+/// Each subnet may contain zero or more pools. Pool4 and Pool6 is the most
+/// basic "chunk" of configuration. It contains a range of assigneable
+/// addresses.
+///
+/// Below is a sketch of configuration inheritance (not implemented yet).
+/// Let's investigate the following configuration:
+///
+/// preferred-lifetime 500;
+/// valid-lifetime 1000;
+/// subnet6 2001:db8:1::/48 {
+/// pool6 2001::db8:1::1 - 2001::db8:1::ff;
+/// };
+/// subnet6 2001:db8:2::/48 {
+/// valid-lifetime 2000;
+/// pool6 2001::db8:2::1 - 2001::db8:2::ff;
+/// };
+/// Parameters defined in a global scope are applicable to everything until
+/// they are overwritten in a smaller scope, in this case subnet6.
+/// In the example above, the first subnet6 has preferred lifetime of 500s
+/// and a valid lifetime of 1000s. The second subnet has preferred lifetime
+/// of 500s, but valid lifetime of 2000s.
+///
+/// Parameter inheritance is likely to be implemented in configuration handling
+/// routines, so there is no storage capability in a global scope for
+/// subnet-specific parameters.
+///
+/// @todo: Implement Subnet4 support (ticket #2237)
+/// @todo: Implement option definition support
+/// @todo: Implement parameter inheritance
+class CfgMgr : public boost::noncopyable {
+public:
+
+ /// @brief returns a single instance of Configuration Manager
+ ///
+ /// CfgMgr is a singleton and this method is the only way of
+ /// accessing it.
+ static CfgMgr& instance();
+
+ /// @brief get IPv6 subnet by address
+ ///
+ /// Finds a matching subnet, based on an address. This can be used
+ /// in two cases: when trying to find an appropriate lease based on
+ /// a) relay link address (that must be the address that is on link)
+ /// b) our global address on the interface the message was received on
+ /// (for directly connected clients)
+ ///
+ /// @param hint an address that belongs to a searched subnet
+ Subnet6Ptr getSubnet6(const isc::asiolink::IOAddress& hint);
+
+ /// @brief get IPv6 subnet by interface-id
+ ///
+ /// Another possibility to find a subnet is based on interface-id.
+ ///
+ /// @param interface_id content of interface-id option returned by a relay
+ /// @todo This method is not currently supported.
+ Subnet6Ptr getSubnet6(OptionPtr interface_id);
+
+ /// @brief adds an IPv6 subnet
+ void addSubnet6(const Subnet6Ptr& subnet);
+
+ /// @todo: Add subnet6 removal routines. Currently it is not possible
+ /// to remove subnets. The only case where subnet6 removal would be
+ /// needed is a dynamic server reconfiguration - a use case that is not
+ /// planned to be supported any time soon.
+
+ /// @brief removes all subnets
+ ///
+ /// This method removes all existing subnets. It is used during
+ /// reconfiguration - old configuration is wiped and new definitions
+ /// are used to recreate subnets.
+ ///
+ /// @todo Implement more intelligent approach. Note that comparison
+ /// between old and new configuration is tricky. For example: is
+ /// 2000::/64 and 2000::/48 the same subnet or is it something
+ /// completely new?
+ void deleteSubnets6() {
+ subnets6_.clear();
+ }
+
+ /// @brief get IPv4 subnet by address
+ ///
+ /// Finds a matching subnet, based on an address. This can be used
+ /// in two cases: when trying to find an appropriate lease based on
+ /// a) relay link address (that must be the address that is on link)
+ /// b) our global address on the interface the message was received on
+ /// (for directly connected clients)
+ ///
+ /// @param hint an address that belongs to a searched subnet
+ Subnet4Ptr getSubnet4(const isc::asiolink::IOAddress& hint);
+
+ /// @brief adds a subnet4
+ void addSubnet4(const Subnet4Ptr& subnet);
+
+ /// @brief removes all IPv4 subnets
+ void removeSubnets4();
+protected:
+
+ /// @brief Protected constructor.
+ ///
+ /// This constructor is protected for 2 reasons. First, it forbids any
+ /// instantiations of this class (CfgMgr is a singleton). Second, it
+ /// allows derived class to instantiate it. That is useful for testing
+ /// purposes.
+ CfgMgr();
+
+ /// @brief virtual desctructor
+ virtual ~CfgMgr();
+
+ /// @brief a container for IPv6 subnets.
+ ///
+ /// That is a simple vector of pointers. It does not make much sense to
+ /// optimize access time (e.g. using a map), because typical search
+ /// pattern will use calling inRange() method on each subnet until
+ /// a match is found.
+ Subnet6Collection subnets6_;
+
+ /// @brief a container for IPv4 subnets.
+ ///
+ /// That is a simple vector of pointers. It does not make much sense to
+ /// optimize access time (e.g. using a map), because typical search
+ /// pattern will use calling inRange() method on each subnet until
+ /// a match is found.
+ Subnet4Collection subnets4_;
+};
+
+} // namespace isc::dhcp
+} // namespace isc
+
+#endif
diff --git a/src/lib/dhcp/duid.cc b/src/lib/dhcp/duid.cc
new file mode 100644
index 0000000..db7ba25
--- /dev/null
+++ b/src/lib/dhcp/duid.cc
@@ -0,0 +1,90 @@
+// 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 <vector>
+#include <exceptions/exceptions.h>
+#include <stdint.h>
+#include <util/io_utilities.h>
+#include <dhcp/duid.h>
+
+namespace isc {
+namespace dhcp {
+
+DUID::DUID(const std::vector<uint8_t>& duid) {
+ if (duid.size() > MAX_DUID_LEN) {
+ isc_throw(OutOfRange, "DUID too large");
+ } else {
+ duid_ = duid;
+ }
+}
+
+DUID::DUID(const uint8_t * data, size_t len) {
+ if (len > MAX_DUID_LEN) {
+ isc_throw(OutOfRange, "DUID too large");
+ }
+
+ duid_ = std::vector<uint8_t>(data, data + len);
+}
+
+const std::vector<uint8_t> DUID::getDuid() const {
+ return (duid_);
+}
+
+DUID::DUIDType DUID::getType() const {
+ if (duid_.size() < 2) {
+ return (DUID_UNKNOWN);
+ }
+ uint16_t type = (duid_[0] << 8) + duid_[1];
+ if (type < DUID_MAX) {
+ return (static_cast<DUID::DUIDType>(type));
+ } else {
+ return (DUID_UNKNOWN);
+ }
+}
+
+bool DUID::operator == (const DUID& other) const {
+ return (this->duid_ == other.duid_);
+}
+
+bool DUID::operator != (const DUID& other) const {
+ return (this->duid_ != other.duid_);
+}
+
+/// constructor based on vector<uint8_t>
+ClientId::ClientId(const std::vector<uint8_t>& clientid)
+ :DUID(clientid) {
+}
+
+/// constructor based on C-style data
+ClientId::ClientId(const uint8_t *clientid, size_t len)
+ :DUID(clientid, len) {
+}
+
+/// @brief returns a copy of client-id data
+const std::vector<uint8_t> ClientId::getClientId() const {
+ return (duid_);
+}
+
+// compares two client-ids
+bool ClientId::operator == (const ClientId& other) const {
+ return (this->duid_ == other.duid_);
+}
+
+// compares two client-ids
+bool ClientId::operator != (const ClientId& other) const {
+ return (this->duid_ != other.duid_);
+}
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
diff --git a/src/lib/dhcp/duid.h b/src/lib/dhcp/duid.h
new file mode 100644
index 0000000..5f8ad58
--- /dev/null
+++ b/src/lib/dhcp/duid.h
@@ -0,0 +1,104 @@
+// 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 DUID_H
+#define DUID_H
+
+#include <asiolink/io_address.h>
+#include <vector>
+#include <stdint.h>
+#include <unistd.h>
+
+namespace isc {
+namespace dhcp {
+
+/// @brief Holds DUID (DHCPv6 Unique Identifier)
+///
+/// This class holds DUID, that is used in client-id, server-id and
+/// several other options. It is used to identify DHCPv6 entity.
+class DUID {
+ public:
+ /// @brief maximum duid size
+ /// As defined in RFC3315, section 9.1
+ static const size_t MAX_DUID_LEN = 128;
+
+ /// @brief specifies DUID type
+ typedef enum {
+ DUID_UNKNOWN = 0, ///< invalid/unknown type
+ DUID_LLT = 1, ///< link-layer + time, see RFC3315, section 9.2
+ DUID_EN = 2, ///< enterprise-id, see RFC3315, section 9.3
+ DUID_LL = 3, ///< link-layer, see RFC3315, section 9.4
+ DUID_UUID = 4, ///< UUID, see RFC6355
+ DUID_MAX ///< not a real type, just maximum defined value + 1
+ } DUIDType;
+
+ /// @brief creates a DUID
+ DUID(const std::vector<uint8_t>& duid);
+
+ /// @brief creates a DUID
+ DUID(const uint8_t *duid, size_t len);
+
+ /// @brief returns a const reference to the actual DUID value
+ ///
+ /// Note: For safety reasons, this method returns a copy of data as
+ /// otherwise the reference would be only valid as long as the object that
+ /// returned it. In any case, this method should be used only sporadically.
+ /// If there are frequent uses, we must implement some other method
+ /// (e.g. storeSelf()) that will avoid data copying.
+ const std::vector<uint8_t> getDuid() const;
+
+ /// @brief returns DUID type
+ DUIDType getType() const;
+
+ // compares two DUIDs
+ bool operator == (const DUID& other) const;
+
+ // compares two DUIDs
+ bool operator != (const DUID& other) const;
+
+ protected:
+ /// the actual content of the DUID
+ std::vector<uint8_t> duid_;
+};
+
+typedef boost::shared_ptr<DUID> DuidPtr;
+
+/// @brief Holds Client identifier or client IPv4 address
+///
+/// This class is intended to be a generic IPv4 client identifier. It can hold
+/// a client-id
+class ClientId : DUID {
+ public:
+
+ /// constructor based on vector<uint8_t>
+ ClientId(const std::vector<uint8_t>& clientid);
+
+ /// constructor based on C-style data
+ ClientId(const uint8_t *clientid, size_t len);
+
+ /// @brief returns reference to the client-id data
+ ///
+ const std::vector<uint8_t> getClientId() const;
+
+ // compares two client-ids
+ bool operator == (const ClientId& other) const;
+
+ // compares two client-ids
+ bool operator != (const ClientId& other) const;
+};
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
+
+#endif /* DUID_H */
diff --git a/src/lib/dhcp/lease_mgr.cc b/src/lib/dhcp/lease_mgr.cc
new file mode 100644
index 0000000..59582fb
--- /dev/null
+++ b/src/lib/dhcp/lease_mgr.cc
@@ -0,0 +1,107 @@
+// 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 "lease_mgr.h"
+#include <exceptions/exceptions.h>
+#include <boost/foreach.hpp>
+#include <boost/algorithm/string.hpp>
+#include <sstream>
+#include <iostream>
+#include <map>
+#include <iostream>
+#include <string>
+#include <sstream>
+#include <algorithm>
+#include <iterator>
+#include <time.h>
+
+using namespace std;
+
+using namespace isc::dhcp;
+
+LeaseMgr* LeaseMgr::instance_ = NULL;
+
+Lease6::Lease6(LeaseType type, const isc::asiolink::IOAddress& addr, DuidPtr duid,
+ uint32_t iaid, uint32_t preferred, uint32_t valid, uint32_t t1,
+ uint32_t t2, SubnetID subnet_id, uint8_t prefixlen)
+ :type_(type), addr_(addr), prefixlen_(prefixlen), iaid_(iaid), duid_(duid),
+ preferred_lft_(preferred), valid_lft_(valid), t1_(t1), t2_(t2),
+ subnet_id_(subnet_id), fixed_(false), fqdn_fwd_(false),
+ fqdn_rev_(false) {
+ if (!duid) {
+ isc_throw(InvalidOperation, "DUID must be specified for a lease");
+ }
+
+ cltt_ = time(NULL);
+}
+
+LeaseMgr& LeaseMgr::instance() {
+ if (!instance_) {
+ isc_throw(InvalidOperation, "LeaseManager not instantiated yet");
+ }
+ return (*instance_);
+}
+
+void LeaseMgr::destroy_instance() {
+ if (!instance_) {
+ isc_throw(InvalidOperation, "LeaseManager not instantiated yet");
+ }
+ delete instance_;
+ instance_ = NULL;
+}
+
+LeaseMgr::LeaseMgr(const std::string& dbconfig) {
+ if (instance_) {
+ isc_throw(InvalidOperation, "LeaseManager already instantiated");
+ }
+
+ // remember the pointer to the singleton instance
+ instance_ = this;
+
+ if (dbconfig.length() == 0) {
+ return;
+ }
+
+ vector<string> tokens;
+
+ // we need to pass a string to is_any_of, not just char *. Otherwise there
+ // are cryptic warnings on Debian6 running g++ 4.4 in /usr/include/c++/4.4
+ // /bits/stl_algo.h:2178 "array subscript is above array bounds"
+ boost::split(tokens, dbconfig, boost::is_any_of( string("\t ") ));
+ BOOST_FOREACH(std::string token, tokens) {
+ size_t pos = token.find("=");
+ if (pos != string::npos) {
+ string name = token.substr(0, pos);
+ string value = token.substr(pos + 1);
+ parameters_.insert(pair<string,string>(name, value));
+ } else {
+ isc_throw(InvalidParameter, "Cannot parse " << token
+ << ", expected format is name=value");
+ }
+
+ }
+}
+
+std::string LeaseMgr::getParameter(const std::string& name) const {
+ std::map<std::string, std::string>::const_iterator param
+ = parameters_.find(name);
+ if (param == parameters_.end()) {
+ isc_throw(BadValue, "Parameter not found");
+ }
+ return (param->second);
+}
+
+LeaseMgr::~LeaseMgr() {
+ instance_ = NULL;
+}
diff --git a/src/lib/dhcp/lease_mgr.h b/src/lib/dhcp/lease_mgr.h
new file mode 100644
index 0000000..e859dea
--- /dev/null
+++ b/src/lib/dhcp/lease_mgr.h
@@ -0,0 +1,516 @@
+// 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 LEASE_MGR_H
+#define LEASE_MGR_H
+
+#include <string>
+#include <fstream>
+#include <vector>
+#include <map>
+#include <asiolink/io_address.h>
+#include <boost/noncopyable.hpp>
+#include <boost/shared_ptr.hpp>
+#include <dhcp/option.h>
+#include <dhcp/duid.h>
+#include <dhcp/subnet.h>
+
+/// @file dhcp/lease_mgr.h
+/// @brief An abstract API for lease database
+///
+/// This file contains declarations of Lease4, Lease6 and LeaseMgr classes.
+/// They are essential components of the interface to any database backend.
+/// Each concrete database backend (e.g. MySQL) will define a class derived
+/// from LeaseMgr class.
+///
+/// Failover considerations:
+/// There are no intermediate plans to implement DHCPv4 failover
+/// (draft-ietf-dhc-failover-12.txt). Currently (Oct. 2012) the DHCPv6 failover
+/// is being defined in DHC WG in IETF (draft-ietf-dhcpv6-failover-requirements,
+/// draft-ietf-dhcpv6-dailover-design), but the work is not advanced enough
+/// for implementation plans yet. v4 failover requires additional parameters
+/// to be kept with a lease. It is likely that v6 failover will require similar
+/// fields. Such implementation will require database schema extension.
+/// We have designed a way to expand/upgrade schemas during upgrades: a database
+/// schema is versioned and sanity checks about required version will be done
+/// upon start and/or upgrade. With this mechanism in place, we can add new
+/// fields to the database. In particular we can use that capability to
+/// introduce failover related fields.
+///
+/// However, there is another approach that can be reliably used to provide
+/// failover, even without the actual failover protocol implemented. As the
+/// first backend will use MySQL, we will be able to use Multi-Master capability
+/// offered by MySQL and use two separatate Kea instances connecting to the
+/// same database.
+///
+/// Nevertheless, we hope to have failover protocol eventually implemented in
+/// the Kea.
+
+namespace isc {
+namespace dhcp {
+
+/// @brief Structure that holds a lease for IPv4 address
+///
+/// For performance reasons it is a simple structure, not a class. If we chose
+/// make it a class, all fields would have to made private and getters/setters
+/// would be required. As this is a critical part of the code that will be used
+/// extensively, direct access is warranted.
+struct Lease4 {
+ /// IPv4 address
+ isc::asiolink::IOAddress addr_;
+
+ /// @brief Address extension
+ ///
+ /// It is envisaged that in some cases IPv4 address will be accompanied with some
+ /// additional data. One example of such use are Address + Port solutions (or
+ /// Port-restricted Addresses), where several clients may get the same address, but
+ /// different port ranges. This feature is not expected to be widely used.
+ /// Under normal circumstances, the value should be 0.
+ uint32_t ext_;
+
+ /// @brief hardware address
+ std::vector<uint8_t> hwaddr_;
+
+ /// @brief client identifier
+ boost::shared_ptr<ClientId> client_id_;
+
+ /// @brief renewal timer
+ ///
+ /// Specifies renewal time. Although technically it is a property of IA container,
+ /// not the address itself, since our data model does not define separate IA
+ /// entity, we are keeping it in the lease. In case of multiple addresses/prefixes
+ /// for the same IA, each must have consistent T1 and T2 values. Specified in
+ /// seconds since cltt.
+ uint32_t t1_;
+
+ /// @brief rebinding timer
+ ///
+ /// Specifies rebinding time. Although technically it is a property of IA container,
+ /// not the address itself, since our data model does not define separate IA
+ /// entity, we are keeping it in the lease. In case of multiple addresses/prefixes
+ /// for the same IA, each must have consistent T1 and T2 values. Specified in
+ /// seconds since cltt.
+ uint32_t t2_;
+
+ /// @brief valid lifetime
+ ///
+ /// Expressed as number of seconds since cltt
+ uint32_t valid_lft_;
+
+ /// @brief client last transmission time
+ ///
+ /// Specifies a timestamp, when last transmission from a client was received.
+ time_t cltt_;
+
+ /// @brief Subnet identifier
+ ///
+ /// Specifies subnet-id of the subnet that the lease belongs to
+ SubnetID subnet_id_;
+
+ /// @brief Is this a fixed lease?
+ ///
+ /// Fixed leases are kept after they are released/expired.
+ bool fixed_;
+
+ /// @brief client hostname
+ ///
+ /// This field may be empty
+ std::string hostname_;
+
+ /// @brief did we update AAAA record for this lease?
+ bool fqdn_fwd_;
+
+ /// @brief did we update PTR record for this lease?
+ bool fqdn_rev_;
+
+ /// @brief Lease comments.
+ ///
+ /// Currently not used. It may be used for keeping comments made by the
+ /// system administrator.
+ std::string comments_;
+
+ /// @todo: Add DHCPv4 failover related fields here
+};
+
+/// @brief Pointer to a Lease4 structure.
+typedef boost::shared_ptr<Lease4> Lease4Ptr;
+
+/// @brief A collection of IPv4 leases.
+typedef std::vector< boost::shared_ptr<Lease4Ptr> > Lease4Collection;
+
+/// @brief Structure that holds a lease for IPv6 address and/or prefix
+///
+/// For performance reasons it is a simple structure, not a class. Had we chose to
+/// make it a class, all fields would have to be made private and getters/setters
+/// would be required. As this is a critical part of the code that will be used
+/// extensively, direct access rather than through getters/setters is warranted.
+struct Lease6 {
+ typedef enum {
+ LEASE_IA_NA, /// the lease contains non-temporary IPv6 address
+ LEASE_IA_TA, /// the lease contains temporary IPv6 address
+ LEASE_IA_PD /// the lease contains IPv6 prefix (for prefix delegation)
+ } LeaseType;
+
+ Lease6(LeaseType type, const isc::asiolink::IOAddress& addr, DuidPtr duid,
+ uint32_t iaid, uint32_t preferred, uint32_t valid, uint32_t t1,
+ uint32_t t2, SubnetID subnet_id, uint8_t prefixlen_ = 0);
+
+ /// @brief specifies lease type (normal addr, temporary addr, prefix)
+ LeaseType type_;
+
+ /// IPv6 address
+ isc::asiolink::IOAddress addr_;
+
+ /// IPv6 prefix length (used only for PD)
+ uint8_t prefixlen_;
+
+ /// @brief IAID
+ ///
+ /// Identity Association IDentifier. DHCPv6 stores all addresses and prefixes
+ /// in IA containers (IA_NA, IA_TA, IA_PD). Most containers may appear more
+ /// than once in a message. To differentiate between them, IAID field is present
+ uint32_t iaid_;
+
+ /// @brief hardware address
+ ///
+ /// This field is not really used and is optional at best. The concept of identifying
+ /// clients by their hardware address was replaced in DHCPv6 by DUID concept. Each
+ /// client has its own unique DUID (DHCP Unique IDentifier). Furthermore, client's
+ /// HW address is not always available, because client may be behind a relay (relay
+ /// stores only link-local address).
+ std::vector<uint8_t> hwaddr_;
+
+ /// @brief client identifier
+ boost::shared_ptr<DUID> duid_;
+
+ /// @brief preferred lifetime
+ ///
+ /// This parameter specifies preferred lifetime since the lease was assigned/renewed
+ /// (cltt), expressed in seconds.
+ uint32_t preferred_lft_;
+
+ /// @brief valid lifetime
+ ///
+ /// This parameter specified valid lifetime since the lease was assigned/renewed
+ /// (cltt), expressed in seconds.
+ uint32_t valid_lft_;
+
+ /// @brief T1 timer
+ ///
+ /// Specifies renewal time. Although technically it is a property of IA container,
+ /// not the address itself, since our data model does not define separate IA
+ /// entity, we are keeping it in the lease. In case of multiple addresses/prefixes
+ /// for the same IA, each must have consistent T1 and T2 values. Specified in
+ /// seconds since cltt.
+ /// This value will also be useful for failover to calculate the next expected
+ /// client transmission time.
+ uint32_t t1_;
+
+ /// @brief T2 timer
+ ///
+ /// Specifies rebinding time. Although technically it is a property of IA container,
+ /// not the address itself, since our data model does not define separate IA
+ /// entity, we are keeping it in the lease. In case of multiple addresses/prefixes
+ /// for the same IA, each must have consistent T1 and T2 values. Specified in
+ /// seconds since cltt.
+ uint32_t t2_;
+
+ /// @brief client last transmission time
+ ///
+ /// Specifies a timestamp, when last transmission from a client was received.
+ time_t cltt_;
+
+ /// @brief Subnet identifier
+ ///
+ /// Specifies subnet-id of the subnet that the lease belongs to
+ SubnetID subnet_id_;
+
+ /// @brief Is this a fixed lease?
+ ///
+ /// Fixed leases are kept after they are released/expired.
+ bool fixed_;
+
+ /// @brief client hostname
+ ///
+ /// This field may be empty
+ std::string hostname_;
+
+ /// @brief did we update AAAA record for this lease?
+ bool fqdn_fwd_;
+
+ /// @brief did we update PTR record for this lease?
+ bool fqdn_rev_;
+
+ /// @brief Lease comments
+ ///
+ /// This field is currently not used.
+ std::string comments_;
+
+ /// @todo: Add DHCPv6 failover related fields here
+};
+
+/// @brief Pointer to a Lease6 structure.
+typedef boost::shared_ptr<Lease6> Lease6Ptr;
+
+/// @brief Const pointer to a Lease6 structure.
+typedef boost::shared_ptr<const Lease6> ConstLease6Ptr;
+
+/// @brief A collection of IPv6 leases.
+typedef std::vector< boost::shared_ptr<Lease6Ptr> > Lease6Collection;
+
+/// @brief Abstract Lease Manager
+///
+/// This is an abstract API for lease database backends. It provides unified
+/// interface to all backends. As this is an abstract class, it should not
+/// be used directly, but rather specialized derived class should be used
+/// instead.
+///
+/// This class is a meta-singleton. At any given time, there is only one
+/// instance of any classes derived from that class. That is achieved with
+/// defining only a single protected constructor, so every derived class has
+/// to use it. Furthermore, this sole constructor registers the first instance
+/// (and throws InvalidOperation if there is an attempt to create a second one).
+class LeaseMgr : public boost::noncopyable {
+public:
+ /// Client Hardware address
+ typedef std::vector<uint8_t> HWAddr;
+
+ /// @brief returns a single instance of LeaseMgr
+ ///
+ /// LeaseMgr is a singleton and this method is the only way of
+ /// accessing it. LeaseMgr must be created first. See
+ /// isc::dhcp::LeaseMgrFactory class (work of ticket #2342.
+ /// Otherwise instance() will throw InvalidOperation exception.
+ /// @throw InvalidOperation if LeaseMgr not instantiated
+ static LeaseMgr& instance();
+
+ /// @brief destroys the only instance of LeaseMgr
+ ///
+ /// This method is used mostly in tests, where LeaseMgr is destroyed
+ /// at the end of each test, just to be created at the beginning of
+ /// the next one.
+ static void destroy_instance();
+
+ /// @brief Adds an IPv4 lease.
+ ///
+ /// @param lease lease to be added
+ virtual bool addLease(const Lease4Ptr& lease) = 0;
+
+ /// @brief Adds an IPv6 lease.
+ ///
+ /// @param lease lease to be added
+ virtual bool addLease(const Lease6Ptr& lease) = 0;
+
+ /// @brief Returns existing IPv4 lease for specified IPv4 address and subnet_id
+ ///
+ /// This method is used to get a lease for specific subnet_id. There can be
+ /// at most one lease for any given subnet, so this method returns a single
+ /// pointer.
+ ///
+ /// @param addr address of the searched lease
+ /// @param subnet_id ID of the subnet the lease must belong to
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(isc::asiolink::IOAddress addr,
+ SubnetID subnet_id) const = 0;
+
+ /// @brief Returns an IPv4 lease for specified IPv4 address
+ ///
+ /// This method return a lease that is associated with a given address.
+ /// For other query types (by hardware addr, by client-id) there can be
+ /// several leases in different subnets (e.g. for mobile clients that
+ /// got address in different subnets). However, for a single address
+ /// there can be only one lease, so this method returns a pointer to
+ /// a single lease, not a container of leases.
+ ///
+ /// @param addr address of the searched lease
+ /// @param subnet_id ID of the subnet the lease must belong to
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(isc::asiolink::IOAddress addr) const = 0;
+
+ /// @brief Returns existing IPv4 leases for specified hardware address.
+ ///
+ /// Although in the usual case there will be only one lease, for mobile
+ /// clients or clients with multiple static/fixed/reserved leases there
+ /// can be more than one. Thus return type is a container, not a single
+ /// pointer.
+ ///
+ /// @param hwaddr hardware address of the client
+ ///
+ /// @return lease collection
+ virtual Lease4Collection getLease4(const HWAddr& hwaddr) const = 0;
+
+ /// @brief Returns existing IPv4 leases for specified hardware address
+ /// and a subnet
+ ///
+ /// There can be at most one lease for a given HW address in a single
+ /// pool, so this method with either return a single lease or NULL.
+ ///
+ /// @param hwaddr hardware address of the client
+ /// @param subnet_id identifier of the subnet that lease must belong to
+ ///
+ /// @return a pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(const HWAddr& hwaddr,
+ SubnetID subnet_id) const = 0;
+
+ /// @brief Returns existing IPv4 lease for specified client-id
+ ///
+ /// Although in the usual case there will be only one lease, for mobile
+ /// clients or clients with multiple static/fixed/reserved leases there
+ /// can be more than one. Thus return type is a container, not a single
+ /// pointer.
+ ///
+ /// @param clientid client identifier
+ ///
+ /// @return lease collection
+ virtual Lease4Collection getLease4(const ClientId& clientid) const = 0;
+
+ /// @brief Returns existing IPv4 lease for specified client-id
+ ///
+ /// There can be at most one lease for a given HW address in a single
+ /// pool, so this method with either return a single lease or NULL.
+ ///
+ /// @param clientid client identifier
+ /// @param subnet_id identifier of the subnet that lease must belong to
+ ///
+ /// @return a pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(const ClientId& clientid,
+ SubnetID subnet_id) const = 0;
+
+ /// @brief Returns existing IPv6 lease for a given IPv6 address.
+ ///
+ /// For a given address, we assume that there will be only one lease.
+ /// The assumtion here is that there will not be site or link-local
+ /// addresses used, so there is no way of having address duplication.
+ ///
+ /// @param addr address of the searched lease
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ virtual Lease6Ptr getLease6(const isc::asiolink::IOAddress& addr) const = 0;
+
+ /// @brief Returns existing IPv6 leases for a given DUID+IA combination
+ ///
+ /// Although in the usual case there will be only one lease, for mobile
+ /// clients or clients with multiple static/fixed/reserved leases there
+ /// can be more than one. Thus return type is a container, not a single
+ /// pointer.
+ ///
+ /// @param duid client DUID
+ /// @param iaid IA identifier
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ virtual Lease6Collection getLease6(const DUID& duid,
+ uint32_t iaid) const = 0;
+
+ /// @brief Returns existing IPv6 lease for a given DUID+IA combination
+ ///
+ /// @param duid client DUID
+ /// @param iaid IA identifier
+ /// @param subnet_id subnet id of the subnet the lease belongs to
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ virtual Lease6Ptr getLease6(const DUID& duid, uint32_t iaid,
+ SubnetID subnet_id) const = 0;
+
+ /// @brief Updates IPv4 lease.
+ ///
+ /// @param lease4 The lease to be updated.
+ ///
+ /// If no such lease is present, an exception will be thrown.
+ virtual void updateLease4(const Lease4Ptr& lease4) = 0;
+
+ /// @brief Updates IPv4 lease.
+ ///
+ /// @param lease4 The lease to be updated.
+ ///
+ /// If no such lease is present, an exception will be thrown.
+ virtual void updateLease6(const Lease6Ptr& lease6) = 0;
+
+ /// @brief Deletes a lease.
+ ///
+ /// @param addr IPv4 address of the lease to be deleted.
+ ///
+ /// @return true if deletion was successful, false if no such lease exists
+ virtual bool deleteLease4(uint32_t addr) = 0;
+
+ /// @brief Deletes a lease.
+ ///
+ /// @param addr IPv4 address of the lease to be deleted.
+ ///
+ /// @return true if deletion was successful, false if no such lease exists
+ virtual bool deleteLease6(const isc::asiolink::IOAddress& addr) = 0;
+
+ /// @brief Returns backend name.
+ ///
+ /// Each backend have specific name, e.g. "mysql" or "sqlite".
+ virtual std::string getName() const = 0;
+
+ /// @brief Returns description of the backend.
+ ///
+ /// This description may be multiline text that describes the backend.
+ virtual std::string getDescription() const = 0;
+
+ /// @brief Returns backend version.
+ ///
+ /// @todo: We will need to implement 3 version functions eventually:
+ /// A. abstract API version
+ /// B. backend version
+ /// C. database version (stored in the database scheme)
+ ///
+ /// and then check that:
+ /// B>=A and B=C (it is ok to have newer backend, as it should be backward
+ /// compatible)
+ /// Also if B>C, some database upgrade procedure may be triggered
+ virtual std::string getVersion() const = 0;
+
+ /// @todo: Add host management here
+ /// As host reservation is outside of scope for 2012, support for hosts
+ /// is currently postponed.
+
+protected:
+ /// @brief The sole lease manager constructor
+ ///
+ /// dbconfig is a generic way of passing parameters. Parameters are passed
+ /// in the "name=value" format, separated by spaces. Values may be enclosed
+ /// in double quotes, if needed. This ctor guarantees that there will be
+ /// only one instance of any derived classes. If there is a second instance
+ /// being created with the first one still around, it will throw
+ /// InvalidOperation.
+ ///
+ /// @param dbconfig database configuration
+ /// @throw InvalidOperation when trying to create second LeaseMgr
+ LeaseMgr(const std::string& dbconfig);
+
+ /// @brief Destructor
+ virtual ~LeaseMgr();
+
+ /// @brief returns value of the parameter
+ std::string getParameter(const std::string& name) const;
+
+ /// @brief list of parameters passed in dbconfig
+ ///
+ /// That will be mostly used for storing database name, username,
+ /// password and other parameters required for DB access. It is not
+ /// intended to keep any DHCP-related parameters.
+ std::map<std::string, std::string> parameters_;
+
+ static LeaseMgr* instance_;
+};
+
+}; // end of isc::dhcp namespace
+
+}; // end of isc namespace
+
+#endif // LEASE_MGR_H
diff --git a/src/lib/dhcp/libdhcp++.dox b/src/lib/dhcp/libdhcp++.dox
new file mode 100644
index 0000000..013b6f2
--- /dev/null
+++ b/src/lib/dhcp/libdhcp++.dox
@@ -0,0 +1,79 @@
+/**
+ at page libdhcp libdhcp++
+
+ at section libdhcpIntro Libdhcp++ Library Introduction
+
+libdhcp++ is an all-purpose DHCP-manipulation library, written in
+C++. It offers packet parsing and assembly, DHCPv4 and DHCPv6
+options parsing and ssembly, interface detection (currently on
+Linux systems only) and socket operations. It is a generic purpose library that
+can be used by server, client, relay, performance tools and other DHCP-related
+tools. For server specific library, see \ref libdhcpsrv. Please do not
+add any server-specific code to libdhcp++ and use \ref libdhcpsrv instead.
+
+The following classes for packet manipulation are implemented:
+
+- isc::dhcp::Pkt4 - represents DHCPv4 packet.
+- isc::dhcp::Pkt6 - represents DHCPv6 packet.
+
+There are two pointer types defined: Pkt4Ptr and Pkt6Ptr. They are
+smart pointer and are using boost::shared_ptr. There are not const
+versions defined, as we assume that hooks can modify any aspect of
+the packet at almost any stage of processing.
+
+Both packets use collection of Option objects to represent DHCPv4
+and DHCPv6 options. The base class -- Option -- can be used to
+represent generic option that contains collection of
+bytes. Depending on if the option is instantiated as v4 or v6
+option, it will adjust its header (DHCPv4 options use 1 octet for
+type and 1 octet for length, while DHCPv6 options use 2 bytes for
+each).
+
+There are many specialized classes that are intended to handle options with
+specific content:
+- isc::dhcp::Option4AddrLst -- DHCPv4 option, contains one or more IPv4 addresses;
+- isc::dhcp::Option6AddrLst -- DHCPv6 option, contains one or more IPv6 addresses;
+- isc::dhcp::Option6IAAddr -- DHCPv6 option, represents IAADDR_OPTION (an option that
+ contains IPv6 address with extra parameters);
+- isc::dhcp::Option6IA -- DHCPv6 option used to store IA_NA and its suboptions.
+
+All options can store sub-options (i.e. options that are stored within option
+rather than in a message directly). This functionality is commonly used in
+DHCPv6, but is rarely used in DHCPv4. isc::dhcp::Option::addOption(),
+isc::dhcp::Option::delOption(), isc::dhcp::Option::getOption() can be used
+for that purpose.
+
+ at section libdhcpIfaceMgr Interface Manager
+
+Interface Manager (or IfaceMgr) is an abstraction layer about low-level
+network operations. In particlar, it provides information about existing
+network interfaces See isc::dhcp::IfaceMgr::Iface class and
+isc::dhcp::IfaceMgr::detectIfaces() and isc::dhcp::IfaceMgr::getIface().
+
+Currently there is interface detection is implemented in Linux only. There
+are plans to implement such support for other OSes, but they remain low
+priority for now.
+
+Generic parts of the code are isc::dhcp::IfaceMgr class in
+src/lib/dhcp/iface_mgr.cc file. OS-specific code is located in separate
+files, e.g. iface_mgr_linux.cc. Such separation should be maintained when
+additional code will be developed.
+
+For systems that interface detection is not supported on, there is a stub
+mechanism implemented. It assumes that interface name is read from a text
+file. This is a temporary solution and will be removed as soon as proper
+interface detection is implemented. It is not going to be developed further.
+To use this feature, store interfaces.txt file. It uses a simple syntax.
+Each line represents an interface name, followed by IPv4 or IPv6 address
+that follows it. This is usually link-local IPv6 address that the server
+should bind to. In theory this mechanism also supports IPv4, but it was
+never tested. The code currently supports only a single interface defined
+that way.
+
+Another useful methods are dedicated to transmission
+(isc::dhcp::IfaceMgr::send(), 2 overloads) and reception
+(isc::dhcp::IfaceMgr::receive4() and isc::dhcp::IfaceMgr::receive6()).
+Note that receive4() and receive6() methods may return NULL, e.g.
+when timeout is reached or if dhcp daemon receives a signal.
+
+*/
\ No newline at end of file
diff --git a/src/lib/dhcp/libdhcsrv.dox b/src/lib/dhcp/libdhcsrv.dox
new file mode 100644
index 0000000..bb4a8ec
--- /dev/null
+++ b/src/lib/dhcp/libdhcsrv.dox
@@ -0,0 +1,86 @@
+/**
+ @page libdhcpsrv libdhcpsrv - Server DHCP library
+
+This library contains code useful for DHCPv4 and DHCPv6 server operations, like
+Lease Manager that stores leases information, configuration manager that stores
+configuration etc. The code here is server specific. For generic (useful in
+server, client, relay and other tools like perfdhcp) code, please see
+\ref libdhcp.
+
+This library contains several crucial elements of the DHCP server operation:
+
+- isc::dhcp::LeaseMgr - Lease Manager is a name for database backend that stores
+ leases.
+- isc::dhcp::CfgMgr - Configuration Manager that holds DHCP specific
+ configuration information (subnets, pools, options, timer values etc.) in
+ easy to use format.
+- AllocEngine - allocation engine that handles new requestes and allocates new
+ leases.
+
+ at section leasemgr Lease Manager
+
+LeaseMgr provides a common, unified abstract API for all database backends. All
+backends are derived from the base class isc::dhcp::LeaseMgr. Currently the
+only available backend is MySQL (see \ref isc::dhcp::MySqlLeaseMgr).
+
+ at section cfgmgr Configuration Manager
+
+Configuration Manager (\ref isc::dhcp::CfgMgr) stores configuration information
+necessary for DHCPv4 and DHCPv6 server operation. In particular, it stores
+subnets (\ref isc::dhcp::Subnet4 and \ref isc::dhcp::Subnet6) together with
+their pools (\ref isc::dhcp::Pool4 and \ref isc::dhcp::Pool6), options and
+other information specified by the used in BIND10 configuration.
+
+ at section allocengine Allocation Engine
+
+Allocation Engine (\ref isc::dhcp::AllocEngine) is what its name say - an engine
+that handles allocation of new leases. It takes parameters that the client
+provided (client-id, DUID, subnet, a hint if the user provided one, etc.) and
+then attempts to allocate a lease.
+
+There is no single best soluction to the address assignment problem. Server
+is expected to pick an address from its available pools is currently not used.
+There are many possible algorithms that can do that, each with its own advantages
+and drawbacks. This allocation engine must provide robust operation is radically
+different scenarios, so there address selection problem was abstracted into
+separate module, called allocator. Its sole purpose is to pick an address from
+a pool. Allocation engine will then check if the picked address is free and if
+it is not, then will ask allocator to pick again.
+
+At lease 3 allocators will be implemented:
+
+- Iterative - it iterates over all addresses in available pools, one
+by one. The advantages of this approach are speed (typically it only needs to
+increase last address), the guarantee to cover all addresses and predictability.
+This allocator behaves very good in case of nearing depletion. Even when pools
+are almost completely allocated, it still will be able to allocate outstanding
+leases efficiently. Predictability can also be considered a serious flaw in
+some environments, as prediction of the next address is trivial and can be
+leveraged by an attacker. Another drawback of this allocator is that it does
+not attempt to give the same address to returning clients (clients that released
+or expired their leases and are requesting a new lease will likely to get a
+different lease). This allocator is implemented in \ref isc::dhcp::AllocEngine::IterativeAllocator.
+
+- Hashed - ISC-DHCP uses hash of the client-id or DUID to determine, which
+address is tried first. If that address is not available, the result is hashed
+again. That procedure is repeated until available address is found or there
+are no more addresses left. The benefit of that approach is that it provides
+a relative lease stability, so returning old clients are likely to get the same
+address again. The drawbacks are increased computation cost, as each iteration
+requires use of a hashing function. That is especially difficult when the
+pools are almost depleted. It also may be difficult to guarantee that the
+repeated hashing will iterate over all available addresses in all pools. Flawed
+hash algorithm can go into cycles that iterate over only part of the addresses.
+It is difficult to detect such issues as only some initial seed (client-id
+or DUID) values may trigger short cycles. This allocator is currently not
+implemented.
+
+- Random - Another possible approach to address selection is randomization. This
+allocator can pick an address randomly from the configured pool. The benefit
+of this approach is that it is easy to implement and makes attacks based on
+address prediction more difficult. The drawback of this approach is that
+returning clients are almost guaranteed to get a different address. Another
+drawback is that with almost depleted pools it is increasingly difficult to
+"guess" an address that is free. This allocator is currently not implemented.
+
+*/
\ No newline at end of file
diff --git a/src/lib/dhcp/option4_addrlst.h b/src/lib/dhcp/option4_addrlst.h
index 3bedc6d..01a8a4b 100644
--- a/src/lib/dhcp/option4_addrlst.h
+++ b/src/lib/dhcp/option4_addrlst.h
@@ -20,6 +20,7 @@
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
+#include <asiolink/io_address.h>
#include <util/buffer.h>
#include <dhcp/option.h>
diff --git a/src/lib/dhcp/option6_int.h b/src/lib/dhcp/option6_int.h
new file mode 100644
index 0000000..5fd5c19
--- /dev/null
+++ b/src/lib/dhcp/option6_int.h
@@ -0,0 +1,189 @@
+// 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 OPTION6_INT_H_
+#define OPTION6_INT_H_
+
+#include <dhcp/libdhcp++.h>
+#include <dhcp/option.h>
+#include <dhcp/option_data_types.h>
+#include <util/io_utilities.h>
+
+#include <stdint.h>
+
+namespace isc {
+namespace dhcp {
+
+/// This template class represents DHCPv6 option with single value.
+/// This value is of integer type and can be any of the following:
+/// - uint8_t,
+/// - uint16_t,
+/// - uint32_t,
+/// - int8_t,
+/// - int16_t,
+/// - int32_t.
+///
+/// @param T data field type (see above).
+template<typename T>
+class Option6Int: public Option {
+
+public:
+ /// @brief Constructor.
+ ///
+ /// @param type option type.
+ /// @param value option value.
+ ///
+ /// @throw isc::dhcp::InvalidDataType if data field type provided
+ /// as template parameter is not a supported integer type.
+ Option6Int(uint16_t type, T value)
+ : Option(Option::V6, type), value_(value) {
+ if (!OptionDataTypes<T>::valid) {
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ }
+
+ /// @brief Constructor.
+ ///
+ /// This constructor creates option from a buffer. This construtor
+ /// may throw exception if \ref unpack function throws during buffer
+ /// parsing.
+ ///
+ /// @param type option type.
+ /// @param begin iterator to first byte of option data.
+ /// @param end iterator to end of option data (first byte after option end).
+ ///
+ /// @throw isc::OutOfRange if provided buffer is shorter than data size.
+ /// @throw isc::dhcp::InvalidDataType if data field type provided
+ /// as template parameter is not a supported integer type.
+ Option6Int(uint16_t type, OptionBufferConstIter begin,
+ OptionBufferConstIter end)
+ : Option(Option::V6, type) {
+ if (!OptionDataTypes<T>::valid) {
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ unpack(begin, end);
+ }
+
+ /// Writes option in wire-format to buf, returns pointer to first unused
+ /// byte after stored option.
+ ///
+ /// @param [out] buf buffer (option will be stored here)
+ ///
+ /// @throw isc::dhcp::InvalidDataType if size of a data field type is not
+ /// equal to 1, 2 or 4 bytes. The data type is not checked in this function
+ /// because it is checked in a constructor.
+ void pack(isc::util::OutputBuffer& buf) {
+ buf.writeUint16(type_);
+ buf.writeUint16(len() - OPTION6_HDR_LEN);
+ // Depending on the data type length we use different utility functions
+ // writeUint16 or writeUint32 which write the data in the network byte
+ // order to the provided buffer. The same functions can be safely used
+ // for either unsiged or signed integers so there is not need to create
+ // special cases for intX_t types.
+ switch (OptionDataTypes<T>::len) {
+ case 1:
+ buf.writeUint8(value_);
+ break;
+ case 2:
+ buf.writeUint16(value_);
+ break;
+ case 4:
+ buf.writeUint32(value_);
+ break;
+ default:
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ LibDHCP::packOptions6(buf, options_);
+ }
+
+ /// @brief Parses received buffer
+ ///
+ /// Parses received buffer and returns offset to the first unused byte after
+ /// parsed option.
+ ///
+ /// @param begin iterator to first byte of option data
+ /// @param end iterator to end of option data (first byte after option end)
+ ///
+ /// @throw isc::OutOfRange if provided buffer is shorter than data size.
+ /// @throw isc::dhcp::InvalidDataType if size of a data field type is not
+ /// equal to 1, 2 or 4 bytes. The data type is not checked in this function
+ /// because it is checked in a constructor.
+ virtual void unpack(OptionBufferConstIter begin, OptionBufferConstIter end) {
+ if (distance(begin, end) < sizeof(T)) {
+ isc_throw(OutOfRange, "Option " << getType() << " truncated");
+ }
+ // @todo consider what to do if buffer is longer than data type.
+
+ // Depending on the data type length we use different utility functions
+ // readUint16 or readUint32 which read the data laid in the network byte
+ // order from the provided buffer. The same functions can be safely used
+ // for either unsiged or signed integers so there is not need to create
+ // special cases for intX_t types.
+ int data_size_len = OptionDataTypes<T>::len;
+ switch (data_size_len) {
+ case 1:
+ value_ = *begin;
+ break;
+ case 2:
+ value_ = isc::util::readUint16(&(*begin));
+ break;
+ case 4:
+ value_ = isc::util::readUint32(&(*begin));
+ break;
+ default:
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ // Use local variable to set a new value for this iterator.
+ // When using OptionDataTypes<T>::len directly some versions
+ // of clang complain about unresolved reference to
+ // OptionDataTypes structure during linking.
+ begin += data_size_len;
+ LibDHCP::unpackOptions6(OptionBuffer(begin, end), options_);
+ }
+
+ /// @brief Set option value.
+ ///
+ /// @param value new option value.
+ void setValue(T value) { value_ = value; }
+
+ /// @brief Return option value.
+ ///
+ /// @return option value.
+ T getValue() const { return value_; }
+
+ /// @brief returns complete length of option
+ ///
+ /// Returns length of this option, including option header and suboptions
+ ///
+ /// @return length of this option
+ virtual uint16_t len() {
+ uint16_t length = OPTION6_HDR_LEN + sizeof(T);
+ // length of all suboptions
+ for (Option::OptionCollection::iterator it = options_.begin();
+ it != options_.end();
+ ++it) {
+ length += (*it).second->len();
+ }
+ return (length);
+ }
+
+private:
+
+ T value_; ///< Value conveyed by the option.
+};
+
+} // isc::dhcp namespace
+} // isc namespace
+
+#endif /* OPTION6_INT_H_ */
diff --git a/src/lib/dhcp/option6_int_array.h b/src/lib/dhcp/option6_int_array.h
new file mode 100644
index 0000000..57aad1e
--- /dev/null
+++ b/src/lib/dhcp/option6_int_array.h
@@ -0,0 +1,228 @@
+// 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 OPTION6_INT_ARRAY_H_
+#define OPTION6_INT_ARRAY_H_
+
+#include <dhcp/libdhcp++.h>
+#include <dhcp/option.h>
+#include <dhcp/option_data_types.h>
+#include <util/io_utilities.h>
+
+#include <stdint.h>
+
+namespace isc {
+namespace dhcp {
+
+/// This template class represents DHCPv6 option with array of
+/// integer values. The type of the elements in the array can be
+/// any of the following:
+/// - uint8_t,
+/// - uint16_t,
+/// - uint32_t,
+/// - int8_t,
+/// - int16_t,
+/// - int32_t.
+///
+/// @warning Since this option may convey variable number of integer
+/// values, sub-options are should not be added in this option as
+/// there is no way to distinguish them from other data. The API will
+/// allow addition of sub-options but they will be ignored during
+/// packing and unpacking option data.
+///
+/// @param T data field type (see above).
+template<typename T>
+class Option6IntArray: public Option {
+
+public:
+
+ /// @brief Constructor.
+ ///
+ /// Creates option with empty values vector.
+ ///
+ /// @param type option type.
+ ///
+ /// @throw isc::dhcp::InvalidDataType if data field type provided
+ /// as template parameter is not a supported integer type.
+ Option6IntArray(uint16_t type)
+ : Option(Option::V6, type),
+ values_(0) {
+ if (!OptionDataTypes<T>::valid) {
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ }
+
+ /// @brief Constructor.
+ ///
+ /// @param type option type.
+ /// @param buf buffer with option data (must not be empty).
+ ///
+ /// @throw isc::OutOfRange if provided buffer is empty or its length
+ /// is not multiple of size of the data type in bytes.
+ /// @throw isc::dhcp::InvalidDataType if data field type provided
+ /// as template parameter is not a supported integer type.
+ Option6IntArray(uint16_t type, const OptionBuffer& buf)
+ : Option(Option::V6, type) {
+ if (!OptionDataTypes<T>::valid) {
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ unpack(buf.begin(), buf.end());
+ }
+
+ /// @brief Constructor.
+ ///
+ /// This constructor creates option from a buffer. This construtor
+ /// may throw exception if \ref unpack function throws during buffer
+ /// parsing.
+ ///
+ /// @param type option type.
+ /// @param begin iterator to first byte of option data.
+ /// @param end iterator to end of option data (first byte after option end).
+ ///
+ /// @throw isc::OutOfRange if provided buffer is empty or its length
+ /// is not multiple of size of the data type in bytes.
+ /// @throw isc::dhcp::InvalidDataType if data field type provided
+ /// as template parameter is not a supported integer type.
+ Option6IntArray(uint16_t type, OptionBufferConstIter begin,
+ OptionBufferConstIter end)
+ : Option(Option::V6, type) {
+ if (!OptionDataTypes<T>::valid) {
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ unpack(begin, end);
+ }
+
+ /// Writes option in wire-format to buf, returns pointer to first unused
+ /// byte after stored option.
+ ///
+ /// @param [out] buf buffer (option will be stored here)
+ ///
+ /// @throw isc::dhcp::InvalidDataType if size of a data fields type is not
+ /// equal to 1, 2 or 4 bytes. The data type is not checked in this function
+ /// because it is checked in a constructor.
+ void pack(isc::util::OutputBuffer& buf) {
+ buf.writeUint16(type_);
+ buf.writeUint16(len() - OPTION6_HDR_LEN);
+ for (int i = 0; i < values_.size(); ++i) {
+ // Depending on the data type length we use different utility functions
+ // writeUint16 or writeUint32 which write the data in the network byte
+ // order to the provided buffer. The same functions can be safely used
+ // for either unsiged or signed integers so there is not need to create
+ // special cases for intX_t types.
+ switch (OptionDataTypes<T>::len) {
+ case 1:
+ buf.writeUint8(values_[i]);
+ break;
+ case 2:
+ buf.writeUint16(values_[i]);
+ break;
+ case 4:
+ buf.writeUint32(values_[i]);
+ break;
+ default:
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ }
+ // We don't pack sub-options here because we have array-type option.
+ // We don't allow sub-options in array-type options as there is no
+ // way to distinguish them from the data fields on option reception.
+ }
+
+ /// @brief Parses received buffer
+ ///
+ /// Parses received buffer and returns offset to the first unused byte after
+ /// parsed option.
+ ///
+ /// @param begin iterator to first byte of option data
+ /// @param end iterator to end of option data (first byte after option end)
+ ///
+ /// @throw isc::dhcp::InvalidDataType if size of a data fields type is not
+ /// equal to 1, 2 or 4 bytes. The data type is not checked in this function
+ /// because it is checked in a constructor.
+ virtual void unpack(OptionBufferConstIter begin, OptionBufferConstIter end) {
+ if (distance(begin, end) == 0) {
+ isc_throw(OutOfRange, "option " << getType() << " empty");
+ }
+ if (distance(begin, end) % sizeof(T) != 0) {
+ isc_throw(OutOfRange, "option " << getType() << " truncated");
+ }
+ // @todo consider what to do if buffer is longer than data type.
+
+ values_.clear();
+ while (begin != end) {
+ // Depending on the data type length we use different utility functions
+ // readUint16 or readUint32 which read the data laid in the network byte
+ // order from the provided buffer. The same functions can be safely used
+ // for either unsiged or signed integers so there is not need to create
+ // special cases for intX_t types.
+ int data_size_len = OptionDataTypes<T>::len;
+ switch (data_size_len) {
+ case 1:
+ values_.push_back(*begin);
+ break;
+ case 2:
+ values_.push_back(isc::util::readUint16(&(*begin)));
+ break;
+ case 4:
+ values_.push_back(isc::util::readUint32(&(*begin)));
+ break;
+ default:
+ isc_throw(dhcp::InvalidDataType, "non-integer type");
+ }
+ // Use local variable to set a new value for this iterator.
+ // When using OptionDataTypes<T>::len directly some versions
+ // of clang complain about unresolved reference to
+ // OptionDataTypes structure during linking.
+ begin += data_size_len;
+ }
+ // We do not unpack sub-options here because we have array-type option.
+ // Such option have variable number of data fields, thus there is no
+ // way to assess where sub-options start.
+ }
+
+ /// @brief Return collection of option values.
+ ///
+ /// @return collection of values.
+ const std::vector<T>& getValues() const { return (values_); }
+
+ /// @brief Set option values.
+ ///
+ /// @param values collection of values to be set for option.
+ void setValues(const std::vector<T>& values) { values_ = values; }
+
+ /// @brief returns complete length of option
+ ///
+ /// Returns length of this option, including option header and suboptions
+ ///
+ /// @return length of this option
+ virtual uint16_t len() {
+ uint16_t length = OPTION6_HDR_LEN + values_.size() * sizeof(T);
+ // length of all suboptions
+ for (Option::OptionCollection::iterator it = options_.begin();
+ it != options_.end();
+ ++it) {
+ length += (*it).second->len();
+ }
+ return (length);
+ }
+
+private:
+
+ std::vector<T> values_;
+};
+
+} // isc::dhcp namespace
+} // isc namespace
+
+#endif /* OPTION6_INT_ARRAY_H_ */
diff --git a/src/lib/dhcp/option_data_types.h b/src/lib/dhcp/option_data_types.h
new file mode 100644
index 0000000..4e8d8a6
--- /dev/null
+++ b/src/lib/dhcp/option_data_types.h
@@ -0,0 +1,89 @@
+// 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 OPTION_DATA_TYPES_H_
+#define OPTION_DATA_TYPES_H_
+
+#include <exceptions/exceptions.h>
+
+#include <stdint.h>
+
+namespace isc {
+namespace dhcp {
+
+/// @brief Exception to be thrown when invalid type specified as template parameter.
+class InvalidDataType : public Exception {
+public:
+ InvalidDataType(const char* file, size_t line, const char* what) :
+ isc::Exception(file, line, what) { };
+};
+
+/// @brief Trait class for integer data types supported in DHCP option definitions.
+///
+/// This is useful to check whether the type specified as template parameter
+/// is supported by classes like Option6Int, Option6IntArray and some template
+/// factory functions in OptionDefinition class.
+template<typename T>
+struct OptionDataTypes {
+ static const bool valid = false;
+ static const int len = 0;
+};
+
+/// int8_t type is supported.
+template<>
+struct OptionDataTypes<int8_t> {
+ static const bool valid = true;
+ static const int len = 1;
+};
+
+/// int16_t type is supported.
+template<>
+struct OptionDataTypes<int16_t> {
+ static const bool valid = true;
+ static const int len = 2;
+};
+
+/// int32_t type is supported.
+template<>
+struct OptionDataTypes<int32_t> {
+ static const bool valid = true;
+ static const int len = 4;
+};
+
+/// uint8_t type is supported.
+template<>
+struct OptionDataTypes<uint8_t> {
+ static const bool valid = true;
+ static const int len = 1;
+};
+
+/// uint16_t type is supported.
+template<>
+struct OptionDataTypes<uint16_t> {
+ static const bool valid = true;
+ static const int len = 2;
+};
+
+/// uint32_t type is supported.
+template<>
+struct OptionDataTypes<uint32_t> {
+ static const bool valid = true;
+ static const int len = 4;
+};
+
+
+} // isc::dhcp namespace
+} // isc namespace
+
+#endif /* OPTION_DATA_TYPES_H_ */
diff --git a/src/lib/dhcp/option_definition.cc b/src/lib/dhcp/option_definition.cc
new file mode 100644
index 0000000..f562316
--- /dev/null
+++ b/src/lib/dhcp/option_definition.cc
@@ -0,0 +1,252 @@
+// 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 <dhcp/dhcp6.h>
+#include <dhcp/option_definition.h>
+#include <dhcp/option4_addrlst.h>
+#include <dhcp/option6_addrlst.h>
+#include <dhcp/option6_ia.h>
+#include <dhcp/option6_iaaddr.h>
+#include <dhcp/option6_int.h>
+#include <dhcp/option6_int_array.h>
+
+using namespace std;
+using namespace isc::util;
+
+namespace isc {
+namespace dhcp {
+
+OptionDefinition::DataTypeUtil::DataTypeUtil() {
+ data_types_["empty"] = EMPTY_TYPE;
+ data_types_["boolean"] = BOOLEAN_TYPE;
+ data_types_["int8"] = INT8_TYPE;
+ data_types_["int16"] = INT16_TYPE;
+ data_types_["int32"] = INT32_TYPE;
+ data_types_["uint8"] = UINT8_TYPE;
+ data_types_["uint16"] = UINT16_TYPE;
+ data_types_["uint32"] = UINT32_TYPE;
+ data_types_["ipv4-address"] = IPV4_ADDRESS_TYPE;
+ data_types_["ipv6-address"] = IPV6_ADDRESS_TYPE;
+ data_types_["string"] = STRING_TYPE;
+ data_types_["fqdn"] = FQDN_TYPE;
+ data_types_["record"] = RECORD_TYPE;
+}
+
+OptionDefinition::DataType
+OptionDefinition::DataTypeUtil::getDataType(const std::string& data_type) {
+ std::map<std::string, DataType>::const_iterator data_type_it =
+ data_types_.find(data_type);
+ if (data_type_it != data_types_.end()) {
+ return (data_type_it->second);
+ }
+ return UNKNOWN_TYPE;
+}
+
+OptionDefinition::OptionDefinition(const std::string& name,
+ const uint16_t code,
+ const std::string& type,
+ const bool array_type /* = false */)
+ : name_(name),
+ code_(code),
+ type_(UNKNOWN_TYPE),
+ array_type_(array_type) {
+ // Data type is held as enum value by this class.
+ // Use the provided option type string to get the
+ // corresponding enum value.
+ type_ = DataTypeUtil::instance().getDataType(type);
+}
+
+OptionDefinition::OptionDefinition(const std::string& name,
+ const uint16_t code,
+ const DataType type,
+ const bool array_type /* = false */)
+ : name_(name),
+ code_(code),
+ type_(type),
+ array_type_(array_type) {
+}
+
+void
+OptionDefinition::addRecordField(const std::string& data_type_name) {
+ DataType data_type = DataTypeUtil::instance().getDataType(data_type_name);
+ addRecordField(data_type);
+}
+
+void
+OptionDefinition::addRecordField(const DataType data_type) {
+ if (type_ != RECORD_TYPE) {
+ isc_throw(isc::InvalidOperation, "'record' option type must be used"
+ " to add data fields to the record");
+ }
+ if (data_type >= UNKNOWN_TYPE) {
+ isc_throw(isc::BadValue, "attempted to add invalid data type to the record");
+ }
+ record_fields_.push_back(data_type);
+}
+
+Option::Factory*
+OptionDefinition::getFactory() const {
+ // @todo This function must be extended to return more factory
+ // functions that create instances of more specialized options.
+ // This requires us to first implement those more specialized
+ // options that will be derived from Option class.
+ if (type_ == IPV6_ADDRESS_TYPE && array_type_) {
+ return (factoryAddrList6);
+ } else if (type_ == IPV4_ADDRESS_TYPE && array_type_) {
+ return (factoryAddrList4);
+ } else if (type_ == EMPTY_TYPE) {
+ return (factoryEmpty);
+ } else if (code_ == D6O_IA_NA && haveIA6Format()) {
+ return (factoryIA6);
+ } else if (code_ == D6O_IAADDR && haveIAAddr6Format()) {
+ return (factoryIAAddr6);
+ } else if (type_ == UINT8_TYPE) {
+ if (array_type_) {
+ return (factoryGeneric);
+ } else {
+ return (factoryInteger<uint8_t>);
+ }
+ } else if (type_ == UINT16_TYPE) {
+ if (array_type_) {
+ return (factoryIntegerArray<uint16_t>);
+ } else {
+ return (factoryInteger<uint16_t>);
+ }
+ } else if (type_ == UINT32_TYPE) {
+ if (array_type_) {
+ return (factoryIntegerArray<uint32_t>);
+ } else {
+ return (factoryInteger<uint32_t>);
+ }
+ }
+ // Factory generic returns instance of Option class. However, once we
+ // implement CustomOption class we may want to return factory function
+ // that will create instance of CustomOption rather than Option.
+ // CustomOption will allow to access particular data fields within the
+ // option rather than raw data buffer.
+ return (factoryGeneric);
+}
+
+void
+OptionDefinition::sanityCheckUniverse(const Option::Universe expected_universe,
+ const Option::Universe actual_universe) {
+ if (expected_universe != actual_universe) {
+ isc_throw(isc::BadValue, "invalid universe specified for the option");
+ }
+}
+
+void
+OptionDefinition::validate() const {
+ // Option name must not be empty.
+ if (name_.empty()) {
+ isc_throw(isc::BadValue, "option name must not be empty");
+ }
+ // Option name must not contain spaces.
+ if (name_.find(" ") != string::npos) {
+ isc_throw(isc::BadValue, "option name must not contain spaces");
+ }
+ // Unsupported option types are not allowed.
+ if (type_ >= UNKNOWN_TYPE) {
+ isc_throw(isc::OutOfRange, "option type value " << type_
+ << " is out of range");
+ }
+}
+
+bool
+OptionDefinition::haveIAx6Format(OptionDefinition::DataType first_type) const {
+ return (haveType(RECORD_TYPE) &&
+ record_fields_.size() == 3 &&
+ record_fields_[0] == first_type &&
+ record_fields_[1] == UINT32_TYPE &&
+ record_fields_[2] == UINT32_TYPE);
+}
+
+bool
+OptionDefinition::haveIA6Format() const {
+ // Expect that IA_NA option format is defined as record.
+ // Although it consists of 3 elements of the same (uint32)
+ // type it can't be defined as array of uint32 elements because
+ // arrays do not impose limitations on number of elements in
+ // the array while this limitation is needed for IA_NA - need
+ // exactly 3 elements.
+ return (haveIAx6Format(UINT32_TYPE));
+}
+
+bool
+OptionDefinition::haveIAAddr6Format() const {
+ return (haveIAx6Format(IPV6_ADDRESS_TYPE));
+}
+
+OptionPtr
+OptionDefinition::factoryAddrList4(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf) {
+ sanityCheckUniverse(u, Option::V4);
+ boost::shared_ptr<Option4AddrLst> option(new Option4AddrLst(type, buf.begin(),
+ buf.begin() + buf.size()));
+ return (option);
+}
+
+OptionPtr
+OptionDefinition::factoryAddrList6(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf) {
+ sanityCheckUniverse(u, Option::V6);
+ boost::shared_ptr<Option6AddrLst> option(new Option6AddrLst(type, buf.begin(),
+ buf.begin() + buf.size()));
+ return (option);
+}
+
+
+OptionPtr
+OptionDefinition::factoryEmpty(Option::Universe u, uint16_t type, const OptionBuffer& buf) {
+ if (buf.size() > 0) {
+ isc_throw(isc::BadValue, "input option buffer must be empty"
+ " when creating empty option instance");
+ }
+ OptionPtr option(new Option(u, type));
+ return (option);
+}
+
+OptionPtr
+OptionDefinition::factoryGeneric(Option::Universe u, uint16_t type, const OptionBuffer& buf) {
+ OptionPtr option(new Option(u, type, buf));
+ return (option);
+}
+
+OptionPtr
+OptionDefinition::factoryIA6(Option::Universe u, uint16_t type, const OptionBuffer& buf) {
+ sanityCheckUniverse(u, Option::V6);
+ if (buf.size() != Option6IA::OPTION6_IA_LEN) {
+ isc_throw(isc::OutOfRange, "input option buffer has invalid size, expeted "
+ << Option6IA::OPTION6_IA_LEN << " bytes");
+ }
+ boost::shared_ptr<Option6IA> option(new Option6IA(type, buf.begin(),
+ buf.begin() + buf.size()));
+ return (option);
+}
+
+OptionPtr
+OptionDefinition::factoryIAAddr6(Option::Universe u, uint16_t type, const OptionBuffer& buf) {
+ sanityCheckUniverse(u, Option::V6);
+ if (buf.size() != Option6IAAddr::OPTION6_IAADDR_LEN) {
+ isc_throw(isc::OutOfRange, "input option buffer has invalid size, expeted "
+ << Option6IAAddr::OPTION6_IAADDR_LEN << " bytes");
+ }
+ boost::shared_ptr<Option6IAAddr> option(new Option6IAAddr(type, buf.begin(),
+ buf.begin() + buf.size()));
+ return (option);
+}
+
+
+} // end of isc::dhcp namespace
+} // end of isc namespace
diff --git a/src/lib/dhcp/option_definition.h b/src/lib/dhcp/option_definition.h
new file mode 100644
index 0000000..c274ce9
--- /dev/null
+++ b/src/lib/dhcp/option_definition.h
@@ -0,0 +1,383 @@
+// 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 OPTION_DEFINITION_H_
+#define OPTION_DEFINITION_H_
+
+#include <dhcp/option_data_types.h>
+#include <dhcp/option6_int.h>
+#include <dhcp/option6_int_array.h>
+#include <dhcp/option.h>
+
+namespace isc {
+namespace dhcp {
+
+/// @brief Base class representing a DHCP option definition.
+///
+/// This is a base class representing a DHCP option definition, which describes
+/// the format of the option. In particular, it defines:
+/// - option name,
+/// - option code,
+/// - data fields order and their types,
+/// - sub options space that the particular option encapsulates.
+///
+/// The option type specifies the data type(s) which an option conveys. If
+/// this is a single value the option type points to the data type of the
+/// value. For example, DHCPv6 option 8 comprises a two-byte option code, a
+/// two-byte option length and two-byte field that carries a uint16 value
+/// (RFC 3315 - http://ietf.org/rfc/rfc3315.txt). In such a case, the option
+/// type is defined as "uint16".
+///
+/// When the option has a more complex structure, the option type may be
+/// defined as "array", "record" or even "array of records".
+///
+/// Array types should be used when the option contains multiple contiguous
+/// data values of the same type laid. For example, DHCPv6 option 6 includes
+/// multiple fields holding uint16 codes of requested DHCPv6 options (RFC 3315).
+/// Such an option can be represented with this class by setting the option
+/// type to "uint16" and the array indicator (array_type) to true. The number
+/// of elements in the array is effectively unlimited (although it is actually
+/// limited by the maximal DHCPv6 option length).
+///
+/// Should the option comprise data fields of different types, the "record"
+/// option type is used. In such cases the data field types within the record
+/// are specified using \ref OptionDefinition::addRecordField.
+///
+/// When the OptionDefinition object has been sucessfully created, it can be
+/// queried to return the appropriate option factory function for the specified
+/// specified option format. There are a number of "standard" factory functions
+/// that cover well known (common) formats. If the particular format does not
+/// match any common format the generic factory function is returned.
+///
+/// The following data type strings are supported:
+/// - "empty" (option does not contain data fields)
+/// - "boolean"
+/// - "int8"
+/// - "int16"
+/// - "int32"
+/// - "uint8"
+/// - "uint16"
+/// - "uint32"
+/// - "ipv4-address" (IPv4 Address)
+/// - "ipv6-address" (IPV6 Address)
+/// - "string"
+/// - "fqdn" (fully qualified name)
+/// - "record" (set of data fields of different types)
+///
+/// @todo Extend the comment to describe "generic factories".
+/// @todo Extend this class to use custom namespaces.
+/// @todo Extend this class with more factory functions.
+class OptionDefinition {
+public:
+
+ /// Data types of DHCP option fields.
+ enum DataType {
+ EMPTY_TYPE,
+ BOOLEAN_TYPE,
+ INT8_TYPE,
+ INT16_TYPE,
+ INT32_TYPE,
+ UINT8_TYPE,
+ UINT16_TYPE,
+ UINT32_TYPE,
+ IPV4_ADDRESS_TYPE,
+ IPV6_ADDRESS_TYPE,
+ STRING_TYPE,
+ FQDN_TYPE,
+ RECORD_TYPE,
+ UNKNOWN_TYPE
+ };
+
+ /// List of fields within the record.
+ typedef std::vector<DataType> RecordFieldsCollection;
+ /// Const iterator for record data fields.
+ typedef std::vector<DataType>::const_iterator RecordFieldsConstIter;
+
+private:
+
+ /// @brief Utility class for operations on DataTypes.
+ ///
+ /// This class is implemented as the singleton because the list of
+ /// supported data types need only be loaded only once into memory as it
+ /// can persist for all option definitions.
+ ///
+ /// @todo This class can be extended to return the string value
+ /// representing the data type from the enum value.
+ class DataTypeUtil {
+ public:
+
+ /// @brief Return the sole instance of this class.
+ ///
+ /// @return instance of this class.
+ static DataTypeUtil& instance() {
+ static DataTypeUtil instance;
+ return (instance);
+ }
+
+ /// @brief Convert type given as string value to option data type.
+ ///
+ /// @param data_type_name data type string.
+ ///
+ /// @return option data type.
+ DataType getDataType(const std::string& data_type_name);
+
+ private:
+ /// @brief Private constructor.
+ ///
+ /// Constructor initializes the internal data structures, e.g.
+ /// mapping between data type name and the corresponding enum.
+ /// This constructor is private to ensure that exactly one
+ /// instance of this class can be created using \ref instance
+ /// function.
+ DataTypeUtil();
+
+ /// Map of data types, maps name of the type to enum value.
+ std::map<std::string, DataType> data_types_;
+ };
+
+public:
+ /// @brief Constructor.
+ ///
+ /// @param name option name.
+ /// @param code option code.
+ /// @param type option data type as string.
+ /// @param array_type array indicator, if true it indicates that the
+ /// option fields are the array.
+ OptionDefinition(const std::string& name,
+ const uint16_t code,
+ const std::string& type,
+ const bool array_type = false);
+
+ /// @brief Constructor.
+ ///
+ /// @param name option name.
+ /// @param code option code.
+ /// @param type option data type.
+ /// @param array_type array indicator, if true it indicates that the
+ /// option fields are the array.
+ OptionDefinition(const std::string& name,
+ const uint16_t code,
+ const DataType type,
+ const bool array_type = false);
+
+ /// @brief Adds data field to the record.
+ ///
+ /// @param data_type_name name of the data type for the field.
+ ///
+ /// @throw isc::InvalidOperation if option type is not set to RECORD_TYPE.
+ /// @throw isc::BadValue if specified invalid data type.
+ void addRecordField(const std::string& data_type_name);
+
+ /// @brief Adds data field to the record.
+ ///
+ /// @param data_type data type for the field.
+ ///
+ /// @throw isc::InvalidOperation if option type is not set to RECORD_TYPE.
+ /// @throw isc::BadValue if specified invalid data type.
+ void addRecordField(const DataType data_type);
+
+ /// @brief Return array type indicator.
+ ///
+ /// The method returns the bool value to indicate whether the option is a
+ /// a single value or an array of values.
+ ///
+ /// @return true if option comprises an array of values.
+ bool getArrayType() const { return (array_type_); }
+
+ /// @brief Return option code.
+ ///
+ /// @return option code.
+ uint16_t getCode() const { return (code_); }
+
+ /// @brief Return factory function for the given definition.
+ ///
+ /// @return pointer to factory function.
+ Option::Factory* getFactory() const;
+
+ /// @brief Return option name.
+ ///
+ /// @return option name.
+ const std::string& getName() const { return (name_); }
+
+ /// @brief Return list of record fields.
+ ///
+ /// @return list of record fields.
+ const RecordFieldsCollection& getRecordFields() const { return (record_fields_); }
+
+ /// @brief Return option data type.
+ ///
+ /// @return option data type.
+ DataType getType() const { return (type_); };
+
+ /// @brief Check if the option definition is valid.
+ ///
+ /// @throw isc::OutOfRange if invalid option type was specified.
+ /// @throw isc::BadValue if invalid option name was specified,
+ /// e.g. empty or containing spaces.
+ void validate() const;
+
+ /// @brief Check if specified format is IA_NA option format.
+ ///
+ /// @return true if specified format is IA_NA option format.
+ bool haveIA6Format() const;
+
+ /// @brief Check if specified format is IAADDR option format.
+ ///
+ /// @return true if specified format is IAADDR option format.
+ bool haveIAAddr6Format() const;
+
+ /// @brief Factory to create option with address list.
+ ///
+ /// @param u universe (must be V4).
+ /// @param type option type.
+ /// @param buf option buffer with a list of IPv4 addresses.
+ ///
+ /// @throw isc::OutOfRange if length of the provided option buffer
+ /// is not multiple of IPV4 address length.
+ static OptionPtr factoryAddrList4(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf);
+
+ /// @brief Factory to create option with address list.
+ ///
+ /// @param u universe (must be V6).
+ /// @param type option type.
+ /// @param buf option buffer with a list of IPv6 addresses.
+ ///
+ /// @throw isc::OutOfaRange if length of provided option buffer
+ /// is not multiple of IPV6 address length.
+ static OptionPtr factoryAddrList6(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf);
+
+ /// @brief Empty option factory.
+ ///
+ /// @param u universe (V6 or V4).
+ /// @param type option type.
+ /// @param buf option buffer (must be empty).
+ static OptionPtr factoryEmpty(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf);
+
+ /// @brief Factory to create generic option.
+ ///
+ /// @param u universe (V6 or V4).
+ /// @param type option type.
+ /// @param buf option buffer.
+ static OptionPtr factoryGeneric(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf);
+
+ /// @brief Factory for IA-type of option.
+ ///
+ /// @param u universe (must be V6).
+ /// @param type option type.
+ /// @param buf option buffer.
+ ///
+ /// @throw isc::OutOfRange if provided option buffer is too short or
+ /// too long. Expected size is 12 bytes.
+ /// @throw isc::BadValue if specified universe value is not V6.
+ static OptionPtr factoryIA6(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf);
+
+ /// @brief Factory for IAADDR-type of option.
+ ///
+ /// @param u universe (must be V6).
+ /// @param type option type.
+ /// @param buf option buffer.
+ ///
+ /// @throw isc::OutOfRange if provided option buffer is too short or
+ /// too long. Expected size is 24 bytes.
+ /// @throw isc::BadValue if specified universe value is not V6.
+ static OptionPtr factoryIAAddr6(Option::Universe u, uint16_t type,
+ const OptionBuffer& buf);
+
+ /// @brief Factory function to create option with integer value.
+ ///
+ /// @param type option type.
+ /// @param buf option buffer.
+ /// @tparam T type of the data field (must be one of the uintX_t or intX_t).
+ ///
+ /// @throw isc::OutOfRange if provided option buffer length is invalid.
+ template<typename T>
+ static OptionPtr factoryInteger(Option::Universe, uint16_t type, const OptionBuffer& buf) {
+ if (buf.size() > sizeof(T)) {
+ isc_throw(isc::OutOfRange, "provided option buffer is too large, expected: "
+ << sizeof(T) << " bytes");
+ }
+ OptionPtr option(new Option6Int<T>(type, buf.begin(), buf.end()));
+ return (option);
+ }
+
+ /// @brief Factory function to create option with array of integer values.
+ ///
+ /// @param type option type.
+ /// @param buf option buffer.
+ /// @tparam T type of the data field (must be one of the uintX_t or intX_t).
+ ///
+ /// @throw isc::OutOfRange if provided option buffer length is invalid.
+ template<typename T>
+ static OptionPtr factoryIntegerArray(Option::Universe, uint16_t type, const OptionBuffer& buf) {
+ if (buf.size() == 0) {
+ isc_throw(isc::OutOfRange, "option buffer length must be greater than zero");
+ } else if (buf.size() % OptionDataTypes<T>::len != 0) {
+ isc_throw(isc::OutOfRange, "option buffer length must be multiple of "
+ << OptionDataTypes<T>::len << " bytes");
+ }
+ OptionPtr option(new Option6IntArray<T>(type, buf.begin(), buf.end()));
+ return (option);
+ }
+
+private:
+
+ /// @brief Check if specified option format is a record with 3 fields
+ /// where first one is custom, and two others are uint32.
+ ///
+ /// This is a helper function for functions that detect IA_NA and IAAddr
+ /// option formats.
+ ///
+ /// @param first_type type of the first data field.
+ ///
+ /// @return true if actual option format matches expected format.
+ bool haveIAx6Format(const OptionDefinition::DataType first_type) const;
+
+ /// @brief Check if specified type matches option definition type.
+ ///
+ /// @return true if specified type matches option definition type.
+ inline bool haveType(const DataType type) const {
+ return (type == type_);
+ }
+
+ /// @brief Sanity check universe value.
+ ///
+ /// @param expected_universe expected universe value.
+ /// @param actual_universe actual universe value.
+ ///
+ /// @throw isc::BadValue if expected universe and actual universe don't match.
+ static inline void sanityCheckUniverse(const Option::Universe expected_universe,
+ const Option::Universe actual_universe);
+
+ /// Option name.
+ std::string name_;
+ /// Option code.
+ uint16_t code_;
+ /// Option data type.
+ DataType type_;
+ /// Indicates wheter option is a single value or array.
+ bool array_type_;
+ /// Collection of data fields within the record.
+ RecordFieldsCollection record_fields_;
+};
+
+
+} // namespace isc::dhcp
+} // namespace isc
+
+#endif
diff --git a/src/lib/dhcp/pool.cc b/src/lib/dhcp/pool.cc
new file mode 100644
index 0000000..1cf47a3
--- /dev/null
+++ b/src/lib/dhcp/pool.cc
@@ -0,0 +1,118 @@
+// 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 <asiolink/io_address.h>
+#include <dhcp/addr_utilities.h>
+#include <dhcp/pool.h>
+
+using namespace isc::asiolink;
+
+namespace isc {
+namespace dhcp {
+
+Pool::Pool(const isc::asiolink::IOAddress& first,
+ const isc::asiolink::IOAddress& last)
+ :id_(getNextID()), first_(first), last_(last) {
+}
+
+bool Pool::inRange(const isc::asiolink::IOAddress& addr) const {
+ return (first_.smallerEqual(addr) && addr.smallerEqual(last_));
+}
+
+Pool4::Pool4(const isc::asiolink::IOAddress& first,
+ const isc::asiolink::IOAddress& last)
+ :Pool(first, last) {
+ // check if specified address boundaries are sane
+ if (first.getFamily() != AF_INET || last.getFamily() != AF_INET) {
+ isc_throw(BadValue, "Invalid Pool4 address boundaries: not IPv4");
+ }
+
+ if (last < first) {
+ isc_throw(BadValue, "Upper boundary is smaller than lower boundary.");
+ }
+}
+
+Pool4::Pool4(const isc::asiolink::IOAddress& prefix,
+ uint8_t prefix_len)
+ :Pool(prefix, IOAddress("0.0.0.0")) {
+
+ // check if the prefix is sane
+ if (prefix.getFamily() != AF_INET) {
+ isc_throw(BadValue, "Invalid Pool4 address boundaries: not IPv4");
+ }
+
+ // check if the prefix length is sane
+ if (prefix_len == 0 || prefix_len > 32) {
+ isc_throw(BadValue, "Invalid prefix length");
+ }
+
+ // Let's now calculate the last address in defined pool
+ last_ = lastAddrInPrefix(prefix, prefix_len);
+}
+
+
+Pool6::Pool6(Pool6Type type, const isc::asiolink::IOAddress& first,
+ const isc::asiolink::IOAddress& last)
+ :Pool(first, last), type_(type), prefix_len_(0) {
+
+ // check if specified address boundaries are sane
+ if (first.getFamily() != AF_INET6 || last.getFamily() != AF_INET6) {
+ isc_throw(BadValue, "Invalid Pool6 address boundaries: not IPv6");
+ }
+
+ if (last < first) {
+ isc_throw(BadValue, "Upper boundary is smaller than lower boundary.");
+ // This check is a bit strict. If we decide that it is too strict,
+ // we need to comment it and uncomment lines below.
+ // On one hand, letting the user specify 2001::f - 2001::1 is nice, but
+ // on the other hand, 2001::1 may be a typo and the user really meant
+ // 2001::1:0 (or 1 followed by some hex digit), so a at least a warning
+ // would be useful.
+
+ // first_ = last;
+ // last_ = first;
+ }
+
+ // TYPE_PD is not supported by this constructor. first-last style
+ // parameters are for IA and TA only. There is another dedicated
+ // constructor for that (it uses prefix/length)
+ if ((type != TYPE_IA) && (type != TYPE_TA)) {
+ isc_throw(BadValue, "Invalid Pool6 type specified");
+ }
+}
+
+Pool6::Pool6(Pool6Type type, const isc::asiolink::IOAddress& prefix,
+ uint8_t prefix_len)
+ :Pool(prefix, IOAddress("::")),
+ type_(type), prefix_len_(prefix_len) {
+
+ // check if the prefix is sane
+ if (prefix.getFamily() != AF_INET6) {
+ isc_throw(BadValue, "Invalid Pool6 address boundaries: not IPv6");
+ }
+
+ // check if the prefix length is sane
+ if (prefix_len == 0 || prefix_len > 128) {
+ isc_throw(BadValue, "Invalid prefix length");
+ }
+
+ /// @todo: We should probably implement checks against weird addresses
+ /// here, like ::, starting with fe80, starting with ff etc. .
+
+ // Let's now calculate the last address in defined pool
+ last_ = lastAddrInPrefix(prefix, prefix_len);
+}
+
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
diff --git a/src/lib/dhcp/pool.h b/src/lib/dhcp/pool.h
new file mode 100644
index 0000000..dd68fdd
--- /dev/null
+++ b/src/lib/dhcp/pool.h
@@ -0,0 +1,184 @@
+// 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 POOL_H
+#define POOL_H
+
+#include <vector>
+#include <asiolink/io_address.h>
+#include <boost/shared_ptr.hpp>
+
+namespace isc {
+namespace dhcp {
+
+/// @brief base class for Pool4 and Pool6
+///
+/// Stores information about pool of IPv4 or IPv6 addresses.
+/// That is a basic component of a configuration.
+class Pool {
+
+public:
+
+ /// @brief returns Pool-id
+ ///
+ /// @return pool-id value
+ /// Pool-id is an unique value that can be used to identify a pool.
+ uint32_t getId() const {
+ return (id_);
+ }
+
+ /// @brief Returns the first address in a pool.
+ ///
+ /// @return first address in a pool
+ const isc::asiolink::IOAddress& getFirstAddress() const {
+ return (first_);
+ }
+
+ /// @brief Returns the last address in a pool.
+ /// @return last address in a pool
+ const isc::asiolink::IOAddress& getLastAddress() const {
+ return (last_);
+ }
+
+ /// @brief Checks if a given address is in the range.
+ ///
+ /// @return true, if the address is in pool
+ bool inRange(const isc::asiolink::IOAddress& addr) const;
+
+protected:
+
+ /// @brief protected constructor
+ ///
+ /// This constructor is protected to prevent anyone from instantiating
+ /// Pool class directly. Instances of Pool4 and Pool6 should be created
+ /// instead.
+ Pool(const isc::asiolink::IOAddress& first,
+ const isc::asiolink::IOAddress& last);
+
+ /// @brief returns the next unique Pool-ID
+ ///
+ /// @return the next unique Pool-ID
+ static uint32_t getNextID() {
+ static uint32_t id = 0;
+ return (id++);
+ }
+
+ /// @brief pool-id
+ ///
+ /// This ID is used to identify this specific pool.
+ uint32_t id_;
+
+ /// @brief The first address in a pool
+ isc::asiolink::IOAddress first_;
+
+ /// @brief The last address in a pool
+ isc::asiolink::IOAddress last_;
+
+ /// @brief Comments field
+ ///
+ /// @todo: This field is currently not used.
+ std::string comments_;
+};
+
+/// @brief Pool information for IPv4 addresses
+///
+/// It holds information about pool4, i.e. a range of IPv4 address space that
+/// is configured for DHCP allocation.
+class Pool4 : public Pool {
+public:
+ /// @brief the constructor for Pool4 "min-max" style definition
+ ///
+ /// @param first the first address in a pool
+ /// @param last the last address in a pool
+ Pool4(const isc::asiolink::IOAddress& first,
+ const isc::asiolink::IOAddress& last);
+
+ /// @brief the constructor for Pool4 "prefix/len" style definition
+ ///
+ /// @param prefix specifies prefix of the pool
+ /// @param prefix_len specifies length of the prefix of the pool
+ Pool4(const isc::asiolink::IOAddress& prefix,
+ uint8_t prefix_len);
+};
+
+/// @brief a pointer an IPv4 Pool
+typedef boost::shared_ptr<Pool4> Pool4Ptr;
+
+/// @brief a container for IPv4 Pools
+typedef std::vector<Pool4Ptr> Pool4Collection;
+
+/// @brief Pool information for IPv6 addresses and prefixes
+///
+/// It holds information about pool6, i.e. a range of IPv6 address space that
+/// is configured for DHCP allocation.
+class Pool6 : public Pool {
+public:
+
+ /// @brief specifies Pool type
+ ///
+ /// Currently there are 3 pool types defined in DHCPv6:
+ /// - Non-temporary addresses (conveyed in IA_NA)
+ /// - Temporary addresses (conveyed in IA_TA)
+ /// - Delegated Prefixes (conveyed in IA_PD)
+ /// There is a new one being worked on (IA_PA, see draft-ietf-dhc-host-gen-id), but
+ /// support for it is not planned for now.
+ typedef enum {
+ TYPE_IA,
+ TYPE_TA,
+ TYPE_PD
+ } Pool6Type;
+
+ /// @brief the constructor for Pool6 "min-max" style definition
+ ///
+ /// @param type type of the pool (IA, TA or PD)
+ /// @param first the first address in a pool
+ /// @param last the last address in a pool
+ Pool6(Pool6Type type, const isc::asiolink::IOAddress& first,
+ const isc::asiolink::IOAddress& last);
+
+ /// @brief the constructor for Pool6 "prefix/len" style definition
+ ///
+ /// @param type type of the pool (IA, TA or PD)
+ /// @param prefix specifies prefix of the pool
+ /// @param prefix_len specifies length of the prefix of the pool
+ Pool6(Pool6Type type, const isc::asiolink::IOAddress& prefix,
+ uint8_t prefix_len);
+
+ /// @brief returns pool type
+ ///
+ /// @return pool type
+ Pool6Type getType() const {
+ return (type_);
+ }
+
+private:
+ /// @brief defines a pool type
+ Pool6Type type_;
+
+ /// @brief prefix length
+ /// used by TYPE_PD only (zeroed for other types)
+ uint8_t prefix_len_;
+};
+
+/// @brief a pointer an IPv6 Pool
+typedef boost::shared_ptr<Pool6> Pool6Ptr;
+
+/// @brief a container for IPv6 Pools
+typedef std::vector<Pool6Ptr> Pool6Collection;
+
+} // end of isc::dhcp namespace
+} // end of isc namespace
+
+
+#endif // POOL_H
diff --git a/src/lib/dhcp/subnet.cc b/src/lib/dhcp/subnet.cc
new file mode 100644
index 0000000..f6ce1b1
--- /dev/null
+++ b/src/lib/dhcp/subnet.cc
@@ -0,0 +1,196 @@
+// 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 <dhcp/addr_utilities.h>
+#include <asiolink/io_address.h>
+#include <dhcp/subnet.h>
+
+using namespace isc::asiolink;
+
+namespace isc {
+namespace dhcp {
+
+Subnet::Subnet(const isc::asiolink::IOAddress& prefix, uint8_t len,
+ const Triplet<uint32_t>& t1,
+ const Triplet<uint32_t>& t2,
+ const Triplet<uint32_t>& valid_lifetime)
+ :id_(getNextID()), prefix_(prefix), prefix_len_(len), t1_(t1),
+ t2_(t2), valid_(valid_lifetime),
+ last_allocated_(lastAddrInPrefix(prefix, len)) {
+ if ( (prefix.getFamily() == AF_INET6 && len > 128) ||
+ (prefix.getFamily() == AF_INET && len > 32) ) {
+ isc_throw(BadValue, "Invalid prefix length specified for subnet: " << len);
+ }
+}
+
+bool Subnet::inRange(const isc::asiolink::IOAddress& addr) const {
+ IOAddress first = firstAddrInPrefix(prefix_, prefix_len_);
+ IOAddress last = lastAddrInPrefix(prefix_, prefix_len_);
+
+ return ((first <= addr) && (addr <= last));
+}
+
+void
+Subnet::addOption(OptionPtr& option, bool persistent /* = false */) {
+ validateOption(option);
+ options_.push_back(OptionDescriptor(option, persistent));
+}
+
+void
+Subnet::delOptions() {
+ options_.clear();
+}
+
+Subnet4::Subnet4(const isc::asiolink::IOAddress& prefix, uint8_t length,
+ const Triplet<uint32_t>& t1,
+ const Triplet<uint32_t>& t2,
+ const Triplet<uint32_t>& valid_lifetime)
+ :Subnet(prefix, length, t1, t2, valid_lifetime) {
+ if (prefix.getFamily() != AF_INET) {
+ isc_throw(BadValue, "Non IPv4 prefix " << prefix.toText()
+ << " specified in subnet4");
+ }
+}
+
+void Subnet4::addPool4(const Pool4Ptr& pool) {
+ IOAddress first_addr = pool->getFirstAddress();
+ IOAddress last_addr = pool->getLastAddress();
+
+ if (!inRange(first_addr) || !inRange(last_addr)) {
+ isc_throw(BadValue, "Pool4 (" << first_addr.toText() << "-" << last_addr.toText()
+ << " does not belong in this (" << prefix_ << "/" << prefix_len_
+ << ") subnet4");
+ }
+
+ /// @todo: Check that pools do not overlap
+
+ pools_.push_back(pool);
+}
+
+Pool4Ptr Subnet4::getPool4(const isc::asiolink::IOAddress& hint /* = IOAddress("::")*/ ) {
+ Pool4Ptr candidate;
+ for (Pool4Collection::iterator pool = pools_.begin(); pool != pools_.end(); ++pool) {
+
+ // if we won't find anything better, then let's just use the first pool
+ if (!candidate) {
+ candidate = *pool;
+ }
+
+ // if the client provided a pool and there's a pool that hint is valid in,
+ // then let's use that pool
+ if ((*pool)->inRange(hint)) {
+ return (*pool);
+ }
+ }
+ return (candidate);
+}
+
+void
+Subnet4::validateOption(const OptionPtr& option) const {
+ if (!option) {
+ isc_throw(isc::BadValue, "option configured for subnet must not be NULL");
+ } else if (option->getUniverse() != Option::V4) {
+ isc_throw(isc::BadValue, "expected V4 option to be added to the subnet");
+ }
+}
+
+bool Subnet4::inPool(const isc::asiolink::IOAddress& addr) const {
+
+ // Let's start with checking if it even belongs to that subnet.
+ if (!inRange(addr)) {
+ return (false);
+ }
+
+ for (Pool4Collection::const_iterator pool = pools_.begin(); pool != pools_.end(); ++pool) {
+ if ((*pool)->inRange(addr)) {
+ return (true);
+ }
+ }
+ // there's no pool that address belongs to
+ return (false);
+}
+
+Subnet6::Subnet6(const isc::asiolink::IOAddress& prefix, uint8_t length,
+ const Triplet<uint32_t>& t1,
+ const Triplet<uint32_t>& t2,
+ const Triplet<uint32_t>& preferred_lifetime,
+ const Triplet<uint32_t>& valid_lifetime)
+ :Subnet(prefix, length, t1, t2, valid_lifetime),
+ preferred_(preferred_lifetime){
+ if (prefix.getFamily() != AF_INET6) {
+ isc_throw(BadValue, "Non IPv6 prefix " << prefix.toText()
+ << " specified in subnet6");
+ }
+}
+
+void Subnet6::addPool6(const Pool6Ptr& pool) {
+ IOAddress first_addr = pool->getFirstAddress();
+ IOAddress last_addr = pool->getLastAddress();
+
+ if (!inRange(first_addr) || !inRange(last_addr)) {
+ isc_throw(BadValue, "Pool6 (" << first_addr.toText() << "-" << last_addr.toText()
+ << " does not belong in this (" << prefix_ << "/" << prefix_len_
+ << ") subnet6");
+ }
+
+ /// @todo: Check that pools do not overlap
+
+ pools_.push_back(pool);
+}
+
+Pool6Ptr Subnet6::getPool6(const isc::asiolink::IOAddress& hint /* = IOAddress("::")*/ ) {
+ Pool6Ptr candidate;
+ for (Pool6Collection::iterator pool = pools_.begin(); pool != pools_.end(); ++pool) {
+
+ // if we won't find anything better, then let's just use the first pool
+ if (!candidate) {
+ candidate = *pool;
+ }
+
+ // if the client provided a pool and there's a pool that hint is valid in,
+ // then let's use that pool
+ if ((*pool)->inRange(hint)) {
+ return (*pool);
+ }
+ }
+ return (candidate);
+}
+
+void
+Subnet6::validateOption(const OptionPtr& option) const {
+ if (!option) {
+ isc_throw(isc::BadValue, "option configured for subnet must not be NULL");
+ } else if (option->getUniverse() != Option::V6) {
+ isc_throw(isc::BadValue, "expected V6 option to be added to the subnet");
+ }
+}
+
+bool Subnet6::inPool(const isc::asiolink::IOAddress& addr) const {
+
+ // Let's start with checking if it even belongs to that subnet.
+ if (!inRange(addr)) {
+ return (false);
+ }
+
+ for (Pool6Collection::const_iterator pool = pools_.begin(); pool != pools_.end(); ++pool) {
+ if ((*pool)->inRange(addr)) {
+ return (true);
+ }
+ }
+ // there's no pool that address belongs to
+ return (false);
+}
+
+} // end of isc::dhcp namespace
+} // end of isc namespace
diff --git a/src/lib/dhcp/subnet.h b/src/lib/dhcp/subnet.h
new file mode 100644
index 0000000..894d807
--- /dev/null
+++ b/src/lib/dhcp/subnet.h
@@ -0,0 +1,494 @@
+// 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 SUBNET_H
+#define SUBNET_H
+
+#include <asiolink/io_address.h>
+#include <dhcp/pool.h>
+#include <dhcp/triplet.h>
+#include <dhcp/option.h>
+#include <boost/shared_ptr.hpp>
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/hashed_index.hpp>
+#include <boost/multi_index/sequenced_index.hpp>
+#include <boost/multi_index/mem_fun.hpp>
+#include <boost/multi_index/member.hpp>
+
+namespace isc {
+namespace dhcp {
+
+/// @brief a base class for Subnet4 and Subnet6
+///
+/// This class presents a common base for IPv4 and IPv6 subnets.
+/// In a physical sense, a subnet defines a single network link with all devices
+/// attached to it. In most cases all devices attached to a single link can
+/// share the same parameters. Therefore Subnet holds several values that are
+/// typically shared by all hosts: renew timer (T1), rebind timer (T2) and
+/// leased addresses lifetime (valid-lifetime). It also holds the set
+/// of DHCP option instances configured for the subnet. These options are
+/// included in DHCP messages being sent to clients which are connected
+/// to the particular subnet.
+///
+/// @todo: Implement support for options here
+
+
+/// @brief Unique indentifier for a subnet (both v4 and v6)
+typedef uint32_t SubnetID;
+
+class Subnet {
+public:
+
+ /// @brief Option descriptor.
+ ///
+ /// Option descriptor holds information about option configured for
+ /// a particular subnet. This information comprises the actual option
+ /// instance and information whether this option is sent to DHCP client
+ /// only on request (persistent = false) or always (persistent = true).
+ struct OptionDescriptor {
+ /// Option instance.
+ OptionPtr option;
+ /// Persistent flag, if true option is always sent to the client,
+ /// if false option is sent to the client on request.
+ bool persistent;
+
+ /// @brief Constructor.
+ ///
+ /// @param opt option
+ /// @param persist if true option is always sent.
+ OptionDescriptor(OptionPtr& opt, bool persist)
+ : option(opt), persistent(persist) {};
+ };
+
+ /// @brief Extractor class to extract key with another key.
+ ///
+ /// This class solves the problem of accessing index key values
+ /// that are stored in objects nested in other objects.
+ /// Each OptionDescriptor structure contains the OptionPtr object.
+ /// The value retured by one of its accessors (getType) is used
+ /// as an indexing value in the multi_index_container defined below.
+ /// There is no easy way to mark that value returned by Option::getType
+ /// should be an index of this multi_index_container. There are standard
+ /// key extractors such as 'member' or 'mem_fun' but they are not
+ /// sufficient here. The former can be used to mark that member of
+ /// the structure that is held in the container should be used as an
+ /// indexing value. The latter can be used if the indexing value is
+ /// a product of the class being held in the container. In this complex
+ /// scenario when the indexing value is a product of the function that
+ /// is wrapped by the structure, this new extractor template has to be
+ /// defined. The template class provides a 'chain' of two extractors
+ /// to access the value returned by nested object and to use it as
+ /// indexing value.
+ /// For some more examples of complex keys see:
+ /// http://www.cs.brown.edu/~jwicks/boost/libs/multi_index/doc/index.html
+ ///
+ /// @tparam KeyExtractor1 extractor used to access data in
+ /// OptionDescriptor::option
+ /// @tparam KeyExtractor2 extractor used to access
+ /// OptionDescriptor::option member.
+ template<typename KeyExtractor1, typename KeyExtractor2>
+ class KeyFromKey {
+ public:
+ typedef typename KeyExtractor1::result_type result_type;
+
+ /// @brief Constructor.
+ KeyFromKey()
+ : key1_(KeyExtractor1()), key2_(KeyExtractor2()) { };
+
+ /// @brief Extract key with another key.
+ ///
+ /// @param arg the key value.
+ ///
+ /// @tparam key value type.
+ template<typename T>
+ result_type operator() (T& arg) const {
+ return (key1_(key2_(arg)));
+ }
+ private:
+ KeyExtractor1 key1_; ///< key 1.
+ KeyExtractor2 key2_; ///< key 2.
+ };
+
+ /// @brief Multi index container for DHCP option descriptors.
+ ///
+ /// This container comprises three indexes to access option
+ /// descriptors:
+ /// - sequenced index: used to access elements in the order they
+ /// have been added to the container,
+ /// - option type index: used to search option descriptors containing
+ /// options with specific option code (aka option type).
+ /// - persistency flag index: used to search option descriptors with
+ /// 'persistent' flag set to true.
+ ///
+ /// This container is the equivalent of three separate STL containers:
+ /// - std::list of all options,
+ /// - std::multimap of options with option code used as a multimap key,
+ /// - std::multimap of option descriptors with option persistency flag
+ /// used as a multimap key.
+ /// The major advantage of this container over 3 separate STL containers
+ /// is automatic synchronization of all indexes when elements are added,
+ /// removed or modified in the container. With separate containers,
+ /// the synchronization would have to be guaranteed by the Subnet class
+ /// code. This would increase code complexity and presumably it would
+ /// be much harder to add new search criteria (indexes).
+ ///
+ /// @todo we may want to search for options using option spaces when
+ /// they are implemented.
+ ///
+ /// @see http://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/index.html
+ typedef boost::multi_index_container<
+ // Container comprises elements of OptionDescriptor type.
+ OptionDescriptor,
+ // Here we start enumerating various indexes.
+ boost::multi_index::indexed_by<
+ // Sequenced index allows accessing elements in the same way
+ // as elements in std::list.
+ // Sequenced is an index #0.
+ boost::multi_index::sequenced<>,
+ // Start definition of index #1.
+ boost::multi_index::hashed_non_unique<
+ // KeyFromKey is the index key extractor that allows accessing
+ // option type being held by the OptionPtr through
+ // OptionDescriptor structure.
+ KeyFromKey<
+ // Use option type as the index key. The type is held
+ // in OptionPtr object so we have to call Option::getType
+ // to retrieve this key for each element.
+ boost::multi_index::mem_fun<
+ Option,
+ uint16_t,
+ &Option::getType
+ >,
+ // Indicate that OptionPtr is a member of
+ // OptionDescriptor structure.
+ boost::multi_index::member<
+ OptionDescriptor,
+ OptionPtr,
+ &OptionDescriptor::option
+ >
+ >
+ >,
+ // Start definition of index #2.
+ // Use 'persistent' struct member as a key.
+ boost::multi_index::hashed_non_unique<
+ boost::multi_index::member<
+ OptionDescriptor,
+ bool,
+ &OptionDescriptor::persistent
+ >
+ >
+ >
+ > OptionContainer;
+
+ /// Type of the index #1 - option type.
+ typedef OptionContainer::nth_index<1>::type OptionContainerTypeIndex;
+ /// Type of the index #2 - option persistency flag.
+ typedef OptionContainer::nth_index<2>::type OptionContainerPersistIndex;
+
+ /// @brief checks if specified address is in range
+ bool inRange(const isc::asiolink::IOAddress& addr) const;
+
+ /// @brief Add new option instance to the collection.
+ ///
+ /// @param option option instance.
+ /// @param persistent if true, send an option regardless if client
+ /// requested it or not.
+ ///
+ /// @throw isc::BadValue if invalid option provided.
+ void addOption(OptionPtr& option, bool persistent = false);
+
+ /// @brief Delete all options configured for the subnet.
+ void delOptions();
+
+ /// @brief checks if the specified address is in pools
+ ///
+ /// Note the difference between inSubnet() and inPool(). For a given
+ /// subnet (e.g. 2001::/64) there may be one or more pools defined
+ /// that may or may not cover entire subnet, e.g. pool 2001::1-2001::10).
+ /// inPool() returning true implies inSubnet(), but the reverse implication
+ /// is not always true. For the given example, 2001::1234:abcd would return
+ /// true for inSubnet(), but false for inPool() check.
+ ///
+ /// @param addr this address will be checked if it belongs to any pools in
+ /// that subnet
+ /// @return true if the address is in any of the pools
+ virtual bool inPool(const isc::asiolink::IOAddress& addr) const = 0;
+
+ /// @brief return valid-lifetime for addresses in that prefix
+ Triplet<uint32_t> getValid() const {
+ return (valid_);
+ }
+
+ /// @brief returns T1 (renew timer), expressed in seconds
+ Triplet<uint32_t> getT1() const {
+ return (t1_);
+ }
+
+ /// @brief returns T2 (rebind timer), expressed in seconds
+ Triplet<uint32_t> getT2() const {
+ return (t2_);
+ }
+
+ /// @brief Return a collection of options.
+ ///
+ /// @return reference to collection of options configured for a subnet.
+ /// The returned reference is valid as long as the Subnet object which
+ /// returned it still exists.
+ const OptionContainer& getOptions() {
+ return (options_);
+ }
+
+ /// @brief returns the last address that was tried from this pool
+ ///
+ /// This method returns the last address that was attempted to be allocated
+ /// from this subnet. This is used as helper information for the next
+ /// iteration of the allocation algorithm.
+ ///
+ /// @todo: Define map<SubnetID, IOAddress> somewhere in the
+ /// AllocEngine::IterativeAllocator and keep the data there
+ ///
+ /// @return address that was last tried from this pool
+ isc::asiolink::IOAddress getLastAllocated() const {
+ return (last_allocated_);
+ }
+
+ /// @brief sets the last address that was tried from this pool
+ ///
+ /// This method sets the last address that was attempted to be allocated
+ /// from this subnet. This is used as helper information for the next
+ /// iteration of the allocation algorithm.
+ ///
+ /// @todo: Define map<SubnetID, IOAddress> somewhere in the
+ /// AllocEngine::IterativeAllocator and keep the data there
+ void setLastAllocated(const isc::asiolink::IOAddress& addr) {
+ last_allocated_ = addr;
+ }
+
+ /// @brief returns unique ID for that subnet
+ /// @return unique ID for that subnet
+ SubnetID getID() const { return (id_); }
+
+protected:
+ /// @brief protected constructor
+ //
+ /// By making the constructor protected, we make sure that noone will
+ /// ever instantiate that class. Pool4 and Pool6 should be used instead.
+ Subnet(const isc::asiolink::IOAddress& prefix, uint8_t len,
+ const Triplet<uint32_t>& t1,
+ const Triplet<uint32_t>& t2,
+ const Triplet<uint32_t>& valid_lifetime);
+
+ /// @brief virtual destructor
+ ///
+ /// A virtual destructor is needed because other classes
+ /// derive from this class.
+ virtual ~Subnet() { };
+
+ /// @brief returns the next unique Subnet-ID
+ ///
+ /// @return the next unique Subnet-ID
+ static SubnetID getNextID() {
+ static SubnetID id = 0;
+ return (id++);
+ }
+
+ /// @brief Check if option is valid and can be added to a subnet.
+ ///
+ /// @param option option to be validated.
+ virtual void validateOption(const OptionPtr& option) const = 0;
+
+ /// @brief subnet-id
+ ///
+ /// Subnet-id is a unique value that can be used to find or identify
+ /// a Subnet4 or Subnet6.
+ SubnetID id_;
+
+ /// @brief a prefix of the subnet
+ isc::asiolink::IOAddress prefix_;
+
+ /// @brief a prefix length of the subnet
+ uint8_t prefix_len_;
+
+ /// @brief a tripet (min/default/max) holding allowed renew timer values
+ Triplet<uint32_t> t1_;
+
+ /// @brief a tripet (min/default/max) holding allowed rebind timer values
+ Triplet<uint32_t> t2_;
+
+ /// @brief a tripet (min/default/max) holding allowed valid lifetime values
+ Triplet<uint32_t> valid_;
+
+ /// @brief a collection of DHCP options configured for a subnet.
+ OptionContainer options_;
+
+ /// @brief last allocated address
+ ///
+ /// This is the last allocated address that was previously allocated from
+ /// this particular subnet. Some allocation algorithms (e.g. iterative) use
+ /// that value, others do not. It should be noted that although the value
+ /// is usually correct, there are cases when it is invalid, e.g. after
+ /// removing a pool, restarting or changing allocation algorithms. For
+ /// that purpose it should be only considered a help that should not be
+ /// fully trusted.
+ isc::asiolink::IOAddress last_allocated_;
+};
+
+/// @brief A configuration holder for IPv4 subnet.
+///
+/// This class represents an IPv4 subnet.
+class Subnet4 : public Subnet {
+public:
+
+ /// @brief Constructor with all parameters
+ ///
+ /// @param prefix Subnet4 prefix
+ /// @param length prefix length
+ /// @param t1 renewal timer (in seconds)
+ /// @param t2 rebind timer (in seconds)
+ /// @param valid_lifetime preferred lifetime of leases (in seconds)
+ Subnet4(const isc::asiolink::IOAddress& prefix, uint8_t length,
+ const Triplet<uint32_t>& t1,
+ const Triplet<uint32_t>& t2,
+ const Triplet<uint32_t>& valid_lifetime);
+
+ /// @brief Returns a pool that specified address belongs to
+ ///
+ /// @param hint address that the returned pool should cover (optional)
+ /// @return Pointer to found pool4 (or NULL)
+ Pool4Ptr getPool4(const isc::asiolink::IOAddress& hint =
+ isc::asiolink::IOAddress("0.0.0.0"));
+
+ /// @brief Adds a new pool.
+ /// @param pool pool to be added
+ void addPool4(const Pool4Ptr& pool);
+
+ /// @brief returns all pools
+ ///
+ /// The reference is only valid as long as the object that returned it.
+ ///
+ /// @return a collection of all pools
+ const Pool4Collection& getPools() const {
+ return pools_;
+ }
+
+ /// @brief checks if the specified address is in pools
+ ///
+ /// See the description in \ref Subnet::inPool().
+ ///
+ /// @param addr this address will be checked if it belongs to any pools in that subnet
+ /// @return true if the address is in any of the pools
+ bool inPool(const isc::asiolink::IOAddress& addr) const;
+
+protected:
+
+ /// @brief Check if option is valid and can be added to a subnet.
+ ///
+ /// @param option option to be validated.
+ ///
+ /// @throw isc::BadValue if provided option is invalid.
+ virtual void validateOption(const OptionPtr& option) const;
+
+ /// @brief collection of pools in that list
+ Pool4Collection pools_;
+};
+
+/// @brief A pointer to a Subnet4 object
+typedef boost::shared_ptr<Subnet4> Subnet4Ptr;
+
+/// @brief A collection of Subnet6 objects
+typedef std::vector<Subnet4Ptr> Subnet4Collection;
+
+
+/// @brief A configuration holder for IPv6 subnet.
+///
+/// This class represents an IPv6 subnet.
+class Subnet6 : public Subnet {
+public:
+
+ /// @brief Constructor with all parameters
+ ///
+ /// @param prefix Subnet6 prefix
+ /// @param length prefix length
+ /// @param t1 renewal timer (in seconds)
+ /// @param t2 rebind timer (in seconds)
+ /// @param preferred_lifetime preferred lifetime of leases (in seconds)
+ /// @param valid_lifetime preferred lifetime of leases (in seconds)
+ Subnet6(const isc::asiolink::IOAddress& prefix, uint8_t length,
+ const Triplet<uint32_t>& t1,
+ const Triplet<uint32_t>& t2,
+ const Triplet<uint32_t>& preferred_lifetime,
+ const Triplet<uint32_t>& valid_lifetime);
+
+ /// @brief Returns preverred lifetime (in seconds)
+ ///
+ /// @return a triplet with preferred lifetime
+ Triplet<uint32_t> getPreferred() const {
+ return (preferred_);
+ }
+
+ /// @brief Returns a pool that specified address belongs to
+ ///
+ /// @param hint address that the returned pool should cover (optional)
+ /// @return Pointer to found pool6 (or NULL)
+ Pool6Ptr getPool6(const isc::asiolink::IOAddress& hint =
+ isc::asiolink::IOAddress("::"));
+
+ /// @brief Adds a new pool.
+ /// @param pool pool to be added
+ void addPool6(const Pool6Ptr& pool);
+
+ /// @brief returns all pools
+ ///
+ /// The reference is only valid as long as the object that
+ /// returned it.
+ ///
+ /// @return a collection of all pools
+ const Pool6Collection& getPools() const {
+ return pools_;
+ }
+
+ /// @brief checks if the specified address is in pools
+ ///
+ /// See the description in \ref Subnet::inPool().
+ ///
+ /// @param addr this address will be checked if it belongs to any pools in that subnet
+ /// @return true if the address is in any of the pools
+ bool inPool(const isc::asiolink::IOAddress& addr) const;
+
+protected:
+
+ /// @brief Check if option is valid and can be added to a subnet.
+ ///
+ /// @param option option to be validated.
+ ///
+ /// @throw isc::BadValue if provided option is invalid.
+ virtual void validateOption(const OptionPtr& option) const;
+
+ /// @brief collection of pools in that list
+ Pool6Collection pools_;
+
+ /// @brief a triplet with preferred lifetime (in seconds)
+ Triplet<uint32_t> preferred_;
+};
+
+/// @brief A pointer to a Subnet6 object
+typedef boost::shared_ptr<Subnet6> Subnet6Ptr;
+
+/// @brief A collection of Subnet6 objects
+typedef std::vector<Subnet6Ptr> Subnet6Collection;
+
+} // end of isc::dhcp namespace
+} // end of isc namespace
+
+#endif // SUBNET_T
diff --git a/src/lib/dhcp/tests/.gitignore b/src/lib/dhcp/tests/.gitignore
index 313429d..89ea505 100644
--- a/src/lib/dhcp/tests/.gitignore
+++ b/src/lib/dhcp/tests/.gitignore
@@ -1 +1,2 @@
/libdhcp++_unittests
+/libdhcpsrv_unittests
diff --git a/src/lib/dhcp/tests/Makefile.am b/src/lib/dhcp/tests/Makefile.am
index 9e00ab0..fcbdec8 100644
--- a/src/lib/dhcp/tests/Makefile.am
+++ b/src/lib/dhcp/tests/Makefile.am
@@ -24,7 +24,7 @@ TESTS_ENVIRONMENT = \
TESTS =
if HAVE_GTEST
-TESTS += libdhcp++_unittests
+TESTS += libdhcp++_unittests libdhcpsrv_unittests
libdhcp___unittests_SOURCES = run_unittests.cc
libdhcp___unittests_SOURCES += libdhcp++_unittest.cc
libdhcp___unittests_SOURCES += iface_mgr_unittest.cc
@@ -32,26 +32,52 @@ libdhcp___unittests_SOURCES += option6_iaaddr_unittest.cc
libdhcp___unittests_SOURCES += option6_ia_unittest.cc
libdhcp___unittests_SOURCES += option6_addrlst_unittest.cc
libdhcp___unittests_SOURCES += option4_addrlst_unittest.cc
+libdhcp___unittests_SOURCES += option6_int_unittest.cc
+libdhcp___unittests_SOURCES += option6_int_array_unittest.cc
libdhcp___unittests_SOURCES += option_unittest.cc
+libdhcp___unittests_SOURCES += option_definition_unittest.cc
libdhcp___unittests_SOURCES += pkt6_unittest.cc
libdhcp___unittests_SOURCES += pkt4_unittest.cc
+libdhcp___unittests_SOURCES += duid_unittest.cc
libdhcp___unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES) $(LOG4CPLUS_INCLUDES)
libdhcp___unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
-
libdhcp___unittests_CXXFLAGS = $(AM_CXXFLAGS)
+libdhcpsrv_unittests_SOURCES = run_unittests.cc
+libdhcpsrv_unittests_SOURCES += cfgmgr_unittest.cc triplet_unittest.cc
+libdhcpsrv_unittests_SOURCES += pool_unittest.cc subnet_unittest.cc
+libdhcpsrv_unittests_SOURCES += addr_utilities_unittest.cc
+libdhcpsrv_unittests_SOURCES += memfile_lease_mgr.cc memfile_lease_mgr.h
+libdhcpsrv_unittests_SOURCES += lease_mgr_unittest.cc
+libdhcpsrv_unittests_SOURCES += alloc_engine_unittest.cc
+
+libdhcpsrv_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES) $(LOG4CPLUS_INCLUDES)
+libdhcpsrv_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS)
+libdhcpsrv_unittests_CXXFLAGS = $(AM_CXXFLAGS)
+libdhcpsrv_unittests_LDADD = $(GTEST_LDADD)
+libdhcpsrv_unittests_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
+libdhcpsrv_unittests_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
+libdhcpsrv_unittests_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcp++.la
+libdhcpsrv_unittests_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcpsrv.la
+libdhcpsrv_unittests_LDADD += $(top_builddir)/src/lib/dhcp/libb10-dhcp++.la
+libdhcpsrv_unittests_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
+
+
if USE_CLANGPP
# This is to workaround unused variables tcout and tcerr in
# log4cplus's streams.h and unused parameters from some of the
# Boost headers.
libdhcp___unittests_CXXFLAGS += -Wno-unused-variable -Wno-unused-parameter
+libdhcpsrv_unittests_CXXFLAGS += -Wno-unused-variable -Wno-unused-parameter
endif
+
libdhcp___unittests_LDADD = $(top_builddir)/src/lib/dhcp/libb10-dhcp++.la
libdhcp___unittests_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
libdhcp___unittests_LDADD += $(top_builddir)/src/lib/util/libb10-util.la
libdhcp___unittests_LDADD += $(top_builddir)/src/lib/asiolink/libb10-asiolink.la
libdhcp___unittests_LDADD += $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
+libdhcp___unittests_LDADD += $(top_builddir)/src/lib/log/libb10-log.la
libdhcp___unittests_LDADD += $(GTEST_LDADD)
endif
diff --git a/src/lib/dhcp/tests/addr_utilities_unittest.cc b/src/lib/dhcp/tests/addr_utilities_unittest.cc
new file mode 100644
index 0000000..2ea4e2a
--- /dev/null
+++ b/src/lib/dhcp/tests/addr_utilities_unittest.cc
@@ -0,0 +1,154 @@
+
+// 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 <stdint.h>
+#include <stdlib.h>
+
+#include <gtest/gtest.h>
+#include <vector>
+
+#include <dhcp/addr_utilities.h>
+
+using namespace std;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+
+// This test verifies that lastAddrInPrefix is able to handle IPv4 operations.
+TEST(AddrUtilitiesTest, lastAddrInPrefix4) {
+ IOAddress addr1("192.0.2.1");
+
+ // Prefixes rounded to addresses are easy...
+ EXPECT_EQ("192.255.255.255", lastAddrInPrefix(addr1, 8).toText());
+ EXPECT_EQ("192.0.255.255", lastAddrInPrefix(addr1, 16).toText());
+ EXPECT_EQ("192.0.2.255", lastAddrInPrefix(addr1, 24).toText());
+
+ // these are trickier
+ EXPECT_EQ("192.0.2.127", lastAddrInPrefix(addr1, 25).toText());
+ EXPECT_EQ("192.0.2.63", lastAddrInPrefix(addr1, 26).toText());
+ EXPECT_EQ("192.0.2.31", lastAddrInPrefix(addr1, 27).toText());
+ EXPECT_EQ("192.0.2.15", lastAddrInPrefix(addr1, 28).toText());
+ EXPECT_EQ("192.0.2.7", lastAddrInPrefix(addr1, 29).toText());
+ EXPECT_EQ("192.0.2.3", lastAddrInPrefix(addr1, 30).toText());
+
+ // that doesn't make much sense as /31 subnet consists of network address
+ // and a broadcast address, with 0 usable addresses.
+ EXPECT_EQ("192.0.2.1", lastAddrInPrefix(addr1, 31).toText());
+ EXPECT_EQ("192.0.2.1", lastAddrInPrefix(addr1, 32).toText());
+
+ // Let's check extreme cases
+ IOAddress anyAddr("0.0.0.0");
+ EXPECT_EQ("127.255.255.255", lastAddrInPrefix(anyAddr, 1).toText());
+ EXPECT_EQ("255.255.255.255", lastAddrInPrefix(anyAddr, 0).toText());
+ EXPECT_EQ("0.0.0.0", lastAddrInPrefix(anyAddr, 32).toText());
+}
+
+// This test checks if firstAddrInPrefix is able to handle IPv4 operations.
+TEST(AddrUtilitiesTest, firstAddrInPrefix4) {
+ IOAddress addr1("192.223.2.255");
+
+ // Prefixes rounded to addresses are easy...
+ EXPECT_EQ("192.0.0.0", firstAddrInPrefix(addr1, 8).toText());
+ EXPECT_EQ("192.223.0.0", firstAddrInPrefix(addr1, 16).toText());
+ EXPECT_EQ("192.223.2.0", firstAddrInPrefix(addr1, 24).toText());
+
+ // these are trickier
+ EXPECT_EQ("192.223.2.128", firstAddrInPrefix(addr1, 25).toText());
+ EXPECT_EQ("192.223.2.192", firstAddrInPrefix(addr1, 26).toText());
+ EXPECT_EQ("192.223.2.224", firstAddrInPrefix(addr1, 27).toText());
+ EXPECT_EQ("192.223.2.240", firstAddrInPrefix(addr1, 28).toText());
+ EXPECT_EQ("192.223.2.248", firstAddrInPrefix(addr1, 29).toText());
+ EXPECT_EQ("192.223.2.252", firstAddrInPrefix(addr1, 30).toText());
+
+ // that doesn't make much sense as /31 subnet consists of network address
+ // and a broadcast address, with 0 usable addresses.
+ EXPECT_EQ("192.223.2.254", firstAddrInPrefix(addr1, 31).toText());
+ EXPECT_EQ("192.223.2.255", firstAddrInPrefix(addr1, 32).toText());
+
+ // Let's check extreme cases.
+ IOAddress bcast("255.255.255.255");
+ EXPECT_EQ("128.0.0.0", firstAddrInPrefix(bcast, 1).toText());
+ EXPECT_EQ("0.0.0.0", firstAddrInPrefix(bcast, 0).toText());
+ EXPECT_EQ("255.255.255.255", firstAddrInPrefix(bcast, 32).toText());
+
+}
+
+/// This test checks if lastAddrInPrefix properly supports IPv6 operations
+TEST(AddrUtilitiesTest, lastAddrInPrefix6) {
+ IOAddress addr1("2001:db8:1:1234:5678:abcd:1234:beef");
+
+ // Prefixes rounded to nibbles are easy...
+ EXPECT_EQ("2001:db8:1:1234:5678:abcd:1234:ffff",
+ lastAddrInPrefix(addr1, 112).toText());
+ EXPECT_EQ("2001:db8:1:1234:5678:abcd:123f:ffff",
+ lastAddrInPrefix(addr1, 108).toText());
+ EXPECT_EQ("2001:db8:1:1234:5678:abcd:12ff:ffff",
+ lastAddrInPrefix(addr1, 104).toText());
+ EXPECT_EQ("2001:db8:1:1234:ffff:ffff:ffff:ffff",
+ lastAddrInPrefix(addr1, 64).toText());
+
+ IOAddress addr2("2001::");
+
+ // These are tricker, though, as they are done in 1 bit increments
+
+ // the last address in 2001::/127 pool should be 2001::1
+ EXPECT_EQ("2001::1", lastAddrInPrefix(addr2, 127).toText());
+
+ EXPECT_EQ("2001::3", lastAddrInPrefix(addr2, 126).toText());
+ EXPECT_EQ("2001::7", lastAddrInPrefix(addr2, 125).toText());
+ EXPECT_EQ("2001::f", lastAddrInPrefix(addr2, 124).toText());
+ EXPECT_EQ("2001::1f", lastAddrInPrefix(addr2, 123).toText());
+ EXPECT_EQ("2001::3f", lastAddrInPrefix(addr2, 122).toText());
+ EXPECT_EQ("2001::7f", lastAddrInPrefix(addr2, 121).toText());
+ EXPECT_EQ("2001::ff", lastAddrInPrefix(addr2, 120).toText());
+
+ // Let's check extreme cases
+ IOAddress anyAddr("::");
+ EXPECT_EQ("7fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
+ lastAddrInPrefix(anyAddr, 1).toText());
+ EXPECT_EQ("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
+ lastAddrInPrefix(anyAddr, 0).toText());
+ EXPECT_EQ("::", lastAddrInPrefix(anyAddr, 128).toText());
+}
+
+/// This test checks if firstAddrInPrefix properly supports IPv6 operations
+TEST(AddrUtilitiesTest, firstAddrInPrefix6) {
+ IOAddress addr1("2001:db8:1:1234:5678:1234:abcd:beef");
+
+ // Prefixes rounded to nibbles are easy...
+ EXPECT_EQ("2001:db8:1:1234:5678:1234::",
+ firstAddrInPrefix(addr1, 96).toText());
+ EXPECT_EQ("2001:db8:1:1234:5678:1230::",
+ firstAddrInPrefix(addr1, 92).toText());
+ EXPECT_EQ("2001:db8:1:1234:5678:1200::",
+ firstAddrInPrefix(addr1, 88).toText());
+ EXPECT_EQ("2001:db8:1:1234::",
+ firstAddrInPrefix(addr1, 64).toText());
+
+ IOAddress addr2("2001::ffff");
+
+ // These are tricker, though, as they are done in 1 bit increments
+
+ // the first address in 2001::/127 pool should be 2001::1
+ EXPECT_EQ("2001::fffe", firstAddrInPrefix(addr2, 127).toText());
+
+ EXPECT_EQ("2001::fffc", firstAddrInPrefix(addr2, 126).toText());
+ EXPECT_EQ("2001::fff8", firstAddrInPrefix(addr2, 125).toText());
+ EXPECT_EQ("2001::fff0", firstAddrInPrefix(addr2, 124).toText());
+ EXPECT_EQ("2001::ffe0", firstAddrInPrefix(addr2, 123).toText());
+ EXPECT_EQ("2001::ffc0", firstAddrInPrefix(addr2, 122).toText());
+ EXPECT_EQ("2001::ff80", firstAddrInPrefix(addr2, 121).toText());
+ EXPECT_EQ("2001::ff00", firstAddrInPrefix(addr2, 120).toText());
+}
diff --git a/src/lib/dhcp/tests/alloc_engine_unittest.cc b/src/lib/dhcp/tests/alloc_engine_unittest.cc
new file mode 100644
index 0000000..bbb4bbd
--- /dev/null
+++ b/src/lib/dhcp/tests/alloc_engine_unittest.cc
@@ -0,0 +1,349 @@
+// 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 <asiolink/io_address.h>
+#include <dhcp/lease_mgr.h>
+#include <dhcp/duid.h>
+#include <dhcp/alloc_engine.h>
+#include <dhcp/cfgmgr.h>
+#include "memfile_lease_mgr.h"
+#include <boost/shared_ptr.hpp>
+#include <iostream>
+#include <sstream>
+#include <map>
+#include <gtest/gtest.h>
+
+using namespace std;
+using namespace isc;
+using namespace isc::asiolink;
+using namespace isc::dhcp;
+using namespace isc::dhcp::test; // Memfile_LeaseMgr
+using namespace boost;
+
+namespace {
+
+class NakedAllocEngine : public AllocEngine {
+public:
+ NakedAllocEngine(AllocEngine::AllocType engine_type, unsigned int attempts)
+ :AllocEngine(engine_type, attempts) {
+ }
+ using AllocEngine::Allocator;
+ using AllocEngine::IterativeAllocator;
+};
+
+// empty class for now, but may be extended once Addr6 becomes bigger
+class AllocEngineTest : public ::testing::Test {
+public:
+ AllocEngineTest() {
+ duid_ = boost::shared_ptr<DUID>(new DUID(vector<uint8_t>(8, 0x42)));
+ iaid_ = 42;
+
+ // instantiate cfg_mgr
+ CfgMgr& cfg_mgr = CfgMgr::instance();
+
+ subnet_ = Subnet6Ptr(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+ pool_ = Pool6Ptr(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8:1::10"),
+ IOAddress("2001:db8:1::20")));
+ subnet_->addPool6(pool_);
+ cfg_mgr.addSubnet6(subnet_);
+
+ leasemgr_ = new Memfile_LeaseMgr("");
+ }
+
+ void checkLease6(const Lease6Ptr& lease) {
+ // that is belongs to the right subnet
+ EXPECT_EQ(lease->subnet_id_, subnet_->getID());
+ EXPECT_TRUE(subnet_->inRange(lease->addr_));
+ EXPECT_TRUE(subnet_->inPool(lease->addr_));
+
+ // that it have proper parameters
+ EXPECT_EQ(iaid_, lease->iaid_);
+ EXPECT_EQ(subnet_->getValid(), lease->valid_lft_);
+ EXPECT_EQ(subnet_->getPreferred(), lease->preferred_lft_);
+ EXPECT_EQ(subnet_->getT1(), lease->t1_);
+ EXPECT_EQ(subnet_->getT2(), lease->t2_);
+ EXPECT_EQ(0, lease->prefixlen_); // this is IA_NA, not IA_PD
+ EXPECT_TRUE(false == lease->fqdn_fwd_);
+ EXPECT_TRUE(false == lease->fqdn_rev_);
+ EXPECT_TRUE(*lease->duid_ == *duid_);
+ // @todo: check cltt
+ }
+
+ ~AllocEngineTest() {
+ LeaseMgr::instance().destroy_instance();
+ leasemgr_ = NULL;
+ }
+
+ DuidPtr duid_;
+ uint32_t iaid_;
+ Subnet6Ptr subnet_;
+ Pool6Ptr pool_;
+ LeaseMgr* leasemgr_;
+};
+
+// This test checks if the Allocation Engine can be instantiated and that it
+// parses parameters string properly.
+TEST_F(AllocEngineTest, constructor) {
+
+ AllocEngine* x = NULL;
+
+ // Hashed and random allocators are not supported yet
+ ASSERT_THROW(x = new AllocEngine(AllocEngine::ALLOC_HASHED, 5), NotImplemented);
+ ASSERT_THROW(x = new AllocEngine(AllocEngine::ALLOC_RANDOM, 5), NotImplemented);
+
+ ASSERT_NO_THROW(x = new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
+
+ delete x;
+}
+
+/// @todo: This method is taken from mysql_lease_mgr_utilities.cc from ticket
+/// #2342. Get rid of one instance once the code is merged
+void
+detailCompareLease6(const Lease6Ptr& first, const Lease6Ptr& second) {
+ EXPECT_EQ(first->type_, second->type_);
+
+ // Compare address strings - odd things happen when they are different
+ // as the EXPECT_EQ appears to call the operator uint32_t() function,
+ // which causes an exception to be thrown for IPv6 addresses.
+ EXPECT_EQ(first->addr_.toText(), second->addr_.toText());
+ EXPECT_EQ(first->prefixlen_, second->prefixlen_);
+ EXPECT_EQ(first->iaid_, second->iaid_);
+ EXPECT_TRUE(first->hwaddr_ == second->hwaddr_);
+ EXPECT_TRUE(*first->duid_ == *second->duid_);
+ EXPECT_EQ(first->preferred_lft_, second->preferred_lft_);
+ EXPECT_EQ(first->valid_lft_, second->valid_lft_);
+ EXPECT_EQ(first->cltt_, second->cltt_);
+ EXPECT_EQ(first->subnet_id_, second->subnet_id_);
+}
+
+
+// This test checks if the simple allocation can succeed
+TEST_F(AllocEngineTest, simpleAlloc) {
+
+ AllocEngine* engine = NULL;
+ ASSERT_NO_THROW(engine = new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
+ ASSERT_TRUE(engine);
+
+ Lease6Ptr lease = engine->allocateAddress6(subnet_, duid_, iaid_, IOAddress("::"),
+ false);
+
+ // check that we got a lease
+ ASSERT_TRUE(lease);
+
+ // do all checks on the lease
+ checkLease6(lease);
+
+ // Check that the lease is indeed in LeaseMgr
+ Lease6Ptr from_mgr = LeaseMgr::instance().getLease6(lease->addr_);
+ ASSERT_TRUE(from_mgr);
+
+ // Now check that the lease in LeaseMgr has the same parameters
+ detailCompareLease6(lease, from_mgr);
+}
+
+// This test checks if the fake allocation (for SOLICIT) can succeed
+TEST_F(AllocEngineTest, fakeAlloc) {
+
+ AllocEngine* engine = NULL;
+ ASSERT_NO_THROW(engine = new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
+ ASSERT_TRUE(engine);
+
+ Lease6Ptr lease = engine->allocateAddress6(subnet_, duid_, iaid_, IOAddress("::"),
+ true);
+
+ // check that we got a lease
+ ASSERT_TRUE(lease);
+
+ // do all checks on the lease
+ checkLease6(lease);
+
+ // Check that the lease is NOT in LeaseMgr
+ Lease6Ptr from_mgr = LeaseMgr::instance().getLease6(lease->addr_);
+ ASSERT_FALSE(from_mgr);
+}
+
+// This test checks if the allocation with a hint that is valid (in range,
+// in pool and free) can succeed
+TEST_F(AllocEngineTest, allocWithValidHint) {
+
+ AllocEngine* engine = NULL;
+ ASSERT_NO_THROW(engine = new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
+ ASSERT_TRUE(engine);
+
+ Lease6Ptr lease = engine->allocateAddress6(subnet_, duid_, iaid_,
+ IOAddress("2001:db8:1::15"),
+ false);
+
+ // check that we got a lease
+ ASSERT_TRUE(lease);
+
+ // we should get what we asked for
+ EXPECT_EQ(lease->addr_.toText(), "2001:db8:1::15");
+
+ // do all checks on the lease
+ checkLease6(lease);
+
+ // Check that the lease is indeed in LeaseMgr
+ Lease6Ptr from_mgr = LeaseMgr::instance().getLease6(lease->addr_);
+ ASSERT_TRUE(from_mgr);
+
+ // Now check that the lease in LeaseMgr has the same parameters
+ detailCompareLease6(lease, from_mgr);
+}
+
+// This test checks if the allocation with a hint that is in range,
+// in pool, but is currently used) can succeed
+TEST_F(AllocEngineTest, allocWithUsedHint) {
+
+ AllocEngine* engine = NULL;
+ ASSERT_NO_THROW(engine = new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
+ ASSERT_TRUE(engine);
+
+ // let's create a lease and put it in the LeaseMgr
+ DuidPtr duid2 = boost::shared_ptr<DUID>(new DUID(vector<uint8_t>(8, 0xff)));
+ Lease6Ptr used(new Lease6(Lease6::LEASE_IA_NA, IOAddress("2001:db8:1::1f"),
+ duid2, 1, 2, 3, 4, 5, subnet_->getID()));
+ ASSERT_TRUE(LeaseMgr::instance().addLease(used));
+
+ // another client comes in and request an address that is in pool, but
+ // unfortunately it is used already. The same address must not be allocated
+ // twice.
+ Lease6Ptr lease = engine->allocateAddress6(subnet_, duid_, iaid_,
+ IOAddress("2001:db8:1::1f"),
+ false);
+ // check that we got a lease
+ ASSERT_TRUE(lease);
+
+ // allocated address must be different
+ EXPECT_TRUE(used->addr_.toText() != lease->addr_.toText());
+
+ // we should NOT get what we asked for, because it is used already
+ EXPECT_TRUE(lease->addr_.toText() != "2001:db8:1::1f");
+
+ // do all checks on the lease
+ checkLease6(lease);
+
+ // Check that the lease is indeed in LeaseMgr
+ Lease6Ptr from_mgr = LeaseMgr::instance().getLease6(lease->addr_);
+ ASSERT_TRUE(from_mgr);
+
+ // Now check that the lease in LeaseMgr has the same parameters
+ detailCompareLease6(lease, from_mgr);
+}
+
+// This test checks if the allocation with a hint that is out the blue
+// can succeed. The invalid hint should be ignored completely.
+TEST_F(AllocEngineTest, allocBogusHint) {
+
+ AllocEngine* engine = NULL;
+ ASSERT_NO_THROW(engine = new AllocEngine(AllocEngine::ALLOC_ITERATIVE, 100));
+ ASSERT_TRUE(engine);
+
+ // Client would like to get a 3000::abc lease, which does not belong to any
+ // supported lease. Allocation engine should ignore it and carry on
+ // with the normal allocation
+ Lease6Ptr lease = engine->allocateAddress6(subnet_, duid_, iaid_,
+ IOAddress("3000::abc"),
+ false);
+ // check that we got a lease
+ ASSERT_TRUE(lease);
+
+ // we should NOT get what we asked for, because it is used already
+ EXPECT_TRUE(lease->addr_.toText() != "3000::abc");
+
+ // do all checks on the lease
+ checkLease6(lease);
+
+ // Check that the lease is indeed in LeaseMgr
+ Lease6Ptr from_mgr = LeaseMgr::instance().getLease6(lease->addr_);
+ ASSERT_TRUE(from_mgr);
+
+ // Now check that the lease in LeaseMgr has the same parameters
+ detailCompareLease6(lease, from_mgr);
+}
+
+// This test verifies that the allocator picks addresses that belong to the
+// pool
+TEST_F(AllocEngineTest, IterativeAllocator) {
+ NakedAllocEngine::Allocator* alloc = new NakedAllocEngine::IterativeAllocator();
+
+ for (int i = 0; i < 1000; ++i) {
+ IOAddress candidate = alloc->pickAddress(subnet_, duid_, IOAddress("::"));
+
+ EXPECT_TRUE(subnet_->inPool(candidate));
+ }
+
+ delete alloc;
+}
+
+
+// This test verifies that the iterative allocator really walks over all addresses
+// in all pools in specified subnet. It also must not pick the same address twice
+// unless it runs out of pool space and must start over.
+TEST_F(AllocEngineTest, IterativeAllocator_manyPools) {
+ NakedAllocEngine::IterativeAllocator* alloc = new NakedAllocEngine::IterativeAllocator();
+
+ // let's start from 2, as there is 2001:db8:1::10 - 2001:db8:1::20 pool already.
+ for (int i = 2; i < 10; ++i) {
+ stringstream min, max;
+
+ min << "2001:db8:1::" << hex << i*16 + 1;
+ max << "2001:db8:1::" << hex << i*16 + 9;
+
+ Pool6Ptr pool(new Pool6(Pool6::TYPE_IA, IOAddress(min.str()),
+ IOAddress(max.str())));
+ // cout << "Adding pool: " << min.str() << "-" << max.str() << endl;
+ subnet_->addPool6(pool);
+ }
+
+ int total = 17 + 8*9; // first pool (::10 - ::20) has 17 addresses in it,
+ // there are 8 extra pools with 9 addresses in each.
+
+ // Let's keep picked addresses here and check their uniqueness.
+ std::map<IOAddress, int> generated_addrs;
+ int cnt = 0;
+ while (++cnt) {
+ IOAddress candidate = alloc->pickAddress(subnet_, duid_, IOAddress("::"));
+ EXPECT_TRUE(subnet_->inPool(candidate));
+
+ // One way to easily verify that the iterative allocator really works is
+ // to uncomment the following line and observe its output that it
+ // covers all defined subnets.
+ // cout << candidate.toText() << endl;
+
+ if (generated_addrs.find(candidate) == generated_addrs.end()) {
+ // we haven't had this
+ generated_addrs[candidate] = 0;
+ } else {
+ // we have seen this address before. That should mean that we
+ // iterated over all addresses.
+ if (generated_addrs.size() == total) {
+ // we have exactly the number of address in all pools
+ break;
+ }
+ ADD_FAILURE() << "Too many or not enough unique addresses generated.";
+ break;
+ }
+
+ if ( cnt>total ) {
+ ADD_FAILURE() << "Too many unique addresses generated.";
+ break;
+ }
+ }
+
+ delete alloc;
+}
+
+}; // end of anonymous namespace
diff --git a/src/lib/dhcp/tests/cfgmgr_unittest.cc b/src/lib/dhcp/tests/cfgmgr_unittest.cc
new file mode 100644
index 0000000..a1ad865
--- /dev/null
+++ b/src/lib/dhcp/tests/cfgmgr_unittest.cc
@@ -0,0 +1,99 @@
+// 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 <iostream>
+#include <sstream>
+#include <arpa/inet.h>
+#include <gtest/gtest.h>
+#include <dhcp/cfgmgr.h>
+#include <exceptions/exceptions.h>
+
+using namespace std;
+using namespace isc::asiolink;
+using namespace isc::dhcp;
+using namespace isc::util;
+using namespace isc;
+
+// don't import the entire boost namespace. It will unexpectedly hide uint8_t
+// for some systems.
+using boost::scoped_ptr;
+
+namespace {
+
+// This test verifies if the configuration manager is able to hold and return
+// valid leases
+TEST(CfgMgrTest, subnet4) {
+ CfgMgr& cfg_mgr = CfgMgr::instance();
+
+ ASSERT_TRUE(&cfg_mgr != 0);
+
+ Subnet4Ptr subnet1(new Subnet4(IOAddress("192.0.2.0"), 26, 1, 2, 3));
+ Subnet4Ptr subnet2(new Subnet4(IOAddress("192.0.2.64"), 26, 1, 2, 3));
+ Subnet4Ptr subnet3(new Subnet4(IOAddress("192.0.2.128"), 26, 1, 2, 3));
+
+ // there shouldn't be any subnet configured at this stage
+ EXPECT_EQ( Subnet4Ptr(), cfg_mgr.getSubnet4(IOAddress("192.0.2.0")));
+
+ cfg_mgr.addSubnet4(subnet1);
+
+ // Now we have only one subnet, any request will be served from it
+ EXPECT_EQ(subnet1, cfg_mgr.getSubnet4(IOAddress("192.0.2.63")));
+
+ // Now we add more subnets and check that both old and new subnets
+ // are accessible.
+ cfg_mgr.addSubnet4(subnet2);
+ cfg_mgr.addSubnet4(subnet3);
+
+ EXPECT_EQ(subnet3, cfg_mgr.getSubnet4(IOAddress("192.0.2.191")));
+ EXPECT_EQ(subnet1, cfg_mgr.getSubnet4(IOAddress("192.0.2.15")));
+ EXPECT_EQ(subnet2, cfg_mgr.getSubnet4(IOAddress("192.0.2.85")));
+
+ // Try to find an address that does not belong to any subnet
+ EXPECT_EQ(Subnet4Ptr(), cfg_mgr.getSubnet4(IOAddress("192.0.2.192")));
+}
+
+// This test verifies if the configuration manager is able to hold and return
+// valid leases
+TEST(CfgMgrTest, DISABLED_subnet6) {
+ CfgMgr& cfg_mgr = CfgMgr::instance();
+
+ ASSERT_TRUE(&cfg_mgr != 0);
+
+ Subnet6Ptr subnet1(new Subnet6(IOAddress("2000::"), 48, 1, 2, 3, 4));
+ Subnet6Ptr subnet2(new Subnet6(IOAddress("3000::"), 48, 1, 2, 3, 4));
+ Subnet6Ptr subnet3(new Subnet6(IOAddress("4000::"), 48, 1, 2, 3, 4));
+
+ // there shouldn't be any subnet configured at this stage
+ EXPECT_EQ( Subnet6Ptr(), cfg_mgr.getSubnet6(IOAddress("2000::1")));
+
+ cfg_mgr.addSubnet6(subnet1);
+
+ // Now we have only one subnet, any request will be served from it
+ EXPECT_EQ(subnet1, cfg_mgr.getSubnet6(IOAddress("2000::1")));
+
+ cfg_mgr.addSubnet6(subnet2);
+ cfg_mgr.addSubnet6(subnet3);
+
+ EXPECT_EQ(subnet3, cfg_mgr.getSubnet6(IOAddress("4000::123")));
+ EXPECT_EQ(subnet2, cfg_mgr.getSubnet6(IOAddress("3000::dead:beef")));
+ EXPECT_EQ(Subnet6Ptr(), cfg_mgr.getSubnet6(IOAddress("5000::1")));
+
+ cfg_mgr.deleteSubnets6();
+ EXPECT_EQ(Subnet6Ptr(), cfg_mgr.getSubnet6(IOAddress("200::123")));
+ EXPECT_EQ(Subnet6Ptr(), cfg_mgr.getSubnet6(IOAddress("3000::123")));
+ EXPECT_EQ(Subnet6Ptr(), cfg_mgr.getSubnet6(IOAddress("4000::123")));
+}
+
+} // end of anonymous namespace
diff --git a/src/lib/dhcp/tests/duid_unittest.cc b/src/lib/dhcp/tests/duid_unittest.cc
new file mode 100644
index 0000000..aaf6d91
--- /dev/null
+++ b/src/lib/dhcp/tests/duid_unittest.cc
@@ -0,0 +1,169 @@
+// 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 <config.h>
+#include <iostream>
+#include <sstream>
+#include <arpa/inet.h>
+#include <gtest/gtest.h>
+#include <exceptions/exceptions.h>
+#include <boost/scoped_ptr.hpp>
+#include <asiolink/io_address.h>
+#include <dhcp/duid.h>
+
+using namespace std;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+
+// don't import the entire boost namespace. It will unexpectedly hide uint8_t
+// for some systems.
+using boost::scoped_ptr;
+
+namespace {
+
+// This test verifies if the constructors are working as expected
+// and process passed parameters.
+TEST(DuidTest, constructor) {
+
+ uint8_t data1[] = {0, 1, 2, 3, 4, 5, 6};
+
+ vector<uint8_t> data2(data1, data1 + sizeof(data1));
+
+ scoped_ptr<DUID> duid1(new DUID(data1, sizeof(data1)));
+ scoped_ptr<DUID> duid2(new DUID(data2));
+
+ vector<uint8_t> vecdata = duid1->getDuid();
+ EXPECT_TRUE(data2 == vecdata);
+ EXPECT_EQ(DUID::DUID_LLT, duid1->getType());
+
+ vecdata = duid2->getDuid();
+ EXPECT_TRUE(data2 == vecdata);
+
+ EXPECT_EQ(DUID::DUID_LLT, duid2->getType());
+}
+
+// This test verifies if DUID size restrictions are implemented
+// properly.
+TEST(DuidTest, size) {
+ const int MAX_DUID_SIZE = 128;
+ uint8_t data[MAX_DUID_SIZE + 1];
+ vector<uint8_t> data2;
+ for (uint8_t i = 0; i < MAX_DUID_SIZE + 1; ++i) {
+ data[i] = i;
+ if (i < MAX_DUID_SIZE)
+ data2.push_back(i);
+ }
+ ASSERT_EQ(data2.size(), MAX_DUID_SIZE);
+
+ scoped_ptr<DUID> duidmaxsize1(new DUID(data, MAX_DUID_SIZE));
+ scoped_ptr<DUID> duidmaxsize2(new DUID(data2));
+
+ EXPECT_THROW(
+ scoped_ptr<DUID> toolarge1(new DUID(data, MAX_DUID_SIZE + 1)),
+ OutOfRange);
+
+ // that's one too much
+ data2.push_back(128);
+
+ EXPECT_THROW(
+ scoped_ptr<DUID> toolarge2(new DUID(data2)),
+ OutOfRange);
+}
+
+// This test verifies if the implementation supports all defined
+// DUID types.
+TEST(DuidTest, getType) {
+ uint8_t llt[] = {0, 1, 2, 3, 4, 5, 6};
+ uint8_t en[] = {0, 2, 2, 3, 4, 5, 6};
+ uint8_t ll[] = {0, 3, 2, 3, 4, 5, 6};
+ uint8_t uuid[] = {0, 4, 2, 3, 4, 5, 6};
+ uint8_t invalid[] = {0,55, 2, 3, 4, 5, 6};
+
+ scoped_ptr<DUID> duid_llt(new DUID(llt, sizeof(llt)));
+ scoped_ptr<DUID> duid_en(new DUID(en, sizeof(en)));
+ scoped_ptr<DUID> duid_ll(new DUID(ll, sizeof(ll)));
+ scoped_ptr<DUID> duid_uuid(new DUID(uuid, sizeof(uuid)));
+ scoped_ptr<DUID> duid_invalid(new DUID(invalid, sizeof(invalid)));
+
+ EXPECT_EQ(DUID::DUID_LLT, duid_llt->getType());
+ EXPECT_EQ(DUID::DUID_EN, duid_en->getType());
+ EXPECT_EQ(DUID::DUID_LL, duid_ll->getType());
+ EXPECT_EQ(DUID::DUID_UUID, duid_uuid->getType());
+ EXPECT_EQ(DUID::DUID_UNKNOWN, duid_invalid->getType());
+}
+
+// This test checks if the comparison operators are sane.
+TEST(DuidTest, operators) {
+ uint8_t data1[] = {0, 1, 2, 3, 4, 5, 6};
+ uint8_t data2[] = {0, 1, 2, 3, 4};
+ uint8_t data3[] = {0, 1, 2, 3, 4, 5, 7}; // last digit different
+ uint8_t data4[] = {0, 1, 2, 3, 4, 5, 6}; // the same as 1
+
+ scoped_ptr<DUID> duid1(new DUID(data1, sizeof(data1)));
+ scoped_ptr<DUID> duid2(new DUID(data2, sizeof(data2)));
+ scoped_ptr<DUID> duid3(new DUID(data3, sizeof(data3)));
+ scoped_ptr<DUID> duid4(new DUID(data4, sizeof(data4)));
+
+ EXPECT_TRUE(*duid1 == *duid4);
+ EXPECT_FALSE(*duid1 == *duid2);
+ EXPECT_FALSE(*duid1 == *duid3);
+
+ EXPECT_FALSE(*duid1 != *duid4);
+ EXPECT_TRUE(*duid1 != *duid2);
+ EXPECT_TRUE(*duid1 != *duid3);
+}
+
+// This test verifies if the ClientId constructors are working properly
+// and passed parameters are used
+TEST(ClientIdTest, constructor) {
+ IOAddress addr2("192.0.2.1");
+ IOAddress addr3("2001:db8:1::1");
+
+ uint8_t data1[] = {0, 1, 2, 3, 4, 5, 6};
+ vector<uint8_t> data2(data1, data1 + sizeof(data1));
+
+ // checks for C-style construtor (uint8_t * + len)
+ scoped_ptr<ClientId> id1(new ClientId(data1, sizeof(data1)));
+ vector<uint8_t> vecdata = id1->getClientId();
+ EXPECT_TRUE(data2 == vecdata);
+
+ // checks for vector-based constructor
+ scoped_ptr<ClientId> id2(new ClientId(data2));
+ vecdata = id2->getClientId();
+ EXPECT_TRUE(data2 == vecdata);
+}
+
+// This test checks if the comparison operators are sane.
+TEST(ClientIdTest, operators) {
+ uint8_t data1[] = {0, 1, 2, 3, 4, 5, 6};
+ uint8_t data2[] = {0, 1, 2, 3, 4};
+ uint8_t data3[] = {0, 1, 2, 3, 4, 5, 7}; // last digit different
+ uint8_t data4[] = {0, 1, 2, 3, 4, 5, 6}; // the same as 1
+
+ scoped_ptr<ClientId> id1(new ClientId(data1, sizeof(data1)));
+ scoped_ptr<ClientId> id2(new ClientId(data2, sizeof(data2)));
+ scoped_ptr<ClientId> id3(new ClientId(data3, sizeof(data3)));
+ scoped_ptr<ClientId> id4(new ClientId(data4, sizeof(data4)));
+
+ EXPECT_TRUE(*id1 == *id4);
+ EXPECT_FALSE(*id1 == *id2);
+ EXPECT_FALSE(*id1 == *id3);
+
+ EXPECT_FALSE(*id1 != *id4);
+ EXPECT_TRUE(*id1 != *id2);
+ EXPECT_TRUE(*id1 != *id3);
+}
+
+} // end of anonymous namespace
diff --git a/src/lib/dhcp/tests/iface_mgr_unittest.cc b/src/lib/dhcp/tests/iface_mgr_unittest.cc
index 2c7b86b..462910b 100644
--- a/src/lib/dhcp/tests/iface_mgr_unittest.cc
+++ b/src/lib/dhcp/tests/iface_mgr_unittest.cc
@@ -1096,7 +1096,7 @@ void parse_ifconfig(const std::string& textFile, IfaceMgr::IfaceCollection& ifac
addr = addr.substr(0, addr.find_first_of(" "));
IOAddress a(addr);
iface->addAddress(a);
- } else if(line.find("Metric")) {
+ } else if(line.find("Metric") != string::npos) {
// flags
if (line.find("UP") != string::npos) {
iface->flag_up_ = true;
diff --git a/src/lib/dhcp/tests/lease_mgr_unittest.cc b/src/lib/dhcp/tests/lease_mgr_unittest.cc
new file mode 100644
index 0000000..e46bd09
--- /dev/null
+++ b/src/lib/dhcp/tests/lease_mgr_unittest.cc
@@ -0,0 +1,170 @@
+// 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 <iostream>
+#include <sstream>
+#include <gtest/gtest.h>
+#include <asiolink/io_address.h>
+#include <dhcp/lease_mgr.h>
+#include <dhcp/duid.h>
+#include "memfile_lease_mgr.h"
+
+using namespace std;
+using namespace isc;
+using namespace isc::asiolink;
+using namespace isc::dhcp;
+using namespace isc::dhcp::test; // Memfile_LeaseMgr
+
+namespace {
+// empty class for now, but may be extended once Addr6 becomes bigger
+class LeaseMgrTest : public ::testing::Test {
+public:
+ LeaseMgrTest() {
+ }
+};
+
+// This test checks if the LeaseMgr can be instantiated and that it
+// parses parameters string properly.
+TEST_F(LeaseMgrTest, constructor) {
+
+ // should not throw any exceptions here
+ Memfile_LeaseMgr * leaseMgr = new Memfile_LeaseMgr("");
+ delete leaseMgr;
+
+ leaseMgr = new Memfile_LeaseMgr("param1=value1 param2=value2");
+
+ EXPECT_EQ("value1", leaseMgr->getParameter("param1"));
+ EXPECT_EQ("value2", leaseMgr->getParameter("param2"));
+ EXPECT_THROW(leaseMgr->getParameter("param3"), BadValue);
+
+ delete leaseMgr;
+}
+
+// There's no point in calling any other methods in LeaseMgr, as they
+// are purely virtual, so we would only call Memfile_LeaseMgr methods.
+// Those methods are just stubs that does not return anything.
+// It seems likely that we will need to extend the memfile code for
+// allocation engine tests, so we may implement tests that call
+// Memfile_LeaseMgr methods then.
+
+TEST_F(LeaseMgrTest, addGetDelete) {
+ Memfile_LeaseMgr * leaseMgr = new Memfile_LeaseMgr("");
+
+ IOAddress addr("2001:db8:1::456");
+
+ uint8_t llt[] = {0, 1, 2, 3, 4, 5, 6, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf};
+ DuidPtr duid(new DUID(llt, sizeof(llt)));
+
+ uint32_t iaid = 7; // just a number
+
+ SubnetID subnet_id = 8; // just another number
+
+ Lease6Ptr lease(new Lease6(Lease6::LEASE_IA_NA, addr,
+ duid, iaid, 100, 200, 50, 80,
+ subnet_id));
+
+ EXPECT_TRUE(leaseMgr->addLease(lease));
+
+ // should not be allowed to add a second lease with the same address
+ EXPECT_FALSE(leaseMgr->addLease(lease));
+
+ Lease6Ptr x = leaseMgr->getLease6(IOAddress("2001:db8:1::234"));
+ EXPECT_EQ(Lease6Ptr(), x);
+
+ x = leaseMgr->getLease6(IOAddress("2001:db8:1::456"));
+ ASSERT_TRUE(x);
+
+ EXPECT_EQ(x->addr_.toText(), addr.toText());
+ EXPECT_TRUE(*x->duid_ == *duid);
+ EXPECT_EQ(x->iaid_, iaid);
+ EXPECT_EQ(x->subnet_id_, subnet_id);
+
+ // These are not important from lease management perspective, but
+ // let's check them anyway.
+ EXPECT_EQ(x->type_, Lease6::LEASE_IA_NA);
+ EXPECT_EQ(x->preferred_lft_, 100);
+ EXPECT_EQ(x->valid_lft_, 200);
+ EXPECT_EQ(x->t1_, 50);
+ EXPECT_EQ(x->t2_, 80);
+
+ // should return false - there's no such address
+ EXPECT_FALSE(leaseMgr->deleteLease6(IOAddress("2001:db8:1::789")));
+
+ // this one should succeed
+ EXPECT_TRUE(leaseMgr->deleteLease6(IOAddress("2001:db8:1::456")));
+
+ // after the lease is deleted, it should really be gone
+ x = leaseMgr->getLease6(IOAddress("2001:db8:1::456"));
+ EXPECT_EQ(Lease6Ptr(), x);
+
+ delete leaseMgr;
+}
+
+// This test checks there that leaseMgr is really a singleton and that
+// no more than one can be created.
+TEST_F(LeaseMgrTest, singleton) {
+ Memfile_LeaseMgr* leaseMgr1 = NULL;
+ Memfile_LeaseMgr* leaseMgr2 = NULL;
+
+ EXPECT_THROW(LeaseMgr::instance(), InvalidOperation);
+
+ EXPECT_NO_THROW( leaseMgr1 = new Memfile_LeaseMgr("") );
+
+ EXPECT_NO_THROW(LeaseMgr::instance());
+
+ // There can be only one instance of any LeaseMgr derived
+ // objects instantiated at any time.
+ ASSERT_THROW(leaseMgr2 = new Memfile_LeaseMgr(""), InvalidOperation);
+
+ delete leaseMgr1;
+
+ ASSERT_NO_THROW(leaseMgr2 = new Memfile_LeaseMgr("") );
+
+ delete leaseMgr2;
+}
+
+// This test checks if the Lease6 structure can be instantiated correctly
+TEST(Lease6, ctor) {
+
+ IOAddress addr("2001:db8:1::456");
+
+ uint8_t llt[] = {0, 1, 2, 3, 4, 5, 6, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf};
+ DuidPtr duid(new DUID(llt, sizeof(llt)));
+
+ uint32_t iaid = 7; // just a number
+
+ SubnetID subnet_id = 8; // just another number
+
+ Lease6Ptr x(new Lease6(Lease6::LEASE_IA_NA, addr,
+ duid, iaid, 100, 200, 50, 80,
+ subnet_id));
+
+ EXPECT_TRUE(x->addr_ == addr);
+ EXPECT_TRUE(*x->duid_ == *duid);
+ EXPECT_TRUE(x->iaid_ == iaid);
+ EXPECT_TRUE(x->subnet_id_ == subnet_id);
+ EXPECT_TRUE(x->type_ == Lease6::LEASE_IA_NA);
+ EXPECT_TRUE(x->preferred_lft_ == 100);
+ EXPECT_TRUE(x->valid_lft_ == 200);
+ EXPECT_TRUE(x->t1_ == 50);
+ EXPECT_TRUE(x->t2_ == 80);
+
+ // Lease6 must be instantiated with a DUID, not with NULL pointer
+ EXPECT_THROW(new Lease6(Lease6::LEASE_IA_NA, addr,
+ DuidPtr(), iaid, 100, 200, 50, 80,
+ subnet_id), InvalidOperation);
+}
+
+}; // end of anonymous namespace
diff --git a/src/lib/dhcp/tests/memfile_lease_mgr.cc b/src/lib/dhcp/tests/memfile_lease_mgr.cc
new file mode 100644
index 0000000..195fd8b
--- /dev/null
+++ b/src/lib/dhcp/tests/memfile_lease_mgr.cc
@@ -0,0 +1,113 @@
+// 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 "memfile_lease_mgr.h"
+
+using namespace isc::dhcp;
+using namespace isc::dhcp::test;
+
+Memfile_LeaseMgr::Memfile_LeaseMgr(const std::string& dbconfig)
+ : LeaseMgr(dbconfig) {
+}
+
+Memfile_LeaseMgr::~Memfile_LeaseMgr() {
+}
+
+bool Memfile_LeaseMgr::addLease(const Lease4Ptr&) {
+ return (false);
+}
+
+bool Memfile_LeaseMgr::addLease(const Lease6Ptr& lease) {
+ if (getLease6(lease->addr_)) {
+ // there is a lease with specified address already
+ return (false);
+ }
+ storage6_.insert(lease);
+ return (true);
+}
+
+Lease4Ptr Memfile_LeaseMgr::getLease4(isc::asiolink::IOAddress) const {
+ return (Lease4Ptr());
+}
+
+Lease4Collection Memfile_LeaseMgr::getLease4(const HWAddr& ) const {
+ return (Lease4Collection());
+}
+
+Lease4Ptr Memfile_LeaseMgr::getLease4(isc::asiolink::IOAddress ,
+ SubnetID) const {
+ return (Lease4Ptr());
+}
+
+Lease4Ptr Memfile_LeaseMgr::getLease4(const HWAddr&,
+ SubnetID) const {
+ return (Lease4Ptr());
+}
+
+
+Lease4Ptr Memfile_LeaseMgr::getLease4(const ClientId&,
+ SubnetID) const {
+ return (Lease4Ptr());
+}
+
+Lease4Collection Memfile_LeaseMgr::getLease4(const ClientId& ) const {
+ return (Lease4Collection());
+}
+
+Lease6Ptr Memfile_LeaseMgr::getLease6(const isc::asiolink::IOAddress& addr) const {
+ Lease6Storage::iterator l = storage6_.find(addr);
+ if (l == storage6_.end()) {
+ return (Lease6Ptr());
+ } else {
+ return (*l);
+ }
+}
+
+Lease6Collection Memfile_LeaseMgr::getLease6(const DUID& , uint32_t ) const {
+ return (Lease6Collection());
+}
+
+Lease6Ptr Memfile_LeaseMgr::getLease6(const DUID&, uint32_t,
+ SubnetID) const {
+
+ return (Lease6Ptr());
+}
+
+void Memfile_LeaseMgr::updateLease4(const Lease4Ptr& ) {
+}
+
+void Memfile_LeaseMgr::updateLease6(const Lease6Ptr& ) {
+
+}
+
+bool Memfile_LeaseMgr::deleteLease4(uint32_t ) {
+ return (false);
+}
+
+bool Memfile_LeaseMgr::deleteLease6(const isc::asiolink::IOAddress& addr) {
+ Lease6Storage::iterator l = storage6_.find(addr);
+ if (l == storage6_.end()) {
+ // no such lease
+ return (false);
+ } else {
+ storage6_.erase(l);
+ return (true);
+ }
+}
+
+std::string Memfile_LeaseMgr::getDescription() const {
+ return (std::string("This is a dummy memfile backend implementation.\n"
+ "It does not offer any useful lease management and its only\n"
+ "purpose is to test abstract lease manager API."));
+}
diff --git a/src/lib/dhcp/tests/memfile_lease_mgr.h b/src/lib/dhcp/tests/memfile_lease_mgr.h
new file mode 100644
index 0000000..c5a41e6
--- /dev/null
+++ b/src/lib/dhcp/tests/memfile_lease_mgr.h
@@ -0,0 +1,228 @@
+// 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 MEMFILE_LEASE_MGR_H
+#define MEMFILE_LEASE_MGR_H
+
+#include <dhcp/lease_mgr.h>
+#include <boost/multi_index_container.hpp>
+#include <boost/multi_index/indexed_by.hpp>
+#include <boost/multi_index/ordered_index.hpp>
+#include <boost/multi_index/member.hpp>
+
+namespace isc {
+namespace dhcp {
+namespace test {
+
+// This is a concrete implementation of a Lease database.
+//
+// It is for testing purposes only. It is NOT a production code.
+//
+// It does not do anything useful now, and is used for abstract LeaseMgr
+// class testing. It may later evolve into more useful backend if the
+// need arises. We can reuse code from memfile benchmark. See code in
+// tests/tools/dhcp-ubench/memfile_bench.{cc|h}
+class Memfile_LeaseMgr : public LeaseMgr {
+public:
+
+ /// @brief The sole lease manager constructor
+ ///
+ /// dbconfig is a generic way of passing parameters. Parameters
+ /// are passed in the "name=value" format, separated by spaces.
+ /// Values may be enclosed in double quotes, if needed.
+ ///
+ /// @param dbconfig database configuration
+ Memfile_LeaseMgr(const std::string& dbconfig);
+
+ /// @brief Destructor (closes file)
+ virtual ~Memfile_LeaseMgr();
+
+ /// @brief Adds an IPv4 lease.
+ ///
+ /// @todo Not implemented yet
+ /// @param lease lease to be added
+ virtual bool addLease(const Lease4Ptr& lease);
+
+ /// @brief Adds an IPv6 lease.
+ ///
+ /// @param lease lease to be added
+ virtual bool addLease(const Lease6Ptr& lease);
+
+ /// @brief Returns existing IPv4 lease for specified IPv4 address.
+ ///
+ /// @todo Not implemented yet
+ /// @param addr address of the searched lease
+ ///
+ /// @return a collection of leases
+ virtual Lease4Ptr getLease4(isc::asiolink::IOAddress addr) const;
+
+ /// @brief Returns existing IPv4 lease for specific address and subnet
+ ///
+ /// @todo Not implemented yet
+ /// @param addr address of the searched lease
+ /// @param subnet_id ID of the subnet the lease must belong to
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(isc::asiolink::IOAddress addr,
+ SubnetID subnet_id) const;
+
+ /// @brief Returns existing IPv4 leases for specified hardware address.
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// Although in the usual case there will be only one lease, for mobile
+ /// clients or clients with multiple static/fixed/reserved leases there
+ /// can be more than one. Thus return type is a container, not a single
+ /// pointer.
+ ///
+ /// @param hwaddr hardware address of the client
+ ///
+ /// @return lease collection
+ virtual Lease4Collection getLease4(const HWAddr& hwaddr) const;
+
+ /// @brief Returns existing IPv4 leases for specified hardware address
+ /// and a subnet
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// There can be at most one lease for a given HW address in a single
+ /// pool, so this method with either return a single lease or NULL.
+ ///
+ /// @param hwaddr hardware address of the client
+ /// @param subnet_id identifier of the subnet that lease must belong to
+ ///
+ /// @return a pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(const HWAddr& hwaddr,
+ SubnetID subnet_id) const;
+
+ /// @brief Returns existing IPv4 lease for specified client-id
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param clientid client identifier
+ virtual Lease4Collection getLease4(const ClientId& clientid) const;
+
+ /// @brief Returns existing IPv4 lease for specified client-id
+ ///
+ /// There can be at most one lease for a given HW address in a single
+ /// pool, so this method with either return a single lease or NULL.
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param clientid client identifier
+ /// @param subnet_id identifier of the subnet that lease must belong to
+ ///
+ /// @return a pointer to the lease (or NULL if a lease is not found)
+ virtual Lease4Ptr getLease4(const ClientId& clientid,
+ SubnetID subnet_id) const;
+
+ /// @brief Returns existing IPv6 lease for a given IPv6 address.
+ ///
+ /// @param addr address of the searched lease
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ Lease6Ptr getLease6(const isc::asiolink::IOAddress& addr) const;
+
+ /// @brief Returns existing IPv6 lease for a given DUID+IA combination
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param duid client DUID
+ /// @param iaid IA identifier
+ ///
+ /// @return collection of IPv6 leases
+ Lease6Collection getLease6(const DUID& duid, uint32_t iaid) const;
+
+ /// @brief Returns existing IPv6 lease for a given DUID+IA combination
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param duid client DUID
+ /// @param iaid IA identifier
+ /// @param subnet_id identifier of the subnet the lease must belong to
+ ///
+ /// @return smart pointer to the lease (or NULL if a lease is not found)
+ Lease6Ptr getLease6(const DUID& duid, uint32_t iaid, SubnetID subnet_id) const;
+
+ /// @brief Updates IPv4 lease.
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param lease4 The lease to be updated.
+ ///
+ /// If no such lease is present, an exception will be thrown.
+ void updateLease4(const Lease4Ptr& lease4);
+
+ /// @brief Updates IPv4 lease.
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param lease4 The lease to be updated.
+ ///
+ /// If no such lease is present, an exception will be thrown.
+ void updateLease6(const Lease6Ptr& lease6);
+
+ /// @brief Deletes a lease.
+ ///
+ /// @todo Not implemented yet
+ ///
+ /// @param addr IPv4 address of the lease to be deleted.
+ ///
+ /// @return true if deletion was successful, false if no such lease exists
+ bool deleteLease4(uint32_t addr);
+
+ /// @brief Deletes a lease.
+ ///
+ /// @param addr IPv4 address of the lease to be deleted.
+ ///
+ /// @return true if deletion was successful, false if no such lease exists
+ bool deleteLease6(const isc::asiolink::IOAddress& addr);
+
+ /// @brief Returns backend name.
+ ///
+ /// Each backend have specific name, e.g. "mysql" or "sqlite".
+ std::string getName() const { return ("memfile"); }
+
+ /// @brief Returns description of the backend.
+ ///
+ /// This description may be multiline text that describes the backend.
+ std::string getDescription() const;
+
+ /// @brief Returns backend version.
+ std::string getVersion() const { return ("test-version"); }
+
+ using LeaseMgr::getParameter;
+
+protected:
+
+ typedef boost::multi_index_container< // this is a multi-index container...
+ Lease6Ptr, // it will hold shared_ptr to leases6
+ boost::multi_index::indexed_by< // and will be sorted by
+ // IPv6 address that are unique. That particular key is a member
+ // of the Lease6 structure, is of type IOAddress and can be accessed
+ // by doing &Lease6::addr_
+ boost::multi_index::ordered_unique<
+ boost::multi_index::member<Lease6, isc::asiolink::IOAddress, &Lease6::addr_>
+ >
+ >
+ > Lease6Storage; // Let the whole contraption be called Lease6Storage.
+
+ Lease6Storage storage6_;
+};
+
+}; // end of isc::dhcp::test namespace
+}; // end of isc::dhcp namespace
+}; // end of isc namespace
+
+#endif // MEMFILE_LEASE_MGR_H
diff --git a/src/lib/dhcp/tests/option6_int_array_unittest.cc b/src/lib/dhcp/tests/option6_int_array_unittest.cc
new file mode 100644
index 0000000..581d4e1
--- /dev/null
+++ b/src/lib/dhcp/tests/option6_int_array_unittest.cc
@@ -0,0 +1,420 @@
+// 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 <dhcp/dhcp6.h>
+#include <dhcp/option.h>
+#include <dhcp/option6_int_array.h>
+#include <dhcp/option6_iaaddr.h>
+#include <util/buffer.h>
+
+#include <boost/pointer_cast.hpp>
+#include <gtest/gtest.h>
+
+using namespace std;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+using namespace isc::util;
+
+namespace {
+
+/// @brief Option6IntArray test class.
+class Option6IntArrayTest : public ::testing::Test {
+public:
+ /// @brief Constructor.
+ ///
+ /// Initializes the option buffer with some data.
+ Option6IntArrayTest(): buf_(255), out_buf_(255) {
+ for (int i = 0; i < 255; i++) {
+ buf_[i] = 255 - i;
+ }
+ }
+
+ /// @brief Test parsing buffer into array of int8_t or uint8_t values.
+ ///
+ /// @warning this function does not perform type check. Make
+ /// sure that only int8_t or uint8_t type is used.
+ ///
+ /// @tparam T int8_t or uint8_t.
+ template<typename T>
+ void bufferToIntTest8() {
+ // Create option that conveys array of multiple uint8_t or int8_t values.
+ // In fact there is no need to use this template class for array
+ // of uint8_t values because Option class is sufficient - it
+ // returns the buffer which is actually the array of uint8_t.
+ // However, since we allow using uint8_t types with this template
+ // class we have to test it here.
+ boost::shared_ptr<Option6IntArray<T> > opt;
+ const int opt_len = 10;
+ const uint16_t opt_code = 80;
+
+ // Constructor throws exception if provided buffer is empty.
+ EXPECT_THROW(
+ Option6IntArray<T>(opt_code, buf_.begin(), buf_.begin()),
+ isc::OutOfRange
+ );
+
+ // Provided buffer is not empty so it should not throw exception.
+ ASSERT_NO_THROW(
+ opt = boost::shared_ptr<
+ Option6IntArray<T> >(new Option6IntArray<T>(opt_code, buf_.begin(),
+ buf_.begin() + opt_len))
+ );
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ // Option should return the collection of int8_t or uint8_t values that
+ // we can match with the buffer we used to create the option.
+ std::vector<T> values = opt->getValues();
+ // We need to copy values from the buffer to apply sign if signed
+ // type is used.
+ std::vector<T> reference_values;
+ for (int i = 0; i < opt_len; ++i) {
+ // Values have been read from the buffer in network
+ // byte order. We put them back in the same order here.
+ reference_values.push_back(static_cast<T>(buf_[i]));
+ }
+
+ // Compare the values against the reference buffer.
+ ASSERT_EQ(opt_len, values.size());
+ EXPECT_TRUE(std::equal(reference_values.begin(), reference_values.begin()
+ + opt_len, values.begin()));
+
+ // test for pack()
+ opt->pack(out_buf_);
+
+ // Data length is 10 bytes.
+ EXPECT_EQ(10, opt->len() - opt->getHeaderLen());
+ EXPECT_EQ(opt_code, opt->getType());
+ // The total length is 10 bytes for data and 4 bytes for header.
+ ASSERT_EQ(14, out_buf_.getLength());
+
+ // Check if pack worked properly:
+ InputBuffer out(out_buf_.getData(), out_buf_.getLength());
+ // if option type is correct
+ EXPECT_EQ(opt_code, out.readUint16());
+ // if option length is correct
+ EXPECT_EQ(10, out.readUint16());
+ // if data is correct
+ std::vector<uint8_t> out_data;
+ ASSERT_NO_THROW(out.readVector(out_data, opt_len));
+ ASSERT_EQ(opt_len, out_data.size());
+ EXPECT_TRUE(std::equal(buf_.begin(), buf_.begin() + opt_len, out_data.begin()));;
+ }
+
+ /// @brief Test parsing buffer into array of int16_t or uint16_t values.
+ ///
+ /// @warning this function does not perform type check. Make
+ /// sure that only int16_t or uint16_t type is used.
+ ///
+ /// @tparam T int16_t or uint16_t.
+ template<typename T>
+ void bufferToIntTest16() {
+ // Create option that conveys array of multiple uint16_t or int16_t values.
+ boost::shared_ptr<Option6IntArray<T> > opt;
+ const int opt_len = 20;
+ const uint16_t opt_code = 81;
+
+ // Constructor throws exception if provided buffer is empty.
+ EXPECT_THROW(
+ Option6IntArray<T>(opt_code, buf_.begin(), buf_.begin()),
+ isc::OutOfRange
+ );
+
+ // Constructor throws exception if provided buffer's length is not
+ // multiple of 2-bytes.
+ EXPECT_THROW(
+ Option6IntArray<T>(opt_code, buf_.begin(), buf_.begin() + 5),
+ isc::OutOfRange
+ );
+
+ // Now the buffer length is correct.
+ ASSERT_NO_THROW(
+ opt = boost::shared_ptr<
+ Option6IntArray<T> >(new Option6IntArray<T>(opt_code, buf_.begin(),
+ buf_.begin() + opt_len))
+ );
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ // Option should return vector of uint16_t values which should be
+ // constructed from the buffer we provided.
+ std::vector<T> values = opt->getValues();
+ ASSERT_EQ(opt_len, values.size() * sizeof(T));
+ // Create reference values from the buffer so as we can
+ // simply compare two vectors.
+ std::vector<T> reference_values;
+ for (int i = 0; i < opt_len; i += 2) {
+ reference_values.push_back((buf_[i] << 8) |
+ buf_[i + 1]);
+ }
+ EXPECT_TRUE(std::equal(reference_values.begin(), reference_values.end(),
+ values.begin()));
+
+ // Test for pack()
+ opt->pack(out_buf_);
+
+ // Data length is 20 bytes.
+ EXPECT_EQ(20, opt->len() - opt->getHeaderLen());
+ EXPECT_EQ(opt_code, opt->getType());
+ // The total length is 20 bytes for data and 4 bytes for header.
+ ASSERT_EQ(24, out_buf_.getLength());
+
+ // Check if pack worked properly:
+ InputBuffer out(out_buf_.getData(), out_buf_.getLength());
+ // if option type is correct
+ EXPECT_EQ(opt_code, out.readUint16());
+ // if option length is correct
+ EXPECT_EQ(20, out.readUint16());
+ // if data is correct
+ std::vector<uint8_t> out_data;
+ ASSERT_NO_THROW(out.readVector(out_data, opt_len));
+ ASSERT_EQ(opt_len, out_data.size());
+ EXPECT_TRUE(std::equal(buf_.begin(), buf_.begin() + opt_len, out_data.begin()));;
+ }
+
+ /// @brief Test parsing buffer into array of int32_t or uint32_t values.
+ ///
+ /// @warning this function does not perform type check. Make
+ /// sure that only int32_t or uint32_t type is used.
+ ///
+ /// @tparam T int32_t or uint32_t.
+ template<typename T>
+ void bufferToIntTest32() {
+ // Create option that conveys array of multiple uint16_t values.
+ boost::shared_ptr<Option6IntArray<T> > opt;
+ const int opt_len = 40;
+ const uint16_t opt_code = 82;
+
+ // Constructor throws exception if provided buffer is empty.
+ EXPECT_THROW(
+ Option6IntArray<T>(opt_code, buf_.begin(), buf_.begin()),
+ isc::OutOfRange
+ );
+
+ // Constructor throws exception if provided buffer's length is not
+ // multiple of 4-bytes.
+ EXPECT_THROW(
+ Option6IntArray<T>(opt_code, buf_.begin(), buf_.begin() + 9),
+ isc::OutOfRange
+ );
+
+ // Now the buffer length is correct.
+ ASSERT_NO_THROW(
+ opt = boost::shared_ptr<
+ Option6IntArray<T> >(new Option6IntArray<T>(opt_code, buf_.begin(),
+ buf_.begin() + opt_len))
+ );
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ // Option should return vector of uint32_t values which should be
+ // constructed from the buffer we provided.
+ std::vector<T> values = opt->getValues();
+ ASSERT_EQ(opt_len, values.size() * sizeof(T));
+ // Create reference values from the buffer so as we can
+ // simply compare two vectors.
+ std::vector<T> reference_values;
+ for (int i = 0; i < opt_len; i += 4) {
+ reference_values.push_back((buf_[i] << 24) |
+ (buf_[i + 1] << 16 & 0x00FF0000) |
+ (buf_[i + 2] << 8 & 0xFF00) |
+ (buf_[i + 3] & 0xFF));
+ }
+ EXPECT_TRUE(std::equal(reference_values.begin(), reference_values.end(),
+ values.begin()));
+
+ // Test for pack()
+ opt->pack(out_buf_);
+
+ // Data length is 40 bytes.
+ EXPECT_EQ(40, opt->len() - opt->getHeaderLen());
+ EXPECT_EQ(opt_code, opt->getType());
+ // The total length is 40 bytes for data and 4 bytes for header.
+ ASSERT_EQ(44, out_buf_.getLength());
+
+ // Check if pack worked properly:
+ InputBuffer out(out_buf_.getData(), out_buf_.getLength());
+ // if option type is correct
+ EXPECT_EQ(opt_code, out.readUint16());
+ // if option length is correct
+ EXPECT_EQ(40, out.readUint16());
+ // if data is correct
+ std::vector<uint8_t> out_data;
+ ASSERT_NO_THROW(out.readVector(out_data, opt_len));
+ ASSERT_EQ(opt_len, out_data.size());
+ EXPECT_TRUE(std::equal(buf_.begin(), buf_.begin() + opt_len, out_data.begin()));;
+ }
+
+
+ OptionBuffer buf_; ///< Option buffer
+ OutputBuffer out_buf_; ///< Output buffer
+};
+
+/// @todo: below, there is a bunch of tests for options that
+/// convey unsigned values. We should maybe extend these tests for
+/// signed types too.
+
+TEST_F(Option6IntArrayTest, useInvalidType) {
+ const uint16_t opt_code = 80;
+ EXPECT_THROW(
+ boost::scoped_ptr<
+ Option6IntArray<bool> >(new Option6IntArray<bool>(opt_code, OptionBuffer(5))),
+ InvalidDataType
+ );
+
+ EXPECT_THROW(
+ boost::scoped_ptr<
+ Option6IntArray<int64_t> >(new Option6IntArray<int64_t>(opt_code,
+ OptionBuffer(10))),
+ InvalidDataType
+ );
+
+}
+
+TEST_F(Option6IntArrayTest, bufferToUint8) {
+ bufferToIntTest8<uint8_t>();
+}
+
+TEST_F(Option6IntArrayTest, bufferToInt8) {
+ bufferToIntTest8<int8_t>();
+}
+
+TEST_F(Option6IntArrayTest, bufferToUint16) {
+ bufferToIntTest16<uint16_t>();
+}
+
+TEST_F(Option6IntArrayTest, bufferToInt16) {
+ bufferToIntTest16<int16_t>();
+}
+
+TEST_F(Option6IntArrayTest, bufferToUint32) {
+ bufferToIntTest32<uint32_t>();
+}
+
+TEST_F(Option6IntArrayTest, bufferToInt32) {
+ bufferToIntTest32<int32_t>();
+}
+
+TEST_F(Option6IntArrayTest, setValuesUint8) {
+ const uint16_t opt_code = 100;
+ // Create option with empty vector of values.
+ boost::shared_ptr<Option6IntArray<uint8_t> > opt(new Option6IntArray<uint8_t>(opt_code));
+ // Initialize vector with some data and pass to the option.
+ std::vector<uint8_t> values;
+ for (int i = 0; i < 10; ++i) {
+ values.push_back(numeric_limits<uint8_t>::max() - i);
+ }
+ opt->setValues(values);
+
+ // Check if universe, option type and data was set correctly.
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ std::vector<uint8_t> returned_values = opt->getValues();
+ EXPECT_TRUE(std::equal(values.begin(), values.end(), returned_values.begin()));
+}
+
+TEST_F(Option6IntArrayTest, setValuesInt8) {
+ const uint16_t opt_code = 100;
+ // Create option with empty vector of values.
+ boost::shared_ptr<Option6IntArray<int8_t> > opt(new Option6IntArray<int8_t>(opt_code));
+ // Initialize vector with some data and pass to the option.
+ std::vector<int8_t> values;
+ for (int i = 0; i < 10; ++i) {
+ values.push_back(numeric_limits<int8_t>::min() + i);
+ }
+ opt->setValues(values);
+
+ // Check if universe, option type and data was set correctly.
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ std::vector<int8_t> returned_values = opt->getValues();
+ EXPECT_TRUE(std::equal(values.begin(), values.end(), returned_values.begin()));
+}
+
+TEST_F(Option6IntArrayTest, setValuesUint16) {
+ const uint16_t opt_code = 101;
+ // Create option with empty vector of values.
+ boost::shared_ptr<Option6IntArray<uint16_t> > opt(new Option6IntArray<uint16_t>(opt_code));
+ // Initialize vector with some data and pass to the option.
+ std::vector<uint16_t> values;
+ for (int i = 0; i < 10; ++i) {
+ values.push_back(numeric_limits<uint16_t>::max() - i);
+ }
+ opt->setValues(values);
+
+ // Check if universe, option type and data was set correctly.
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ std::vector<uint16_t> returned_values = opt->getValues();
+ EXPECT_TRUE(std::equal(values.begin(), values.end(), returned_values.begin()));
+}
+
+TEST_F(Option6IntArrayTest, setValuesInt16) {
+ const uint16_t opt_code = 101;
+ // Create option with empty vector of values.
+ boost::shared_ptr<Option6IntArray<int16_t> > opt(new Option6IntArray<int16_t>(opt_code));
+ // Initialize vector with some data and pass to the option.
+ std::vector<int16_t> values;
+ for (int i = 0; i < 10; ++i) {
+ values.push_back(numeric_limits<int16_t>::min() + i);
+ }
+ opt->setValues(values);
+
+ // Check if universe, option type and data was set correctly.
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ std::vector<int16_t> returned_values = opt->getValues();
+ EXPECT_TRUE(std::equal(values.begin(), values.end(), returned_values.begin()));
+}
+
+TEST_F(Option6IntArrayTest, setValuesUint32) {
+ const uint32_t opt_code = 101;
+ // Create option with empty vector of values.
+ boost::shared_ptr<Option6IntArray<uint32_t> > opt(new Option6IntArray<uint32_t>(opt_code));
+ // Initialize vector with some data and pass to the option.
+ std::vector<uint32_t> values;
+ for (int i = 0; i < 10; ++i) {
+ values.push_back(numeric_limits<uint32_t>::max() - i);
+ }
+ opt->setValues(values);
+
+ // Check if universe, option type and data was set correctly.
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ std::vector<uint32_t> returned_values = opt->getValues();
+ EXPECT_TRUE(std::equal(values.begin(), values.end(), returned_values.begin()));
+}
+
+TEST_F(Option6IntArrayTest, setValuesInt32) {
+ const uint32_t opt_code = 101;
+ // Create option with empty vector of values.
+ boost::shared_ptr<Option6IntArray<int32_t> > opt(new Option6IntArray<int32_t>(opt_code));
+ // Initialize vector with some data and pass to the option.
+ std::vector<int32_t> values;
+ for (int i = 0; i < 10; ++i) {
+ values.push_back(numeric_limits<int32_t>::min() + i);
+ }
+ opt->setValues(values);
+
+ // Check if universe, option type and data was set correctly.
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(opt_code, opt->getType());
+ std::vector<int32_t> returned_values = opt->getValues();
+ EXPECT_TRUE(std::equal(values.begin(), values.end(), returned_values.begin()));
+}
+
+
+} // anonymous namespace
diff --git a/src/lib/dhcp/tests/option6_int_unittest.cc b/src/lib/dhcp/tests/option6_int_unittest.cc
new file mode 100644
index 0000000..3d39a1a
--- /dev/null
+++ b/src/lib/dhcp/tests/option6_int_unittest.cc
@@ -0,0 +1,413 @@
+// 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 <dhcp/dhcp6.h>
+#include <dhcp/option.h>
+#include <dhcp/option6_int.h>
+#include <dhcp/option6_iaaddr.h>
+#include <util/buffer.h>
+
+#include <boost/pointer_cast.hpp>
+#include <gtest/gtest.h>
+
+using namespace std;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+using namespace isc::util;
+
+namespace {
+
+/// @brief Option6Int test class.
+class Option6IntTest : public ::testing::Test {
+public:
+ /// @brief Constructor.
+ ///
+ /// Initializes the option buffer with some data.
+ Option6IntTest(): buf_(255), out_buf_(255) {
+ for (int i = 0; i < 255; i++) {
+ buf_[i] = 255 - i;
+ }
+ }
+
+ /// @brief Basic test for int8 and uint8 types.
+ ///
+ /// @note this function does not perform type check. Make
+ /// sure that only int8_t or uint8_t type is used.
+ ///
+ /// @tparam T int8_t or uint8_t.
+ template<typename T>
+ void basicTest8() {
+ // Create option that conveys single 8 bit integer value.
+ boost::shared_ptr<Option6Int<T> > opt;
+ // Initialize buffer with this value.
+ buf_[0] = 0xa1;
+ // Constructor may throw in case provided buffer is too short.
+ ASSERT_NO_THROW(
+ opt = boost::shared_ptr<Option6Int<T> >(new Option6Int<T>(D6O_PREFERENCE,
+ buf_.begin(),
+ buf_.end()))
+ );
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_PREFERENCE, opt->getType());
+ // Option should return the same value that we initialized the first
+ // byte of the buffer with.
+ EXPECT_EQ(static_cast<T>(0xa1), opt->getValue());
+
+ // test for pack()
+ opt->pack(out_buf_);
+
+ // Data length is 1 byte.
+ EXPECT_EQ(1, opt->len() - opt->getHeaderLen());
+ EXPECT_EQ(D6O_PREFERENCE, opt->getType());
+ // The total length is 1 byte for data and 4 bytes for header.
+ EXPECT_EQ(5, out_buf_.getLength());
+
+ // Check if pack worked properly:
+ InputBuffer out(out_buf_.getData(), out_buf_.getLength());
+ // if option type is correct
+ EXPECT_EQ(D6O_PREFERENCE, out.readUint16());
+ // if option length is correct
+ EXPECT_EQ(1, out.readUint16());
+ // if data is correct
+ EXPECT_EQ(0xa1, out.readUint8() );
+ }
+
+ /// @brief Basic test for int16 and uint16 types.
+ ///
+ /// @note this function does not perform type check. Make
+ /// sure that only int16_t or uint16_t type is used.
+ ///
+ /// @tparam T int16_t or uint16_t.
+ template<typename T>
+ void basicTest16() {
+ // Create option that conveys single 16-bit integer value.
+ boost::shared_ptr<Option6Int<T> > opt;
+ // Initialize buffer with uint16_t value.
+ buf_[0] = 0xa1;
+ buf_[1] = 0xa2;
+ // Constructor may throw in case provided buffer is too short.
+ ASSERT_NO_THROW(
+ opt = boost::shared_ptr<Option6Int<T> >(new Option6Int<T>(D6O_ELAPSED_TIME,
+ buf_.begin(),
+ buf_.end()))
+ );
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_ELAPSED_TIME, opt->getType());
+ // Option should return the value equal to the contents of first
+ // and second byte of the buffer.
+ EXPECT_EQ(static_cast<T>(0xa1a2), opt->getValue());
+
+ // Test for pack()
+ opt->pack(out_buf_);
+
+ // Data length is 2 bytes.
+ EXPECT_EQ(2, opt->len() - opt->getHeaderLen());
+ EXPECT_EQ(D6O_ELAPSED_TIME, opt->getType());
+ // The total length is 2 byte for data and 4 bytes for header.
+ EXPECT_EQ(6, out_buf_.getLength());
+
+ // Check if pack worked properly:
+ InputBuffer out(out_buf_.getData(), out_buf_.getLength());
+ // if option type is correct
+ EXPECT_EQ(D6O_ELAPSED_TIME, out.readUint16());
+ // if option length is correct
+ EXPECT_EQ(2, out.readUint16());
+ // if data is correct
+ EXPECT_EQ(0xa1a2, out.readUint16() );
+ }
+
+ /// @brief Basic test for int32 and uint32 types.
+ ///
+ /// @note this function does not perform type check. Make
+ /// sure that only int32_t or uint32_t type is used.
+ ///
+ /// @tparam T int32_t or uint32_t.
+ template<typename T>
+ void basicTest32() {
+ // Create option that conveys single 32-bit integer value.
+ boost::shared_ptr<Option6Int<T> > opt;
+ // Initialize buffer with 32-bit integer value.
+ buf_[0] = 0xa1;
+ buf_[1] = 0xa2;
+ buf_[2] = 0xa3;
+ buf_[3] = 0xa4;
+ // Constructor may throw in case provided buffer is too short.
+ ASSERT_NO_THROW(
+ opt = boost::shared_ptr<Option6Int<T> >(new Option6Int<T>(D6O_CLT_TIME,
+ buf_.begin(),
+ buf_.end()))
+ );
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_CLT_TIME, opt->getType());
+ // Option should return the value equal to the value made of
+ // first 4 bytes of the buffer.
+ EXPECT_EQ(static_cast<T>(0xa1a2a3a4), opt->getValue());
+
+ // Test for pack()
+ opt->pack(out_buf_);
+
+ // Data length is 4 bytes.
+ EXPECT_EQ(4, opt->len() - opt->getHeaderLen());
+ EXPECT_EQ(D6O_CLT_TIME, opt->getType());
+ // The total length is 4 bytes for data and 4 bytes for header.
+ EXPECT_EQ(8, out_buf_.getLength());
+
+ // Check if pack worked properly:
+ InputBuffer out(out_buf_.getData(), out_buf_.getLength());
+ // if option type is correct
+ EXPECT_EQ(D6O_CLT_TIME, out.readUint16());
+ // if option length is correct
+ EXPECT_EQ(4, out.readUint16());
+ // if data is correct
+ EXPECT_EQ(0xa1a2a3a4, out.readUint32());
+ }
+
+ OptionBuffer buf_; ///< Option buffer
+ OutputBuffer out_buf_; ///< Output buffer
+};
+
+/// @todo: below, there is a bunch of tests for options that
+/// convey unsigned value. We should maybe extend these tests for
+/// signed types too.
+
+TEST_F(Option6IntTest, useInvalidType) {
+ EXPECT_THROW(
+ boost::scoped_ptr<Option6Int<bool> >(new Option6Int<bool>(D6O_ELAPSED_TIME, 10)),
+ InvalidDataType
+ );
+
+ EXPECT_THROW(
+ boost::scoped_ptr<Option6Int<int64_t> >(new Option6Int<int64_t>(D6O_ELAPSED_TIME, 10)),
+ InvalidDataType
+ );
+
+}
+
+TEST_F(Option6IntTest, basicUint8) {
+ basicTest8<uint8_t>();
+}
+
+TEST_F(Option6IntTest, basicUint16) {
+ basicTest16<uint16_t>();
+}
+
+TEST_F(Option6IntTest, basicUint32) {
+ basicTest32<uint32_t>();
+}
+
+TEST_F(Option6IntTest, basicInt8) {
+ basicTest8<int8_t>();
+}
+
+TEST_F(Option6IntTest, basicInt16) {
+ basicTest16<int16_t>();
+}
+
+TEST_F(Option6IntTest, basicInt32) {
+ basicTest32<int32_t>();
+}
+
+TEST_F(Option6IntTest, setValueUint8) {
+ boost::shared_ptr<Option6Int<uint8_t> > opt(new Option6Int<uint8_t>(D6O_PREFERENCE, 123));
+ // Check if constructor intitialized the option value correctly.
+ EXPECT_EQ(123, opt->getValue());
+ // Override the value.
+ opt->setValue(111);
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_PREFERENCE, opt->getType());
+ // Check if the value has been overriden.
+ EXPECT_EQ(111, opt->getValue());
+}
+
+TEST_F(Option6IntTest, setValueInt8) {
+ boost::shared_ptr<Option6Int<int8_t> > opt(new Option6Int<int8_t>(D6O_PREFERENCE, -123));
+ // Check if constructor intitialized the option value correctly.
+ EXPECT_EQ(-123, opt->getValue());
+ // Override the value.
+ opt->setValue(-111);
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_PREFERENCE, opt->getType());
+ // Check if the value has been overriden.
+ EXPECT_EQ(-111, opt->getValue());
+}
+
+
+TEST_F(Option6IntTest, setValueUint16) {
+ boost::shared_ptr<Option6Int<uint16_t> > opt(new Option6Int<uint16_t>(D6O_ELAPSED_TIME, 123));
+ // Check if constructor intitialized the option value correctly.
+ EXPECT_EQ(123, opt->getValue());
+ // Override the value.
+ opt->setValue(0x0102);
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_ELAPSED_TIME, opt->getType());
+ // Check if the value has been overriden.
+ EXPECT_EQ(0x0102, opt->getValue());
+}
+
+TEST_F(Option6IntTest, setValueInt16) {
+ boost::shared_ptr<Option6Int<int16_t> > opt(new Option6Int<int16_t>(D6O_ELAPSED_TIME, -16500));
+ // Check if constructor intitialized the option value correctly.
+ EXPECT_EQ(-16500, opt->getValue());
+ // Override the value.
+ opt->setValue(-20100);
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_ELAPSED_TIME, opt->getType());
+ // Check if the value has been overriden.
+ EXPECT_EQ(-20100, opt->getValue());
+}
+
+TEST_F(Option6IntTest, setValueUint32) {
+ boost::shared_ptr<Option6Int<uint32_t> > opt(new Option6Int<uint32_t>(D6O_CLT_TIME, 123));
+ // Check if constructor intitialized the option value correctly.
+ EXPECT_EQ(123, opt->getValue());
+ // Override the value.
+ opt->setValue(0x01020304);
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_CLT_TIME, opt->getType());
+ // Check if the value has been overriden.
+ EXPECT_EQ(0x01020304, opt->getValue());
+}
+
+TEST_F(Option6IntTest, setValueint32) {
+ boost::shared_ptr<Option6Int<int32_t> > opt(new Option6Int<int32_t>(D6O_CLT_TIME, -120100));
+ // Check if constructor intitialized the option value correctly.
+ EXPECT_EQ(-120100, opt->getValue());
+ // Override the value.
+ opt->setValue(-125000);
+
+ EXPECT_EQ(Option::V6, opt->getUniverse());
+ EXPECT_EQ(D6O_CLT_TIME, opt->getType());
+ // Check if the value has been overriden.
+ EXPECT_EQ(-125000, opt->getValue());
+}
+
+TEST_F(Option6IntTest, packSuboptions) {
+ // option code is really uint16_t, but using uint8_t
+ // for easier conversion to uint8_t array.
+ uint8_t opt_code = 80;
+
+ boost::shared_ptr<Option6Int<uint32_t> > opt(new Option6Int<uint32_t>(opt_code, 0x01020304));
+ OptionPtr sub1(new Option(Option::V6, 0xcafe));
+
+ boost::shared_ptr<Option6IAAddr> addr1(
+ new Option6IAAddr(D6O_IAADDR, IOAddress("2001:db8:1234:5678::abcd"), 0x5000, 0x7000));
+
+ opt->addOption(sub1);
+ opt->addOption(addr1);
+
+ ASSERT_EQ(28, addr1->len());
+ ASSERT_EQ(4, sub1->len());
+ ASSERT_EQ(40, opt->len());
+
+ uint8_t expected[] = {
+ 0, opt_code, // type
+ 0, 36, // length
+ 0x01, 0x02, 0x03, 0x04, // uint32_t value
+
+ // iaaddr suboption
+ D6O_IAADDR / 256, D6O_IAADDR % 256, // type
+ 0, 24, // len
+ 0x20, 0x01, 0xd, 0xb8, 0x12,0x34, 0x56, 0x78,
+ 0, 0, 0, 0, 0, 0, 0xab, 0xcd, // IP address
+ 0, 0, 0x50, 0, // preferred-lifetime
+ 0, 0, 0x70, 0, // valid-lifetime
+
+ // suboption
+ 0xca, 0xfe, // type
+ 0, 0 // len
+ };
+
+ // Create on-wire format of option and suboptions.
+ opt->pack(out_buf_);
+ // Compare the on-wire data with the reference buffer.
+ ASSERT_EQ(40, out_buf_.getLength());
+ EXPECT_EQ(0, memcmp(out_buf_.getData(), expected, 40));
+}
+
+
+TEST_F(Option6IntTest, unpackSuboptions) {
+ // option code is really uint16_t, but using uint8_t
+ // for easier conversion to uint8_t array.
+ const uint8_t opt_code = 80;
+ // Prepare reference data.
+ uint8_t expected[] = {
+ 0, opt_code, // type
+ 0, 34, // length
+ 0x01, 0x02, // uint16_t value
+
+ // iaaddr suboption
+ D6O_IAADDR / 256, D6O_IAADDR % 256, // type
+ 0, 24, // len
+ 0x20, 0x01, 0xd, 0xb8, 0x12,0x34, 0x56, 0x78,
+ 0, 0, 0, 0, 0, 0, 0xab, 0xcd, // IP address
+ 0, 0, 0x50, 0, // preferred-lifetime
+ 0, 0, 0x70, 0, // valid-lifetime
+
+ // suboption
+ 0xca, 0xfe, // type
+ 0, 0 // len
+ };
+ ASSERT_EQ(38, sizeof(expected));
+
+ memcpy(&buf_[0], expected, sizeof(expected));
+
+ boost::shared_ptr<Option6Int<uint16_t> > opt;
+ EXPECT_NO_THROW(
+ opt = boost::shared_ptr<
+ Option6Int<uint16_t> >(new Option6Int<uint16_t>(opt_code, buf_.begin() + 4,
+ buf_.begin() + sizeof(expected)));
+ );
+ ASSERT_TRUE(opt);
+
+ EXPECT_EQ(opt_code, opt->getType());
+ EXPECT_EQ(0x0102, opt->getValue());
+
+ // Checks for address option
+ OptionPtr subopt = opt->getOption(D6O_IAADDR);
+ ASSERT_TRUE(subopt);
+ boost::shared_ptr<Option6IAAddr> addr(boost::dynamic_pointer_cast<Option6IAAddr>(subopt));
+ ASSERT_TRUE(addr);
+
+ EXPECT_EQ(D6O_IAADDR, addr->getType());
+ EXPECT_EQ(28, addr->len());
+ EXPECT_EQ(0x5000, addr->getPreferred());
+ EXPECT_EQ(0x7000, addr->getValid());
+ EXPECT_EQ("2001:db8:1234:5678::abcd", addr->getAddress().toText());
+
+ // Checks for dummy option
+ subopt = opt->getOption(0xcafe);
+ ASSERT_TRUE(subopt); // should be non-NULL
+
+ EXPECT_EQ(0xcafe, subopt->getType());
+ EXPECT_EQ(4, subopt->len());
+ // There should be no data at all
+ EXPECT_EQ(0, subopt->getData().size());
+
+ // Try to get non-existent option.
+ subopt = opt->getOption(1);
+ // Expecting NULL which means that option does not exist.
+ ASSERT_FALSE(subopt);
+}
+
+} // anonymous namespace
diff --git a/src/lib/dhcp/tests/option_definition_unittest.cc b/src/lib/dhcp/tests/option_definition_unittest.cc
new file mode 100644
index 0000000..4b83517
--- /dev/null
+++ b/src/lib/dhcp/tests/option_definition_unittest.cc
@@ -0,0 +1,610 @@
+// 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 <exceptions/exceptions.h>
+#include <asiolink/io_address.h>
+#include <dhcp/dhcp4.h>
+#include <dhcp/dhcp6.h>
+#include <dhcp/option4_addrlst.h>
+#include <dhcp/option6_addrlst.h>
+#include <dhcp/option6_ia.h>
+#include <dhcp/option6_iaaddr.h>
+#include <dhcp/option6_int.h>
+#include <dhcp/option6_int_array.h>
+#include <dhcp/option_definition.h>
+
+#include <gtest/gtest.h>
+#include <boost/shared_ptr.hpp>
+#include <boost/pointer_cast.hpp>
+
+using namespace std;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::util;
+
+namespace {
+
+/// @brief OptionDefinition test class.
+///
+/// This class does not do anything useful but we keep
+/// it around for the future.
+class OptionDefinitionTest : public ::testing::Test {
+public:
+ // @brief Constructor.
+ OptionDefinitionTest() { }
+};
+
+TEST_F(OptionDefinitionTest, constructor) {
+ // Specify the option data type as string. This should get converted
+ // to enum value returned by getType().
+ OptionDefinition opt_def1("OPTION_CLIENTID", 1, "string");
+ EXPECT_EQ("OPTION_CLIENTID", opt_def1.getName());
+ EXPECT_EQ(1, opt_def1.getCode());
+ EXPECT_EQ(OptionDefinition::STRING_TYPE, opt_def1.getType());
+ EXPECT_FALSE(opt_def1.getArrayType());
+ EXPECT_NO_THROW(opt_def1.validate());
+
+ // Specify the option data type as an enum value.
+ OptionDefinition opt_def2("OPTION_RAPID_COMMIT", 14,
+ OptionDefinition::EMPTY_TYPE);
+ EXPECT_EQ("OPTION_RAPID_COMMIT", opt_def2.getName());
+ EXPECT_EQ(14, opt_def2.getCode());
+ EXPECT_EQ(OptionDefinition::EMPTY_TYPE, opt_def2.getType());
+ EXPECT_FALSE(opt_def2.getArrayType());
+ EXPECT_NO_THROW(opt_def1.validate());
+
+ // Check if it is possible to set that option is an array.
+ OptionDefinition opt_def3("OPTION_NIS_SERVERS", 27,
+ OptionDefinition::IPV6_ADDRESS_TYPE,
+ true);
+ EXPECT_EQ("OPTION_NIS_SERVERS", opt_def3.getName());
+ EXPECT_EQ(27, opt_def3.getCode());
+ EXPECT_EQ(OptionDefinition::IPV6_ADDRESS_TYPE, opt_def3.getType());
+ EXPECT_TRUE(opt_def3.getArrayType());
+ EXPECT_NO_THROW(opt_def3.validate());
+
+ // The created object is invalid if invalid data type is specified but
+ // constructor shouldn't throw exception. The object is validated after
+ // it has been created.
+ EXPECT_NO_THROW(
+ OptionDefinition opt_def4("OPTION_SERVERID",
+ OptionDefinition::UNKNOWN_TYPE + 10,
+ OptionDefinition::STRING_TYPE);
+ );
+}
+
+TEST_F(OptionDefinitionTest, addRecordField) {
+ // We can only add fields to record if the option type has been
+ // specified as 'record'. We try all other types but 'record'
+ // here and expect exception to be thrown.
+ for (int i = 0; i < OptionDefinition::UNKNOWN_TYPE; ++i) {
+ // Do not try for 'record' type because this is the only
+ // type for which adding record will succeed.
+ if (i == OptionDefinition::RECORD_TYPE) {
+ continue;
+ }
+ OptionDefinition opt_def("OPTION_IAADDR", 5,
+ static_cast<OptionDefinition::DataType>(i));
+ EXPECT_THROW(opt_def.addRecordField("uint8"), isc::InvalidOperation);
+ }
+
+ // Positive scenario starts here.
+ OptionDefinition opt_def("OPTION_IAADDR", 5, "record");
+ EXPECT_NO_THROW(opt_def.addRecordField("ipv6-address"));
+ EXPECT_NO_THROW(opt_def.addRecordField("uint32"));
+ // It should not matter if we specify field type by its name or using enum.
+ EXPECT_NO_THROW(opt_def.addRecordField(OptionDefinition::UINT32_TYPE));
+
+ // Check what we have actually added.
+ OptionDefinition::RecordFieldsCollection fields = opt_def.getRecordFields();
+ ASSERT_EQ(3, fields.size());
+ EXPECT_EQ(OptionDefinition::IPV6_ADDRESS_TYPE, fields[0]);
+ EXPECT_EQ(OptionDefinition::UINT32_TYPE, fields[1]);
+ EXPECT_EQ(OptionDefinition::UINT32_TYPE, fields[2]);
+
+ // Let's try some more negative scenarios: use invalid data types.
+ EXPECT_THROW(opt_def.addRecordField("unknown_type_xyz"), isc::BadValue);
+ OptionDefinition::DataType invalid_type =
+ static_cast<OptionDefinition::DataType>(OptionDefinition::UNKNOWN_TYPE + 10);
+ EXPECT_THROW(opt_def.addRecordField(invalid_type), isc::BadValue);
+}
+
+TEST_F(OptionDefinitionTest, validate) {
+ // Not supported option type string is not allowed.
+ OptionDefinition opt_def1("OPTION_CLIENTID", D6O_CLIENTID, "non-existent-type");
+ EXPECT_THROW(opt_def1.validate(), isc::OutOfRange);
+
+ // Not supported option type enum value is not allowed.
+ OptionDefinition opt_def2("OPTION_CLIENTID", D6O_CLIENTID, OptionDefinition::UNKNOWN_TYPE);
+ EXPECT_THROW(opt_def2.validate(), isc::OutOfRange);
+
+ OptionDefinition opt_def3("OPTION_CLIENTID", D6O_CLIENTID,
+ static_cast<OptionDefinition::DataType>(OptionDefinition::UNKNOWN_TYPE
+ + 2));
+ EXPECT_THROW(opt_def3.validate(), isc::OutOfRange);
+
+ // Empty option name is not allowed.
+ OptionDefinition opt_def4("", D6O_CLIENTID, "string");
+ EXPECT_THROW(opt_def4.validate(), isc::BadValue);
+
+ // Option name must not contain spaces.
+ OptionDefinition opt_def5(" OPTION_CLIENTID", D6O_CLIENTID, "string");
+ EXPECT_THROW(opt_def5.validate(), isc::BadValue);
+
+ OptionDefinition opt_def6("OPTION CLIENTID", D6O_CLIENTID, "string");
+ EXPECT_THROW(opt_def6.validate(), isc::BadValue);
+}
+
+TEST_F(OptionDefinitionTest, factoryAddrList6) {
+ OptionDefinition opt_def("OPTION_NIS_SERVERS", D6O_NIS_SERVERS,
+ "ipv6-address", true);
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ // Create a list of some V6 addresses.
+ std::vector<asiolink::IOAddress> addrs;
+ addrs.push_back(asiolink::IOAddress("2001:0db8::ff00:0042:8329"));
+ addrs.push_back(asiolink::IOAddress("2001:0db8::ff00:0042:2319"));
+ addrs.push_back(asiolink::IOAddress("::1"));
+ addrs.push_back(asiolink::IOAddress("::2"));
+
+ // Write addresses to the buffer.
+ OptionBuffer buf(addrs.size() * asiolink::V6ADDRESS_LEN);
+ for (int i = 0; i < addrs.size(); ++i) {
+ asio::ip::address_v6::bytes_type addr_bytes =
+ addrs[i].getAddress().to_v6().to_bytes();
+ ASSERT_EQ(asiolink::V6ADDRESS_LEN, addr_bytes.size());
+ std::copy(addr_bytes.begin(), addr_bytes.end(),
+ buf.begin() + i * asiolink::V6ADDRESS_LEN);
+ }
+ // Create DHCPv6 option from this buffer. Once option is created it is
+ // supposed to have internal list of addresses that it parses out from
+ // the provided buffer.
+ OptionPtr option_v6;
+ ASSERT_NO_THROW(
+ option_v6 = factory(Option::V6, D6O_NIS_SERVERS, buf);
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6AddrLst));
+ boost::shared_ptr<Option6AddrLst> option_cast_v6 =
+ boost::static_pointer_cast<Option6AddrLst>(option_v6);
+ ASSERT_TRUE(option_cast_v6);
+ // Get the list of parsed addresses from the option object.
+ std::vector<asiolink::IOAddress> addrs_returned =
+ option_cast_v6->getAddresses();
+ // The list of addresses must exactly match addresses that we
+ // stored in the buffer to create the option from it.
+ EXPECT_TRUE(std::equal(addrs.begin(), addrs.end(), addrs_returned.begin()));
+
+ // The provided buffer's length must be a multiple of V6 address length.
+ // Let's extend the buffer by one byte so as this condition is not
+ // fulfilled anymore.
+ buf.insert(buf.end(), 1, 1);
+ // It should throw exception then.
+ EXPECT_THROW(
+ factory(Option::V6, D6O_NIS_SERVERS, buf),
+ isc::OutOfRange
+ );
+}
+
+TEST_F(OptionDefinitionTest, factoryAddrList4) {
+ OptionDefinition opt_def("OPTION_NAME_SERVERS", D6O_NIS_SERVERS,
+ "ipv4-address", true);
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ // Create a list of some V6 addresses.
+ std::vector<asiolink::IOAddress> addrs;
+ addrs.push_back(asiolink::IOAddress("192.168.0.1"));
+ addrs.push_back(asiolink::IOAddress("172.16.1.1"));
+ addrs.push_back(asiolink::IOAddress("127.0.0.1"));
+ addrs.push_back(asiolink::IOAddress("213.41.23.12"));
+
+ // Write addresses to the buffer.
+ OptionBuffer buf(addrs.size() * asiolink::V4ADDRESS_LEN);
+ for (int i = 0; i < addrs.size(); ++i) {
+ asio::ip::address_v4::bytes_type addr_bytes =
+ addrs[i].getAddress().to_v4().to_bytes();
+ ASSERT_EQ(asiolink::V4ADDRESS_LEN, addr_bytes.size());
+ std::copy(addr_bytes.begin(), addr_bytes.end(),
+ buf.begin() + i * asiolink::V4ADDRESS_LEN);
+ }
+ // Create DHCPv6 option from this buffer. Once option is created it is
+ // supposed to have internal list of addresses that it parses out from
+ // the provided buffer.
+ OptionPtr option_v4;
+ ASSERT_NO_THROW(
+ option_v4 = factory(Option::V4, DHO_NAME_SERVERS, buf)
+ );
+ ASSERT_TRUE(typeid(*option_v4) == typeid(Option4AddrLst));
+ // Get the list of parsed addresses from the option object.
+ boost::shared_ptr<Option4AddrLst> option_cast_v4 =
+ boost::static_pointer_cast<Option4AddrLst>(option_v4);
+ std::vector<asiolink::IOAddress> addrs_returned =
+ option_cast_v4->getAddresses();
+ // The list of addresses must exactly match addresses that we
+ // stored in the buffer to create the option from it.
+ EXPECT_TRUE(std::equal(addrs.begin(), addrs.end(), addrs_returned.begin()));
+
+ // The provided buffer's length must be a multiple of V4 address length.
+ // Let's extend the buffer by one byte so as this condition is not
+ // fulfilled anymore.
+ buf.insert(buf.end(), 1, 1);
+ // It should throw exception then.
+ EXPECT_THROW(factory(Option::V4, DHO_NIS_SERVERS, buf), isc::OutOfRange);
+}
+
+TEST_F(OptionDefinitionTest, factoryEmpty) {
+ OptionDefinition opt_def("OPTION_RAPID_COMMIT", D6O_RAPID_COMMIT, "empty");
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ // Create option instance and provide empty buffer as expected.
+ OptionPtr option_v6;
+ ASSERT_NO_THROW(
+ option_v6 = factory(Option::V6, D6O_RAPID_COMMIT, OptionBuffer())
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option));
+ // Expect 'empty' DHCPv6 option.
+ EXPECT_EQ(Option::V6, option_v6->getUniverse());
+ EXPECT_EQ(4, option_v6->getHeaderLen());
+ EXPECT_EQ(0, option_v6->getData().size());
+
+ // Repeat the same test scenario for DHCPv4 option.
+ EXPECT_THROW(factory(Option::V4, 214, OptionBuffer(2)),isc::BadValue);
+
+ OptionPtr option_v4;
+ ASSERT_NO_THROW(option_v4 = factory(Option::V4, 214, OptionBuffer()));
+ // Expect 'empty' DHCPv4 option.
+ EXPECT_EQ(Option::V4, option_v4->getUniverse());
+ EXPECT_EQ(2, option_v4->getHeaderLen());
+ EXPECT_EQ(0, option_v4->getData().size());
+
+ // This factory produces empty option (consisting of option type
+ // and length). Attempt to provide some data in the buffer should
+ // result in exception.
+ EXPECT_THROW(factory(Option::V6, D6O_RAPID_COMMIT,OptionBuffer(2)),isc::BadValue);
+}
+
+TEST_F(OptionDefinitionTest, factoryIA6) {
+ // This option consists of IAID, T1 and T2 fields (each 4 bytes long).
+ const int option6_ia_len = 12;
+
+ // Get the factory function pointer.
+ OptionDefinition opt_def("OPTION_IA_NA", D6O_IA_NA, "record", true);
+ // Each data field is uint32.
+ for (int i = 0; i < 3; ++i) {
+ EXPECT_NO_THROW(opt_def.addRecordField("uint32"));
+ }
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ // Check the positive scenario.
+ OptionBuffer buf(12);
+ for (int i = 0; i < buf.size(); ++i) {
+ buf[i] = i;
+ }
+ OptionPtr option_v6;
+ ASSERT_NO_THROW(option_v6 = factory(Option::V6, D6O_IA_NA, buf));
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6IA));
+ boost::shared_ptr<Option6IA> option_cast_v6 =
+ boost::static_pointer_cast<Option6IA>(option_v6);
+ EXPECT_EQ(0x00010203, option_cast_v6->getIAID());
+ EXPECT_EQ(0x04050607, option_cast_v6->getT1());
+ EXPECT_EQ(0x08090A0B, option_cast_v6->getT2());
+
+ // This should work for DHCPv6 only, try passing invalid universe value.
+ EXPECT_THROW(
+ factory(Option::V4, D6O_IA_NA, OptionBuffer(option6_ia_len)),
+ isc::BadValue
+ );
+ // The length of the buffer must be 12 bytes.
+ // Check too short buffer.
+ EXPECT_THROW(
+ factory(Option::V6, D6O_IA_NA, OptionBuffer(option6_ia_len - 1)),
+ isc::OutOfRange
+ );
+ // Check too long buffer.
+ EXPECT_THROW(
+ factory(Option::V6, D6O_IA_NA, OptionBuffer(option6_ia_len + 1)),
+ isc::OutOfRange
+ );
+}
+
+TEST_F(OptionDefinitionTest, factoryIAAddr6) {
+ // This option consists of IPV6 Address (16 bytes) and preferred-lifetime and
+ // valid-lifetime fields (each 4 bytes long).
+ const int option6_iaaddr_len = 24;
+
+ OptionDefinition opt_def("OPTION_IAADDR", D6O_IAADDR, "record");
+ ASSERT_NO_THROW(opt_def.addRecordField("ipv6-address"));
+ ASSERT_NO_THROW(opt_def.addRecordField("uint32"));
+ ASSERT_NO_THROW(opt_def.addRecordField("uint32"));
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ // Check the positive scenario.
+ OptionPtr option_v6;
+ asiolink::IOAddress addr_v6("2001:0db8::ff00:0042:8329");
+ OptionBuffer buf(asiolink::V6ADDRESS_LEN);
+ ASSERT_TRUE(addr_v6.getAddress().is_v6());
+ asio::ip::address_v6::bytes_type addr_bytes =
+ addr_v6.getAddress().to_v6().to_bytes();
+ ASSERT_EQ(asiolink::V6ADDRESS_LEN, addr_bytes.size());
+ std::copy(addr_bytes.begin(), addr_bytes.end(), buf.begin());
+
+ for (int i = 0; i < option6_iaaddr_len - asiolink::V6ADDRESS_LEN; ++i) {
+ buf.push_back(i);
+ }
+ ASSERT_NO_THROW(option_v6 = factory(Option::V6, D6O_IAADDR, buf));
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6IAAddr));
+ boost::shared_ptr<Option6IAAddr> option_cast_v6 =
+ boost::static_pointer_cast<Option6IAAddr>(option_v6);
+ EXPECT_EQ(addr_v6, option_cast_v6->getAddress());
+ EXPECT_EQ(0x00010203, option_cast_v6->getPreferred());
+ EXPECT_EQ(0x04050607, option_cast_v6->getValid());
+
+ // This should work for DHCPv6 only, try passing invalid universe value.
+ EXPECT_THROW(
+ factory(Option::V4, D6O_IAADDR, OptionBuffer(option6_iaaddr_len)),
+ isc::BadValue
+ );
+ // The length of the buffer must be 12 bytes.
+ // Check too short buffer.
+ EXPECT_THROW(
+ factory(Option::V6, D6O_IAADDR, OptionBuffer(option6_iaaddr_len - 1)),
+ isc::OutOfRange
+ );
+ // Check too long buffer.
+ EXPECT_THROW(
+ factory(Option::V6, D6O_IAADDR, OptionBuffer(option6_iaaddr_len + 1)),
+ isc::OutOfRange
+ );
+}
+
+TEST_F(OptionDefinitionTest, factoryIntegerInvalidType) {
+ // The template function factoryInteger<> accepts integer values only
+ // as template typename. Here we try passing different type and
+ // see if it rejects it.
+ EXPECT_THROW(
+ OptionDefinition::factoryInteger<bool>(Option::V6, D6O_PREFERENCE, OptionBuffer(1)),
+ isc::dhcp::InvalidDataType
+ );
+}
+
+TEST_F(OptionDefinitionTest, factoryUint8) {
+ OptionDefinition opt_def("OPTION_PREFERENCE", D6O_PREFERENCE, "uint8");
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ OptionPtr option_v6;
+ // Try to use correct buffer length = 1 byte.
+ ASSERT_NO_THROW(
+ option_v6 = factory(Option::V6, D6O_PREFERENCE, OptionBuffer(1, 1));
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6Int<uint8_t>));
+ // Validate the value.
+ boost::shared_ptr<Option6Int<uint8_t> > option_cast_v6 =
+ boost::static_pointer_cast<Option6Int<uint8_t> >(option_v6);
+ EXPECT_EQ(1, option_cast_v6->getValue());
+
+ // Try to provide too large buffer. Expect exception.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, D6O_PREFERENCE, OptionBuffer(3)),
+ isc::OutOfRange
+ );
+
+ // Try to provide zero-length buffer. Expect exception.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, D6O_PREFERENCE, OptionBuffer()),
+ isc::OutOfRange
+ );
+
+ // @todo Add more cases for DHCPv4
+}
+
+TEST_F(OptionDefinitionTest, factoryUint16) {
+ OptionDefinition opt_def("OPTION_ELAPSED_TIME", D6O_ELAPSED_TIME, "uint16");
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ OptionPtr option_v6;
+ // Try to use correct buffer length = 2 bytes.
+ OptionBuffer buf;
+ buf.push_back(1);
+ buf.push_back(2);
+ ASSERT_NO_THROW(
+ option_v6 = factory(Option::V6, D6O_ELAPSED_TIME, buf);
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6Int<uint16_t>));
+ // Validate the value.
+ boost::shared_ptr<Option6Int<uint16_t> > option_cast_v6 =
+ boost::static_pointer_cast<Option6Int<uint16_t> >(option_v6);
+ EXPECT_EQ(0x0102, option_cast_v6->getValue());
+
+ // Try to provide too large buffer. Expect exception.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, D6O_ELAPSED_TIME, OptionBuffer(3)),
+ isc::OutOfRange
+ );
+ // Try to provide zero-length buffer. Expect exception.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, D6O_ELAPSED_TIME, OptionBuffer(1)),
+ isc::OutOfRange
+ );
+
+ // @todo Add more cases for DHCPv4
+}
+
+TEST_F(OptionDefinitionTest, factoryUint32) {
+ OptionDefinition opt_def("OPTION_CLT_TIME", D6O_CLT_TIME, "uint32");
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ OptionPtr option_v6;
+ OptionBuffer buf;
+ buf.push_back(1);
+ buf.push_back(2);
+ buf.push_back(3);
+ buf.push_back(4);
+ ASSERT_NO_THROW(
+ option_v6 = factory(Option::V6, D6O_CLT_TIME, buf);
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6Int<uint32_t>));
+ // Validate the value.
+ boost::shared_ptr<Option6Int<uint32_t> > option_cast_v6 =
+ boost::static_pointer_cast<Option6Int<uint32_t> >(option_v6);
+ EXPECT_EQ(0x01020304, option_cast_v6->getValue());
+
+ // Try to provide too large buffer. Expect exception.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, D6O_CLT_TIME, OptionBuffer(5)),
+ isc::OutOfRange
+ );
+ // Try to provide zero-length buffer. Expect exception.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, D6O_CLT_TIME, OptionBuffer(2)),
+ isc::OutOfRange
+ );
+
+ // @todo Add more cases for DHCPv4
+}
+
+TEST_F(OptionDefinitionTest, factoryUint16Array) {
+ // Let's define some dummy option.
+ const uint16_t opt_code = 79;
+ OptionDefinition opt_def("OPTION_UINT16_ARRAY", opt_code, "uint16", true);
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ OptionPtr option_v6;
+ // Positive scenario, initiate the buffer with length being
+ // multiple of uint16_t size.
+ // buffer elements will be: 0x112233.
+ OptionBuffer buf(6);
+ for (int i = 0; i < 6; ++i) {
+ buf[i] = i / 2;
+ }
+ // Constructor should succeed because buffer has correct size.
+ EXPECT_NO_THROW(
+ option_v6 = factory(Option::V6, opt_code, buf);
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6IntArray<uint16_t>));
+ boost::shared_ptr<Option6IntArray<uint16_t> > option_cast_v6 =
+ boost::static_pointer_cast<Option6IntArray<uint16_t> >(option_v6);
+ // Get the values from the initiated options and validate.
+ std::vector<uint16_t> values = option_cast_v6->getValues();
+ for (int i = 0; i < values.size(); ++i) {
+ // Expected value is calculated using on the same pattern
+ // as the one we used to initiate buffer:
+ // for i=0, expected = 0x00, for i = 1, expected == 0x11 etc.
+ uint16_t expected = (i << 8) | i;
+ EXPECT_EQ(expected, values[i]);
+ }
+
+ // Provided buffer size must be greater than zero. Check if we
+ // get exception if we provide zero-length buffer.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, opt_code, OptionBuffer()),
+ isc::OutOfRange
+ );
+ // Buffer length must be multiple of data type size.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, opt_code, OptionBuffer(5)),
+ isc::OutOfRange
+ );
+}
+
+TEST_F(OptionDefinitionTest, factoryUint32Array) {
+ // Let's define some dummy option.
+ const uint16_t opt_code = 80;
+
+ OptionDefinition opt_def("OPTION_UINT32_ARRAY", opt_code, "uint32", true);
+ Option::Factory* factory(NULL);
+ EXPECT_NO_THROW(factory = opt_def.getFactory());
+ ASSERT_TRUE(factory != NULL);
+
+ OptionPtr option_v6;
+ // Positive scenario, initiate the buffer with length being
+ // multiple of uint16_t size.
+ // buffer elements will be: 0x111122223333.
+ OptionBuffer buf(12);
+ for (int i = 0; i < buf.size(); ++i) {
+ buf[i] = i / 4;
+ }
+ // Constructor should succeed because buffer has correct size.
+ EXPECT_NO_THROW(
+ option_v6 = factory(Option::V6, opt_code, buf);
+ );
+ ASSERT_TRUE(typeid(*option_v6) == typeid(Option6IntArray<uint32_t>));
+ boost::shared_ptr<Option6IntArray<uint32_t> > option_cast_v6 =
+ boost::static_pointer_cast<Option6IntArray<uint32_t> >(option_v6);
+ // Get the values from the initiated options and validate.
+ std::vector<uint32_t> values = option_cast_v6->getValues();
+ for (int i = 0; i < values.size(); ++i) {
+ // Expected value is calculated using on the same pattern
+ // as the one we used to initiate buffer:
+ // for i=0, expected = 0x0000, for i = 1, expected == 0x1111 etc.
+ uint32_t expected = 0x01010101 * i;
+ EXPECT_EQ(expected, values[i]);
+ }
+
+ // Provided buffer size must be greater than zero. Check if we
+ // get exception if we provide zero-length buffer.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, opt_code, OptionBuffer()),
+ isc::OutOfRange
+ );
+ // Buffer length must be multiple of data type size.
+ EXPECT_THROW(
+ option_v6 = factory(Option::V6, opt_code, OptionBuffer(5)),
+ isc::OutOfRange
+ );
+}
+
+TEST_F(OptionDefinitionTest, recognizeFormat) {
+ // IA_NA option format.
+ OptionDefinition opt_def1("OPTION_IA_NA", D6O_IA_NA, "record");
+ for (int i = 0; i < 3; ++i) {
+ opt_def1.addRecordField("uint32");
+ }
+ EXPECT_TRUE(opt_def1.haveIA6Format());
+ // Create non-matching format to check that this function does not
+ // return 'true' all the time.
+ OptionDefinition opt_def2("OPTION_IA_NA", D6O_IA_NA, "uint16");
+ EXPECT_FALSE(opt_def2.haveIA6Format());
+
+ // IAADDR option format.
+ OptionDefinition opt_def3("OPTION_IAADDR", D6O_IAADDR, "record");
+ opt_def3.addRecordField("ipv6-address");
+ opt_def3.addRecordField("uint32");
+ opt_def3.addRecordField("uint32");
+ EXPECT_TRUE(opt_def3.haveIAAddr6Format());
+ // Create non-matching format to check that this function does not
+ // return 'true' all the time.
+ OptionDefinition opt_def4("OPTION_IAADDR", D6O_IAADDR, "uint32", true);
+ EXPECT_FALSE(opt_def4.haveIAAddr6Format());
+}
+
+} // anonymous namespace
diff --git a/src/lib/dhcp/tests/pool_unittest.cc b/src/lib/dhcp/tests/pool_unittest.cc
new file mode 100644
index 0000000..e596278
--- /dev/null
+++ b/src/lib/dhcp/tests/pool_unittest.cc
@@ -0,0 +1,181 @@
+// 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 <iostream>
+#include <vector>
+#include <sstream>
+#include <gtest/gtest.h>
+#include <dhcp/pool.h>
+#include <asiolink/io_address.h>
+
+using boost::scoped_ptr;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+
+namespace {
+
+TEST(Pool4Test, constructor_first_last) {
+
+ // let's construct 192.0.2.1-192.0.2.255 pool
+ Pool4 pool1(IOAddress("192.0.2.1"), IOAddress("192.0.2.255"));
+
+ EXPECT_EQ(IOAddress("192.0.2.1"), pool1.getFirstAddress());
+ EXPECT_EQ(IOAddress("192.0.2.255"), pool1.getLastAddress());
+
+ // This is Pool4, IPv6 addresses do not belong here
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::1"),
+ IOAddress("192.168.0.5")), BadValue);
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("192.168.0.2"),
+ IOAddress("2001:db8::1")), BadValue);
+
+ // Should throw. Range should be 192.0.2.1-192.0.2.2, not
+ // the other way around.
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("192.0.2.2"),
+ IOAddress("192.0.2.1")), BadValue);
+}
+
+TEST(Pool4Test, constructor_prefix_len) {
+
+ // let's construct 2001:db8:1::/96 pool
+ Pool4 pool1(IOAddress("192.0.2.0"), 25);
+
+ EXPECT_EQ("192.0.2.0", pool1.getFirstAddress().toText());
+ EXPECT_EQ("192.0.2.127", pool1.getLastAddress().toText());
+
+ // No such thing as /33 prefix
+ EXPECT_THROW(Pool4(IOAddress("192.0.2.1"), 33), BadValue);
+
+ // /0 prefix does not make sense
+ EXPECT_THROW(Pool4(IOAddress("192.0.2.0"), 0), BadValue);
+
+ // This is Pool6, IPv4 addresses do not belong here
+ EXPECT_THROW(Pool4(IOAddress("2001:db8::1"), 20), BadValue);
+}
+
+TEST(Pool4Test, in_range) {
+ Pool4 pool1(IOAddress("192.0.2.10"), IOAddress("192.0.2.20"));
+
+ EXPECT_FALSE(pool1.inRange(IOAddress("192.0.2.0")));
+ EXPECT_TRUE(pool1.inRange(IOAddress("192.0.2.10")));
+ EXPECT_TRUE(pool1.inRange(IOAddress("192.0.2.17")));
+ EXPECT_TRUE(pool1.inRange(IOAddress("192.0.2.20")));
+ EXPECT_FALSE(pool1.inRange(IOAddress("192.0.2.21")));
+ EXPECT_FALSE(pool1.inRange(IOAddress("192.0.2.255")));
+ EXPECT_FALSE(pool1.inRange(IOAddress("255.255.255.255")));
+ EXPECT_FALSE(pool1.inRange(IOAddress("0.0.0.0")));
+}
+
+// This test creates 100 pools and verifies that their IDs are unique.
+TEST(Pool4Test, unique_id) {
+
+ const int num_pools = 100;
+ std::vector<Pool4Ptr> pools;
+
+ for (int i = 0; i < num_pools; ++i) {
+ pools.push_back(Pool4Ptr(new Pool4(IOAddress("192.0.2.0"),
+ IOAddress("192.0.2.255"))));
+ }
+
+ for (int i = 0; i < num_pools; ++i) {
+ for (int j = i + 1; j < num_pools; ++j) {
+ if (pools[i]->getId() == pools[j]->getId()) {
+ FAIL() << "Pool-ids must be unique";
+ }
+ }
+ }
+
+}
+
+
+TEST(Pool6Test, constructor_first_last) {
+
+ // let's construct 2001:db8:1:: - 2001:db8:1::ffff:ffff:ffff:ffff pool
+ Pool6 pool1(Pool6::TYPE_IA, IOAddress("2001:db8:1::"),
+ IOAddress("2001:db8:1::ffff:ffff:ffff:ffff"));
+
+ EXPECT_EQ(Pool6::TYPE_IA, pool1.getType());
+ EXPECT_EQ(IOAddress("2001:db8:1::"), pool1.getFirstAddress());
+ EXPECT_EQ(IOAddress("2001:db8:1::ffff:ffff:ffff:ffff"),
+ pool1.getLastAddress());
+
+ // This is Pool6, IPv4 addresses do not belong here
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::1"),
+ IOAddress("192.168.0.5")), BadValue);
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("192.168.0.2"),
+ IOAddress("2001:db8::1")), BadValue);
+
+ // Should throw. Range should be 2001:db8::1 - 2001:db8::2, not
+ // the other way around.
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::2"),
+ IOAddress("2001:db8::1")), BadValue);
+}
+
+TEST(Pool6Test, constructor_prefix_len) {
+
+ // let's construct 2001:db8:1::/96 pool
+ Pool6 pool1(Pool6::TYPE_IA, IOAddress("2001:db8:1::"), 96);
+
+ EXPECT_EQ(Pool6::TYPE_IA, pool1.getType());
+ EXPECT_EQ("2001:db8:1::", pool1.getFirstAddress().toText());
+ EXPECT_EQ("2001:db8:1::ffff:ffff", pool1.getLastAddress().toText());
+
+ // No such thing as /130 prefix
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::"), 130),
+ BadValue);
+
+ // /0 prefix does not make sense
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::"), 0),
+ BadValue);
+
+ // This is Pool6, IPv4 addresses do not belong here
+ EXPECT_THROW(Pool6(Pool6::TYPE_IA, IOAddress("192.168.0.2"), 96),
+ BadValue);
+}
+
+TEST(Pool6Test, in_range) {
+ Pool6 pool1(Pool6::TYPE_IA, IOAddress("2001:db8:1::1"),
+ IOAddress("2001:db8:1::f"));
+
+ EXPECT_FALSE(pool1.inRange(IOAddress("2001:db8:1::")));
+ EXPECT_TRUE(pool1.inRange(IOAddress("2001:db8:1::1")));
+ EXPECT_TRUE(pool1.inRange(IOAddress("2001:db8:1::7")));
+ EXPECT_TRUE(pool1.inRange(IOAddress("2001:db8:1::f")));
+ EXPECT_FALSE(pool1.inRange(IOAddress("2001:db8:1::10")));
+ EXPECT_FALSE(pool1.inRange(IOAddress("::")));
+}
+
+// This test creates 100 pools and verifies that their IDs are unique.
+TEST(Pool6Test, unique_id) {
+
+ const int num_pools = 100;
+ std::vector<Pool6Ptr> pools;
+
+ for (int i = 0; i < num_pools; ++i) {
+ pools.push_back(Pool6Ptr(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8:1::"),
+ IOAddress("2001:db8:1::ffff:ffff:ffff:ffff"))));
+ }
+
+ for (int i = 0; i < num_pools; ++i) {
+ for (int j = i + 1; j < num_pools; ++j) {
+ if (pools[i]->getId() == pools[j]->getId()) {
+ FAIL() << "Pool-ids must be unique";
+ }
+ }
+ }
+
+}
+
+}; // end of anonymous namespace
diff --git a/src/lib/dhcp/tests/run_unittests.cc b/src/lib/dhcp/tests/run_unittests.cc
index db27f76..0126645 100644
--- a/src/lib/dhcp/tests/run_unittests.cc
+++ b/src/lib/dhcp/tests/run_unittests.cc
@@ -13,7 +13,6 @@
// PERFORMANCE OF THIS SOFTWARE.
#include <gtest/gtest.h>
-
#include <log/logger_support.h>
int
diff --git a/src/lib/dhcp/tests/subnet_unittest.cc b/src/lib/dhcp/tests/subnet_unittest.cc
new file mode 100644
index 0000000..be25bc1
--- /dev/null
+++ b/src/lib/dhcp/tests/subnet_unittest.cc
@@ -0,0 +1,421 @@
+// 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 <dhcp/subnet.h>
+#include <dhcp/option.h>
+#include <exceptions/exceptions.h>
+#include <boost/scoped_ptr.hpp>
+#include <gtest/gtest.h>
+#include <asiolink/io_address.h>
+
+// don't import the entire boost namespace. It will unexpectedly hide uint8_t
+// for some systems.
+using boost::scoped_ptr;
+using namespace isc;
+using namespace isc::dhcp;
+using namespace isc::asiolink;
+
+namespace {
+
+TEST(Subnet4Test, constructor) {
+ EXPECT_NO_THROW(Subnet4 subnet1(IOAddress("192.0.2.2"), 16,
+ 1, 2, 3));
+
+ EXPECT_THROW(Subnet4 subnet2(IOAddress("192.0.2.0"), 33, 1, 2, 3),
+ BadValue); // invalid prefix length
+ EXPECT_THROW(Subnet4 subnet3(IOAddress("2001:db8::1"), 24, 1, 2, 3),
+ BadValue); // IPv6 addresses are not allowed in Subnet4
+}
+
+TEST(Subnet4Test, in_range) {
+ Subnet4 subnet(IOAddress("192.0.2.1"), 24, 1000, 2000, 3000);
+
+ EXPECT_EQ(1000, subnet.getT1());
+ EXPECT_EQ(2000, subnet.getT2());
+ EXPECT_EQ(3000, subnet.getValid());
+
+ EXPECT_FALSE(subnet.inRange(IOAddress("192.0.0.0")));
+ EXPECT_TRUE(subnet.inRange(IOAddress("192.0.2.0")));
+ EXPECT_TRUE(subnet.inRange(IOAddress("192.0.2.1")));
+ EXPECT_TRUE(subnet.inRange(IOAddress("192.0.2.255")));
+ EXPECT_FALSE(subnet.inRange(IOAddress("192.0.3.0")));
+ EXPECT_FALSE(subnet.inRange(IOAddress("0.0.0.0")));
+ EXPECT_FALSE(subnet.inRange(IOAddress("255.255.255.255")));
+}
+
+TEST(Subnet4Test, Pool4InSubnet4) {
+
+ Subnet4Ptr subnet(new Subnet4(IOAddress("192.1.2.0"), 24, 1, 2, 3));
+
+ Pool4Ptr pool1(new Pool4(IOAddress("192.1.2.0"), 25));
+ Pool4Ptr pool2(new Pool4(IOAddress("192.1.2.128"), 26));
+ Pool4Ptr pool3(new Pool4(IOAddress("192.1.2.192"), 30));
+
+ subnet->addPool4(pool1);
+
+ // If there's only one pool, get that pool
+ Pool4Ptr mypool = subnet->getPool4();
+ EXPECT_EQ(mypool, pool1);
+
+
+ subnet->addPool4(pool2);
+ subnet->addPool4(pool3);
+
+ // If there are more than one pool and we didn't provide hint, we
+ // should get the first pool
+ mypool = subnet->getPool4();
+
+ EXPECT_EQ(mypool, pool1);
+
+ // If we provide a hint, we should get a pool that this hint belongs to
+ mypool = subnet->getPool4(IOAddress("192.1.2.195"));
+
+ EXPECT_EQ(mypool, pool3);
+
+}
+
+TEST(Subnet4Test, Subnet4_Pool4_checks) {
+
+ Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 8, 1, 2, 3));
+
+ // this one is in subnet
+ Pool4Ptr pool1(new Pool4(IOAddress("192.255.0.0"), 16));
+ subnet->addPool4(pool1);
+
+ // this one is larger than the subnet!
+ Pool4Ptr pool2(new Pool4(IOAddress("193.0.0.0"), 24));
+
+ EXPECT_THROW(subnet->addPool4(pool2), BadValue);
+
+ // this one is totally out of blue
+ Pool4Ptr pool3(new Pool4(IOAddress("1.2.3.4"), 16));
+ EXPECT_THROW(subnet->addPool4(pool3), BadValue);
+}
+
+TEST(Subnet4Test, addInvalidOption) {
+ // Create the V4 subnet.
+ Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.2.0"), 8, 1, 2, 3));
+
+ // Some dummy option code.
+ uint16_t code = 100;
+ // Create option with invalid universe (V6 instead of V4).
+ // Attempt to add this option should result in exception.
+ OptionPtr option1(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
+ EXPECT_THROW(subnet->addOption(option1), isc::BadValue);
+
+ // Create NULL pointer option. Attempt to add NULL option
+ // should result in exception.
+ OptionPtr option2;
+ ASSERT_FALSE(option2);
+ EXPECT_THROW(subnet->addOption(option2), isc::BadValue);
+}
+
+// This test verifies that inRange() and inPool() methods work properly.
+TEST(Subnet4Test, inRangeinPool) {
+ Subnet4Ptr subnet(new Subnet4(IOAddress("192.0.0.0"), 8, 1, 2, 3));
+
+ // this one is in subnet
+ Pool4Ptr pool1(new Pool4(IOAddress("192.2.0.0"), 16));
+ subnet->addPool4(pool1);
+
+ // 192.1.1.1 belongs to the subnet...
+ EXPECT_TRUE(subnet->inRange(IOAddress("192.1.1.1")));
+
+ // ... but it does not belong to any pool within
+ EXPECT_FALSE(subnet->inPool(IOAddress("192.1.1.1")));
+
+ // the last address that is in range, but out of pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("192.1.255.255")));
+ EXPECT_FALSE(subnet->inPool(IOAddress("192.1.255.255")));
+
+ // the first address that is in range, in pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("192.2.0.0")));
+ EXPECT_TRUE (subnet->inPool(IOAddress("192.2.0.0")));
+
+ // let's try something in the middle as well
+ EXPECT_TRUE(subnet->inRange(IOAddress("192.2.3.4")));
+ EXPECT_TRUE (subnet->inPool(IOAddress("192.2.3.4")));
+
+ // the last address that is in range, in pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("192.2.255.255")));
+ EXPECT_TRUE (subnet->inPool(IOAddress("192.2.255.255")));
+
+ // the first address that is in range, but out of pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("192.3.0.0")));
+ EXPECT_FALSE(subnet->inPool(IOAddress("192.3.0.0")));
+}
+
+// Tests for Subnet6
+
+TEST(Subnet6Test, constructor) {
+
+ EXPECT_NO_THROW(Subnet6 subnet1(IOAddress("2001:db8:1::"), 64,
+ 1, 2, 3, 4));
+
+ EXPECT_THROW(Subnet6 subnet2(IOAddress("2001:db8:1::"), 129, 1, 2, 3, 4),
+ BadValue); // invalid prefix length
+ EXPECT_THROW(Subnet6 subnet3(IOAddress("192.168.0.0"), 32, 1, 2, 3, 4),
+ BadValue); // IPv4 addresses are not allowed in Subnet6
+}
+
+TEST(Subnet6Test, in_range) {
+ Subnet6 subnet(IOAddress("2001:db8:1::"), 64, 1000, 2000, 3000, 4000);
+
+ EXPECT_EQ(1000, subnet.getT1());
+ EXPECT_EQ(2000, subnet.getT2());
+ EXPECT_EQ(3000, subnet.getPreferred());
+ EXPECT_EQ(4000, subnet.getValid());
+
+ EXPECT_FALSE(subnet.inRange(IOAddress("2001:db8:0:ffff:ffff:ffff:ffff:ffff")));
+ EXPECT_TRUE(subnet.inRange(IOAddress("2001:db8:1::0")));
+ EXPECT_TRUE(subnet.inRange(IOAddress("2001:db8:1::1")));
+ EXPECT_TRUE(subnet.inRange(IOAddress("2001:db8:1::ffff:ffff:ffff:ffff")));
+ EXPECT_FALSE(subnet.inRange(IOAddress("2001:db8:1:1::")));
+ EXPECT_FALSE(subnet.inRange(IOAddress("::")));
+}
+
+TEST(Subnet6Test, Pool6InSubnet6) {
+
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+
+ Pool6Ptr pool1(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8:1:1::"), 64));
+ Pool6Ptr pool2(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8:1:2::"), 64));
+ Pool6Ptr pool3(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8:1:3::"), 64));
+
+ subnet->addPool6(pool1);
+
+ // If there's only one pool, get that pool
+ Pool6Ptr mypool = subnet->getPool6();
+ EXPECT_EQ(mypool, pool1);
+
+
+ subnet->addPool6(pool2);
+ subnet->addPool6(pool3);
+
+ // If there are more than one pool and we didn't provide hint, we
+ // should get the first pool
+ mypool = subnet->getPool6();
+
+ EXPECT_EQ(mypool, pool1);
+
+ // If we provide a hint, we should get a pool that this hint belongs to
+ mypool = subnet->getPool6(IOAddress("2001:db8:1:3::dead:beef"));
+
+ EXPECT_EQ(mypool, pool3);
+}
+
+TEST(Subnet6Test, Subnet6_Pool6_checks) {
+
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+
+ // this one is in subnet
+ Pool6Ptr pool1(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8:1:1::"), 64));
+ subnet->addPool6(pool1);
+
+ // this one is larger than the subnet!
+ Pool6Ptr pool2(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::"), 48));
+
+ EXPECT_THROW(subnet->addPool6(pool2), BadValue);
+
+
+ // this one is totally out of blue
+ Pool6Ptr pool3(new Pool6(Pool6::TYPE_IA, IOAddress("3000::"), 16));
+ EXPECT_THROW(subnet->addPool6(pool3), BadValue);
+
+
+ Pool6Ptr pool4(new Pool6(Pool6::TYPE_IA, IOAddress("4001:db8:1::"), 80));
+ EXPECT_THROW(subnet->addPool6(pool4), BadValue);
+}
+
+TEST(Subnet6Test, addOptions) {
+ // Create as subnet to add options to it.
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+
+ // Differentiate options by their codes (100-109)
+ for (uint16_t code = 100; code < 110; ++code) {
+ OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
+ ASSERT_NO_THROW(subnet->addOption(option));
+ }
+
+ // Get options from the Subnet and check if all 10 are there.
+ Subnet::OptionContainer options = subnet->getOptions();
+ ASSERT_EQ(10, options.size());
+
+ // Validate codes of added options.
+ uint16_t expected_code = 100;
+ for (Subnet::OptionContainer::const_iterator option_desc = options.begin();
+ option_desc != options.end(); ++option_desc) {
+ ASSERT_TRUE(option_desc->option);
+ EXPECT_EQ(expected_code, option_desc->option->getType());
+ ++expected_code;
+ }
+
+ subnet->delOptions();
+
+ options = subnet->getOptions();
+ EXPECT_EQ(0, options.size());
+}
+
+TEST(Subnet6Test, addNonUniqueOptions) {
+ // Create as subnet to add options to it.
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+
+ // Create a set of options with non-unique codes.
+ for (int i = 0; i < 2; ++i) {
+ // In the inner loop we create options with unique codes (100-109).
+ for (uint16_t code = 100; code < 110; ++code) {
+ OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
+ ASSERT_NO_THROW(subnet->addOption(option));
+ }
+ }
+
+ // Sanity check that all options are there.
+ Subnet::OptionContainer options = subnet->getOptions();
+ ASSERT_EQ(20, options.size());
+
+ // Use container index #1 to get the options by their codes.
+ Subnet::OptionContainerTypeIndex& idx = options.get<1>();
+ // Look for the codes 100-109.
+ for (uint16_t code = 100; code < 110; ++ code) {
+ // For each code we should get two instances of options.
+ std::pair<Subnet::OptionContainerTypeIndex::const_iterator,
+ Subnet::OptionContainerTypeIndex::const_iterator> range =
+ idx.equal_range(code);
+ // Distance between iterators indicates how many options
+ // have been retured for the particular code.
+ ASSERT_EQ(2, distance(range.first, range.second));
+ // Check that returned options actually have the expected option code.
+ for (Subnet::OptionContainerTypeIndex::const_iterator option_desc = range.first;
+ option_desc != range.second; ++option_desc) {
+ ASSERT_TRUE(option_desc->option);
+ EXPECT_EQ(code, option_desc->option->getType());
+ }
+ }
+
+ // Let's try to find some non-exiting option.
+ const uint16_t non_existing_code = 150;
+ std::pair<Subnet::OptionContainerTypeIndex::const_iterator,
+ Subnet::OptionContainerTypeIndex::const_iterator> range =
+ idx.equal_range(non_existing_code);
+ // Empty set is expected.
+ EXPECT_EQ(0, distance(range.first, range.second));
+
+ subnet->delOptions();
+
+ options = subnet->getOptions();
+ EXPECT_EQ(0, options.size());
+}
+
+TEST(Subnet6Test, addInvalidOption) {
+ // Create as subnet to add options to it.
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+
+ // Some dummy option code.
+ uint16_t code = 100;
+ // Create option with invalid universe (V4 instead of V6).
+ // Attempt to add this option should result in exception.
+ OptionPtr option1(new Option(Option::V4, code, OptionBuffer(10, 0xFF)));
+ EXPECT_THROW(subnet->addOption(option1), isc::BadValue);
+
+ // Create NULL pointer option. Attempt to add NULL option
+ // should result in exception.
+ OptionPtr option2;
+ ASSERT_FALSE(option2);
+ EXPECT_THROW(subnet->addOption(option2), isc::BadValue);
+}
+
+TEST(Subnet6Test, addPersistentOption) {
+ // Create as subnet to add options to it.
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8:1::"), 56, 1, 2, 3, 4));
+
+ // Add 10 options to the subnet with option codes 100 - 109.
+ for (uint16_t code = 100; code < 110; ++code) {
+ OptionPtr option(new Option(Option::V6, code, OptionBuffer(10, 0xFF)));
+ // We create 10 options and want some of them to be flagged
+ // persistent and some non-persistent. Persistent options are
+ // those that server sends to clients regardless if they ask
+ // for them or not. We pick 3 out of 10 options and mark them
+ // non-persistent and 7 other options persistent.
+ // Code values: 102, 105 and 108 are divisable by 3
+ // and options with these codes will be flagged non-persistent.
+ // Options with other codes will be flagged persistent.
+ bool persistent = (code % 3) ? true : false;
+ ASSERT_NO_THROW(subnet->addOption(option, persistent));
+ }
+
+ // Get added options from the subnet.
+ Subnet::OptionContainer options = subnet->getOptions();
+
+ // options.get<2> returns reference to container index #2. This
+ // index is used to access options by the 'persistent' flag.
+ Subnet::OptionContainerPersistIndex& idx = options.get<2>();
+
+ // Get all persistent options.
+ std::pair<Subnet::OptionContainerPersistIndex::const_iterator,
+ Subnet::OptionContainerPersistIndex::const_iterator> range_persistent =
+ idx.equal_range(true);
+ // 3 out of 10 options have been flagged persistent.
+ ASSERT_EQ(7, distance(range_persistent.first, range_persistent.second));
+
+ // Get all non-persistent options.
+ std::pair<Subnet::OptionContainerPersistIndex::const_iterator,
+ Subnet::OptionContainerPersistIndex::const_iterator> range_non_persistent =
+ idx.equal_range(false);
+ // 7 out of 10 options have been flagged persistent.
+ ASSERT_EQ(3, distance(range_non_persistent.first, range_non_persistent.second));
+
+ subnet->delOptions();
+
+ options = subnet->getOptions();
+ EXPECT_EQ(0, options.size());
+}
+
+// This test verifies that inRange() and inPool() methods work properly.
+TEST(Subnet6Test, inRangeinPool) {
+ Subnet6Ptr subnet(new Subnet6(IOAddress("2001:db8::"), 32, 1, 2, 3, 4));
+
+ // this one is in subnet
+ Pool6Ptr pool1(new Pool6(Pool6::TYPE_IA, IOAddress("2001:db8::10"),
+ IOAddress("2001:db8::20")));
+ subnet->addPool6(pool1);
+
+ // 192.1.1.1 belongs to the subnet...
+ EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::1")));
+ // ... but it does not belong to any pool within
+ EXPECT_FALSE(subnet->inPool(IOAddress("2001:db8::1")));
+
+ // the last address that is in range, but out of pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::f")));
+ EXPECT_FALSE(subnet->inPool(IOAddress("2001:db8::f")));
+
+ // the first address that is in range, in pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::10")));
+ EXPECT_TRUE (subnet->inPool(IOAddress("2001:db8::10")));
+
+ // let's try something in the middle as well
+ EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::18")));
+ EXPECT_TRUE (subnet->inPool(IOAddress("2001:db8::18")));
+
+ // the last address that is in range, in pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::20")));
+ EXPECT_TRUE (subnet->inPool(IOAddress("2001:db8::20")));
+
+ // the first address that is in range, but out of pool
+ EXPECT_TRUE(subnet->inRange(IOAddress("2001:db8::21")));
+ EXPECT_FALSE(subnet->inPool(IOAddress("2001:db8::21")));
+}
+
+};
diff --git a/src/lib/dhcp/tests/triplet_unittest.cc b/src/lib/dhcp/tests/triplet_unittest.cc
new file mode 100644
index 0000000..727eb8a
--- /dev/null
+++ b/src/lib/dhcp/tests/triplet_unittest.cc
@@ -0,0 +1,104 @@
+// 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 <stdint.h>
+#include <gtest/gtest.h>
+#include <dhcp/triplet.h>
+#include <exceptions/exceptions.h>
+
+using namespace isc::dhcp;
+using namespace isc;
+
+namespace {
+
+// constructor validation
+TEST(TripletTest, constructor) {
+
+ const uint32_t min = 10;
+ const uint32_t value = 20;
+ const uint32_t max = 30;
+
+ Triplet<uint32_t> x(min, value, max);
+
+ EXPECT_EQ(min, x.getMin());
+ EXPECT_EQ(value, x.get());
+ EXPECT_EQ(max, x.getMax());
+
+ // requested values below min should return allowed min value
+ EXPECT_EQ(min, x.get(min - 5));
+
+ EXPECT_EQ(min, x.get(min));
+
+ // requesting a value from within the range (min < x < max) should
+ // return the requested value
+ EXPECT_EQ(17, x.get(17));
+
+ EXPECT_EQ(max, x.get(max));
+
+ EXPECT_EQ(max, x.get(max + 5));
+
+ // this will be boring. It is expected to return 42 no matter what
+ Triplet<uint32_t> y(42);
+
+ EXPECT_EQ(42, y.getMin()); // min, default and max are equal to 42
+ EXPECT_EQ(42, y.get()); // it returns ...
+ EXPECT_EQ(42, y.getMax()); // the exact value...
+
+ // requested values below or above are ignore
+ EXPECT_EQ(42, y.get(5)); // all...
+ EXPECT_EQ(42, y.get(42)); // the...
+ EXPECT_EQ(42, y.get(80)); // time!
+}
+
+// Triplets must be easy to use.
+// Simple to/from int conversions must be done on the fly.
+TEST(TripletTest, operator) {
+
+ uint32_t x = 47;
+
+ Triplet<uint32_t> foo(1,2,3);
+ Triplet<uint32_t> bar(4,5,6);
+
+ foo = bar;
+
+ EXPECT_EQ(4, foo.getMin());
+ EXPECT_EQ(5, foo.get());
+ EXPECT_EQ(6, foo.getMax());
+
+ // assignment operator: uint32_t => triplet
+ Triplet<uint32_t> y(0);
+ y = x;
+
+ EXPECT_EQ(x, y.get());
+
+ // let's try the other way around: triplet => uint32_t
+ uint32_t z = 0;
+ z = y;
+
+ EXPECT_EQ(x, z);
+}
+
+// check if specified values are sane
+TEST(TripletTest, sanity_check) {
+
+ // min is larger than default
+ EXPECT_THROW(Triplet<uint32_t>(6,5,5), BadValue);
+
+ // max is smaller than default
+ EXPECT_THROW(Triplet<uint32_t>(5,5,4), BadValue);
+
+}
+
+}; // end of anonymous namespace
diff --git a/src/lib/dhcp/triplet.h b/src/lib/dhcp/triplet.h
new file mode 100644
index 0000000..d9388fe
--- /dev/null
+++ b/src/lib/dhcp/triplet.h
@@ -0,0 +1,115 @@
+// 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 TRIPLET_H
+#define TRIPLET_H
+
+#include <exceptions/exceptions.h>
+
+namespace isc {
+namespace dhcp {
+
+/// @brief this template specifies a parameter value
+///
+/// This template class is used to store configuration parameters, like lifetime or T1.
+/// It defines 3 parameters: min, default, and max value. There are 2 constructors:
+/// - simple (just one value that sets all parameters)
+/// - extended (that sets default value and two thresholds)
+/// It will be used with integer types. It provides necessary operators, so
+/// it can be assigned to a plain integer or integer assigned to a Triplet.
+/// See TripletTest.operator test for details on an easy Triplet usage.
+template <class T>
+class Triplet {
+public:
+
+ /// @brief base type to Triple conversion
+ ///
+ /// Typically: uint32_t to Triplet assignment. It is very convenient
+ /// to be able to simply write Triplet<uint32_t> x = 7;
+ Triplet<T> operator=(T other) {
+ min_ = other;
+ default_ = other;
+ max_ = other;
+ return *this;
+ }
+
+ /// @brief triplet to base type conversion
+ ///
+ /// Typically: Triplet to uint32_t assignment. It is very convenient
+ /// to be able to simply write uint32_t z = x; (where x is a Triplet)
+ operator T() const {
+ return (default_);
+ }
+
+ /// @brief sets a fixed value
+ ///
+ /// This constructor assigns a fixed (i.e. no range, just a single value)
+ /// value.
+ Triplet(T value)
+ :min_(value), default_(value), max_(value) {
+ }
+
+ /// @brief sets the default value and thresholds
+ ///
+ /// @throw BadValue if min <= def <= max rule is violated
+ Triplet(T min, T def, T max)
+ :min_(min), default_(def), max_(max) {
+ if ( (min_ > def) || (def > max_) ) {
+ isc_throw(BadValue, "Invalid triplet values.");
+ }
+ }
+
+ /// @brief returns a minimum allowed value
+ T getMin() const { return min_;}
+
+ /// @brief returns the default value
+ T get() const { return default_;}
+
+ /// @brief returns value with a hint
+ ///
+ /// DHCP protocol treats any values sent by a client as hints.
+ /// This is a method that implements that. We can assign any value
+ /// from configured range that client asks.
+ T get(T hint) const {
+ if (hint <= min_) {
+ return (min_);
+ }
+
+ if (hint >= max_) {
+ return (max_);
+ }
+
+ return (hint);
+ }
+
+ /// @brief returns a maximum allowed value
+ T getMax() const { return max_; }
+
+protected:
+
+ /// @brief the minimum value
+ T min_;
+
+ /// @brief the default value
+ T default_;
+
+ /// @brief the maximum value
+ T max_;
+};
+
+
+} // namespace isc::dhcp
+} // namespace isc
+
+#endif // ifdef TRIPLET_H
diff --git a/src/lib/dns/Makefile.am b/src/lib/dns/Makefile.am
index 38809e0..5cf0732 100644
--- a/src/lib/dns/Makefile.am
+++ b/src/lib/dns/Makefile.am
@@ -95,6 +95,7 @@ libb10_dns___la_SOURCES += edns.h edns.cc
libb10_dns___la_SOURCES += exceptions.h exceptions.cc
libb10_dns___la_SOURCES += labelsequence.h labelsequence.cc
libb10_dns___la_SOURCES += masterload.h masterload.cc
+libb10_dns___la_SOURCES += master_lexer.h master_lexer.cc
libb10_dns___la_SOURCES += message.h message.cc
libb10_dns___la_SOURCES += messagerenderer.h messagerenderer.cc
libb10_dns___la_SOURCES += name.h name.cc
@@ -107,7 +108,6 @@ libb10_dns___la_SOURCES += rdatafields.h rdatafields.cc
libb10_dns___la_SOURCES += rrclass.cc
libb10_dns___la_SOURCES += rrparamregistry.h
libb10_dns___la_SOURCES += rrset.h rrset.cc
-libb10_dns___la_SOURCES += rrsetlist.h rrsetlist.cc
libb10_dns___la_SOURCES += rrttl.h rrttl.cc
libb10_dns___la_SOURCES += rrtype.cc
libb10_dns___la_SOURCES += question.h question.cc
@@ -146,14 +146,16 @@ libdns___include_HEADERS = \
exceptions.h \
labelsequence.h \
message.h \
+ master_lexer.h \
+ masterload.h \
messagerenderer.h \
name.h \
question.h \
+ opcode.h \
rcode.h \
rdata.h \
rrparamregistry.h \
rrset.h \
- rrsetlist.h \
rrttl.h \
tsigkey.h
# Purposely not installing these headers:
diff --git a/src/lib/dns/benchmarks/message_renderer_bench.cc b/src/lib/dns/benchmarks/message_renderer_bench.cc
index 6376498..abf3192 100644
--- a/src/lib/dns/benchmarks/message_renderer_bench.cc
+++ b/src/lib/dns/benchmarks/message_renderer_bench.cc
@@ -39,7 +39,7 @@ public:
renderer_(NULL),
names_(names)
{}
- MessageRendererBenchMark() {
+ ~MessageRendererBenchMark() {
delete renderer_;
}
unsigned int run() {
diff --git a/src/lib/dns/benchmarks/oldmessagerenderer.h b/src/lib/dns/benchmarks/oldmessagerenderer.h
index d408081..acbd757 100644
--- a/src/lib/dns/benchmarks/oldmessagerenderer.h
+++ b/src/lib/dns/benchmarks/oldmessagerenderer.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __OLDMESSAGERENDERER_H
-#define __OLDMESSAGERENDERER_H 1
+#ifndef OLDMESSAGERENDERER_H
+#define OLDMESSAGERENDERER_H 1
//
// This is a copy of an older version of MessageRenderer class. It is kept
@@ -49,7 +49,7 @@ private:
};
}
}
-#endif // __OLDMESSAGERENDERER_H
+#endif // OLDMESSAGERENDERER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/benchmarks/rdatarender_bench.cc b/src/lib/dns/benchmarks/rdatarender_bench.cc
index 38ee2ac..65576ee 100644
--- a/src/lib/dns/benchmarks/rdatarender_bench.cc
+++ b/src/lib/dns/benchmarks/rdatarender_bench.cc
@@ -42,9 +42,10 @@ template <typename T>
class RdataRenderBenchMark {
public:
RdataRenderBenchMark(const vector<T>& dataset) :
- dataset_(dataset)
+ dataset_(dataset),
+ renderer_(NULL)
{}
- RdataRenderBenchMark() {
+ ~RdataRenderBenchMark() {
delete renderer_;
}
unsigned int run() {
diff --git a/src/lib/dns/character_string.h b/src/lib/dns/character_string.h
index 7961274..2a68778 100644
--- a/src/lib/dns/character_string.h
+++ b/src/lib/dns/character_string.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __CHARACTER_STRING_H
-#define __CHARACTER_STRING_H
+#ifndef CHARACTER_STRING_H
+#define CHARACTER_STRING_H
#include <string>
#include <exceptions/exceptions.h>
@@ -54,4 +54,4 @@ namespace characterstr {
} // namespace dns
} // namespace isc
-#endif // __CHARACTER_STRING_H
+#endif // CHARACTER_STRING_H
diff --git a/src/lib/dns/edns.h b/src/lib/dns/edns.h
index a7bc4c4..dcd552f 100644
--- a/src/lib/dns/edns.h
+++ b/src/lib/dns/edns.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __EDNS_H
-#define __EDNS_H 1
+#ifndef EDNS_H
+#define EDNS_H 1
#include <stdint.h>
@@ -438,7 +438,7 @@ EDNS* createEDNSFromRR(const Name& name, const RRClass& rrclass,
std::ostream& operator<<(std::ostream& os, const EDNS& edns);
}
}
-#endif // __EDNS_H
+#endif // EDNS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/exceptions.h b/src/lib/dns/exceptions.h
index bd696a5..070b152 100644
--- a/src/lib/dns/exceptions.h
+++ b/src/lib/dns/exceptions.h
@@ -17,8 +17,8 @@
// style for the header guide (e.g. module-name_file-name_H) throughout the
// package.
-#ifndef __DNS_EXCEPTIONS_H
-#define __DNS_EXCEPTIONS_H 1
+#ifndef DNS_EXCEPTIONS_H
+#define DNS_EXCEPTIONS_H 1
#include <exceptions/exceptions.h>
@@ -52,7 +52,7 @@ public:
};
}
}
-#endif // __DNS_EXCEPTIONS_H
+#endif // DNS_EXCEPTIONS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/gen-rdatacode.py.in b/src/lib/dns/gen-rdatacode.py.in
index f3cd5df..e51dfc5 100755
--- a/src/lib/dns/gen-rdatacode.py.in
+++ b/src/lib/dns/gen-rdatacode.py.in
@@ -74,7 +74,7 @@ def import_classheader(class_txt, type_txt, type_code, file):
# for each CLASS_n/TYPE_m.h
rdata_header = open(file, 'r')
content = ''
- guard_macro = '__' + class_txt.upper() + '_' + type_txt.upper()
+ guard_macro = class_txt.upper() + '_' + type_txt.upper()
guard_macro += '_' + type_code + '_H'
for line in rdata_header.readlines():
if re.match('// BEGIN_HEADER_GUARD', line):
diff --git a/src/lib/dns/labelsequence.h b/src/lib/dns/labelsequence.h
index 3f6a03a..6c97454 100644
--- a/src/lib/dns/labelsequence.h
+++ b/src/lib/dns/labelsequence.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LABELSEQUENCE_H
-#define __LABELSEQUENCE_H 1
+#ifndef LABELSEQUENCE_H
+#define LABELSEQUENCE_H 1
#include <dns/name.h>
#include <util/buffer.h>
diff --git a/src/lib/dns/master_lexer.cc b/src/lib/dns/master_lexer.cc
new file mode 100644
index 0000000..2a5c886
--- /dev/null
+++ b/src/lib/dns/master_lexer.cc
@@ -0,0 +1,47 @@
+// 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 <dns/master_lexer.h>
+
+#include <cassert>
+#include <string>
+
+namespace {
+const char* const error_text[] = {
+ "lexer not started", // NOT_STARTED
+ "unbalanced parentheses", // UNBALANCED_PAREN
+ "unexpected end of input", // UNEXPECTED_END
+ "unbalanced quotes" // UNBALANCED_QUOTES
+};
+const size_t error_text_max_count = sizeof(error_text) / sizeof(error_text[0]);
+}
+
+namespace isc {
+namespace dns {
+
+std::string
+MasterLexer::Token::getErrorText() const {
+ if (type_ != ERROR) {
+ isc_throw(InvalidOperation,
+ "Token::getErrorText() for non error type");
+ }
+
+ // The class integrity ensures the following:
+ assert(val_.error_code_ < error_text_max_count);
+ return (error_text[val_.error_code_]);
+}
+
+
+} // end of namespace dns
+} // end of namespace isc
diff --git a/src/lib/dns/master_lexer.h b/src/lib/dns/master_lexer.h
new file mode 100644
index 0000000..bd86a04
--- /dev/null
+++ b/src/lib/dns/master_lexer.h
@@ -0,0 +1,241 @@
+// 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 MASTER_LEXER_H
+#define MASTER_LEXER_H 1
+
+#include <exceptions/exceptions.h>
+
+#include <string>
+
+#include <stdint.h>
+
+namespace isc {
+namespace dns {
+
+class MasterLexer {
+public:
+ class Token; // we define it separately for better readability
+};
+
+/// \brief Tokens for \c MasterLexer
+///
+/// This is a simple value-class encapsulating a type of a lexer token and
+/// (if it has a value) its value. Essentially, the class provides
+/// constructors corresponding to different types of tokens, and corresponding
+/// getter methods. The type and value are fixed at the time of construction
+/// and will never be modified throughout the lifetime of the object.
+/// The getter methods are still provided to maximize the safety; an
+/// application cannot refer to a value that is invalid for the type of token.
+///
+/// This class is intentionally implemented as copyable and assignable
+/// (using the default version of copy constructor and assignment operator),
+/// but it's mainly for internal implementation convenience. Applications will
+/// simply refer to Token object as a reference via the \c MasterLexer class.
+class MasterLexer::Token {
+public:
+ /// \brief Enumeration for token types
+ ///
+ /// \note At the time of initial implementation, all numeric tokens
+ /// that would be extracted from \c MasterLexer should be represented
+ /// as an unsigned 32-bit integer. If we see the need for larger integers
+ /// or negative numbers, we can then extend the token types.
+ enum Type {
+ END_OF_LINE, ///< End of line detected (if asked for detecting it)
+ END_OF_FILE, ///< End of file detected (if asked for detecting it)
+ INITIAL_WS, ///< White spaces at the beginning of a line
+ NOVALUE_TYPE_MAX = INITIAL_WS, ///< Max integer corresponding to
+ /// no-value (type only) types.
+ /// Mainly for internal use.
+ STRING, ///< A single string
+ QSTRING, ///< A single string quoted by double-quotes (").
+ NUMBER, ///< A decimal number (unsigned 32-bit)
+ ERROR ///< Error detected in getting a token
+ };
+
+ /// \brief Enumeration for lexer error codes
+ enum ErrorCode {
+ NOT_STARTED, ///< The lexer is just initialized and has no token
+ UNBALANCED_PAREN, ///< Unbalanced parentheses detected
+ UNEXPECTED_END, ///< The lexer reaches the end of line or file
+ /// unexpectedly
+ UNBALANCED_QUOTES, ///< Unbalanced quotations detected
+ MAX_ERROR_CODE ///< Max integer corresponding to valid error codes.
+ /// (excluding this one). Mainly for internal use.
+ };
+
+ /// \brief A simple representation of a range of a string.
+ ///
+ /// This is a straightforward pair of the start pointer of a string
+ /// and its length. The \c STRING and \c QSTRING types of tokens
+ /// will be primarily represented in this form.
+ ///
+ /// Any character can be stored in the valid range of the region.
+ /// In particular, there can be a nul character (\0) in the middle of
+ /// the region. On the other hand, it is not ensured that the string
+ /// is nul-terminated. So the usual string manipulation API may not work
+ /// as expected.
+ struct StringRegion {
+ const char* beg; ///< The start address of the string
+ size_t len; ///< The length of the string in bytes
+ };
+
+ /// \brief Constructor for non-value type of token.
+ ///
+ /// \throw InvalidParameter A value type token is specified.
+ /// \param type The type of the token. It must indicate a non-value
+ /// type (not larger than \c NOVALUE_TYPE_MAX).
+ explicit Token(Type type) : type_(type) {
+ if (type > NOVALUE_TYPE_MAX) {
+ isc_throw(InvalidParameter, "Token per-type constructor "
+ "called with invalid type: " << type);
+ }
+ }
+
+ /// \brief Constructor for string and quoted-string types of token.
+ ///
+ /// The optional \c quoted parameter specifies whether it's a quoted or
+ /// non quoted string.
+ ///
+ /// The string is specified as a pair of a pointer to the start address
+ /// and its length. Any character can be contained in any position of
+ /// the valid range (see \c StringRegion).
+ ///
+ /// When it's a quoted string, the quotation marks must be excluded
+ /// from the specified range.
+ ///
+ /// \param str_beg The start address of the string
+ /// \param str_len The size of the string in bytes
+ /// \param quoted true if it's a quoted string; false otherwise.
+ Token(const char* str_beg, size_t str_len, bool quoted = false) :
+ type_(quoted ? QSTRING : STRING)
+ {
+ val_.str_region_.beg = str_beg;
+ val_.str_region_.len = str_len;
+ }
+
+ /// \brief Constructor for number type of token.
+ ///
+ /// \brief number An unsigned 32-bit integer corresponding to the token
+ /// value.
+ explicit Token(uint32_t number) : type_(NUMBER) {
+ val_.number_ = number;
+ }
+
+ /// \brief Constructor for error type of token.
+ ///
+ /// \throw InvalidParameter Invalid error code value is specified.
+ /// \brief error_code A pre-defined constant of \c ErrorCode.
+ explicit Token(ErrorCode error_code) : type_(ERROR) {
+ if (!(error_code < MAX_ERROR_CODE)) {
+ isc_throw(InvalidParameter, "Invalid master lexer error code: "
+ << error_code);
+ }
+ val_.error_code_ = error_code;
+ }
+
+ /// \brief Return the token type.
+ ///
+ /// \throw none
+ Type getType() const { return (type_); }
+
+ /// \brief Return the value of a string-variant token.
+ ///
+ /// \throw InvalidOperation Called on a non string-variant types of token.
+ /// \return A reference to \c StringRegion corresponding to the string
+ /// token value.
+ const StringRegion& getStringRegion() const {
+ if (type_ != STRING && type_ != QSTRING) {
+ isc_throw(InvalidOperation,
+ "Token::getStringRegion() for non string-variant type");
+ }
+ return (val_.str_region_);
+ }
+
+ /// \brief Return the value of a string-variant token as a string object.
+ ///
+ /// Note that the underlying string may contain a nul (\0) character
+ /// in the middle. The returned string object will contain all characters
+ /// of the valid range of the underlying string. So some string
+ /// operations such as c_str() may not work as expected.
+ ///
+ /// \throw InvalidOperation Called on a non string-variant types of token.
+ /// \throw std::bad_alloc Resource allocation failure in constructing the
+ /// string object.
+ /// \return A std::string object corresponding to the string token value.
+ std::string getString() const {
+ if (type_ != STRING && type_ != QSTRING) {
+ isc_throw(InvalidOperation,
+ "Token::getString() for non string-variant type");
+ }
+ return (std::string(val_.str_region_.beg,
+ val_.str_region_.beg + val_.str_region_.len));
+ }
+
+ /// \brief Return the value of a string-variant token as a string object.
+ ///
+ /// \throw InvalidOperation Called on a non number type of token.
+ /// \return The integer corresponding to the number token value.
+ uint32_t getNumber() const {
+ if (type_ != NUMBER) {
+ isc_throw(InvalidOperation,
+ "Token::getNumber() for non number type");
+ }
+ return (val_.number_);
+ }
+
+ /// \brief Return the error code of a error type token.
+ ///
+ /// \throw InvalidOperation Called on a non error type of token.
+ /// \return The error code of the token.
+ ErrorCode getErrorCode() const {
+ if (type_ != ERROR) {
+ isc_throw(InvalidOperation,
+ "Token::getErrorCode() for non error type");
+ }
+ return (val_.error_code_);
+ };
+
+ /// \brief Return a textual description of the error of a error type token.
+ ///
+ /// The returned string would be useful to produce a log message when
+ /// a zone file parser encounters an error.
+ ///
+ /// \throw InvalidOperation Called on a non error type of token.
+ /// \throw std::bad_alloc Resource allocation failure in constructing the
+ /// string object.
+ /// \return A string object that describes the meaning of the error.
+ std::string getErrorText() const;
+
+private:
+ Type type_; // this is not const so the class can be assignable
+
+ // We use a union to represent different types of token values via the
+ // unified Token class. The class integrity should ensure valid operation
+ // on the union; getter methods should only refer to the member set at
+ // the construction.
+ union {
+ StringRegion str_region_;
+ uint32_t number_;
+ ErrorCode error_code_;
+ } val_;
+};
+
+} // namespace dns
+} // namespace isc
+#endif // MASTER_LEXER_H
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/lib/dns/masterload.h b/src/lib/dns/masterload.h
index e252285..44b3d62 100644
--- a/src/lib/dns/masterload.h
+++ b/src/lib/dns/masterload.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MASTERLOAD_H
-#define __MASTERLOAD_H 1
+#ifndef MASTERLOAD_H
+#define MASTERLOAD_H 1
#include <iosfwd>
@@ -244,7 +244,7 @@ void masterLoad(std::istream& input, const Name& origin,
//@}
}
-#endif // __MASTERLOAD_H
+#endif // MASTERLOAD_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/message.h b/src/lib/dns/message.h
index 85754ac..8aaaa48 100644
--- a/src/lib/dns/message.h
+++ b/src/lib/dns/message.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_H
-#define __MESSAGE_H 1
+#ifndef MESSAGE_H
+#define MESSAGE_H 1
#include <stdint.h>
@@ -687,7 +687,7 @@ typedef boost::shared_ptr<const Message> ConstMessagePtr;
std::ostream& operator<<(std::ostream& os, const Message& message);
}
}
-#endif // __MESSAGE_H
+#endif // MESSAGE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/messagerenderer.h b/src/lib/dns/messagerenderer.h
index 4816ad5..092d6de 100644
--- a/src/lib/dns/messagerenderer.h
+++ b/src/lib/dns/messagerenderer.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGERENDERER_H
-#define __MESSAGERENDERER_H 1
+#ifndef MESSAGERENDERER_H
+#define MESSAGERENDERER_H 1
#include <util/buffer.h>
@@ -397,7 +397,7 @@ private:
};
}
}
-#endif // __MESSAGERENDERER_H
+#endif // MESSAGERENDERER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/name.h b/src/lib/dns/name.h
index 261caee..a3e3674 100644
--- a/src/lib/dns/name.h
+++ b/src/lib/dns/name.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NAME_H
-#define __NAME_H 1
+#ifndef NAME_H
+#define NAME_H 1
#include <stdint.h>
@@ -724,7 +724,7 @@ operator<<(std::ostream& os, const Name& name);
}
}
-#endif // __NAME_H
+#endif // NAME_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/name_internal.h b/src/lib/dns/name_internal.h
index 8595df1..d60ee7a 100644
--- a/src/lib/dns/name_internal.h
+++ b/src/lib/dns/name_internal.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NAME_INTERNAL_H
-#define __NAME_INTERNAL_H 1
+#ifndef NAME_INTERNAL_H
+#define NAME_INTERNAL_H 1
// This is effectively a "private" namespace for the Name class implementation,
// but exposed publicly so the definitions in it can be shared with other
@@ -36,7 +36,7 @@ extern const uint8_t maptolower[];
} // end of name
} // end of dns
} // end of isc
-#endif // __NAME_INTERNAL_H
+#endif // NAME_INTERNAL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/nsec3hash.h b/src/lib/dns/nsec3hash.h
index e082ee8..f1ca1a3 100644
--- a/src/lib/dns/nsec3hash.h
+++ b/src/lib/dns/nsec3hash.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSEC3HASH_H
-#define __NSEC3HASH_H 1
+#ifndef NSEC3HASH_H
+#define NSEC3HASH_H 1
#include <string>
#include <vector>
@@ -276,7 +276,7 @@ void setNSEC3HashCreator(const NSEC3HashCreator* new_creator);
}
}
-#endif // __NSEC3HASH_H
+#endif // NSEC3HASH_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/opcode.h b/src/lib/dns/opcode.h
index dd88062..8e93877 100644
--- a/src/lib/dns/opcode.h
+++ b/src/lib/dns/opcode.h
@@ -18,8 +18,8 @@
#include <ostream>
-#ifndef __OPCODE_H
-#define __OPCODE_H 1
+#ifndef OPCODE_H
+#define OPCODE_H 1
namespace isc {
namespace dns {
diff --git a/src/lib/dns/python/edns_python.cc b/src/lib/dns/python/edns_python.cc
index 8f0f1a4..e9d54c1 100644
--- a/src/lib/dns/python/edns_python.cc
+++ b/src/lib/dns/python/edns_python.cc
@@ -269,7 +269,6 @@ EDNS_createFromRR(const s_EDNS* null_self, PyObject* args) {
const PyObject* rrtype;
const PyObject* rrttl;
const PyObject* rdata;
- s_EDNS* edns_obj = NULL;
assert(null_self == NULL);
@@ -277,7 +276,7 @@ EDNS_createFromRR(const s_EDNS* null_self, PyObject* args) {
&rrclass_type, &rrclass, &rrtype_type, &rrtype,
&rrttl_type, &rrttl, &rdata_type, &rdata)) {
uint8_t extended_rcode;
- edns_obj = PyObject_New(s_EDNS, &edns_type);
+ s_EDNS* edns_obj = PyObject_New(s_EDNS, &edns_type);
if (edns_obj == NULL) {
return (NULL);
}
diff --git a/src/lib/dns/python/edns_python.h b/src/lib/dns/python/edns_python.h
index 30d92ab..2106b22 100644
--- a/src/lib/dns/python/edns_python.h
+++ b/src/lib/dns/python/edns_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_EDNS_H
-#define __PYTHON_EDNS_H 1
+#ifndef PYTHON_EDNS_H
+#define PYTHON_EDNS_H 1
#include <Python.h>
@@ -57,7 +57,7 @@ const EDNS& PyEDNS_ToEDNS(const PyObject* edns_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_EDNS_H
+#endif // PYTHON_EDNS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/message_python.h b/src/lib/dns/python/message_python.h
index be23890..f3c1488 100644
--- a/src/lib/dns/python/message_python.h
+++ b/src/lib/dns/python/message_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_MESSAGE_H
-#define __PYTHON_MESSAGE_H 1
+#ifndef PYTHON_MESSAGE_H
+#define PYTHON_MESSAGE_H 1
#include <Python.h>
@@ -33,7 +33,7 @@ extern PyTypeObject message_type;
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_MESSAGE_H
+#endif // PYTHON_MESSAGE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/messagerenderer_python.h b/src/lib/dns/python/messagerenderer_python.h
index ea9a940..f6ea922 100644
--- a/src/lib/dns/python/messagerenderer_python.h
+++ b/src/lib/dns/python/messagerenderer_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_MESSAGERENDERER_H
-#define __PYTHON_MESSAGERENDERER_H 1
+#ifndef PYTHON_MESSAGERENDERER_H
+#define PYTHON_MESSAGERENDERER_H 1
#include <Python.h>
@@ -50,7 +50,7 @@ MessageRenderer& PyMessageRenderer_ToMessageRenderer(PyObject* messagerenderer_o
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_MESSAGERENDERER_H
+#endif // PYTHON_MESSAGERENDERER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/name_python.h b/src/lib/dns/python/name_python.h
index 86d7fd0..d18c0d9 100644
--- a/src/lib/dns/python/name_python.h
+++ b/src/lib/dns/python/name_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_NAME_H
-#define __PYTHON_NAME_H 1
+#ifndef PYTHON_NAME_H
+#define PYTHON_NAME_H 1
#include <Python.h>
@@ -74,7 +74,7 @@ const Name& PyName_ToName(const PyObject* name_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_NAME_H
+#endif // PYTHON_NAME_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/nsec3hash_python.h b/src/lib/dns/python/nsec3hash_python.h
index fa9b9b6..51a5fde 100644
--- a/src/lib/dns/python/nsec3hash_python.h
+++ b/src/lib/dns/python/nsec3hash_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_NSEC3HASH_H
-#define __PYTHON_NSEC3HASH_H 1
+#ifndef PYTHON_NSEC3HASH_H
+#define PYTHON_NSEC3HASH_H 1
#include <Python.h>
@@ -40,7 +40,7 @@ bool initModulePart_NSEC3Hash(PyObject* mod);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_NSEC3HASH_H
+#endif // PYTHON_NSEC3HASH_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/opcode_python.h b/src/lib/dns/python/opcode_python.h
index d0aec15..6e9967e 100644
--- a/src/lib/dns/python/opcode_python.h
+++ b/src/lib/dns/python/opcode_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_OPCODE_H
-#define __PYTHON_OPCODE_H 1
+#ifndef PYTHON_OPCODE_H
+#define PYTHON_OPCODE_H 1
#include <Python.h>
@@ -57,7 +57,7 @@ const Opcode& PyOpcode_ToOpcode(const PyObject* opcode_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_OPCODE_H
+#endif // PYTHON_OPCODE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/pydnspp_common.h b/src/lib/dns/python/pydnspp_common.h
index 3cc69c4..5ca1cd8 100644
--- a/src/lib/dns/python/pydnspp_common.h
+++ b/src/lib/dns/python/pydnspp_common.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LIBDNS_PYTHON_COMMON_H
-#define __LIBDNS_PYTHON_COMMON_H 1
+#ifndef LIBDNS_PYTHON_COMMON_H
+#define LIBDNS_PYTHON_COMMON_H 1
#include <Python.h>
@@ -106,7 +106,7 @@ convertToPyHash(HashvalType val) {
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __LIBDNS_PYTHON_COMMON_H
+#endif // LIBDNS_PYTHON_COMMON_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/pydnspp_towire.h b/src/lib/dns/python/pydnspp_towire.h
index e987a29..7ad70cd 100644
--- a/src/lib/dns/python/pydnspp_towire.h
+++ b/src/lib/dns/python/pydnspp_towire.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LIBDNS_PYTHON_TOWIRE_H
-#define __LIBDNS_PYTHON_TOWIRE_H 1
+#ifndef LIBDNS_PYTHON_TOWIRE_H
+#define LIBDNS_PYTHON_TOWIRE_H 1
#include <Python.h>
@@ -120,7 +120,7 @@ toWireWrapper(const PYSTRUCT* const self, PyObject* args) {
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __LIBDNS_PYTHON_TOWIRE_H
+#endif // LIBDNS_PYTHON_TOWIRE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/question_python.h b/src/lib/dns/python/question_python.h
index f5d78b1..99b37c7 100644
--- a/src/lib/dns/python/question_python.h
+++ b/src/lib/dns/python/question_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_QUESTION_H
-#define __PYTHON_QUESTION_H 1
+#ifndef PYTHON_QUESTION_H
+#define PYTHON_QUESTION_H 1
#include <Python.h>
@@ -59,7 +59,7 @@ const Question& PyQuestion_ToQuestion(const PyObject* question_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_QUESTION_H
+#endif // PYTHON_QUESTION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/rcode_python.h b/src/lib/dns/python/rcode_python.h
index a149406..704821a 100644
--- a/src/lib/dns/python/rcode_python.h
+++ b/src/lib/dns/python/rcode_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_RCODE_H
-#define __PYTHON_RCODE_H 1
+#ifndef PYTHON_RCODE_H
+#define PYTHON_RCODE_H 1
#include <Python.h>
@@ -57,7 +57,7 @@ const Rcode& PyRcode_ToRcode(const PyObject* rcode_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_RCODE_H
+#endif // PYTHON_RCODE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/rdata_python.h b/src/lib/dns/python/rdata_python.h
index c7ddd57..6fa6631 100644
--- a/src/lib/dns/python/rdata_python.h
+++ b/src/lib/dns/python/rdata_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_RDATA_H
-#define __PYTHON_RDATA_H 1
+#ifndef PYTHON_RDATA_H
+#define PYTHON_RDATA_H 1
#include <Python.h>
@@ -61,7 +61,7 @@ const isc::dns::rdata::Rdata& PyRdata_ToRdata(const PyObject* rdata_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_RDATA_H
+#endif // PYTHON_RDATA_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/rrclass_python.h b/src/lib/dns/python/rrclass_python.h
index f58bba6..df5ca70 100644
--- a/src/lib/dns/python/rrclass_python.h
+++ b/src/lib/dns/python/rrclass_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_RRCLASS_H
-#define __PYTHON_RRCLASS_H 1
+#ifndef PYTHON_RRCLASS_H
+#define PYTHON_RRCLASS_H 1
#include <Python.h>
@@ -61,7 +61,7 @@ const RRClass& PyRRClass_ToRRClass(const PyObject* rrclass_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_RRCLASS_H
+#endif // PYTHON_RRCLASS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/rrset_python.h b/src/lib/dns/python/rrset_python.h
index 2435397..9faac95 100644
--- a/src/lib/dns/python/rrset_python.h
+++ b/src/lib/dns/python/rrset_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_RRSET_H
-#define __PYTHON_RRSET_H 1
+#ifndef PYTHON_RRSET_H
+#define PYTHON_RRSET_H 1
#include <Python.h>
@@ -71,7 +71,7 @@ RRsetPtr PyRRset_ToRRsetPtr(PyObject* rrset_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_RRSET_H
+#endif // PYTHON_RRSET_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/rrttl_python.h b/src/lib/dns/python/rrttl_python.h
index 9dbc982..9ad904f 100644
--- a/src/lib/dns/python/rrttl_python.h
+++ b/src/lib/dns/python/rrttl_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_RRTTL_H
-#define __PYTHON_RRTTL_H 1
+#ifndef PYTHON_RRTTL_H
+#define PYTHON_RRTTL_H 1
#include <Python.h>
@@ -60,7 +60,7 @@ const RRTTL& PyRRTTL_ToRRTTL(const PyObject* rrttl_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_RRTTL_H
+#endif // PYTHON_RRTTL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/rrtype_python.h b/src/lib/dns/python/rrtype_python.h
index 596598e..3595952 100644
--- a/src/lib/dns/python/rrtype_python.h
+++ b/src/lib/dns/python/rrtype_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_RRTYPE_H
-#define __PYTHON_RRTYPE_H 1
+#ifndef PYTHON_RRTYPE_H
+#define PYTHON_RRTYPE_H 1
#include <Python.h>
@@ -61,7 +61,7 @@ const RRType& PyRRType_ToRRType(const PyObject* rrtype_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_RRTYPE_H
+#endif // PYTHON_RRTYPE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/serial_python.h b/src/lib/dns/python/serial_python.h
index 48b5199..9a495be 100644
--- a/src/lib/dns/python/serial_python.h
+++ b/src/lib/dns/python/serial_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_SERIAL_H
-#define __PYTHON_SERIAL_H 1
+#ifndef PYTHON_SERIAL_H
+#define PYTHON_SERIAL_H 1
#include <Python.h>
@@ -57,7 +57,7 @@ const Serial& PySerial_ToSerial(const PyObject* Serial_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_SERIAL_H
+#endif // PYTHON_SERIAL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/tsig_python.h b/src/lib/dns/python/tsig_python.h
index e4e9fff..0bd57d7 100644
--- a/src/lib/dns/python/tsig_python.h
+++ b/src/lib/dns/python/tsig_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_TSIGCONTEXT_H
-#define __PYTHON_TSIGCONTEXT_H 1
+#ifndef PYTHON_TSIGCONTEXT_H
+#define PYTHON_TSIGCONTEXT_H 1
#include <Python.h>
@@ -52,7 +52,7 @@ TSIGContext& PyTSIGContext_ToTSIGContext(PyObject* tsigcontext_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_TSIGCONTEXT_H
+#endif // PYTHON_TSIGCONTEXT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/tsig_rdata_python.h b/src/lib/dns/python/tsig_rdata_python.h
index a84d9e8..85dd366 100644
--- a/src/lib/dns/python/tsig_rdata_python.h
+++ b/src/lib/dns/python/tsig_rdata_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_TSIG_H
-#define __PYTHON_TSIG_H 1
+#ifndef PYTHON_TSIG_H
+#define PYTHON_TSIG_H 1
#include <Python.h>
@@ -61,7 +61,7 @@ const rdata::any::TSIG& PyTSIG_ToTSIG(const PyObject* tsig_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_TSIG_H
+#endif // PYTHON_TSIG_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/tsigerror_python.h b/src/lib/dns/python/tsigerror_python.h
index 0b5b630..6258ab3 100644
--- a/src/lib/dns/python/tsigerror_python.h
+++ b/src/lib/dns/python/tsigerror_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_TSIGERROR_H
-#define __PYTHON_TSIGERROR_H 1
+#ifndef PYTHON_TSIGERROR_H
+#define PYTHON_TSIGERROR_H 1
#include <Python.h>
@@ -37,7 +37,7 @@ PyObject* createTSIGErrorObject(const TSIGError& source);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_TSIGERROR_H
+#endif // PYTHON_TSIGERROR_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/tsigkey_python.h b/src/lib/dns/python/tsigkey_python.h
index 6c3d2e3..ec09e2c 100644
--- a/src/lib/dns/python/tsigkey_python.h
+++ b/src/lib/dns/python/tsigkey_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_TSIGKEY_H
-#define __PYTHON_TSIGKEY_H 1
+#ifndef PYTHON_TSIGKEY_H
+#define PYTHON_TSIGKEY_H 1
#include <Python.h>
@@ -68,7 +68,7 @@ const TSIGKeyRing& PyTSIGKeyRing_ToTSIGKeyRing(const PyObject* tsigkeyring_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_TSIGKEY_H
+#endif // PYTHON_TSIGKEY_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/python/tsigrecord_python.h b/src/lib/dns/python/tsigrecord_python.h
index d6252e1..ec505f7 100644
--- a/src/lib/dns/python/tsigrecord_python.h
+++ b/src/lib/dns/python/tsigrecord_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_TSIGRECORD_H
-#define __PYTHON_TSIGRECORD_H 1
+#ifndef PYTHON_TSIGRECORD_H
+#define PYTHON_TSIGRECORD_H 1
#include <Python.h>
@@ -58,7 +58,7 @@ const TSIGRecord& PyTSIGRecord_ToTSIGRecord(PyObject* tsigrecord_obj);
} // namespace python
} // namespace dns
} // namespace isc
-#endif // __PYTHON_TSIGRECORD_H
+#endif // PYTHON_TSIGRECORD_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/question.h b/src/lib/dns/question.h
index 5d2783b..4b5b233 100644
--- a/src/lib/dns/question.h
+++ b/src/lib/dns/question.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __QUESTION_H
-#define __QUESTION_H 1
+#ifndef QUESTION_H
+#define QUESTION_H 1
#include <iostream>
#include <string>
@@ -288,7 +288,7 @@ private:
std::ostream& operator<<(std::ostream& os, const Question& question);
} // end of namespace dns
} // end of namespace isc
-#endif // __QUESTION_H
+#endif // QUESTION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rcode.h b/src/lib/dns/rcode.h
index 0c63285..f294615 100644
--- a/src/lib/dns/rcode.h
+++ b/src/lib/dns/rcode.h
@@ -18,8 +18,8 @@
#include <ostream>
-#ifndef __RCODE_H
-#define __RCODE_H 1
+#ifndef RCODE_H
+#define RCODE_H 1
namespace isc {
namespace dns {
diff --git a/src/lib/dns/rdata.h b/src/lib/dns/rdata.h
index afcf4b3..f77ea6e 100644
--- a/src/lib/dns/rdata.h
+++ b/src/lib/dns/rdata.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RDATA_H
-#define __RDATA_H 1
+#ifndef RDATA_H
+#define RDATA_H 1
#include <stdint.h>
@@ -509,7 +509,7 @@ int compareNames(const Name& n1, const Name& n2);
} // end of namespace "rdata"
}
}
-#endif // __RDATA_H
+#endif // RDATA_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rdata/generic/afsdb_18.cc b/src/lib/dns/rdata/generic/afsdb_18.cc
index 6afc4de..ec76ee0 100644
--- a/src/lib/dns/rdata/generic/afsdb_18.cc
+++ b/src/lib/dns/rdata/generic/afsdb_18.cc
@@ -57,7 +57,6 @@ AFSDB::AFSDB(const std::string& afsdb_str) :
try {
const uint32_t subtype = tokenToNum<int32_t, 16>(getToken(iss));
const Name servername(getToken(iss));
- string server;
if (!iss.eof()) {
isc_throw(InvalidRdataText, "Unexpected input for AFSDB"
diff --git a/src/lib/dns/rdata/generic/detail/ds_like.h b/src/lib/dns/rdata/generic/detail/ds_like.h
index b5a35cd..333de4c 100644
--- a/src/lib/dns/rdata/generic/detail/ds_like.h
+++ b/src/lib/dns/rdata/generic/detail/ds_like.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __DS_LIKE_H
-#define __DS_LIKE_H 1
+#ifndef DS_LIKE_H
+#define DS_LIKE_H 1
#include <stdint.h>
@@ -218,7 +218,7 @@ private:
}
}
}
-#endif // __DS_LIKE_H
+#endif // DS_LIKE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rdata/generic/detail/nsec3param_common.h b/src/lib/dns/rdata/generic/detail/nsec3param_common.h
index 515777b..1891fae 100644
--- a/src/lib/dns/rdata/generic/detail/nsec3param_common.h
+++ b/src/lib/dns/rdata/generic/detail/nsec3param_common.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSEC3PARAM_COMMON_H
-#define __NSEC3PARAM_COMMON_H 1
+#ifndef NSEC3PARAM_COMMON_H
+#define NSEC3PARAM_COMMON_H 1
#include <util/buffer.h>
@@ -127,7 +127,7 @@ ParseNSEC3ParamResult parseNSEC3ParamWire(const char* const rrtype_name,
}
}
-#endif // __NSEC3PARAM_COMMON_H
+#endif // NSEC3PARAM_COMMON_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rdata/generic/detail/nsec_bitmap.h b/src/lib/dns/rdata/generic/detail/nsec_bitmap.h
index 85cae2e..0b2102f 100644
--- a/src/lib/dns/rdata/generic/detail/nsec_bitmap.h
+++ b/src/lib/dns/rdata/generic/detail/nsec_bitmap.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSECBITMAP_H
-#define __NSECBITMAP_H 1
+#ifndef NSECBITMAP_H
+#define NSECBITMAP_H 1
#include <stdint.h>
@@ -100,7 +100,7 @@ void bitmapsToText(const std::vector<uint8_t>& typebits,
}
}
-#endif // __NSECBITMAP_H
+#endif // NSECBITMAP_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rdata/generic/detail/txt_like.h b/src/lib/dns/rdata/generic/detail/txt_like.h
index a0ab7ac..fdab6bf 100644
--- a/src/lib/dns/rdata/generic/detail/txt_like.h
+++ b/src/lib/dns/rdata/generic/detail/txt_like.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TXT_LIKE_H
-#define __TXT_LIKE_H 1
+#ifndef TXT_LIKE_H
+#define TXT_LIKE_H 1
#include <stdint.h>
@@ -217,7 +217,7 @@ private:
// END_RDATA_NAMESPACE
// END_ISC_NAMESPACE
-#endif // __TXT_LIKE_H
+#endif // TXT_LIKE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rdatafields.h b/src/lib/dns/rdatafields.h
index 16880f0..efdc453 100644
--- a/src/lib/dns/rdatafields.h
+++ b/src/lib/dns/rdatafields.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RDATAFIELDS_H
-#define __RDATAFIELDS_H 1
+#ifndef RDATAFIELDS_H
+#define RDATAFIELDS_H 1
#include <stdint.h>
@@ -420,7 +420,7 @@ private:
}
}
}
-#endif // __RDATAFIELDS_H
+#endif // RDATAFIELDS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rrclass-placeholder.h b/src/lib/dns/rrclass-placeholder.h
index 80035d8..70d6b78 100644
--- a/src/lib/dns/rrclass-placeholder.h
+++ b/src/lib/dns/rrclass-placeholder.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRCLASS_H
-#define __RRCLASS_H 1
+#ifndef RRCLASS_H
+#define RRCLASS_H 1
#include <stdint.h>
@@ -283,7 +283,7 @@ std::ostream&
operator<<(std::ostream& os, const RRClass& rrclass);
}
}
-#endif // __RRCLASS_H
+#endif // RRCLASS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rrparamregistry.h b/src/lib/dns/rrparamregistry.h
index ae41b5f..b1ca225 100644
--- a/src/lib/dns/rrparamregistry.h
+++ b/src/lib/dns/rrparamregistry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRPARAMREGISTRY_H
-#define __RRPARAMREGISTRY_H 1
+#ifndef RRPARAMREGISTRY_H
+#define RRPARAMREGISTRY_H 1
#include <string>
@@ -506,7 +506,7 @@ private:
}
}
-#endif // __RRPARAMREGISTRY_H
+#endif // RRPARAMREGISTRY_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rrset.cc b/src/lib/dns/rrset.cc
index 17a02cd..7ea01d0 100644
--- a/src/lib/dns/rrset.cc
+++ b/src/lib/dns/rrset.cc
@@ -64,8 +64,12 @@ AbstractRRset::toText() const {
it->next();
} while (!it->isLast());
+ if (getRRsig()) {
+ s += getRRsig()->toText();
+ }
+
return (s);
-}
+}
namespace {
template <typename T>
diff --git a/src/lib/dns/rrset.h b/src/lib/dns/rrset.h
index 7019f93..9c1715b 100644
--- a/src/lib/dns/rrset.h
+++ b/src/lib/dns/rrset.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRSET_H
-#define __RRSET_H 1
+#ifndef RRSET_H
+#define RRSET_H 1
#include <iostream>
#include <string>
@@ -267,6 +267,9 @@ public:
/// the resulting string with a trailing newline character.
/// (following the BIND9 convention)
///
+ /// If any RRSIGs are associated with the RRset, they are also
+ /// appended to the returned string.
+ ///
/// If the class is not ANY or NONE, the RRset must contain some RDATA;
/// otherwise, an exception of class \c EmptyRRset will be thrown.
/// If resource allocation fails, a corresponding standard exception
@@ -293,6 +296,8 @@ public:
/// RRset would cause truncation, and handles the case appropriately
/// (this is a TODO item, and not implemented in this version).
///
+ /// If any RRSIGs are associated with the RRset, they are also rendered.
+ ///
/// Note: perhaps we may want to add more arguments to convey optional
/// information such as an "rrset-order" policy or how to handle truncation
/// case. This is a TODO item.
@@ -929,7 +934,7 @@ private:
std::ostream& operator<<(std::ostream& os, const AbstractRRset& rrset);
} // end of namespace dns
} // end of namespace isc
-#endif // __RRSET_H
+#endif // RRSET_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rrsetlist.cc b/src/lib/dns/rrsetlist.cc
deleted file mode 100644
index fcdcfbb..0000000
--- a/src/lib/dns/rrsetlist.cc
+++ /dev/null
@@ -1,60 +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 <vector>
-
-#include <boost/foreach.hpp>
-
-#include <exceptions/exceptions.h>
-
-#include <dns/rrclass.h>
-#include <dns/rrtype.h>
-#include <dns/rrset.h>
-#include <dns/rrsetlist.h>
-
-namespace isc {
-namespace dns {
-
-void
-RRsetList::addRRset(RRsetPtr rrsetptr) {
- ConstRRsetPtr rrset_found = findRRset(rrsetptr->getType(),
- rrsetptr->getClass());
- if (rrset_found != NULL) {
- isc_throw(DuplicateRRset, "RRset is being doubly added to RRsetList: "
- "type=" << rrsetptr->getType() << ", class=" <<
- rrsetptr->getClass());
- }
- rrsets_.push_back(rrsetptr);
-}
-
-void
-RRsetList::append(RRsetList& source) {
- BOOST_FOREACH(RRsetPtr rrset, source) {
- addRRset(rrset);
- }
-}
-
-RRsetPtr
-RRsetList::findRRset(const RRType& rrtype, const RRClass& rrclass) {
- BOOST_FOREACH(RRsetPtr rrsetptr, rrsets_) {
- if ((rrsetptr->getClass() == rrclass) &&
- (rrsetptr->getType() == rrtype)) {
- return (rrsetptr);
- }
- }
- return (RRsetPtr());
-}
-
-}
-}
diff --git a/src/lib/dns/rrsetlist.h b/src/lib/dns/rrsetlist.h
deleted file mode 100644
index 0e05b5b..0000000
--- a/src/lib/dns/rrsetlist.h
+++ /dev/null
@@ -1,132 +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 __RRSETLIST_H
-#define __RRSETLIST_H 1
-
-#include <iostream>
-#include <iterator>
-#include <vector>
-
-#include <boost/shared_ptr.hpp>
-
-#include <dns/rrset.h>
-#include <dns/rrclass.h>
-#include <dns/rrtype.h>
-
-namespace isc {
-namespace dns {
-
-class DuplicateRRset : public Exception {
-public:
- DuplicateRRset(const char* file, size_t line, const char* what) :
- isc::Exception(file, line, what) {}
-};
-
-template <typename T, typename P, typename R>
-class RRsetListIterator :
- public std::iterator<std::input_iterator_tag, RRsetPtr> {
-public:
- RRsetListIterator() {}
- explicit RRsetListIterator(const T& it) :
- it_(it) {}
- RRsetListIterator& operator++()
- {
- ++it_;
- return (*this);
- }
- RRsetListIterator operator++(int)
- {
- RRsetListIterator tmp(*this);
- ++it_;
- return (tmp);
- }
- R operator*() const
- {
- return (*it_);
- }
- P operator->() const
- {
- return (&(operator*()));
- }
- bool operator==(const RRsetListIterator& other)
- {
- return (it_ == other.it_);
- }
- bool operator!=(const RRsetListIterator& other)
- {
- return (it_ != other.it_);
- }
-
-private:
- T it_;
-};
-
-/// A set of RRsets.
-///
-/// \note Do not use this class unless you really understand what
-/// you're doing and you're 100% sure that this class is the best choice
-/// for your purpose.
-///
-/// Counter intuitively, this class is not a "list" of RRsets but a
-/// "set" of them; it doesn't allow multiple RRsets of the same RR
-/// type and RR class to be added at the same time. And, for that
-/// reason, adding an RRset is more expensive than you'd expect. The
-/// class name is confusing, but was named so as a result of
-/// compromise: "RRsetset" would look awkward; RRsets would be
-/// confusing (with RRset).
-///
-/// In any case, if you want a list like container of RRsets, your best choice
-/// would be \c std::vector<RRset> or \c std::list<RRset>, not this class.
-/// In fact, in many cases \c RRsetList will be a suboptimal choice.
-/// This class is defined publicly as part of libdns++ for a historical
-/// reason and is actually quite specific to a particular need for libdatasrc.
-/// If you are tempted to use it, think twice to assess if this class
-/// is really what you want. Again, in many cases the answer will be no.
-class RRsetList {
-private:
- RRsetList(const RRsetList& source);
- RRsetList& operator=(const RRsetList& source);
-public:
- RRsetList() {}
- void addRRset(RRsetPtr new_rrsetptr);
- void append(RRsetList& source);
- RRsetPtr findRRset(const RRType& rrtype, const RRClass& rrclass);
-
- typedef RRsetListIterator<std::vector<RRsetPtr>::iterator,
- RRsetPtr*,
- RRsetPtr&> iterator;
- typedef RRsetListIterator<std::vector<RRsetPtr>::const_iterator,
- const RRsetPtr*,
- const RRsetPtr&> const_iterator;
-
- const_iterator begin() const { return (const_iterator(rrsets_.begin())); }
- const_iterator end() const { return (const_iterator(rrsets_.end())); }
-
- iterator begin() { return (iterator(rrsets_.begin())); }
- iterator end() { return (iterator(rrsets_.end())); }
-
- size_t size() const { return (rrsets_.size()); }
-
-private:
- std::vector<RRsetPtr> rrsets_;
-};
-
-} // end of namespace dns
-} // end of namespace isc
-#endif // __RRSETLIST_H
-
-// Local Variables:
-// mode: c++
-// End:
diff --git a/src/lib/dns/rrttl.h b/src/lib/dns/rrttl.h
index bf23295..62bf886 100644
--- a/src/lib/dns/rrttl.h
+++ b/src/lib/dns/rrttl.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRTTL_H
-#define __RRTTL_H 1
+#ifndef RRTTL_H
+#define RRTTL_H 1
#include <stdint.h>
@@ -255,7 +255,7 @@ std::ostream&
operator<<(std::ostream& os, const RRTTL& rrttl);
}
}
-#endif // __RRTTL_H
+#endif // RRTTL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/rrtype-placeholder.h b/src/lib/dns/rrtype-placeholder.h
index dad1b2b..273a486 100644
--- a/src/lib/dns/rrtype-placeholder.h
+++ b/src/lib/dns/rrtype-placeholder.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RRTYPE_H
-#define __RRTYPE_H 1
+#ifndef RRTYPE_H
+#define RRTYPE_H 1
#include <stdint.h>
@@ -235,11 +235,11 @@ public:
///
/// \param other the \c RRType object to compare against.
/// \return true if the two RRTypes are not equal; otherwise false.
- bool nequals(const RRType& other) const
+ bool nequals(const RRType& other) const
{ return (typecode_ != other.typecode_); }
/// \brief Same as \c nequals().
bool operator!=(const RRType& other) const { return (nequals(other)); }
-
+
/// \brief Less-than comparison for RRType against \c other
///
/// We define the less-than relationship based on their type codes;
@@ -317,8 +317,8 @@ std::ostream&
operator<<(std::ostream& os, const RRType& rrtype);
}
}
-#endif // __RRTYPE_H
+#endif // RRTYPE_H
-// Local Variables:
+// Local Variables:
// mode: c++
-// End:
+// End:
diff --git a/src/lib/dns/serial.h b/src/lib/dns/serial.h
index 3549860..678fb22 100644
--- a/src/lib/dns/serial.h
+++ b/src/lib/dns/serial.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SERIAL_H
-#define __SERIAL_H 1
+#ifndef SERIAL_H
+#define SERIAL_H 1
#include <stdint.h>
#include <iostream>
@@ -152,4 +152,4 @@ std::ostream& operator<<(std::ostream& os, const Serial& serial);
} // end namespace dns
} // end namespace isc
-#endif // __SERIAL_H
+#endif // SERIAL_H
diff --git a/src/lib/dns/tests/Makefile.am b/src/lib/dns/tests/Makefile.am
index 0abb389..6df0e62 100644
--- a/src/lib/dns/tests/Makefile.am
+++ b/src/lib/dns/tests/Makefile.am
@@ -24,6 +24,7 @@ run_unittests_SOURCES = unittest_util.h unittest_util.cc
run_unittests_SOURCES += edns_unittest.cc
run_unittests_SOURCES += labelsequence_unittest.cc
run_unittests_SOURCES += messagerenderer_unittest.cc
+run_unittests_SOURCES += master_lexer_token_unittest.cc
run_unittests_SOURCES += name_unittest.cc
run_unittests_SOURCES += nsec3hash_unittest.cc
run_unittests_SOURCES += rrclass_unittest.cc rrtype_unittest.cc
@@ -56,7 +57,7 @@ run_unittests_SOURCES += rdata_minfo_unittest.cc
run_unittests_SOURCES += rdata_tsig_unittest.cc
run_unittests_SOURCES += rdata_naptr_unittest.cc
run_unittests_SOURCES += rdata_hinfo_unittest.cc
-run_unittests_SOURCES += rrset_unittest.cc rrsetlist_unittest.cc
+run_unittests_SOURCES += rrset_unittest.cc
run_unittests_SOURCES += question_unittest.cc
run_unittests_SOURCES += rrparamregistry_unittest.cc
run_unittests_SOURCES += masterload_unittest.cc
diff --git a/src/lib/dns/tests/labelsequence_unittest.cc b/src/lib/dns/tests/labelsequence_unittest.cc
index 90d470d..62cbcec 100644
--- a/src/lib/dns/tests/labelsequence_unittest.cc
+++ b/src/lib/dns/tests/labelsequence_unittest.cc
@@ -860,8 +860,12 @@ TEST_F(LabelSequenceTest, badDeserialize) {
const uint8_t toomany_offsets[] = { Name::MAX_LABELS + 1 };
EXPECT_THROW(LabelSequence ls(toomany_offsets), isc::BadValue);
- // exceed MAX_LABEL_LEN
- const uint8_t offsets_toolonglabel[] = { 2, 0, 64 };
+ // (second) offset does not match actual label length
+ const uint8_t offsets_wrongoffset[] = { 2, 0, 64, 1 };
+ EXPECT_THROW(LabelSequence ls(offsets_wrongoffset), isc::BadValue);
+
+ // offset matches, but exceeds MAX_LABEL_LEN
+ const uint8_t offsets_toolonglabel[] = { 2, 0, 64, 64 };
EXPECT_THROW(LabelSequence ls(offsets_toolonglabel), isc::BadValue);
// Inconsistent data: an offset is lower than the previous offset
diff --git a/src/lib/dns/tests/master_lexer_token_unittest.cc b/src/lib/dns/tests/master_lexer_token_unittest.cc
new file mode 100644
index 0000000..a63b9ca
--- /dev/null
+++ b/src/lib/dns/tests/master_lexer_token_unittest.cc
@@ -0,0 +1,156 @@
+// 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/master_lexer.h>
+
+#include <gtest/gtest.h>
+
+#include <string>
+
+using namespace isc::dns;
+
+namespace {
+
+const char TEST_STRING[] = "string token";
+// This excludes the ending \0 character
+const size_t TEST_STRING_LEN = sizeof(TEST_STRING) - 1;
+
+class MasterLexerTokenTest : public ::testing::Test {
+protected:
+ MasterLexerTokenTest() :
+ token_eof(MasterLexer::Token::END_OF_FILE),
+ token_str(TEST_STRING, TEST_STRING_LEN),
+ token_num(42),
+ token_err(MasterLexer::Token::UNEXPECTED_END)
+ {}
+
+ const MasterLexer::Token token_eof; // an example of non-value type token
+ const MasterLexer::Token token_str;
+ const MasterLexer::Token token_num;
+ const MasterLexer::Token token_err;
+};
+
+
+TEST_F(MasterLexerTokenTest, strings) {
+ // basic construction and getter checks
+ EXPECT_EQ(MasterLexer::Token::STRING, token_str.getType());
+ EXPECT_EQ(std::string("string token"), token_str.getString());
+ const MasterLexer::Token::StringRegion str_region =
+ token_str.getStringRegion();
+ EXPECT_EQ(TEST_STRING, str_region.beg);
+ EXPECT_EQ(TEST_STRING_LEN, str_region.len);
+
+ // Even if the stored string contains a nul character (in this case,
+ // it happens to be at the end of the string, but could be in the middle),
+ // getString() should return a string object containing the nul.
+ std::string expected_str("string token");
+ expected_str.push_back('\0');
+ EXPECT_EQ(expected_str,
+ MasterLexer::Token(TEST_STRING, TEST_STRING_LEN + 1).getString());
+
+ // Construct type of qstring
+ EXPECT_EQ(MasterLexer::Token::QSTRING,
+ MasterLexer::Token(TEST_STRING, sizeof(TEST_STRING), true).
+ getType());
+ // if we explicitly set 'quoted' to false, it should be normal string
+ EXPECT_EQ(MasterLexer::Token::STRING,
+ MasterLexer::Token(TEST_STRING, sizeof(TEST_STRING), false).
+ getType());
+
+ // getString/StringRegion() aren't allowed for non string(-variant) types
+ EXPECT_THROW(token_eof.getString(), isc::InvalidOperation);
+ EXPECT_THROW(token_num.getString(), isc::InvalidOperation);
+ EXPECT_THROW(token_eof.getStringRegion(), isc::InvalidOperation);
+ EXPECT_THROW(token_num.getStringRegion(), isc::InvalidOperation);
+}
+
+TEST_F(MasterLexerTokenTest, numbers) {
+ EXPECT_EQ(42, token_num.getNumber());
+ EXPECT_EQ(MasterLexer::Token::NUMBER, token_num.getType());
+
+ // It's copyable and assignable.
+ MasterLexer::Token token(token_num);
+ EXPECT_EQ(42, token.getNumber());
+ EXPECT_EQ(MasterLexer::Token::NUMBER, token.getType());
+
+ token = token_num;
+ EXPECT_EQ(42, token.getNumber());
+ EXPECT_EQ(MasterLexer::Token::NUMBER, token.getType());
+
+ // it's okay to replace it with a different type of token
+ token = token_eof;
+ EXPECT_EQ(MasterLexer::Token::END_OF_FILE, token.getType());
+
+ // Possible max value
+ token = MasterLexer::Token(0xffffffff);
+ EXPECT_EQ(4294967295u, token.getNumber());
+
+ // getNumber() isn't allowed for non number types
+ EXPECT_THROW(token_eof.getNumber(), isc::InvalidOperation);
+ EXPECT_THROW(token_str.getNumber(), isc::InvalidOperation);
+}
+
+TEST_F(MasterLexerTokenTest, novalues) {
+ // Just checking we can construct them and getType() returns correct value.
+ EXPECT_EQ(MasterLexer::Token::END_OF_FILE, token_eof.getType());
+ EXPECT_EQ(MasterLexer::Token::END_OF_LINE,
+ MasterLexer::Token(MasterLexer::Token::END_OF_LINE).getType());
+ EXPECT_EQ(MasterLexer::Token::INITIAL_WS,
+ MasterLexer::Token(MasterLexer::Token::INITIAL_WS).getType());
+
+ // Special types of tokens cannot have value-based types
+ EXPECT_THROW(MasterLexer::Token t(MasterLexer::Token::STRING),
+ isc::InvalidParameter);
+ EXPECT_THROW(MasterLexer::Token t(MasterLexer::Token::QSTRING),
+ isc::InvalidParameter);
+ EXPECT_THROW(MasterLexer::Token t(MasterLexer::Token::NUMBER),
+ isc::InvalidParameter);
+ EXPECT_THROW(MasterLexer::Token t(MasterLexer::Token::ERROR),
+ isc::InvalidParameter);
+}
+
+TEST_F(MasterLexerTokenTest, errors) {
+ EXPECT_EQ(MasterLexer::Token::ERROR, token_err.getType());
+ EXPECT_EQ(MasterLexer::Token::UNEXPECTED_END, token_err.getErrorCode());
+ EXPECT_EQ("unexpected end of input", token_err.getErrorText());
+ EXPECT_EQ("lexer not started",
+ MasterLexer::Token(MasterLexer::Token::NOT_STARTED).
+ getErrorText());
+ EXPECT_EQ("unbalanced parentheses",
+ MasterLexer::Token(MasterLexer::Token::UNBALANCED_PAREN).
+ getErrorText());
+ EXPECT_EQ("unbalanced quotes",
+ MasterLexer::Token(MasterLexer::Token::UNBALANCED_QUOTES).
+ getErrorText());
+
+ // getErrorCode/Text() isn't allowed for non number types
+ EXPECT_THROW(token_num.getErrorCode(), isc::InvalidOperation);
+ EXPECT_THROW(token_num.getErrorText(), isc::InvalidOperation);
+
+ // Only the pre-defined error code is accepted. Hardcoding '4' (max code
+ // + 1) is intentional; it'd be actually better if we notice it when we
+ // update the enum list (which shouldn't happen too often).
+ EXPECT_THROW(MasterLexer::Token(MasterLexer::Token::ErrorCode(4)),
+ isc::InvalidParameter);
+
+ // Check the coexistence of "from number" and "from error-code"
+ // constructors won't cause confusion.
+ EXPECT_EQ(MasterLexer::Token::NUMBER,
+ MasterLexer::Token(static_cast<uint32_t>(
+ MasterLexer::Token::NOT_STARTED)).
+ getType());
+}
+}
diff --git a/src/lib/dns/tests/rdata_unittest.h b/src/lib/dns/tests/rdata_unittest.h
index 1bc0fa4..f593609 100644
--- a/src/lib/dns/tests/rdata_unittest.h
+++ b/src/lib/dns/tests/rdata_unittest.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RDATA_UNITTEST_H
-#define __RDATA_UNITTEST_H 1
+#ifndef RDATA_UNITTEST_H
+#define RDATA_UNITTEST_H 1
#include <util/buffer.h>
#include <dns/messagerenderer.h>
@@ -44,7 +44,7 @@ protected:
}
}
}
-#endif // __RDATA_UNITTEST_H
+#endif // RDATA_UNITTEST_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/tests/rrparamregistry_unittest.cc b/src/lib/dns/tests/rrparamregistry_unittest.cc
index d2bec5c..c155b53 100644
--- a/src/lib/dns/tests/rrparamregistry_unittest.cc
+++ b/src/lib/dns/tests/rrparamregistry_unittest.cc
@@ -37,6 +37,7 @@ protected:
{
ostringstream oss1;
oss1 << test_class_code;
+ // cppcheck-suppress useInitializationList
test_class_unknown_str = "CLASS" + oss1.str();
ostringstream oss2;
@@ -60,7 +61,7 @@ protected:
// we assume class/type numbers are officially unassigned. If not we'll
// need to update the test cases.
- static const uint16_t test_class_code = 65533;
+ static const uint16_t test_class_code = 65533;
static const uint16_t test_type_code = 65534;
static const string test_class_str;
static const string test_type_str;
@@ -77,7 +78,7 @@ TEST_F(RRParamRegistryTest, addRemove) {
// the first removal attempt should succeed
EXPECT_TRUE(RRParamRegistry::getRegistry().removeType(test_type_code));
- // then toText() should treat it as an "unknown"
+ // then toText() should treat it as an "unknown"
EXPECT_EQ(test_type_unknown_str, RRType(test_type_code).toText());
// attempt of removing non-existent mapping should result in 'false'
EXPECT_FALSE(RRParamRegistry::getRegistry().removeType(test_type_code));
diff --git a/src/lib/dns/tests/rrset_unittest.cc b/src/lib/dns/tests/rrset_unittest.cc
index 5596bcb..725eea7 100644
--- a/src/lib/dns/tests/rrset_unittest.cc
+++ b/src/lib/dns/tests/rrset_unittest.cc
@@ -359,4 +359,12 @@ TEST_F(RRsetRRSIGTest, getRRsigDataCount) {
rrset_a->removeRRsig();
EXPECT_EQ(0, rrset_a->getRRsigDataCount());
}
+
+TEST_F(RRsetRRSIGTest, toText) {
+ // toText() should also return the associated RRSIG.
+ EXPECT_EQ("test.example.com. 3600 IN AAAA 2001:db8::1234\n"
+ "test.example.com. 3600 IN RRSIG AAAA 5 3 7200 "
+ "20100322084538 20100220084538 1 example.com. FAKEFAKEFAKEFAKE\n",
+ rrset_aaaa->toText());
+}
}
diff --git a/src/lib/dns/tests/rrsetlist_unittest.cc b/src/lib/dns/tests/rrsetlist_unittest.cc
deleted file mode 100644
index 080f888..0000000
--- a/src/lib/dns/tests/rrsetlist_unittest.cc
+++ /dev/null
@@ -1,188 +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 <vector>
-#include <boost/foreach.hpp>
-
-#include <dns/rdata.h>
-#include <dns/rdataclass.h>
-#include <dns/rrclass.h>
-#include <dns/rrtype.h>
-#include <dns/rrsetlist.h>
-#include <dns/rrset.h>
-#include <dns/rrttl.h>
-
-#include <gtest/gtest.h>
-
-using namespace std;
-using namespace isc::dns;
-using namespace isc::dns::rdata;
-
-namespace {
-class RRsetListTest : public ::testing::Test {
-protected:
- RRsetListTest() : example_name(Name("example.com")),
- example_ttl(RRTTL(3600))
- {}
- void setupList(RRsetList& list);
- Name example_name;
- RRTTL example_ttl;
-};
-
-const in::A rdata_in_a("192.0.2.1");
-const in::AAAA rdata_in_aaaa("2001:db8::1234");
-const generic::NS rdata_ns("ns.example.com");
-const generic::SOA rdata_soa(Name("ns.example.com"), Name("root.example.com"),
- 2010012601, 3600, 300, 3600000, 1200);
-const generic::CNAME rdata_cname("target.example.com");
-const generic::DNAME rdata_dname("dtarget.example.com");
-
-void
-RRsetListTest::setupList(RRsetList& list) {
- RRsetPtr a(new RRset(Name("example.com"), RRClass::IN(),
- RRType::A(), example_ttl));
- RRsetPtr aaaa(new RRset(Name("example.com"), RRClass::IN(),
- RRType::AAAA(), example_ttl));
- RRsetPtr ns(new RRset(Name("example.com"), RRClass::IN(),
- RRType::NS(), example_ttl));
- RRsetPtr soa(new RRset(Name("example.com"), RRClass::IN(),
- RRType::SOA(), example_ttl));
- RRsetPtr cname(new RRset(Name("example.com"), RRClass::IN(),
- RRType::CNAME(), example_ttl));
-
- a->addRdata(rdata_in_a);
- aaaa->addRdata(rdata_in_aaaa);
- ns->addRdata(rdata_ns);
- soa->addRdata(rdata_soa);
- cname->addRdata(rdata_cname);
-
- list.addRRset(a);
- list.addRRset(aaaa);
- list.addRRset(ns);
- list.addRRset(soa);
- list.addRRset(cname);
-}
-
-TEST_F(RRsetListTest, emptyOnInitialCreate) {
- RRsetList list;
- EXPECT_EQ(list.size(), 0);
-}
-
-TEST_F(RRsetListTest, addRRsets) {
- RRsetList list;
- setupList(list);
- EXPECT_EQ(list.size(), 5);
-}
-
-TEST_F(RRsetListTest, append) {
- RRsetList list1;
- setupList(list1);
- RRsetList list2;
- RRsetPtr dname(new RRset(Name("example.com"), RRClass::IN(),
- RRType::DNAME(), example_ttl));
- dname->addRdata(rdata_dname);
- list2.addRRset(dname);
- list1.append(list2);
- EXPECT_EQ(list2.size(), 1);
- EXPECT_EQ(list1.size(), 6);
-
- RRsetPtr rrset = list1.findRRset(RRType::DNAME(), RRClass::IN());
- EXPECT_EQ(RRType::DNAME(), rrset->getType());
-
- EXPECT_THROW(list1.append(list2), DuplicateRRset);
-}
-
-TEST_F(RRsetListTest, extraRRset) {
- RRsetList list;
- setupList(list);
- RRsetPtr cname(new RRset(Name("another.example.com"), RRClass::IN(),
- RRType::CNAME(), example_ttl));
- EXPECT_THROW(list.addRRset(cname), DuplicateRRset);
-}
-
-void
-checkFindResult(RRsetList& list, const Name& name,
- const RRType& rrtype, const RRClass& rrclass,
- const RRTTL& rrttl)
-{
- RRsetPtr rrset = list.findRRset(rrtype, rrclass);;
- EXPECT_EQ(name, rrset->getName());
- EXPECT_EQ(rrtype, rrset->getType());
- EXPECT_EQ(rrclass, rrset->getClass());
- EXPECT_EQ(rrttl, rrset->getTTL());
-}
-
-TEST_F(RRsetListTest, findRRset) {
- RRsetList list;
- setupList(list);
-
- checkFindResult(list, example_name, RRType::A(), RRClass::IN(),
- example_ttl);
- checkFindResult(list, example_name, RRType::CNAME(), RRClass::IN(),
- example_ttl);
- checkFindResult(list, example_name, RRType::AAAA(), RRClass::IN(),
- example_ttl);
- checkFindResult(list, example_name, RRType::NS(), RRClass::IN(),
- example_ttl);
- checkFindResult(list, example_name, RRType::SOA(), RRClass::IN(),
- example_ttl);
-}
-
-TEST_F(RRsetListTest, checkData) {
- RRsetList list;
- RRsetPtr a(new RRset(Name("example.com"), RRClass::IN(),
- RRType::A(), example_ttl));
- a->addRdata(rdata_in_a);
- list.addRRset(a);
-
- RdataIteratorPtr it =
- list.findRRset(RRType::A(), RRClass::IN())->getRdataIterator();
- EXPECT_FALSE(it->isLast());
- EXPECT_EQ("192.0.2.1", it->getCurrent().toText());
-}
-
-TEST_F(RRsetListTest, iterate) {
- RRsetList list;
- setupList(list);
-
- bool has_a = false, has_aaaa = false, has_ns = false, has_soa = false,
- has_cname = false;
- int i = 0;
- BOOST_FOREACH(RRsetPtr rrset, list) {
- if (rrset->getType() == RRType::A()) {
- has_a = true;
- }
- if (rrset->getType() == RRType::AAAA()) {
- has_aaaa = true;
- }
- if (rrset->getType() == RRType::NS()) {
- has_ns = true;
- }
- if (rrset->getType() == RRType::SOA()) {
- has_soa = true;
- }
- if (rrset->getType() == RRType::CNAME()) {
- has_cname = true;
- }
- ++i;
- }
- EXPECT_TRUE(has_a);
- EXPECT_TRUE(has_aaaa);
- EXPECT_TRUE(has_ns);
- EXPECT_TRUE(has_soa);
- EXPECT_TRUE(has_cname);
- EXPECT_TRUE(i == 5);
-}
-
-}
diff --git a/src/lib/dns/tests/unittest_util.h b/src/lib/dns/tests/unittest_util.h
index ebb514d..f50df14 100644
--- a/src/lib/dns/tests/unittest_util.h
+++ b/src/lib/dns/tests/unittest_util.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UNITTEST_UTIL_H
-#define __UNITTEST_UTIL_H 1
+#ifndef UNITTEST_UTIL_H
+#define UNITTEST_UTIL_H 1
#include <vector>
#include <string>
@@ -111,7 +111,7 @@ public:
};
}
-#endif // __UNITTEST_UTIL_H
+#endif // UNITTEST_UTIL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/tsig.h b/src/lib/dns/tsig.h
index 9ccc580..a7ec011 100644
--- a/src/lib/dns/tsig.h
+++ b/src/lib/dns/tsig.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TSIG_H
-#define __TSIG_H 1
+#ifndef TSIG_H
+#define TSIG_H 1
#include <boost/noncopyable.hpp>
@@ -433,7 +433,7 @@ private:
}
}
-#endif // __TSIG_H
+#endif // TSIG_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/tsigerror.h b/src/lib/dns/tsigerror.h
index 8efd3ae..5b8056d 100644
--- a/src/lib/dns/tsigerror.h
+++ b/src/lib/dns/tsigerror.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TSIGERROR_H
-#define __TSIGERROR_H 1
+#ifndef TSIGERROR_H
+#define TSIGERROR_H 1
#include <ostream>
#include <string>
@@ -331,7 +331,7 @@ std::ostream& operator<<(std::ostream& os, const TSIGError& tsig_error);
}
}
-#endif // __TSIGERROR_H
+#endif // TSIGERROR_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/tsigkey.h b/src/lib/dns/tsigkey.h
index 6081dd3..1bbd3fe 100644
--- a/src/lib/dns/tsigkey.h
+++ b/src/lib/dns/tsigkey.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TSIGKEY_H
-#define __TSIGKEY_H 1
+#ifndef TSIGKEY_H
+#define TSIGKEY_H 1
#include <cryptolink/cryptolink.h>
@@ -353,7 +353,7 @@ private:
}
}
-#endif // __TSIGKEY_H
+#endif // TSIGKEY_H
// Local Variables:
// mode: c++
diff --git a/src/lib/dns/tsigrecord.h b/src/lib/dns/tsigrecord.h
index 03de746..b5e8de3 100644
--- a/src/lib/dns/tsigrecord.h
+++ b/src/lib/dns/tsigrecord.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TSIGRECORD_H
-#define __TSIGRECORD_H 1
+#ifndef TSIGRECORD_H
+#define TSIGRECORD_H 1
#include <ostream>
#include <string>
@@ -301,7 +301,7 @@ std::ostream& operator<<(std::ostream& os, const TSIGRecord& record);
}
}
-#endif // __TSIGRECORD_H
+#endif // TSIGRECORD_H
// Local Variables:
// mode: c++
diff --git a/src/lib/exceptions/exceptions.h b/src/lib/exceptions/exceptions.h
index 010fd39..d7e270d 100644
--- a/src/lib/exceptions/exceptions.h
+++ b/src/lib/exceptions/exceptions.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __EXCEPTIONS_H
-#define __EXCEPTIONS_H 1
+#ifndef EXCEPTIONS_H
+#define EXCEPTIONS_H 1
#include <stdexcept>
#include <string>
@@ -230,7 +230,7 @@ public:
} while (1)
}
-#endif // __EXCEPTIONS_H
+#endif // EXCEPTIONS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/log/compiler/message.cc b/src/lib/log/compiler/message.cc
index 86c5f20..7bff8bd 100644
--- a/src/lib/log/compiler/message.cc
+++ b/src/lib/log/compiler/message.cc
@@ -109,18 +109,20 @@ currentTime() {
// Get a text representation of the current time.
time_t curtime;
time(&curtime);
- char* buffer = ctime(&curtime);
+ struct tm* timeinfo;
+ timeinfo = localtime(&curtime);
- // Convert to string and strip out the trailing newline
- string current_time = buffer;
- return (isc::util::str::trim(current_time));
+ char buffer[80];
+ strftime(buffer, 80, "%a %b %d %Y %H:%M", timeinfo);
+
+ return (std::string(buffer));
}
/// \brief Create Header Sentinel
///
/// Given the name of a file, create an \#ifdef sentinel name. The name is
-/// __<name>_<ext>, where <name> is the name of the file, and <ext>
+/// <name>_<ext>, where <name> is the name of the file, and <ext>
/// is the extension less the leading period. The sentinel will be upper-case.
///
/// \param file Filename object representing the file.
@@ -132,7 +134,7 @@ sentinel(Filename& file) {
string name = file.name();
string ext = file.extension();
- string sentinel_text = "__" + name + "_" + ext.substr(1);
+ string sentinel_text = name + "_" + ext.substr(1);
isc::util::str::uppercase(sentinel_text);
return (sentinel_text);
}
diff --git a/src/lib/log/dummylog.h b/src/lib/log/dummylog.h
index ef5af13..6f6ae97 100644
--- a/src/lib/log/dummylog.h
+++ b/src/lib/log/dummylog.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_DUMMYLOG_H
-#define _ISC_DUMMYLOG_H 1
+#ifndef ISC_DUMMYLOG_H
+#define ISC_DUMMYLOG_H 1
#include <string>
@@ -58,4 +58,4 @@ void dlog(const std::string& message, bool error_flag=false);
}
}
-#endif // _ISC_DUMMYLOG_H
+#endif // ISC_DUMMYLOG_H
diff --git a/src/lib/log/log_dbglevels.h b/src/lib/log/log_dbglevels.h
index d713714..a459bed 100644
--- a/src/lib/log/log_dbglevels.h
+++ b/src/lib/log/log_dbglevels.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOG_DBGLVLS_H
-#define __LOG_DBGLVLS_H
+#ifndef LOG_DBGLVLS_H
+#define LOG_DBGLVLS_H
/// \file
///
@@ -90,4 +90,4 @@ const int DBGLVL_TRACE_DETAIL_DATA = 55;
} // Anonymous namespace
-#endif // __LOG_DBGLVLS_H
+#endif // LOG_DBGLVLS_H
diff --git a/src/lib/log/log_formatter.h b/src/lib/log/log_formatter.h
index eebdb1a..8cb34c7 100644
--- a/src/lib/log/log_formatter.h
+++ b/src/lib/log/log_formatter.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOG_FORMATTER_H
-#define __LOG_FORMMATER_H
+#ifndef LOG_FORMATTER_H
+#define LOG_FORMATTER_H
#include <cstddef>
#include <string>
diff --git a/src/lib/log/log_messages.h b/src/lib/log/log_messages.h
index 10e1501..2b70553 100644
--- a/src/lib/log/log_messages.h
+++ b/src/lib/log/log_messages.h
@@ -1,7 +1,7 @@
// File created from log_messages.mes on Thu Jul 7 15:32:06 2011
-#ifndef __LOG_MESSAGES_H
-#define __LOG_MESSAGES_H
+#ifndef LOG_MESSAGES_H
+#define LOG_MESSAGES_H
#include <log/message_types.h>
@@ -32,4 +32,4 @@ extern const isc::log::MessageID LOG_WRITE_ERROR;
} // namespace log
} // namespace isc
-#endif // __LOG_MESSAGES_H
+#endif // LOG_MESSAGES_H
diff --git a/src/lib/log/logger.h b/src/lib/log/logger.h
index 6405488..e3ba163 100644
--- a/src/lib/log/logger.h
+++ b/src/lib/log/logger.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_H
-#define __LOGGER_H
+#ifndef LOGGER_H
+#define LOGGER_H
#include <cassert>
#include <cstdlib>
@@ -33,9 +33,9 @@ namespace log {
/// \page LoggingApi Logging API
/// \section LoggingApiOverview Overview
/// BIND 10 logging uses the concepts of the widely-used Java logging
-/// package log4j (http://logging.apache.log/log4j), albeit implemented
+/// package log4j (http://logging.apache.log/log4j), albeit implemented
/// in C++ using an open-source port. Features of the system are:
-///
+///
/// - Within the code objects - known as loggers - can be created and
/// used to log messages. These loggers have names; those with the
/// same name share characteristics (such as output destination).
@@ -50,7 +50,7 @@ namespace log {
/// message is logged, it is output only if it is logged at a level equal
/// to the logger severity level or greater, e.g. if the logger's severity
/// is WARN, only messages logged at WARN, ERROR or FATAL will be output.
-///
+///
/// \section LoggingApiLoggerNames BIND 10 Logger Names
/// Within BIND 10, the root logger root logger is given the name of the
/// program (via the stand-alone function setRootLoggerName()). Other loggers
@@ -58,7 +58,7 @@ namespace log {
/// This name appears in logging output, allowing users to identify both
/// the BIND 10 program and the component within the program that generated
/// the message.
-///
+///
/// When creating a logger, the abbreviated name "<sublogger>" can be used;
/// the program name will be prepended to it when the logger is created.
/// In this way, individual libraries can have their own loggers without
@@ -66,7 +66,7 @@ namespace log {
/// - The origin of the message will be clearly identified.
/// - The same component can have different options (e.g. logging severity)
/// in different programs at the same time.
-///
+///
/// \section LoggingApiLoggingMessages Logging Messages
/// Instead of embedding the text of messages within the code, each message
/// is referred to using a symbolic name. The logging code uses this name as
@@ -320,4 +320,4 @@ private:
} // namespace isc
-#endif // __LOGGER_H
+#endif // LOGGER_H
diff --git a/src/lib/log/logger_impl.h b/src/lib/log/logger_impl.h
index 10d3db4..7280d5c 100644
--- a/src/lib/log/logger_impl.h
+++ b/src/lib/log/logger_impl.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_IMPL_H
-#define __LOGGER_IMPL_H
+#ifndef LOGGER_IMPL_H
+#define LOGGER_IMPL_H
#include <stdarg.h>
#include <time.h>
@@ -200,4 +200,4 @@ private:
} // namespace isc
-#endif // __LOGGER_IMPL_H
+#endif // LOGGER_IMPL_H
diff --git a/src/lib/log/logger_level.h b/src/lib/log/logger_level.h
index ea60c3c..ac4a61a 100644
--- a/src/lib/log/logger_level.h
+++ b/src/lib/log/logger_level.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_LEVEL_H
-#define __LOGGER_LEVEL_H
+#ifndef LOGGER_LEVEL_H
+#define LOGGER_LEVEL_H
#include <string>
@@ -73,4 +73,4 @@ isc::log::Severity getSeverity(const std::string& sev_str);
} // namespace log
} // namespace isc
-#endif // __LOGGER_LEVEL_H
+#endif // LOGGER_LEVEL_H
diff --git a/src/lib/log/logger_level_impl.h b/src/lib/log/logger_level_impl.h
index 17b866d..4e18e46 100644
--- a/src/lib/log/logger_level_impl.h
+++ b/src/lib/log/logger_level_impl.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_LEVEL_IMPL_H
-#define __LOGGER_LEVEL_IMPL_H
+#ifndef LOGGER_LEVEL_IMPL_H
+#define LOGGER_LEVEL_IMPL_H
#include <log4cplus/logger.h>
#include <log4cplus/version.h>
@@ -131,4 +131,4 @@ public:
} // namespace log
} // namespace isc
-#endif // __LOGGER_LEVEL_IMPL_H
+#endif // LOGGER_LEVEL_IMPL_H
diff --git a/src/lib/log/logger_manager.h b/src/lib/log/logger_manager.h
index dece0c9..63699c9 100644
--- a/src/lib/log/logger_manager.h
+++ b/src/lib/log/logger_manager.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_MANAGER_H
-#define __LOGGER_MANAGER_H
+#ifndef LOGGER_MANAGER_H
+#define LOGGER_MANAGER_H
#include "exceptions/exceptions.h"
#include <log/logger_specification.h>
@@ -138,4 +138,4 @@ private:
} // namespace isc
-#endif // __LOGGER_MANAGER_H
+#endif // LOGGER_MANAGER_H
diff --git a/src/lib/log/logger_manager_impl.h b/src/lib/log/logger_manager_impl.h
index 42a98f1..2bce655 100644
--- a/src/lib/log/logger_manager_impl.h
+++ b/src/lib/log/logger_manager_impl.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_MANAGER_IMPL_H
-#define __LOGGER_MANAGER_IMPL_H
+#ifndef LOGGER_MANAGER_IMPL_H
+#define LOGGER_MANAGER_IMPL_H
#include <string>
@@ -166,4 +166,4 @@ private:
} // namespace log
} // namespace isc
-#endif // __LOGGER_MANAGER_IMPL_H
+#endif // LOGGER_MANAGER_IMPL_H
diff --git a/src/lib/log/logger_name.h b/src/lib/log/logger_name.h
index 82ea2ad..b9ebd1b 100644
--- a/src/lib/log/logger_name.h
+++ b/src/lib/log/logger_name.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_NAME_H
-#define __LOGGER_NAME_H
+#ifndef LOGGER_NAME_H
+#define LOGGER_NAME_H
#include <string>
@@ -54,4 +54,4 @@ std::string expandLoggerName(const std::string& name);
}
}
-#endif // __LOGGER_NAME_H
+#endif // LOGGER_NAME_H
diff --git a/src/lib/log/logger_specification.h b/src/lib/log/logger_specification.h
index 78df054..663b0df 100644
--- a/src/lib/log/logger_specification.h
+++ b/src/lib/log/logger_specification.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_SPECIFICATION_H
-#define __LOGGER_SPECIFICATION_H
+#ifndef LOGGER_SPECIFICATION_H
+#define LOGGER_SPECIFICATION_H
#include <stdint.h>
#include <stdlib.h>
@@ -146,11 +146,11 @@ private:
std::string name_; ///< Logger name
isc::log::Severity severity_; ///< Severity for this logger
int dbglevel_; ///< Debug level
- bool additive_; ///< Chaining output
+ bool additive_; ///< Chaining output
std::vector<OutputOption> options_; ///< Logger options
};
} // namespace log
} // namespace isc
-#endif // __LOGGER_SPEC_IFICATIONH
+#endif // LOGGER_SPECIFICATION_H
diff --git a/src/lib/log/logger_support.h b/src/lib/log/logger_support.h
index 4ce3ced..f59be60 100644
--- a/src/lib/log/logger_support.h
+++ b/src/lib/log/logger_support.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_SUPPORT_H
-#define __LOGGER_SUPPORT_H
+#ifndef LOGGER_SUPPORT_H
+#define LOGGER_SUPPORT_H
#include <unistd.h>
@@ -68,4 +68,4 @@ void initLogger(const std::string& root,
} // namespace log
} // namespace isc
-#endif // __LOGGER_SUPPORT_H
+#endif // LOGGER_SUPPORT_H
diff --git a/src/lib/log/logger_unittest_support.h b/src/lib/log/logger_unittest_support.h
index ce9121b..70f34e8 100644
--- a/src/lib/log/logger_unittest_support.h
+++ b/src/lib/log/logger_unittest_support.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOGGER_UNITTEST_SUPPORT_H
-#define __LOGGER_UNITTEST_SUPPORT_H
+#ifndef LOGGER_UNITTEST_SUPPORT_H
+#define LOGGER_UNITTEST_SUPPORT_H
#include <string>
#include <log/logger.h>
@@ -123,4 +123,4 @@ resetUnitTestRootLogger();
-#endif // __LOGGER_UNITTEST_SUPPORT_H
+#endif // LOGGER_UNITTEST_SUPPORT_H
diff --git a/src/lib/log/logimpl_messages.h b/src/lib/log/logimpl_messages.h
index 1b94838..71a50d6 100644
--- a/src/lib/log/logimpl_messages.h
+++ b/src/lib/log/logimpl_messages.h
@@ -1,7 +1,7 @@
// File created from logimpl_messages.mes on Wed Jun 22 10:57:02 2011
-#ifndef __LOGIMPL_MESSAGES_H
-#define __LOGIMPL_MESSAGES_H
+#ifndef LOGIMPL_MESSAGES_H
+#define LOGIMPL_MESSAGES_H
#include <log/message_types.h>
@@ -15,4 +15,4 @@ extern const isc::log::MessageID LOGIMPL_BELOW_MIN_DEBUG;
} // namespace log
} // namespace isc
-#endif // __LOGIMPL_MESSAGES_H
+#endif // LOGIMPL_MESSAGES_H
diff --git a/src/lib/log/macros.h b/src/lib/log/macros.h
index 42fb42e..f602555 100644
--- a/src/lib/log/macros.h
+++ b/src/lib/log/macros.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOG_MACROS_H
-#define __LOG_MACROS_H
+#ifndef LOG_MACROS_H
+#define LOG_MACROS_H
#include <log/logger.h>
#include <log/log_dbglevels.h>
diff --git a/src/lib/log/message_dictionary.h b/src/lib/log/message_dictionary.h
index 519986d..3d622cd 100644
--- a/src/lib/log/message_dictionary.h
+++ b/src/lib/log/message_dictionary.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_DICTIONARY_H
-#define __MESSAGE_DICTIONARY_H
+#ifndef MESSAGE_DICTIONARY_H
+#define MESSAGE_DICTIONARY_H
#include <cstddef>
#include <string>
@@ -187,4 +187,4 @@ private:
} // namespace log
} // namespace isc
-#endif // __MESSAGE_DICTIONARY_H
+#endif // MESSAGE_DICTIONARY_H
diff --git a/src/lib/log/message_exception.h b/src/lib/log/message_exception.h
index 8b9d58a..5f1ad12 100644
--- a/src/lib/log/message_exception.h
+++ b/src/lib/log/message_exception.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_EXCEPTION_H
-#define __MESSAGE_EXCEPTION_H
+#ifndef MESSAGE_EXCEPTION_H
+#define MESSAGE_EXCEPTION_H
#include <exceptions/exceptions.h>
#include <log/message_types.h>
@@ -117,4 +117,4 @@ private:
} // namespace log
} // namespace isc
-#endif // __MESSAGE_EXCEPTION_H
+#endif // MESSAGE_EXCEPTION_H
diff --git a/src/lib/log/message_initializer.h b/src/lib/log/message_initializer.h
index 28b0e61..3be973d 100644
--- a/src/lib/log/message_initializer.h
+++ b/src/lib/log/message_initializer.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGEINITIALIZER_H
-#define __MESSAGEINITIALIZER_H
+#ifndef MESSAGEINITIALIZER_H
+#define MESSAGEINITIALIZER_H
#include <cstdlib>
#include <string>
@@ -108,4 +108,4 @@ public:
} // namespace log
} // namespace isc
-#endif // __MESSAGEINITIALIZER_H
+#endif // MESSAGEINITIALIZER_H
diff --git a/src/lib/log/message_reader.h b/src/lib/log/message_reader.h
index a468d43..62d50b9 100644
--- a/src/lib/log/message_reader.h
+++ b/src/lib/log/message_reader.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_READER_H
-#define __MESSAGE_READER_H
+#ifndef MESSAGE_READER_H
+#define MESSAGE_READER_H
#include <map>
#include <string>
@@ -212,4 +212,4 @@ private:
} // namespace log
} // namespace isc
-#endif // __MESSAGE_READER_H
+#endif // MESSAGE_READER_H
diff --git a/src/lib/log/message_types.h b/src/lib/log/message_types.h
index 9f625a9..7966f98 100644
--- a/src/lib/log/message_types.h
+++ b/src/lib/log/message_types.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MESSAGE_TYPES_H
-#define __MESSAGE_TYPES_H
+#ifndef MESSAGE_TYPES_H
+#define MESSAGE_TYPES_H
#include <string.h>
@@ -34,4 +34,4 @@ bool equalMessageID(const MessageID& m1, const MessageID& m2);
-#endif // __MESSAGE_TYPES_H
+#endif // MESSAGE_TYPES_H
diff --git a/src/lib/log/output_option.h b/src/lib/log/output_option.h
index 8dfdd70..8dcb28d 100644
--- a/src/lib/log/output_option.h
+++ b/src/lib/log/output_option.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __OUTPUT_OPTION_H
-#define __OUTPUT_OPTION_H
+#ifndef OUTPUT_OPTION_H
+#define OUTPUT_OPTION_H
#include <stdint.h>
#include <stdlib.h>
@@ -82,4 +82,4 @@ OutputOption::Stream getStream(const std::string& stream_str);
} // namespace log
} // namespace isc
-#endif // __OUTPUT_OPTION_H
+#endif // OUTPUT_OPTION_H
diff --git a/src/lib/log/tests/log_formatter_unittest.cc b/src/lib/log/tests/log_formatter_unittest.cc
index 435b200..f0a9a59 100644
--- a/src/lib/log/tests/log_formatter_unittest.cc
+++ b/src/lib/log/tests/log_formatter_unittest.cc
@@ -16,6 +16,7 @@
#include <gtest/gtest.h>
#include <util/unittests/resource.h>
+#include <util/unittests/check_valgrind.h>
#include <log/log_formatter.h>
#include <log/logger_level.h>
@@ -119,12 +120,13 @@ TEST_F(FormatterTest, mismatchedPlaceholders) {
// Likewise, if there's a redundant placeholder (or missing argument), the
// check detects it and aborts the program. Due to the restriction of the
// current implementation, it doesn't throw.
- EXPECT_DEATH({
- isc::util::unittests::dontCreateCoreDumps();
- Formatter(isc::log::INFO, s("Too many arguments in %1 %2"), this).
- arg("only one");
- }, ".*");
-
+ if (!isc::util::unittests::runningOnValgrind()) {
+ EXPECT_DEATH({
+ isc::util::unittests::dontCreateCoreDumps();
+ Formatter(isc::log::INFO, s("Too many arguments in %1 %2"), this).
+ arg("only one");
+ }, ".*");
+ }
#endif /* EXPECT_DEATH */
// Mixed case of above two: the exception will be thrown due to the missing
// placeholder. The other check is disabled due to that.
diff --git a/src/lib/log/tests/logger_example.cc b/src/lib/log/tests/logger_example.cc
index 6f95e5d..08c9084 100644
--- a/src/lib/log/tests/logger_example.cc
+++ b/src/lib/log/tests/logger_example.cc
@@ -118,7 +118,6 @@ int main(int argc, char** argv) {
LoggerSpecification cur_spec(ROOT_NAME);// Current specification
OutputOption cur_opt; // Current output option
vector<LoggerSpecification> loggers; // Set of logger specifications
- vector<OutputOption> options; // Output options for logger
std::string severity; // Severity set for logger
// Initialize logging system - set the root logger name.
diff --git a/src/lib/log/tests/logger_unittest.cc b/src/lib/log/tests/logger_unittest.cc
index a9330a9..7b62d79 100644
--- a/src/lib/log/tests/logger_unittest.cc
+++ b/src/lib/log/tests/logger_unittest.cc
@@ -11,13 +11,10 @@
// 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 <iostream>
-#include <string>
-
#include <gtest/gtest.h>
#include <util/unittests/resource.h>
+#include <util/unittests/check_valgrind.h>
#include <log/logger.h>
#include <log/logger_manager.h>
@@ -27,6 +24,9 @@
#include <util/interprocess_sync_file.h>
+#include <iostream>
+#include <string>
+
using namespace isc;
using namespace isc::log;
using namespace std;
@@ -356,7 +356,6 @@ TEST_F(LoggerTest, IsDebugEnabledLevel) {
// Check that if a logger name is too long, it triggers the appropriate
// assertion.
-
TEST_F(LoggerTest, LoggerNameLength) {
// The following statements should just declare a logger and nothing
// should happen.
@@ -374,12 +373,14 @@ TEST_F(LoggerTest, LoggerNameLength) {
// Too long a logger name should trigger an assertion failure.
// Note that we just check that it dies - we don't check what message is
// output.
- EXPECT_DEATH({
- isc::util::unittests::dontCreateCoreDumps();
+ if (!isc::util::unittests::runningOnValgrind()) {
+ EXPECT_DEATH({
+ isc::util::unittests::dontCreateCoreDumps();
- string ok3(Logger::MAX_LOGGER_NAME_SIZE + 1, 'x');
- Logger l3(ok3.c_str());
- }, ".*");
+ string ok3(Logger::MAX_LOGGER_NAME_SIZE + 1, 'x');
+ Logger l3(ok3.c_str());
+ }, ".*");
+ }
#endif
}
diff --git a/src/lib/log/tests/message_initializer_2_unittest.cc b/src/lib/log/tests/message_initializer_2_unittest.cc
index b479eee..8cc78fa 100644
--- a/src/lib/log/tests/message_initializer_2_unittest.cc
+++ b/src/lib/log/tests/message_initializer_2_unittest.cc
@@ -16,6 +16,7 @@
#include <gtest/gtest.h>
#include <util/unittests/resource.h>
+#include <util/unittests/check_valgrind.h>
using namespace isc::log;
@@ -43,10 +44,12 @@ TEST(MessageInitializerTest2, MessageLoadTest) {
// test for its presence and bypass the test if not available.
#ifdef EXPECT_DEATH
// Adding one more should take us over the limit.
- EXPECT_DEATH({
- isc::util::unittests::dontCreateCoreDumps();
+ if (!isc::util::unittests::runningOnValgrind()) {
+ EXPECT_DEATH({
+ isc::util::unittests::dontCreateCoreDumps();
- MessageInitializer initializer2(values);
- }, ".*");
+ MessageInitializer initializer2(values);
+ }, ".*");
+ }
#endif
}
diff --git a/src/lib/log/tests/tempdir.h.in b/src/lib/log/tests/tempdir.h.in
index 366fea3..96ce8d4 100644
--- a/src/lib/log/tests/tempdir.h.in
+++ b/src/lib/log/tests/tempdir.h.in
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TEMPDIR_H
-#define __TEMPDIR_H
+#ifndef TEMPDIR_H
+#define TEMPDIR_H
/// \brief Define temporary directory
///
@@ -26,4 +26,4 @@ namespace {
std::string TEMP_DIR("@builddir@");
}
-#endif // __TEMPDIR_H
+#endif // TEMPDIR_H
diff --git a/src/lib/nsas/address_entry.h b/src/lib/nsas/address_entry.h
index 8698017..0c165ea 100644
--- a/src/lib/nsas/address_entry.h
+++ b/src/lib/nsas/address_entry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ADDRESS_ENTRY_H
-#define __ADDRESS_ENTRY_H
+#ifndef ADDRESS_ENTRY_H
+#define ADDRESS_ENTRY_H
/// \brief Address Entry
///
@@ -99,4 +99,4 @@ private:
} // namespace isc
-#endif // __ADDRESS_ENTRY_H
+#endif // ADDRESS_ENTRY_H
diff --git a/src/lib/nsas/address_request_callback.h b/src/lib/nsas/address_request_callback.h
index ad0630e..457c587 100644
--- a/src/lib/nsas/address_request_callback.h
+++ b/src/lib/nsas/address_request_callback.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ADDRESS_REQUEST_CALLBACK_H
-#define __ADDRESS_REQUEST_CALLBACK_H
+#ifndef ADDRESS_REQUEST_CALLBACK_H
+#define ADDRESS_REQUEST_CALLBACK_H
#include "asiolink.h"
#include "nameserver_address.h"
@@ -69,4 +69,4 @@ public:
} // namespace nsas
} // namespace isc
-#endif // __ADDRESS_REQUEST_CALLBACK_H
+#endif // ADDRESS_REQUEST_CALLBACK_H
diff --git a/src/lib/nsas/asiolink.h b/src/lib/nsas/asiolink.h
index d95868f..b236a0e 100644
--- a/src/lib/nsas/asiolink.h
+++ b/src/lib/nsas/asiolink.h
@@ -12,10 +12,10 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ASIOLINK_H
-#define __ASIOLINK_H
+#ifndef ASIOLINK_H
+#define ASIOLINK_H
#include <string>
#include <sys/socket.h>
-#endif // __ASIOLINK_H
+#endif // ASIOLINK_H
diff --git a/src/lib/nsas/fetchable.h b/src/lib/nsas/fetchable.h
index 461cfca..7e8ce5c 100644
--- a/src/lib/nsas/fetchable.h
+++ b/src/lib/nsas/fetchable.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __FETCHABLE_H
-#define __FETCHABLE_H
+#ifndef FETCHABLE_H
+#define FETCHABLE_H
/**
* \file fetchable.h
@@ -63,4 +63,4 @@ class Fetchable {
} // namespace nsas
} // namespace isc
-#endif // __FETCHABLE_H
+#endif // FETCHABLE_H
diff --git a/src/lib/nsas/glue_hints.h b/src/lib/nsas/glue_hints.h
index 8e6ecf1..ccac382 100644
--- a/src/lib/nsas/glue_hints.h
+++ b/src/lib/nsas/glue_hints.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __GLUE_HINTS_H
-#define __GLUE_HINTS_H
+#ifndef GLUE_HINTS_H
+#define GLUE_HINTS_H
#include <vector>
@@ -68,4 +68,4 @@ private:
}
-#endif // __GLUE_HINTS_H
+#endif // GLUE_HINTS_H
diff --git a/src/lib/nsas/hash.h b/src/lib/nsas/hash.h
index 85b82c3..cc03b3f 100644
--- a/src/lib/nsas/hash.h
+++ b/src/lib/nsas/hash.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __HASH_H
-#define __HASH_H
+#ifndef HASH_H
+#define HASH_H
#include <stdint.h>
#include <vector>
@@ -122,4 +122,4 @@ private:
} // namspace nsas
} // namespace isc
-#endif // __HASH_H
+#endif // HASH_H
diff --git a/src/lib/nsas/hash_deleter.h b/src/lib/nsas/hash_deleter.h
index 27f066e..6fcd3da 100644
--- a/src/lib/nsas/hash_deleter.h
+++ b/src/lib/nsas/hash_deleter.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __HASH_DELETER_H
-#define __HASH_DELETER_H
+#ifndef HASH_DELETER_H
+#define HASH_DELETER_H
#include <boost/shared_ptr.hpp>
#include <util/lru_list.h>
@@ -72,4 +72,4 @@ void HashDeleter<T>::operator()(T* element) const {
} // namespace nsas
} // namespace isc
-#endif // __HASH_DELETER_H
+#endif // HASH_DELETER_H
diff --git a/src/lib/nsas/hash_key.h b/src/lib/nsas/hash_key.h
index c89b327..5f60735 100644
--- a/src/lib/nsas/hash_key.h
+++ b/src/lib/nsas/hash_key.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __HASH_KEY_H
-#define __HASH_KEY_H
+#ifndef HASH_KEY_H
+#define HASH_KEY_H
#include <dns/rrclass.h>
@@ -93,4 +93,4 @@ struct HashKey {
} // namespace nsas
} // namespace isc
-#endif // __HASH_KEY_H
+#endif // HASH_KEY_H
diff --git a/src/lib/nsas/hash_table.h b/src/lib/nsas/hash_table.h
index 6028473..13cafc7 100644
--- a/src/lib/nsas/hash_table.h
+++ b/src/lib/nsas/hash_table.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __HASH_TABLE_H
-#define __HASH_TABLE_H
+#ifndef HASH_TABLE_H
+#define HASH_TABLE_H
#include <list>
@@ -334,4 +334,4 @@ bool HashTable<T>::addInternal(boost::shared_ptr<T>& object,
} // namespace nsas
} // namespace isc
-#endif // __HASH_TABLE_H
+#endif // HASH_TABLE_H
diff --git a/src/lib/nsas/nameserver_address.h b/src/lib/nsas/nameserver_address.h
index 07b6d4a..5f5c7c9 100644
--- a/src/lib/nsas/nameserver_address.h
+++ b/src/lib/nsas/nameserver_address.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NAMESERVER_ADDRESS_H
-#define __NAMESERVER_ADDRESS_H
+#ifndef NAMESERVER_ADDRESS_H
+#define NAMESERVER_ADDRESS_H
#include <boost/shared_ptr.hpp>
@@ -114,4 +114,4 @@ private:
} // namespace nsas
} // namespace isc
-#endif//__NAMESERVER_ADDRESS_H
+#endif//NAMESERVER_ADDRESS_H
diff --git a/src/lib/nsas/nameserver_address_store.h b/src/lib/nsas/nameserver_address_store.h
index 1af535a..b107b3b 100644
--- a/src/lib/nsas/nameserver_address_store.h
+++ b/src/lib/nsas/nameserver_address_store.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NAMESERVER_ADDRESS_STORE_H
-#define __NAMESERVER_ADDRESS_STORE_H
+#ifndef NAMESERVER_ADDRESS_STORE_H
+#define NAMESERVER_ADDRESS_STORE_H
#include <string>
#include <vector>
@@ -129,4 +129,4 @@ private:
} // namespace isc
-#endif // __NAMESERVER_ADDRESS_STORE_H
+#endif // NAMESERVER_ADDRESS_STORE_H
diff --git a/src/lib/nsas/nameserver_entry.h b/src/lib/nsas/nameserver_entry.h
index 0f214c6..77a640d 100644
--- a/src/lib/nsas/nameserver_entry.h
+++ b/src/lib/nsas/nameserver_entry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NAMESERVER_ENTRY_H
-#define __NAMESERVER_ENTRY_H
+#ifndef NAMESERVER_ENTRY_H
+#define NAMESERVER_ENTRY_H
#include <string>
#include <vector>
@@ -281,4 +281,4 @@ private:
} // namespace dns
} // namespace isc
-#endif // __NAMESERVER_ENTRY_H
+#endif // NAMESERVER_ENTRY_H
diff --git a/src/lib/nsas/nsas_entry.h b/src/lib/nsas/nsas_entry.h
index 9cbed11..e797fd8 100644
--- a/src/lib/nsas/nsas_entry.h
+++ b/src/lib/nsas/nsas_entry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSAS_ENTRY_H
-#define __NSAS_ENTRY_H
+#ifndef NSAS_ENTRY_H
+#define NSAS_ENTRY_H
#include <boost/enable_shared_from_this.hpp>
#include <iostream>
@@ -135,4 +135,4 @@ private:
} // namespace isc
-#endif // __NSAS_ENTRY_H
+#endif // NSAS_ENTRY_H
diff --git a/src/lib/nsas/nsas_entry_compare.h b/src/lib/nsas/nsas_entry_compare.h
index 9e9ba7d..6291456 100644
--- a/src/lib/nsas/nsas_entry_compare.h
+++ b/src/lib/nsas/nsas_entry_compare.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSAS_ENTRY_COMPARE_H
-#define __NSAS_ENTRY_COMPARE_H
+#ifndef NSAS_ENTRY_COMPARE_H
+#define NSAS_ENTRY_COMPARE_H
#include "hash_key.h"
#include "hash_table.h"
@@ -50,4 +50,4 @@ public:
} // namespace nsas
} // namespace isc
-#endif // __NSAS_ENTRY_COMPARE_H
+#endif // NSAS_ENTRY_COMPARE_H
diff --git a/src/lib/nsas/nsas_log.h b/src/lib/nsas/nsas_log.h
index 031f46d..d4fed3c 100644
--- a/src/lib/nsas/nsas_log.h
+++ b/src/lib/nsas/nsas_log.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSAS_LOG__H
-#define __NSAS_LOG__H
+#ifndef NSAS_LOG_H
+#define NSAS_LOG_H
#include <log/macros.h>
#include "nsas_messages.h"
@@ -50,4 +50,4 @@ extern isc::log::Logger nsas_logger; // isc::nsas::logger is the NSAS logger
} // namespace nsas
} // namespace isc
-#endif // __NSAS_LOG__H
+#endif // NSAS_LOG_H
diff --git a/src/lib/nsas/nsas_types.h b/src/lib/nsas/nsas_types.h
index 940cc3e..07190a4 100644
--- a/src/lib/nsas/nsas_types.h
+++ b/src/lib/nsas/nsas_types.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSAS_TYPES_H
-#define __NSAS_TYPES_H
+#ifndef NSAS_TYPES_H
+#define NSAS_TYPES_H
/// \file nsas_types.h
/// \brief Nameserver Address Store Types
@@ -44,4 +44,4 @@ enum AddressFamily {
}
}
-#endif // __NSAS_TYPES_H
+#endif // NSAS_TYPES_H
diff --git a/src/lib/nsas/tests/nsas_test.h b/src/lib/nsas/tests/nsas_test.h
index 2dd95ef..d6b4d92 100644
--- a/src/lib/nsas/tests/nsas_test.h
+++ b/src/lib/nsas/tests/nsas_test.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSAS_TEST_H
-#define __NSAS_TEST_H
+#ifndef NSAS_TEST_H
+#define NSAS_TEST_H
/// \file nsas_test.h
///
@@ -293,4 +293,4 @@ protected:
} // namespace nsas
} // namespace isc
-#endif // __NSAS_TEST_H
+#endif // NSAS_TEST_H
diff --git a/src/lib/nsas/zone_entry.h b/src/lib/nsas/zone_entry.h
index 482b89f..7e5ab5b 100644
--- a/src/lib/nsas/zone_entry.h
+++ b/src/lib/nsas/zone_entry.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ZONE_ENTRY_H
-#define __ZONE_ENTRY_H
+#ifndef ZONE_ENTRY_H
+#define ZONE_ENTRY_H
#include <string>
#include <vector>
@@ -189,4 +189,4 @@ private:
} // namespace nsas
} // namespace isc
-#endif // __ZONE_ENTRY_H
+#endif // ZONE_ENTRY_H
diff --git a/src/lib/python/bind10_config.py.in b/src/lib/python/bind10_config.py.in
index b8975cf..6db64e2 100644
--- a/src/lib/python/bind10_config.py.in
+++ b/src/lib/python/bind10_config.py.in
@@ -51,7 +51,7 @@ def reload():
# tree the programs in the tree (not installed ones) will be used.
#
# B10_FROM_SOURCE_LOCALSTATEDIR is specifically intended to be used for
- # tests where we want to use variuos types of configuration within the test
+ # tests where we want to use various types of configuration within the test
# environment. (We may want to make it even more generic so that the path
# is passed from the boss process)
if "B10_FROM_SOURCE" in os.environ:
@@ -60,6 +60,8 @@ def reload():
else:
DATA_PATH = os.environ["B10_FROM_SOURCE"]
PLUGIN_PATHS = [os.environ["B10_FROM_SOURCE"] +
+ '/src/bin/cfgmgr/local_plugins',
+ os.environ["B10_FROM_SOURCE"] +
'/src/bin/cfgmgr/plugins']
programdirs = ['auth', 'cfgmgr', 'cmdctl', 'ddns', 'dhcp6', 'msgq',
'resolver', 'sockcreator', 'stats', 'xfrin', 'xfrout',
diff --git a/src/lib/python/isc/acl/dns.h b/src/lib/python/isc/acl/dns.h
index 76849c5..424a7f8 100644
--- a/src/lib/python/isc/acl/dns.h
+++ b/src/lib/python/isc/acl/dns.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_ACL_DNS_H
-#define __PYTHON_ACL_DNS_H 1
+#ifndef PYTHON_ACL_DNS_H
+#define PYTHON_ACL_DNS_H 1
#include <Python.h>
@@ -45,7 +45,7 @@ extern PyObject* getACLException(const char* ex_name);
} // namespace acl
} // namespace isc
-#endif // __PYTHON_ACL_DNS_H
+#endif // PYTHON_ACL_DNS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/acl/dns_requestacl_python.h b/src/lib/python/isc/acl/dns_requestacl_python.h
index 8f7ad8a..ea1cb5e 100644
--- a/src/lib/python/isc/acl/dns_requestacl_python.h
+++ b/src/lib/python/isc/acl/dns_requestacl_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_REQUESTACL_H
-#define __PYTHON_REQUESTACL_H 1
+#ifndef PYTHON_REQUESTACL_H
+#define PYTHON_REQUESTACL_H 1
#include <Python.h>
@@ -46,7 +46,7 @@ bool initModulePart_RequestACL(PyObject* mod);
} // namespace dns
} // namespace acl
} // namespace isc
-#endif // __PYTHON_REQUESTACL_H
+#endif // PYTHON_REQUESTACL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/acl/dns_requestcontext_python.h b/src/lib/python/isc/acl/dns_requestcontext_python.h
index 766133b..567e86f 100644
--- a/src/lib/python/isc/acl/dns_requestcontext_python.h
+++ b/src/lib/python/isc/acl/dns_requestcontext_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_REQUESTCONTEXT_H
-#define __PYTHON_REQUESTCONTEXT_H 1
+#ifndef PYTHON_REQUESTCONTEXT_H
+#define PYTHON_REQUESTCONTEXT_H 1
#include <Python.h>
@@ -47,7 +47,7 @@ bool initModulePart_RequestContext(PyObject* mod);
} // namespace dns
} // namespace acl
} // namespace isc
-#endif // __PYTHON_REQUESTCONTEXT_H
+#endif // PYTHON_REQUESTCONTEXT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/acl/dns_requestloader_python.h b/src/lib/python/isc/acl/dns_requestloader_python.h
index 9d0b63e..80cb6be 100644
--- a/src/lib/python/isc/acl/dns_requestloader_python.h
+++ b/src/lib/python/isc/acl/dns_requestloader_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_REQUESTLOADER_H
-#define __PYTHON_REQUESTLOADER_H 1
+#ifndef PYTHON_REQUESTLOADER_H
+#define PYTHON_REQUESTLOADER_H 1
#include <Python.h>
@@ -39,7 +39,7 @@ bool initModulePart_RequestLoader(PyObject* mod);
} // namespace dns
} // namespace acl
} // namespace isc
-#endif // __PYTHON_REQUESTLOADER_H
+#endif // PYTHON_REQUESTLOADER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/bind10/component.py b/src/lib/python/isc/bind10/component.py
index 9c29ace..1f7006c 100644
--- a/src/lib/python/isc/bind10/component.py
+++ b/src/lib/python/isc/bind10/component.py
@@ -45,6 +45,7 @@ COMPONENT_RESTART_DELAY = 10
STATE_DEAD = 'dead'
STATE_STOPPED = 'stopped'
+STATE_RESTARTING = 'restarting'
STATE_RUNNING = 'running'
def get_signame(signal_number):
@@ -68,6 +69,7 @@ class BaseComponent:
explicitly).
- Running - after start() was called, it started successfully and is
now running.
+ - Restarting - the component failed (crashed) and is waiting for a restart
- Dead - it failed and can not be resurrected.
Init
@@ -79,11 +81,11 @@ class BaseComponent:
| | |
|failure | failed() |
| | |
- v | |
+ v | | start()/restart()
+<-----------+ |
| |
| kind == dispensable or kind|== needed and failed late
- +-----------------------------+
+ +-----------------------> Restarting
|
| kind == core or kind == needed and it failed too soon
v
@@ -163,7 +165,7 @@ class BaseComponent:
"""
if self.__state == STATE_DEAD:
raise ValueError("Can't resurrect already dead component")
- if self.running():
+ if self.is_running():
raise ValueError("Can't start already running component")
logger.info(BIND10_COMPONENT_START, self.name())
self.__state = STATE_RUNNING
@@ -188,7 +190,7 @@ class BaseComponent:
"""
# This is not tested. It talks with the outher world, which is out
# of scope of unittests.
- if not self.running():
+ if not self.is_running():
raise ValueError("Can't stop a component which is not running")
logger.info(BIND10_COMPONENT_STOP, self.name())
self.__state = STATE_STOPPED
@@ -234,9 +236,9 @@ class BaseComponent:
logger.error(BIND10_COMPONENT_FAILED, self.name(), self.pid(),
exit_str)
- if not self.running():
+ if not self.is_running():
raise ValueError("Can't fail component that isn't running")
- self.__state = STATE_STOPPED
+ self.__state = STATE_RESTARTING # tentatively set, maybe changed to DEAD
self._failed_internal()
# If it is a core component or the needed component failed to start
# (including it stopped really soon)
@@ -284,7 +286,7 @@ class BaseComponent:
else:
return False
- def running(self):
+ def is_running(self):
"""
Informs if the component is currently running. It assumes the failed
is called whenever the component really fails and there might be some
@@ -296,6 +298,15 @@ class BaseComponent:
"""
return self.__state == STATE_RUNNING
+ def is_restarting(self):
+ """Informs if the component has failed and is waiting for a restart.
+
+ Unlike the case of is_running(), if this returns True it always means
+ the corresponding process has died and not yet restarted.
+
+ """
+ return self.__state == STATE_RESTARTING
+
def _start_internal(self):
"""
This method does the actual starting of a process. You need to override
@@ -560,6 +571,13 @@ class Configurator:
self._running = False
self.__reconfigure_internal(self._components, {})
+ def has_component(self, component):
+ '''Return if a specified component is configured.'''
+ # Values of self._components are tuples of (config, component).
+ # Extract the components of the tuples and see if the given one
+ # is included.
+ return component in map(lambda x: x[1], self._components.values())
+
def reconfigure(self, configuration):
"""
Changes configuration from the current one to the provided. It
@@ -591,7 +609,7 @@ class Configurator:
for cname in old.keys():
if cname not in new:
component = self._components[cname][1]
- if component.running():
+ if component.is_running() or component.is_restarting():
plan.append({
'command': STOP_CMD,
'component': component,
@@ -674,7 +692,7 @@ class Configurator:
self._components[task['name']] = (task['config'],
component)
elif command == STOP_CMD:
- if component.running():
+ if component.is_running():
component.stop()
del self._components[task['name']]
else:
diff --git a/src/lib/python/isc/bind10/sockcreator.py b/src/lib/python/isc/bind10/sockcreator.py
index c681d07..55142ee 100644
--- a/src/lib/python/isc/bind10/sockcreator.py
+++ b/src/lib/python/isc/bind10/sockcreator.py
@@ -214,9 +214,14 @@ class Creator(Parser):
socket.SOCK_STREAM)
env = copy.deepcopy(os.environ)
env['PATH'] = path
+ # We explicitly set close_fs to True; it's False by default before
+ # Python 3.2. If we don't close the remaining FDs, the copy of
+ # 'local' will prevent the child process from terminating when
+ # the parent process died abruptly.
self.__process = subprocess.Popen(['b10-sockcreator'], env=env,
stdin=remote.fileno(),
stdout=remote2.fileno(),
+ close_fds=True,
preexec_fn=self.__preexec_work)
remote.close()
remote2.close()
diff --git a/src/lib/python/isc/bind10/tests/component_test.py b/src/lib/python/isc/bind10/tests/component_test.py
index 3f26870..18efea7 100644
--- a/src/lib/python/isc/bind10/tests/component_test.py
+++ b/src/lib/python/isc/bind10/tests/component_test.py
@@ -191,7 +191,8 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertFalse(self.__start_called)
self.assertFalse(self.__stop_called)
self.assertFalse(self.__failed_called)
- self.assertFalse(component.running())
+ self.assertFalse(component.is_running())
+ self.assertFalse(component.is_restarting())
# We can't stop or fail the component yet
self.assertRaises(ValueError, component.stop)
self.assertRaises(ValueError, component.failed, 1)
@@ -204,7 +205,8 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertTrue(self.__start_called)
self.assertFalse(self.__stop_called)
self.assertFalse(self.__failed_called)
- self.assertTrue(component.running())
+ self.assertTrue(component.is_running())
+ self.assertFalse(component.is_restarting())
def __check_dead(self, component):
"""
@@ -215,7 +217,8 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertFalse(self.__stop_called)
self.assertTrue(self.__failed_called)
self.assertEqual(1, self._exitcode)
- self.assertFalse(component.running())
+ self.assertFalse(component.is_running())
+ self.assertFalse(component.is_restarting())
# Surely it can't be stopped when already dead
self.assertRaises(ValueError, component.stop)
# Nor started
@@ -234,7 +237,8 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertTrue(self.__start_called)
self.assertFalse(self.__stop_called)
self.assertTrue(self.__failed_called)
- self.assertTrue(component.running())
+ self.assertTrue(component.is_running())
+ self.assertFalse(component.is_restarting())
# Check it can't be started again
self.assertRaises(ValueError, component.start)
@@ -246,7 +250,8 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertTrue(self.__start_called)
self.assertFalse(self.__stop_called)
self.assertTrue(self.__failed_called)
- self.assertFalse(component.running())
+ self.assertFalse(component.is_running())
+ self.assertTrue(component.is_restarting())
def __do_start_stop(self, kind):
"""
@@ -270,7 +275,8 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertTrue(self.__start_called)
self.assertTrue(self.__stop_called)
self.assertFalse(self.__failed_called)
- self.assertFalse(component.running())
+ self.assertFalse(component.is_running())
+ self.assertFalse(component.is_restarting())
# Check it can't be stopped twice
self.assertRaises(ValueError, component.stop)
# Or failed
@@ -553,10 +559,10 @@ class ComponentTests(BossUtils, unittest.TestCase):
self.assertIsNone(component.pid())
self.assertEqual(['hello'], component._params)
self.assertEqual('Address', component._address)
- self.assertFalse(component.running())
+ self.assertFalse(component.is_running())
self.assertEqual({}, self.__registered_processes)
component.start()
- self.assertTrue(component.running())
+ self.assertTrue(component.is_running())
# Some versions of unittest miss assertIsInstance
self.assertTrue(isinstance(component._procinfo, TestProcInfo))
self.assertEqual(42, component.pid())
@@ -580,11 +586,11 @@ class ComponentTests(BossUtils, unittest.TestCase):
"""
component = Component('component', self, 'needed', 'Address')
component.start()
- self.assertTrue(component.running())
+ self.assertTrue(component.is_running())
self.assertEqual('component', self.__start_simple_params)
component.pid = lambda: 42
component.stop()
- self.assertFalse(component.running())
+ self.assertFalse(component.is_running())
self.assertEqual(('component', 'Address', 42),
self.__stop_process_params)
@@ -609,7 +615,7 @@ class ComponentTests(BossUtils, unittest.TestCase):
component = Component('component', self, 'needed', 'Address',
[], ProcInfo)
component.start()
- self.assertTrue(component.running())
+ self.assertTrue(component.is_running())
component.kill()
self.assertTrue(process.terminated)
self.assertFalse(process.killed)
@@ -872,12 +878,13 @@ class ConfiguratorTest(BossUtils, unittest.TestCase):
'priority': 6,
'special': 'test',
'process': 'additional',
- 'kind': 'needed'
+ 'kind': 'dispensable' # need to be dispensable so it could restart
}
self.log = []
plan = configurator._build_plan(self.__build_components(self.__core),
bigger)
- self.assertEqual([('additional', 'init'), ('additional', 'needed')],
+ self.assertEqual([('additional', 'init'),
+ ('additional', 'dispensable')],
self.log)
self.assertEqual(1, len(plan))
self.assertTrue('component' in plan[0])
@@ -888,15 +895,29 @@ class ConfiguratorTest(BossUtils, unittest.TestCase):
# Now remove the one component again
# We run the plan so the component is wired into internal structures
configurator._run_plan(plan)
- self.log = []
- plan = configurator._build_plan(self.__build_components(bigger),
- self.__core)
- self.assertEqual([], self.log)
- self.assertEqual([{
- 'command': 'stop',
- 'name': 'additional',
- 'component': component
- }], plan)
+ # We should have the 'additional' component in the configurator.
+ self.assertTrue(configurator.has_component(component))
+ for count in [0, 1]: # repeat two times, see below
+ self.log = []
+ plan = configurator._build_plan(self.__build_components(bigger),
+ self.__core)
+ self.assertEqual([], self.log)
+ self.assertEqual([{
+ 'command': 'stop',
+ 'name': 'additional',
+ 'component': component
+ }], plan)
+
+ if count is 0:
+ # We then emulate unexpected failure of the component (but
+ # before it restarts). It shouldn't confuse the
+ # configurator in the second phase of the test
+ component.failed(0)
+ # Run the plan, confirm the specified component is gone.
+ configurator._run_plan(plan)
+ self.assertFalse(configurator.has_component(component))
+ # There shouldn't be any other object that has the same name
+ self.assertFalse('additional' in configurator._components)
# We want to switch a component. So, prepare the configurator so it
# holds one
diff --git a/src/lib/python/isc/config/ccsession.py b/src/lib/python/isc/config/ccsession.py
index a95316d..8464a01 100644
--- a/src/lib/python/isc/config/ccsession.py
+++ b/src/lib/python/isc/config/ccsession.py
@@ -575,7 +575,7 @@ class UIModuleCCSession(MultiConfigData):
# for type any, we determine the 'type' by what value is set
# (which would be either list or dict)
cur_value, _ = self.get_value(identifier)
- type_any = module_spec['item_type'] == 'any'
+ type_any = isc.config.config_data.spec_part_is_any(module_spec)
# the specified element must be a list or a named_set
if 'list_item_spec' in module_spec or\
@@ -603,7 +603,7 @@ class UIModuleCCSession(MultiConfigData):
self._add_value_to_named_set(identifier, item_name,
item_value)
else:
- raise isc.cc.data.DataNotFoundError(str(identifier) + " is not a list or a named set")
+ raise isc.cc.data.DataTypeError(str(identifier) + " is not a list or a named set")
def _remove_value_from_list(self, identifier, value):
if value is None:
@@ -653,7 +653,7 @@ class UIModuleCCSession(MultiConfigData):
# for type any, we determine the 'type' by what value is set
# (which would be either list or dict)
cur_value, _ = self.get_value(identifier)
- type_any = module_spec['item_type'] == 'any'
+ type_any = isc.config.config_data.spec_part_is_any(module_spec)
# there's two forms of 'remove from list'; the remove-value-from-list
# form, and the 'remove-by-index' form. We can recognize the second
@@ -668,7 +668,7 @@ class UIModuleCCSession(MultiConfigData):
(type_any and type(cur_value) == dict):
self._remove_value_from_named_set(identifier, value_str)
else:
- raise isc.cc.data.DataNotFoundError(str(identifier) + " is not a list or a named_set")
+ raise isc.cc.data.DataTypeError(str(identifier) + " is not a list or a named_set")
diff --git a/src/lib/python/isc/config/config_data.py b/src/lib/python/isc/config/config_data.py
index 413d052..ae61e2a 100644
--- a/src/lib/python/isc/config/config_data.py
+++ b/src/lib/python/isc/config/config_data.py
@@ -45,6 +45,13 @@ def spec_part_is_named_set(spec_part):
named_set specification, and False otherwise."""
return (type(spec_part) == dict and 'named_set_item_spec' in spec_part)
+def spec_part_is_any(spec_part):
+ """Returns true if the given spec_part specifies an element of type
+ any, and False otherwise.
+ """
+ return (type(spec_part) == dict and 'item_type' in spec_part and
+ spec_part['item_type'] == "any")
+
def check_type(spec_part, value):
"""Does nothing if the value is of the correct type given the
specification part relevant for the value. Raises an
@@ -237,7 +244,8 @@ def spec_name_list(spec, prefix="", recurse=False):
elif 'named_set_item_spec' in spec:
# we added a '/' above, but in this one case we don't want it
result.append(prefix[:-1])
- else:
+ # ignore any
+ elif not spec_part_is_any(spec):
for name in spec:
result.append(prefix + name + "/")
if recurse:
@@ -392,14 +400,25 @@ class MultiConfigData:
identifier, or None if not found. The first part of the
identifier (up to the first /) is interpreted as the module
name. Returns None if not found, or if identifier is not a
- string."""
+ string.
+ If an index is given for a List-type element, it returns
+ the specification of the list elements, not of the list itself
+ """
if type(identifier) != str or identifier == "":
return None
if identifier[0] == '/':
identifier = identifier[1:]
module, sep, id = identifier.partition("/")
+ if id != "":
+ id, indices = isc.cc.data.split_identifier_list_indices(id)
+ else:
+ indices = None
try:
- return find_spec_part(self._specifications[module].get_config_spec(), id)
+ spec_part = find_spec_part(self._specifications[module].get_config_spec(), id)
+ if indices is not None and spec_part_is_list(spec_part):
+ return spec_part['list_item_spec']
+ else:
+ return spec_part
except isc.cc.data.DataNotFoundError as dnfe:
return None
except KeyError as ke:
@@ -780,19 +799,75 @@ class MultiConfigData:
indices and named_set names to the completion list. If
the given item_name is for a list or named_set, it'll
return a list of those (appended to item_name), otherwise
- the list will only contain the item_name itself."""
+ the list will only contain the item_name itself.
+
+ If the item is a named set, and it's contents are maps
+ or named_sets as well, a / is appended to the result
+ strings.
+
+ If the item is a list, this method is then called recursively
+ for each list entry.
+
+ This behaviour is slightly arbitrary, and currently reflects
+ the most probable way the resulting data should look like;
+ for lists, bindctl would always expect their contents to
+ be added as well. For named_sets, however, we do not
+ do recursion, since the resulting list may be too long.
+ This will probably change in a revision of the way this
+ data is handled; ideally, the result should always recurse,
+ but only up to a limited depth, and the resulting list
+ should probably be paginated clientside.
+
+ Parameters:
+ item_name (string): the (full) identifier for the list or
+ named_set to enumerate.
+
+ Returns a list of strings with item names
+
+ Examples:
+ _get_list_items("Module/some_item")
+ where item is not a list of a named_set, or where
+ said list or named set is empty, returns
+ ["Module/some_item"]
+ _get_list_items("Module/named_set")
+ where the named_set contains items with names 'a'
+ and 'b', returns
+ [ "Module/named_set/a", "Module/named_set/b" ]
+ _get_list_items("Module/named_set_of_maps")
+ where the named_set contains items with names 'a'
+ and 'b', and those items are maps themselves
+ (or other named_sets), returns
+ [ "Module/named_set/a/", "Module/named_set/b/" ]
+ _get_list_items("Module/list")
+ where the list contains 2 elements, returns
+ [ "Module/list[0]", "Module/list[1]" ]
+ """
spec_part = self.find_spec_part(item_name)
- if 'item_type' in spec_part and \
- spec_part['item_type'] == 'named_set':
- subslash = ""
- if spec_part['named_set_item_spec']['item_type'] == 'map' or\
- spec_part['named_set_item_spec']['item_type'] == 'named_set':
- subslash = "/"
- values, status = self.get_value(item_name)
- if len(values) > 0:
+ if spec_part_is_named_set(spec_part):
+ values, _ = self.get_value(item_name)
+ if values is not None and len(values) > 0:
+ subslash = ""
+ if spec_part['named_set_item_spec']['item_type'] == 'map' or\
+ spec_part['named_set_item_spec']['item_type'] == 'named_set':
+ subslash = "/"
+ # Don't recurse for named_sets (so as not to return too
+ # much data), but do add a / so the client so that
+ # the user can immediately tab-complete further if needed.
return [ item_name + "/" + v + subslash for v in values.keys() ]
else:
return [ item_name ]
+ elif spec_part_is_list(spec_part):
+ values, _ = self.get_value(item_name)
+ if values is not None and len(values) > 0:
+ result = []
+ for i in range(len(values)):
+ name = item_name + '[%d]' % i
+ # Recurse for list entries, so that its sub-contents
+ # are also added to the result
+ result.extend(self._get_list_items(name))
+ return result
+ else:
+ return [ item_name ]
else:
return [ item_name ]
diff --git a/src/lib/python/isc/config/tests/ccsession_test.py b/src/lib/python/isc/config/tests/ccsession_test.py
index 0101d50..ad364ac 100644
--- a/src/lib/python/isc/config/tests/ccsession_test.py
+++ b/src/lib/python/isc/config/tests/ccsession_test.py
@@ -993,10 +993,15 @@ class TestUIModuleCCSession(unittest.TestCase):
self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, 1, "a")
self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, "no_such_item", "a")
- self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, "Spec2/item1", "a")
self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, 1, "a")
self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, "no_such_item", "a")
- self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, "Spec2/item1", "a")
+ # add and remove should raise DataNotFoundError when used with items
+ # that are not a list or named_set (more importantly, they should
+ # not raise TypeError)
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.add_value, "Spec2/item1", "a")
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.remove_value, "Spec2/item1", "a")
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.add_value, "Spec2", "")
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.remove_value, "Spec2", "")
self.assertEqual({}, uccs._local_changes)
uccs.add_value("Spec2/item5", "foo")
@@ -1020,6 +1025,7 @@ class TestUIModuleCCSession(unittest.TestCase):
self.assertRaises(isc.cc.data.DataTypeError,
uccs.remove_value, "Spec2/item5", None)
+
# Check that the difference between no default and default = null
# is recognized
def test_default_null(self):
@@ -1042,9 +1048,9 @@ class TestUIModuleCCSession(unittest.TestCase):
items_as_str = [ '1234', 'foo', 'true', 'false' ]
def test_fails():
- self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, "Spec40/item1", "foo")
- self.assertRaises(isc.cc.data.DataNotFoundError, uccs.add_value, "Spec40/item1", "foo", "bar")
- self.assertRaises(isc.cc.data.DataNotFoundError, uccs.remove_value, "Spec40/item1", "foo")
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.add_value, "Spec40/item1", "foo")
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.add_value, "Spec40/item1", "foo", "bar")
+ self.assertRaises(isc.cc.data.DataTypeError, uccs.remove_value, "Spec40/item1", "foo")
self.assertRaises(isc.cc.data.DataTypeError, uccs.remove_value, "Spec40/item1[0]", None)
# A few helper functions to perform a number of tests
diff --git a/src/lib/python/isc/config/tests/config_data_test.py b/src/lib/python/isc/config/tests/config_data_test.py
index 86fbc11..45feb35 100644
--- a/src/lib/python/isc/config/tests/config_data_test.py
+++ b/src/lib/python/isc/config/tests/config_data_test.py
@@ -252,6 +252,18 @@ class TestConfigData(unittest.TestCase):
self.assertRaises(ConfigDataError, spec_name_list, 1)
self.assertRaises(ConfigDataError, spec_name_list, [ 'a' ])
+ # Test one with type any as well
+ module_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec40.spec")
+ spec_part = module_spec.get_config_spec()
+ name_list = spec_name_list(module_spec.get_config_spec())
+ self.assertEqual(['item1', 'item2', 'item3'], name_list)
+
+ # item3 itself is 'empty'
+ spec_part = find_spec_part(spec_part, 'item3')
+ name_list = spec_name_list(spec_part)
+ self.assertEqual([], name_list)
+
+
def test_init(self):
self.assertRaises(ConfigDataError, ConfigData, "asdf")
@@ -377,12 +389,37 @@ class TestMultiConfigData(unittest.TestCase):
self.assertEqual(None, spec_part)
spec_part = self.mcd.find_spec_part("/Spec2/item1")
self.assertEqual(None, spec_part)
- module_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec2.spec")
+ module_spec = isc.config.module_spec_from_file(self.data_path +
+ os.sep + "spec2.spec")
self.mcd.set_specification(module_spec)
spec_part = self.mcd.find_spec_part("Spec2/item1")
- self.assertEqual({'item_name': 'item1', 'item_type': 'integer', 'item_optional': False, 'item_default': 1, }, spec_part)
+ self.assertEqual({'item_name': 'item1', 'item_type': 'integer',
+ 'item_optional': False, 'item_default': 1, },
+ spec_part)
+
+ # For lists, either the spec of the list itself, or the
+ # spec for the list contents should be returned (the
+ # latter when an index is given in the identifier)
+ spec_part = self.mcd.find_spec_part("Spec2/item5")
+ self.assertEqual({'item_default': ['a', 'b'],
+ 'item_name': 'item5',
+ 'item_optional': False,
+ 'item_type': 'list',
+ 'list_item_spec': {'item_default': '',
+ 'item_name': 'list_element',
+ 'item_optional': False,
+ 'item_type': 'string'}},
+ spec_part)
+ spec_part = self.mcd.find_spec_part("Spec2/item5[0]")
+ self.assertEqual({'item_default': '',
+ 'item_name': 'list_element',
+ 'item_optional': False,
+ 'item_type': 'string'},
+ spec_part)
+
def test_find_spec_part_nested(self):
+ # Check that find_spec_part works for nested lists
module_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec30.spec")
self.mcd.set_specification(module_spec)
spec_part = self.mcd.find_spec_part("/lists/first_list_items[0]/second_list_items[1]/final_element")
@@ -391,6 +428,7 @@ class TestMultiConfigData(unittest.TestCase):
self.assertEqual(None, spec_part)
def test_find_spec_part_nested2(self):
+ # Check that find_spec_part works for nested lists and maps
module_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec31.spec")
self.mcd.set_specification(module_spec)
spec_part = self.mcd.find_spec_part("/lists/first_list_items[0]/second_list_items[1]/map_element/list1[1]/list2[2]")
@@ -638,7 +676,7 @@ class TestMultiConfigData(unittest.TestCase):
self.assertEqual(expected, maps)
# A slash at the end should not produce different output with
- # indices too
+ # indices either
expected2 = [{'default': True,
'type': 'integer',
'name': 'Spec22/value5[1]',
@@ -720,6 +758,8 @@ class TestMultiConfigData(unittest.TestCase):
self.assertRaises(isc.cc.data.DataNotFoundError, self.mcd.unset, "Spec2/doesnotexist")
def test_get_config_item_list(self):
+ # Test get_config_item_list(), which returns a list of the config
+ # items in a specification.
config_items = self.mcd.get_config_item_list()
self.assertEqual([], config_items)
module_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec2.spec")
@@ -729,15 +769,42 @@ class TestMultiConfigData(unittest.TestCase):
config_items = self.mcd.get_config_item_list(None, False)
self.assertEqual(['Spec2'], config_items)
config_items = self.mcd.get_config_item_list(None, True)
- self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3', 'Spec2/item4', 'Spec2/item5', 'Spec2/item6/value1', 'Spec2/item6/value2'], config_items)
+ self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3',
+ 'Spec2/item4', 'Spec2/item5', 'Spec2/item6/value1',
+ 'Spec2/item6/value2'], config_items)
config_items = self.mcd.get_config_item_list("Spec2", True)
- self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3', 'Spec2/item4', 'Spec2/item5', 'Spec2/item6/value1', 'Spec2/item6/value2'], config_items)
+ self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3',
+ 'Spec2/item4', 'Spec2/item5[0]', 'Spec2/item5[1]',
+ 'Spec2/item6/value1', 'Spec2/item6/value2'],
+ config_items)
config_items = self.mcd.get_config_item_list("Spec2")
- self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3', 'Spec2/item4', 'Spec2/item5', 'Spec2/item6'], config_items)
+ self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3',
+ 'Spec2/item4', 'Spec2/item5[0]', 'Spec2/item5[1]',
+ 'Spec2/item6'], config_items)
config_items = self.mcd.get_config_item_list("/Spec2")
- self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3', 'Spec2/item4', 'Spec2/item5', 'Spec2/item6'], config_items)
+ self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3',
+ 'Spec2/item4', 'Spec2/item5[0]', 'Spec2/item5[1]',
+ 'Spec2/item6'], config_items)
+ config_items = self.mcd.get_config_item_list("Spec2", True)
+ self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3',
+ 'Spec2/item4', 'Spec2/item5[0]', 'Spec2/item5[1]',
+ 'Spec2/item6/value1', 'Spec2/item6/value2'],
+ config_items)
+
+ # When lists are empty, it should only show the name
+ self.mcd.set_value('Spec2/item5', [])
config_items = self.mcd.get_config_item_list("Spec2", True)
- self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3', 'Spec2/item4', 'Spec2/item5', 'Spec2/item6/value1', 'Spec2/item6/value2'], config_items)
+ self.assertEqual(['Spec2/item1', 'Spec2/item2', 'Spec2/item3',
+ 'Spec2/item4', 'Spec2/item5', 'Spec2/item6/value1',
+ 'Spec2/item6/value2'], config_items)
+
+ # Also if the list is None (optional value and no default)
+ module_spec = isc.config.module_spec_from_file(self.data_path
+ + os.sep
+ + "spec42.spec")
+ self.mcd.set_specification(module_spec)
+ config_items = self.mcd.get_config_item_list("Spec42", True)
+ self.assertEqual(['Spec42/list_item'], config_items)
def test_is_named_set(self):
module_spec = isc.config.module_spec_from_file(self.data_path + os.sep + "spec32.spec")
@@ -756,7 +823,8 @@ class TestMultiConfigData(unittest.TestCase):
self.assertEqual(['Spec32'], config_items)
config_items = self.mcd.get_config_item_list(None, True)
self.assertEqual(['Spec32/named_set_item', 'Spec32/named_set_item2',
- 'Spec32/named_set_item3'], config_items)
+ 'Spec32/named_set_item3', 'Spec32/named_set_item4'],
+ config_items)
self.mcd.set_value('Spec32/named_set_item', { "aaaa": 4, "aabb": 5,
"bbbb": 6})
config_items = self.mcd.get_config_item_list("/Spec32/named_set_item",
@@ -766,6 +834,19 @@ class TestMultiConfigData(unittest.TestCase):
'Spec32/named_set_item/bbbb',
], config_items)
+ self.mcd.set_value('Spec32/named_set_item', {})
+ config_items = self.mcd.get_config_item_list("/Spec32/named_set_item",
+ True)
+ self.assertEqual(['Spec32/named_set_item'], config_items)
+
+ self.mcd.set_value('Spec32/named_set_item4', { "a": { "aa": 4 } } )
+ config_items = self.mcd.get_config_item_list("/Spec32/named_set_item4",
+ True)
+ self.assertEqual(['Spec32/named_set_item4/a/'], config_items)
+ config_items = self.mcd.get_config_item_list("/Spec32/named_set_item4/a",
+ True)
+ self.assertEqual(['Spec32/named_set_item4/a/aa'], config_items)
+
def test_set_named_set_nonlocal(self):
# Test whether a default named set is copied to local if a subitem
# is changed, and that other items in the set do not get lost
diff --git a/src/lib/python/isc/datasrc/client_python.h b/src/lib/python/isc/datasrc/client_python.h
index 98a256e..71aee8b 100644
--- a/src/lib/python/isc/datasrc/client_python.h
+++ b/src/lib/python/isc/datasrc/client_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_DATASRC_CLIENT_H
-#define __PYTHON_DATASRC_CLIENT_H 1
+#ifndef PYTHON_DATASRC_CLIENT_H
+#define PYTHON_DATASRC_CLIENT_H 1
#include <datasrc/client_list.h>
@@ -47,7 +47,7 @@ wrapDataSourceClient(DataSourceClient* client,
} // namespace python
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_DATASRC_CLIENT_H
+#endif // PYTHON_DATASRC_CLIENT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/datasrc/configurableclientlist_python.h b/src/lib/python/isc/datasrc/configurableclientlist_python.h
index 155d262..bcd76fe 100644
--- a/src/lib/python/isc/datasrc/configurableclientlist_python.h
+++ b/src/lib/python/isc/datasrc/configurableclientlist_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_CONFIGURABLECLIENTLIST_H
-#define __PYTHON_CONFIGURABLECLIENTLIST_H 1
+#ifndef PYTHON_CONFIGURABLECLIENTLIST_H
+#define PYTHON_CONFIGURABLECLIENTLIST_H 1
#include <Python.h>
@@ -37,7 +37,7 @@ bool initModulePart_ConfigurableClientList(PyObject* mod);
} // namespace python
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_CONFIGURABLECLIENTLIST_H
+#endif // PYTHON_CONFIGURABLECLIENTLIST_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/datasrc/datasrc.h b/src/lib/python/isc/datasrc/datasrc.h
index d82881b..5a7a8f0 100644
--- a/src/lib/python/isc/datasrc/datasrc.h
+++ b/src/lib/python/isc/datasrc/datasrc.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_DATASRC_H
-#define __PYTHON_DATASRC_H 1
+#ifndef PYTHON_DATASRC_H
+#define PYTHON_DATASRC_H 1
#include <Python.h>
@@ -43,7 +43,7 @@ extern PyObject* getDataSourceException(const char* ex_name);
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_ACL_DNS_H
+#endif // PYTHON_DATASRC_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/datasrc/finder_python.h b/src/lib/python/isc/datasrc/finder_python.h
index 23bc457..8d4c9b6 100644
--- a/src/lib/python/isc/datasrc/finder_python.h
+++ b/src/lib/python/isc/datasrc/finder_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_DATASRC_FINDER_H
-#define __PYTHON_DATASRC_FINDER_H 1
+#ifndef PYTHON_DATASRC_FINDER_H
+#define PYTHON_DATASRC_FINDER_H 1
#include <Python.h>
@@ -37,7 +37,7 @@ PyObject* createZoneFinderObject(isc::datasrc::ZoneFinderPtr source,
} // namespace python
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_DATASRC_FINDER_H
+#endif // PYTHON_DATASRC_FINDER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/datasrc/iterator_python.h b/src/lib/python/isc/datasrc/iterator_python.h
index 7c1b0eb..c64dea3 100644
--- a/src/lib/python/isc/datasrc/iterator_python.h
+++ b/src/lib/python/isc/datasrc/iterator_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_DATASRC_ITERATOR_H
-#define __PYTHON_DATASRC_ITERATOR_H 1
+#ifndef PYTHON_DATASRC_ITERATOR_H
+#define PYTHON_DATASRC_ITERATOR_H 1
#include <Python.h>
@@ -39,7 +39,7 @@ PyObject* createZoneIteratorObject(isc::datasrc::ZoneIteratorPtr source,
} // namespace python
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_DATASRC_ITERATOR_H
+#endif // PYTHON_DATASRC_ITERATOR_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/datasrc/journal_reader_python.h b/src/lib/python/isc/datasrc/journal_reader_python.h
index 56344df..6708c36 100644
--- a/src/lib/python/isc/datasrc/journal_reader_python.h
+++ b/src/lib/python/isc/datasrc/journal_reader_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_DATASRC_JOURNAL_READER_H
-#define __PYTHON_DATASRC_JOURNAL_READER_H 1
+#ifndef PYTHON_DATASRC_JOURNAL_READER_H
+#define PYTHON_DATASRC_JOURNAL_READER_H 1
#include <Python.h>
@@ -40,7 +40,7 @@ PyObject* createZoneJournalReaderObject(
} // namespace python
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_DATASRC_JOURNAL_READER_H
+#endif // PYTHON_DATASRC_JOURNAL_READER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/datasrc/sqlite3_ds.py b/src/lib/python/isc/datasrc/sqlite3_ds.py
index f9b47c0..dc80afd 100644
--- a/src/lib/python/isc/datasrc/sqlite3_ds.py
+++ b/src/lib/python/isc/datasrc/sqlite3_ds.py
@@ -25,7 +25,7 @@ RR_RDATA_INDEX = 7
# Current major and minor versions of schema
SCHEMA_MAJOR_VERSION = 2
-SCHEMA_MINOR_VERSION = 0
+SCHEMA_MINOR_VERSION = 1
class Sqlite3DSError(Exception):
""" Define exceptions."""
@@ -81,6 +81,7 @@ def create(cur):
rdtype TEXT NOT NULL COLLATE NOCASE,
rdata TEXT NOT NULL)""")
cur.execute("CREATE INDEX nsec3_byhash ON nsec3 (hash)")
+ cur.execute("CREATE INDEX nsec3_byhash_and_rdtype ON nsec3 (hash, rdtype)")
cur.execute("""CREATE TABLE diffs (id INTEGER PRIMARY KEY,
zone_id INTEGER NOT NULL,
version INTEGER NOT NULL,
diff --git a/src/lib/python/isc/datasrc/updater_python.h b/src/lib/python/isc/datasrc/updater_python.h
index 8228578..b09c524 100644
--- a/src/lib/python/isc/datasrc/updater_python.h
+++ b/src/lib/python/isc/datasrc/updater_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_DATASRC_UPDATER_H
-#define __PYTHON_DATASRC_UPDATER_H 1
+#ifndef PYTHON_DATASRC_UPDATER_H
+#define PYTHON_DATASRC_UPDATER_H 1
#include <Python.h>
@@ -40,7 +40,7 @@ PyObject* createZoneUpdaterObject(isc::datasrc::ZoneUpdaterPtr source,
} // namespace python
} // namespace datasrc
} // namespace isc
-#endif // __PYTHON_DATASRC_UPDATER_H
+#endif // PYTHON_DATASRC_UPDATER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/sysinfo/sysinfo.py b/src/lib/python/isc/sysinfo/sysinfo.py
index 97b9e59..8e4610c 100644
--- a/src/lib/python/isc/sysinfo/sysinfo.py
+++ b/src/lib/python/isc/sysinfo/sysinfo.py
@@ -22,6 +22,7 @@ import subprocess
import os.path
import platform
import time
+from datetime import timedelta
class SysInfo:
def __init__(self):
@@ -93,6 +94,18 @@ class SysInfo:
"""Returns the uptime in seconds."""
return self._uptime
+ def get_uptime_desc(self):
+ """Returns the uptime in human readable form.
+
+ The format is the result of str() method of the standard library
+ datetime.timedelta class. It returns None if _uptime is None.
+
+ """
+ if self._uptime is None:
+ return None
+
+ return str(timedelta(seconds=self._uptime))
+
def get_loadavg(self):
"""Returns the load average as 3 floating point values in an array."""
return self._loadavg
@@ -333,11 +346,11 @@ class SysInfoOpenBSD(SysInfoBSD):
pass
try:
+ # We use the size of free-list from the vmstat result.
s = subprocess.check_output(['vmstat'])
lines = s.decode('utf-8').split('\n')
v = re.split('\s+', lines[2])
- used = int(v[4]) * 1024
- self._mem_free = self._mem_total - used
+ self._mem_free = int(v[5]) * 1024
except (subprocess.CalledProcessError, OSError):
pass
@@ -389,17 +402,27 @@ class SysInfoFreeBSD(SysInfoFreeBSDOSX):
super().__init__()
try:
- s = subprocess.check_output(['sysctl', '-n', 'kern.smp.active'])
- self._platform_is_smp = int(s.decode('utf-8').strip()) > 0
- except (subprocess.CalledProcessError, OSError):
+ # There doesn't seem to be an easy way to reliably detect whether
+ # the kernel was built with SMP support on FreeBSD. We use
+ # a sysctl variable that is only defined in SMP kernels.
+ # This assumption seems to hold for several recent versions of
+ # FreeBSD, but it may not always be so for future versions.
+ s = subprocess.check_output(['sysctl', '-n',
+ 'kern.smp.forward_signal_enabled'])
+ self._platform_is_smp = True # the value doesn't matter
+ except subprocess.CalledProcessError:
+ # if this variable isn't defined we should see this exception.
+ # intepret it as an indication of non-SMP kernel.
+ self._platform_is_smp = False
+ except OSError:
pass
try:
+ # We use the size of free-list from the vmstat result.
s = subprocess.check_output(['vmstat', '-H'])
lines = s.decode('utf-8').split('\n')
v = re.split('\s+', lines[2])
- used = int(v[4]) * 1024
- self._mem_free = self._mem_total - used
+ self._mem_free = int(v[5]) * 1024
except (subprocess.CalledProcessError, OSError):
pass
diff --git a/src/lib/python/isc/sysinfo/tests/sysinfo_test.py b/src/lib/python/isc/sysinfo/tests/sysinfo_test.py
index 0add036..8f11df0 100644
--- a/src/lib/python/isc/sysinfo/tests/sysinfo_test.py
+++ b/src/lib/python/isc/sysinfo/tests/sysinfo_test.py
@@ -49,7 +49,7 @@ class MyLinuxFile:
elif self._filename == '/proc/version':
return 'An SMP version string'
elif self._filename == '/proc/uptime':
- return '86400.75 139993.71'
+ return '172800.75 139993.71'
elif self._filename == '/proc/loadavg':
return '0.1 0.2 0.3 0.4'
else:
@@ -171,26 +171,33 @@ def _my_freebsd_os_sysconf(key):
def _my_freebsd_platform_uname():
return ('FreeBSD', 'freebsd', '8.2-RELEASE', '', 'i386')
-def _my_freebsd_osx_subprocess_check_output(command):
+def _my_freebsd_osx_subprocess_check_output(command, faked_output={}):
'''subprocess output shared for freebsd and osx'''
assert type(command) == list, 'command argument is not a list'
if command == ['sysctl', '-n', 'kern.boottime']:
- return bytes('{ sec = ' + str(int(time.time() - 76632)) + ', usec = 0 }\n', 'utf-8')
+ if 'boottime-sysctl' in faked_output:
+ return faked_output['boottime-sysctl']
+ return bytes('{ sec = ' + str(int(time.time() - 76632)) +
+ ', usec = 0 }\n', 'utf-8')
elif command == ['sysctl', '-n', 'vm.loadavg']:
return b'{ 0.2 0.4 0.6 }\n'
else:
return _my_bsd_subprocess_check_output(command)
-def _my_freebsd_subprocess_check_output(command):
+def _my_freebsd_subprocess_check_output(command, faked_output):
assert type(command) == list, 'command argument is not a list'
- if command == ['sysctl', '-n', 'kern.smp.active']:
- return b'1\n'
+ if command == ['sysctl', '-n', 'kern.smp.forward_signal_enabled']:
+ output = faked_output['smp-sysctl']
+ if isinstance(output, Exception):
+ raise output
+ return output
elif command == ['vmstat', '-H']:
return b' procs memory page disks traps cpu\n r b w avm fre flt re pi po fr sr wd0 cd0 int sys cs us sy id\n 0 0 0 343434 123456 47 0 0 0 0 0 2 0 2 80 14 0 1 99\n'
elif command == ['swapctl', '-s', '-k']:
return b'Total: 1013216 0\n'
else:
- freebsd_osx_output = _my_freebsd_osx_subprocess_check_output(command)
+ freebsd_osx_output = \
+ _my_freebsd_osx_subprocess_check_output(command, faked_output)
if freebsd_osx_output is not None:
return freebsd_osx_output
else:
@@ -252,6 +259,7 @@ class SysInfoTest(unittest.TestCase):
self.assertEqual('Unknown', s.get_platform_machine())
self.assertFalse(s.get_platform_is_smp())
self.assertEqual(None, s.get_uptime())
+ self.assertEqual(None, s.get_uptime_desc())
self.assertEqual(None, s.get_loadavg())
self.assertEqual(None, s.get_mem_total())
self.assertEqual(None, s.get_mem_free())
@@ -267,7 +275,11 @@ class SysInfoTest(unittest.TestCase):
def test_sysinfo_factory(self):
"""Test that SysInfoFromFactory returns a valid system-specific
- SysInfo implementation."""
+ SysInfo implementation.
+
+ See sysinfo.SysInfoTestcase() for some of the parameters.
+
+ """
old_platform_system = platform.system
platform.system = _my_testcase_platform_system
@@ -281,6 +293,8 @@ class SysInfoTest(unittest.TestCase):
self.assertEqual('Unknown', s.get_platform_machine())
self.assertFalse(s.get_platform_is_smp())
self.assertEqual(131072, s.get_uptime())
+ # We check that we do NOT add 's' to 'day' (because it's singular):
+ self.assertEqual('1 day, 12:24:32', s.get_uptime_desc())
self.assertEqual(None, s.get_loadavg())
self.assertEqual(None, s.get_mem_total())
self.assertEqual(None, s.get_mem_free())
@@ -312,7 +326,10 @@ class SysInfoTest(unittest.TestCase):
self.assertEqual(NPROCESSORS_LINUX, s.get_num_processors())
self.assertEqual('myhostname', s.get_platform_hostname())
self.assertTrue(s.get_platform_is_smp())
- self.assertEqual(86401, s.get_uptime())
+ self.assertEqual(172801, s.get_uptime())
+ # We check that we add 's' to 'day', and that the mm part has an
+ # additional 0, i.e., not '0:0' but '0:00':
+ self.assertEqual('2 days, 0:00:01', s.get_uptime_desc())
self.assertEqual((0.1, 0.2, 0.3), s.get_loadavg())
self.assertEqual(3157884928, s.get_mem_total())
self.assertEqual(891383808, s.get_mem_free())
@@ -366,7 +383,7 @@ class SysInfoTest(unittest.TestCase):
self.assertEqual((0.7, 0.9, 0.8), s.get_loadavg())
self.assertFalse(s.get_platform_is_smp())
self.assertEqual(543214321, s.get_mem_total())
- self.assertEqual(543214321 - (121212 * 1024), s.get_mem_free())
+ self.assertEqual(123456 * 1024, s.get_mem_free())
self.assertEqual(566791168, s.get_mem_swap_total())
self.assertEqual(566789120, s.get_mem_swap_free())
@@ -379,18 +396,42 @@ class SysInfoTest(unittest.TestCase):
# with mock ones for testing.
platform.system = _my_freebsd_platform_system
os.sysconf = _my_freebsd_os_sysconf
- subprocess.check_output = _my_freebsd_subprocess_check_output
+
+ # We use a lambda object so we can tweak the subprocess output during
+ # the tests later.
+ faked_process_output = { 'smp-sysctl': b'1\n' }
+ subprocess.check_output = lambda command : \
+ _my_freebsd_subprocess_check_output(command, faked_process_output)
+
os.uname = _my_freebsd_platform_uname
s = SysInfoFromFactory()
self.assertEqual(NPROCESSORS_FREEBSD, s.get_num_processors())
self.assertTrue(s.get_platform_is_smp())
+ # We check the kernel SMP support by the availability of a sysctl
+ # variable. The value (especially a 0 value) shouldn't matter.
+ faked_process_output['smp-sysctl'] = b'0\n'
+ s = SysInfoFromFactory()
+ self.assertTrue(s.get_platform_is_smp())
+
+ # if the sysctl raises CalledProcessError, we treat it as non-SMP
+ # kernel.
+ faked_process_output['smp-sysctl'] = \
+ subprocess.CalledProcessError(1, 'sysctl')
+ s = SysInfoFromFactory()
+ self.assertFalse(s.get_platform_is_smp())
+
+ # if it results in OSError, no SMP information will be provided.
+ faked_process_output['smp-sysctl'] = OSError()
+ s = SysInfoFromFactory()
+ self.assertIsNone(s.get_platform_is_smp())
+
self.check_bsd_values(s)
self.assertEqual((0.2, 0.4, 0.6), s.get_loadavg())
self.assertEqual(543214321, s.get_mem_total())
- self.assertEqual(543214321 - (343434 * 1024), s.get_mem_free())
+ self.assertEqual(123456 * 1024, s.get_mem_free())
self.assertEqual(1037533184, s.get_mem_swap_total())
self.assertEqual(1037533184, s.get_mem_swap_free())
diff --git a/src/lib/python/isc/util/cio/socketsession_python.h b/src/lib/python/isc/util/cio/socketsession_python.h
index b0703ac..da83047 100644
--- a/src/lib/python/isc/util/cio/socketsession_python.h
+++ b/src/lib/python/isc/util/cio/socketsession_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_SOCKETSESSION_H
-#define __PYTHON_SOCKETSESSION_H 1
+#ifndef PYTHON_SOCKETSESSION_H
+#define PYTHON_SOCKETSESSION_H 1
#include <Python.h>
@@ -28,7 +28,7 @@ extern PyObject* po_SocketSessionError;
} // namespace io
} // namespace util
} // namespace isc
-#endif // __PYTHON_SOCKETSESSION_H
+#endif // PYTHON_SOCKETSESSION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/util/cio/socketsessionforwarder_python.h b/src/lib/python/isc/util/cio/socketsessionforwarder_python.h
index 2ce220a..968ce7f 100644
--- a/src/lib/python/isc/util/cio/socketsessionforwarder_python.h
+++ b/src/lib/python/isc/util/cio/socketsessionforwarder_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_SOCKETSESSIONFORWARDER_H
-#define __PYTHON_SOCKETSESSIONFORWARDER_H 1
+#ifndef PYTHON_SOCKETSESSIONFORWARDER_H
+#define PYTHON_SOCKETSESSIONFORWARDER_H 1
#include <Python.h>
@@ -38,7 +38,7 @@ bool initModulePart_SocketSessionForwarder(PyObject* mod);
} // namespace io
} // namespace util
} // namespace isc
-#endif // __PYTHON_SOCKETSESSIONFORWARDER_H
+#endif // PYTHON_SOCKETSESSIONFORWARDER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/python/isc/util/cio/socketsessionreceiver_python.h b/src/lib/python/isc/util/cio/socketsessionreceiver_python.h
index 14e8a1b..eb9a884 100644
--- a/src/lib/python/isc/util/cio/socketsessionreceiver_python.h
+++ b/src/lib/python/isc/util/cio/socketsessionreceiver_python.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_SOCKETSESSIONRECEIVER_H
-#define __PYTHON_SOCKETSESSIONRECEIVER_H 1
+#ifndef PYTHON_SOCKETSESSIONRECEIVER_H
+#define PYTHON_SOCKETSESSIONRECEIVER_H 1
#include <Python.h>
@@ -39,7 +39,7 @@ bool initModulePart_SocketSessionReceiver(PyObject* mod);
} // namespace python
} // namespace util
} // namespace isc
-#endif // __PYTHON_SOCKETSESSIONRECEIVER_H
+#endif // PYTHON_SOCKETSESSIONRECEIVER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/resolve/recursive_query.cc b/src/lib/resolve/recursive_query.cc
index 8d03c1c..7eae6fe 100644
--- a/src/lib/resolve/recursive_query.cc
+++ b/src/lib/resolve/recursive_query.cc
@@ -122,8 +122,6 @@ deepestDelegation(Name name, RRClass rrclass,
return (".");
}
-typedef std::vector<std::pair<std::string, uint16_t> > AddressVector;
-
// Here we do not use the typedef above, as the SunStudio compiler
// mishandles this in its name mangling, and wouldn't compile.
// We can probably use a typedef, but need to move it to a central
@@ -161,7 +159,6 @@ RecursiveQuery::setRttRecorder(boost::shared_ptr<RttRecorder>& recorder) {
}
namespace {
-
typedef std::pair<std::string, uint16_t> addr_t;
/*
@@ -171,12 +168,12 @@ typedef std::pair<std::string, uint16_t> addr_t;
*
* Used by RecursiveQuery::sendQuery.
*/
-class RunningQuery : public IOFetch::Callback {
+class RunningQuery : public IOFetch::Callback, public AbstractRunningQuery {
class ResolverNSASCallback : public isc::nsas::AddressRequestCallback {
public:
ResolverNSASCallback(RunningQuery* rq) : rq_(rq) {}
-
+
void success(const isc::nsas::NameserverAddress& address) {
// Success callback, send query to found namesever
LOG_DEBUG(isc::resolve::logger, RESLIB_DBG_CB, RESLIB_RUNQ_SUCCESS)
@@ -184,7 +181,7 @@ public:
rq_->nsasCallbackCalled();
rq_->sendTo(address);
}
-
+
void unreachable() {
// Nameservers unreachable: drop query or send servfail?
LOG_DEBUG(isc::resolve::logger, RESLIB_DBG_CB, RESLIB_RUNQ_FAIL);
@@ -261,7 +258,7 @@ private:
bool done_;
// If we have a client timeout, we call back with a failure message,
- // but we do not stop yet. We use this variable to make sure we
+ // but we do not stop yet. We use this variable to make sure we
// don't call back a second time later
bool callback_called_;
@@ -270,7 +267,7 @@ private:
// Reference to our cache
isc::cache::ResolverCache& cache_;
-
+
// the 'current' zone we are in (i.e.) we start out at the root,
// and for each delegation this gets updated with the zone the
// delegation points to.
@@ -278,7 +275,7 @@ private:
// of the call we use it in take a string, we need update those
// too).
std::string cur_zone_;
-
+
// This is the handler we pass on to the NSAS; it is called when
// the NSAS has an address for us to query
boost::shared_ptr<ResolverNSASCallback> nsas_callback_;
@@ -295,7 +292,7 @@ private:
// The moment in time we sent a query to the nameserver above.
struct timeval current_ns_qsent_time;
-
+
// RunningQuery deletes itself when it is done. In order for us
// to do this safely, we must make sure that there are no events
// that might call back to it. There are two types of events in
@@ -365,7 +362,7 @@ private:
io_.get_io_service().post(query);
}
}
-
+
// 'general' send, ask the NSAS to give us an address.
void send(IOFetch::Protocol protocol = IOFetch::UDP, bool edns = true) {
protocol_ = protocol; // Store protocol being used for this
@@ -397,7 +394,7 @@ private:
nsas_.lookup(cur_zone_, question_.getClass(), nsas_callback_);
}
}
-
+
// Called by our NSAS callback handler so we know we do not have
// an outstanding NSAS call anymore.
void nsasCallbackCalled() {
@@ -422,13 +419,13 @@ private:
// here (classify() will set it when it walks through
// the cname chain to verify it).
Name cname_target(question_.getName());
-
+
isc::resolve::ResponseClassifier::Category category =
isc::resolve::ResponseClassifier::classify(
question_, incoming, cname_target, cname_count_);
bool found_ns = false;
-
+
switch (category) {
case isc::resolve::ResponseClassifier::ANSWER:
case isc::resolve::ResponseClassifier::ANSWERCNAME:
@@ -569,7 +566,7 @@ private:
// SERVFAIL if we get FORMERR instead
}
goto SERVFAIL;
-
+
default:
SERVFAIL:
// Some error in received packet it. Report it and return SERVFAIL
@@ -718,7 +715,7 @@ public:
++outstanding_events_;
lookup_timer.async_wait(boost::bind(&RunningQuery::lookupTimeout, this));
}
-
+
// Setup the timer to send an answer (client_timeout)
if (client_timeout >= 0) {
client_timer.expires_from_now(
@@ -726,10 +723,12 @@ public:
++outstanding_events_;
client_timer.async_wait(boost::bind(&RunningQuery::clientTimeout, this));
}
-
+
doLookup();
}
+ virtual ~RunningQuery() {};
+
// called if we have a lookup timeout; if our callback has
// not been called, call it now. Then stop.
void lookupTimeout() {
@@ -741,7 +740,7 @@ public:
--outstanding_events_;
stop();
}
-
+
// called if we have a client timeout; if our callback has
// not been called, call it now. But do not stop.
void clientTimeout() {
@@ -810,7 +809,7 @@ public:
// XXX is this the place for TCP retry?
assert(outstanding_events_ > 0);
--outstanding_events_;
-
+
if (!done_ && result != IOFetch::TIME_OUT) {
// we got an answer
@@ -890,15 +889,17 @@ public:
stop();
}
}
-
+
// Clear the answer parts of answer_message, and set the rcode
// to servfail
void makeSERVFAIL() {
- isc::resolve::makeErrorMessage(answer_message_, Rcode::SERVFAIL());
+ if (answer_message_) {
+ isc::resolve::makeErrorMessage(answer_message_, Rcode::SERVFAIL());
+ }
}
};
-class ForwardQuery : public IOFetch::Callback {
+class ForwardQuery : public IOFetch::Callback, public AbstractRunningQuery {
private:
// The io service to handle async calls
IOService& io_;
@@ -999,6 +1000,8 @@ public:
send();
}
+ virtual ~ForwardQuery() {};
+
virtual void lookupTimeout() {
if (!callback_called_) {
makeSERVFAIL();
@@ -1076,7 +1079,7 @@ public:
}
-void
+AbstractRunningQuery*
RecursiveQuery::resolve(const QuestionPtr& question,
const isc::resolve::ResolverInterface::CallbackPtr callback)
{
@@ -1096,7 +1099,7 @@ RecursiveQuery::resolve(const QuestionPtr& question,
// Message found, return that
LOG_DEBUG(isc::resolve::logger, RESLIB_DBG_CACHE, RESLIB_RECQ_CACHE_FIND)
.arg(questionText(*question)).arg(1);
-
+
// TODO: err, should cache set rcode as well?
answer_message->setRcode(Rcode::NOERROR());
callback->success(answer_message);
@@ -1119,16 +1122,17 @@ RecursiveQuery::resolve(const QuestionPtr& question,
// delete itself when it is done
LOG_DEBUG(isc::resolve::logger, RESLIB_DBG_TRACE, RESLIB_RECQ_CACHE_NO_FIND)
.arg(questionText(*question)).arg(1);
- new RunningQuery(io, *question, answer_message,
- test_server_, buffer, callback,
- query_timeout_, client_timeout_,
- lookup_timeout_, retries_, nsas_,
- cache_, rtt_recorder_);
+ return (new RunningQuery(io, *question, answer_message,
+ test_server_, buffer, callback,
+ query_timeout_, client_timeout_,
+ lookup_timeout_, retries_, nsas_,
+ cache_, rtt_recorder_));
}
}
+ return (NULL);
}
-void
+AbstractRunningQuery*
RecursiveQuery::resolve(const Question& question,
MessagePtr answer_message,
OutputBufferPtr buffer,
@@ -1146,11 +1150,11 @@ RecursiveQuery::resolve(const Question& question,
// TODO: general 'prepareinitialanswer'
answer_message->setOpcode(isc::dns::Opcode::QUERY());
answer_message->addQuestion(question);
-
+
// First try to see if we have something cached in the messagecache
LOG_DEBUG(isc::resolve::logger, RESLIB_DBG_TRACE, RESLIB_RESOLVE)
.arg(questionText(question)).arg(2);
-
+
if (cache_.lookup(question.getName(), question.getType(),
question.getClass(), *answer_message) &&
answer_message->getRRCount(Message::SECTION_ANSWER) > 0) {
@@ -1181,15 +1185,16 @@ RecursiveQuery::resolve(const Question& question,
// delete itself when it is done
LOG_DEBUG(isc::resolve::logger, RESLIB_DBG_TRACE, RESLIB_RECQ_CACHE_NO_FIND)
.arg(questionText(question)).arg(2);
- new RunningQuery(io, question, answer_message,
- test_server_, buffer, crs, query_timeout_,
- client_timeout_, lookup_timeout_, retries_,
- nsas_, cache_, rtt_recorder_);
+ return (new RunningQuery(io, question, answer_message,
+ test_server_, buffer, crs, query_timeout_,
+ client_timeout_, lookup_timeout_, retries_,
+ nsas_, cache_, rtt_recorder_));
}
}
+ return (NULL);
}
-void
+AbstractRunningQuery*
RecursiveQuery::forward(ConstMessagePtr query_message,
MessagePtr answer_message,
OutputBufferPtr buffer,
@@ -1215,9 +1220,9 @@ RecursiveQuery::forward(ConstMessagePtr query_message,
// everything throught without interpretation, except
// QID, port number. The response will not be cached.
// It will delete itself when it is done
- new ForwardQuery(io, query_message, answer_message,
- upstream_, buffer, callback, query_timeout_,
- client_timeout_, lookup_timeout_);
+ return (new ForwardQuery(io, query_message, answer_message,
+ upstream_, buffer, callback, query_timeout_,
+ client_timeout_, lookup_timeout_));
}
} // namespace asiodns
diff --git a/src/lib/resolve/recursive_query.h b/src/lib/resolve/recursive_query.h
index a819a94..2875441 100644
--- a/src/lib/resolve/recursive_query.h
+++ b/src/lib/resolve/recursive_query.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RECURSIVE_QUERY_H
-#define __RECURSIVE_QUERY_H 1
+#ifndef RECURSIVE_QUERY_H
+#define RECURSIVE_QUERY_H 1
#include <util/buffer.h>
#include <asiodns/dns_service.h>
@@ -52,6 +52,26 @@ private:
std::vector<uint32_t> rtt_; ///< Stored round-trip times
};
+typedef std::vector<std::pair<std::string, uint16_t> > AddressVector;
+
+/// \brief A Running query
+///
+/// This base class represents an active running query object;
+/// i.e. an outstanding query to an authoritative name server or
+/// upstream server (when running in forwarder mode).
+///
+/// It can not be instantiated directly, but is created by
+/// RecursiveQuery::resolve() and RecursiveQuery::forward().
+///
+/// Its only public method is its destructor, and that should in theory
+/// not be called either except in some unit tests. Instances should
+/// delete themselves when the query is finished.
+class AbstractRunningQuery {
+protected:
+ AbstractRunningQuery() {};
+public:
+ virtual ~AbstractRunningQuery() {};
+};
/// \brief Recursive Query
///
@@ -126,8 +146,8 @@ public:
/// \param question The question being answered <qname/qclass/qtype>
/// \param callback Callback object. See
/// \c ResolverInterface::Callback for more information
- void resolve(const isc::dns::QuestionPtr& question,
- const isc::resolve::ResolverInterface::CallbackPtr callback);
+ AbstractRunningQuery* resolve(const isc::dns::QuestionPtr& question,
+ const isc::resolve::ResolverInterface::CallbackPtr callback);
/// \brief Initiates resolving for the given question.
@@ -142,10 +162,17 @@ public:
/// \param buffer An output buffer into which the intermediate responses will
/// be copied.
/// \param server A pointer to the \c DNSServer object handling the client
- void resolve(const isc::dns::Question& question,
- isc::dns::MessagePtr answer_message,
- isc::util::OutputBufferPtr buffer,
- DNSServer* server);
+ /// \return A pointer to the active AbstractRunningQuery object
+ /// created by this call (if any); this object should delete
+ /// itself in normal circumstances, and can normally be ignored
+ /// by the caller, but a pointer is returned for use-cases
+ /// such as unit tests.
+ /// Returns NULL if the data was found internally and no actual
+ /// query was sent.
+ AbstractRunningQuery* resolve(const isc::dns::Question& question,
+ isc::dns::MessagePtr answer_message,
+ isc::util::OutputBufferPtr buffer,
+ DNSServer* server);
/// \brief Initiates forwarding for the given query.
///
@@ -158,7 +185,11 @@ public:
/// \param server Server object that handles receipt and processing of the
/// received messages.
/// \param callback callback object
- void forward(isc::dns::ConstMessagePtr query_message,
+ /// \return A pointer to the active ForwardQuery created by this call;
+ /// this object should delete itself in normal circumstances,
+ /// and can normally be ignored by the caller, but a pointer
+ /// is returned for use-cases such as unit tests.
+ AbstractRunningQuery* forward(isc::dns::ConstMessagePtr query_message,
isc::dns::MessagePtr answer_message,
isc::util::OutputBufferPtr buffer,
DNSServer* server,
@@ -195,4 +226,4 @@ private:
} // namespace asiodns
} // namespace isc
-#endif // __RECURSIVE_QUERY_H
+#endif // RECURSIVE_QUERY_H
diff --git a/src/lib/resolve/resolve.h b/src/lib/resolve/resolve.h
index 0a588e2..c7ff195 100644
--- a/src/lib/resolve/resolve.h
+++ b/src/lib/resolve/resolve.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_RESOLVE_H
-#define _ISC_RESOLVE_H 1
+#ifndef ISC_RESOLVE_H
+#define ISC_RESOLVE_H 1
/// This file includes all other libresolve headers, and provides
/// several helper functions used in resolving.
diff --git a/src/lib/resolve/resolve_log.h b/src/lib/resolve/resolve_log.h
index 828b9d3..15a7a72 100644
--- a/src/lib/resolve/resolve_log.h
+++ b/src/lib/resolve/resolve_log.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RESOLVE_LOG__H
-#define __RESOLVE_LOG__H
+#ifndef RESOLVE_LOG_H
+#define RESOLVE_LOG_H
#include <log/macros.h>
#include "resolve_messages.h"
@@ -50,4 +50,4 @@ extern isc::log::Logger logger;
} // namespace resolve
} // namespace isc
-#endif // __RESOLVE_LOG__H
+#endif // RESOLVE_LOG_H
diff --git a/src/lib/resolve/resolver_callback.h b/src/lib/resolve/resolver_callback.h
index 79138e8..9a24501 100644
--- a/src/lib/resolve/resolver_callback.h
+++ b/src/lib/resolve/resolver_callback.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _ISC_RESOLVER_CALLBACK_H
-#define _ISC_RESOLVER_CALLBACK_H 1
+#ifndef ISC_RESOLVER_CALLBACK_H
+#define ISC_RESOLVER_CALLBACK_H 1
#include <asiodns/dns_server.h>
#include <dns/message.h>
diff --git a/src/lib/resolve/resolver_interface.h b/src/lib/resolve/resolver_interface.h
index 1d01e90..5002c80 100644
--- a/src/lib/resolve/resolver_interface.h
+++ b/src/lib/resolve/resolver_interface.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RESOLVER_INTERFACE_H
-#define __RESOLVER_INTERFACE_H
+#ifndef RESOLVER_INTERFACE_H
+#define RESOLVER_INTERFACE_H
#include <dns/message.h>
@@ -95,4 +95,4 @@ class ResolverInterface {
} // namespace nsas
} // namespace isc
-#endif //__RESOLVER_INTERFACE_H
+#endif //RESOLVER_INTERFACE_H
diff --git a/src/lib/resolve/response_classifier.h b/src/lib/resolve/response_classifier.h
index a027bd0..ce99bf0 100644
--- a/src/lib/resolve/response_classifier.h
+++ b/src/lib/resolve/response_classifier.h
@@ -14,8 +14,8 @@
// $Id$
-#ifndef __RESPONSE_CLASSIFIER_H
-#define __RESPONSE_CLASSIFIER_H
+#ifndef RESPONSE_CLASSIFIER_H
+#define RESPONSE_CLASSIFIER_H
#include <cstddef>
@@ -154,4 +154,4 @@ private:
} // namespace resolve
} // namespace isc
-#endif // __RESPONSE_CLASSIFIER_H
+#endif // RESPONSE_CLASSIFIER_H
diff --git a/src/lib/resolve/tests/recursive_query_unittest.cc b/src/lib/resolve/tests/recursive_query_unittest.cc
index 02721f1..e5e46e1 100644
--- a/src/lib/resolve/tests/recursive_query_unittest.cc
+++ b/src/lib/resolve/tests/recursive_query_unittest.cc
@@ -173,6 +173,9 @@ protected:
// It would delete itself, but after the io_service_, which could
// segfailt in case there were unhandled requests
resolver_.reset();
+ // In a similar note, we wait until the resolver has been cleaned up
+ // until deleting and active test running_query_
+ delete running_query_;
}
void SetUp() {
@@ -218,7 +221,7 @@ protected:
}
// Receive a UDP packet from a mock server; used for testing
- // recursive lookup. The caller must place a RecursiveQuery
+ // recursive lookup. The caller must place a RecursiveQuery
// on the IO Service queue before running this routine.
void recvUDP(const int family, void* buffer, size_t& size) {
ScopedAddrInfo sai(resolveAddress(family, IPPROTO_UDP, true));
@@ -267,7 +270,7 @@ protected:
if (ret < 0) {
isc_throw(IOError, "recvfrom failed: " << strerror(errno));
}
-
+
// Pass the message size back via the size parameter
size = ret;
}
@@ -507,11 +510,13 @@ protected:
vector<uint8_t> callback_data_;
ScopedSocket sock_;
boost::shared_ptr<isc::util::unittests::TestResolver> resolver_;
+ AbstractRunningQuery* running_query_;
};
RecursiveQueryTest::RecursiveQueryTest() :
dns_service_(NULL), callback_(NULL), callback_protocol_(0),
- callback_native_(-1), resolver_(new isc::util::unittests::TestResolver())
+ callback_native_(-1), resolver_(new isc::util::unittests::TestResolver()),
+ running_query_(NULL)
{
nsas_.reset(new isc::nsas::NameserverAddressStore(resolver_));
}
@@ -652,12 +657,12 @@ TEST_F(RecursiveQueryTest, forwarderSend) {
singleAddress(TEST_IPV4_ADDR, port));
Question q(Name("example.com"), RRClass::IN(), RRType::TXT());
- Message query_message(Message::RENDER);
- isc::resolve::initResponseMessage(q, query_message);
+ MessagePtr query_message(new Message(Message::RENDER));
+ isc::resolve::initResponseMessage(q, *query_message);
OutputBufferPtr buffer(new OutputBuffer(0));
MessagePtr answer(new Message(Message::RENDER));
- rq.forward(ConstMessagePtr(&query_message), answer, buffer, &server);
+ running_query_ = rq.forward(query_message, answer, buffer, &server);
char data[4096];
size_t size = sizeof(data);
@@ -693,37 +698,6 @@ createTestSocket() {
return (sock.release());
}
-int
-setSocketTimeout(int sock, size_t tv_sec, size_t tv_usec) {
- const struct timeval timeo = { tv_sec, tv_usec };
- int recv_options = 0;
- if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo))) {
- if (errno == ENOPROTOOPT) { // see RecursiveQueryTest::recvUDP()
- recv_options = MSG_DONTWAIT;
- } else {
- isc_throw(IOError, "set RCVTIMEO failed: " << strerror(errno));
- }
- }
- return (recv_options);
-}
-
-// try to read from the socket max time
-// *num is incremented for every succesfull read
-// returns true if it can read max times, false otherwise
-bool tryRead(int sock, int recv_options, size_t max, int* num) {
- size_t i = 0;
- do {
- char inbuff[512];
- if (recv(sock, inbuff, sizeof(inbuff), recv_options) < 0) {
- return false;
- } else {
- ++i;
- ++*num;
- }
- } while (i < max);
- return true;
-}
-
// Mock resolver callback for testing forward query.
class MockResolverCallback : public isc::resolve::ResolverInterface::Callback {
public:
@@ -780,11 +754,11 @@ TEST_F(RecursiveQueryTest, forwardQueryTimeout) {
Question question(Name("example.net"), RRClass::IN(), RRType::A());
OutputBufferPtr buffer(new OutputBuffer(0));
MessagePtr answer(new Message(Message::RENDER));
- Message query_message(Message::RENDER);
- isc::resolve::initResponseMessage(question, query_message);
+ MessagePtr query_message(new Message(Message::RENDER));
+ isc::resolve::initResponseMessage(question, *query_message);
boost::shared_ptr<MockResolverCallback> callback(new MockResolverCallback(&server));
- query.forward(ConstMessagePtr(&query_message), answer, buffer, &server, callback);
+ running_query_ = query.forward(query_message, answer, buffer, &server, callback);
// Run the test
io_service_.run();
EXPECT_EQ(callback->result, MockResolverCallback::FAILURE);
@@ -815,11 +789,11 @@ TEST_F(RecursiveQueryTest, forwardClientTimeout) {
1000, 10, 4000, 4);
Question q(Name("example.net"), RRClass::IN(), RRType::A());
OutputBufferPtr buffer(new OutputBuffer(0));
- Message query_message(Message::RENDER);
- isc::resolve::initResponseMessage(q, query_message);
+ MessagePtr query_message(new Message(Message::RENDER));
+ isc::resolve::initResponseMessage(q, *query_message);
boost::shared_ptr<MockResolverCallback> callback(new MockResolverCallback(&server));
- query.forward(ConstMessagePtr(&query_message), answer, buffer, &server, callback);
+ running_query_ = query.forward(query_message, answer, buffer, &server, callback);
// Run the test
io_service_.run();
EXPECT_EQ(callback->result, MockResolverCallback::FAILURE);
@@ -850,11 +824,12 @@ TEST_F(RecursiveQueryTest, forwardLookupTimeout) {
Question question(Name("example.net"), RRClass::IN(), RRType::A());
OutputBufferPtr buffer(new OutputBuffer(0));
- Message query_message(Message::RENDER);
- isc::resolve::initResponseMessage(question, query_message);
+ //Message query_message(Message::RENDER);
+ MessagePtr query_message(new Message(Message::RENDER));
+ isc::resolve::initResponseMessage(question, *query_message);
boost::shared_ptr<MockResolverCallback> callback(new MockResolverCallback(&server));
- query.forward(ConstMessagePtr(&query_message), answer, buffer, &server, callback);
+ running_query_ = query.forward(query_message, answer, buffer, &server, callback);
// Run the test
io_service_.run();
EXPECT_EQ(callback->result, MockResolverCallback::FAILURE);
@@ -885,11 +860,11 @@ TEST_F(RecursiveQueryTest, lowtimeouts) {
Question question(Name("example.net"), RRClass::IN(), RRType::A());
OutputBufferPtr buffer(new OutputBuffer(0));
- Message query_message(Message::RENDER);
- isc::resolve::initResponseMessage(question, query_message);
+ MessagePtr query_message(new Message(Message::RENDER));
+ isc::resolve::initResponseMessage(question, *query_message);
boost::shared_ptr<MockResolverCallback> callback(new MockResolverCallback(&server));
- query.forward(ConstMessagePtr(&query_message), answer, buffer, &server, callback);
+ running_query_ = query.forward(query_message, answer, buffer, &server, callback);
// Run the test
io_service_.run();
EXPECT_EQ(callback->result, MockResolverCallback::FAILURE);
@@ -904,7 +879,7 @@ TEST_F(RecursiveQueryTest, lowtimeouts) {
TEST_F(RecursiveQueryTest, DISABLED_recursiveSendOk) {
setDNSService(true, false);
bool done;
-
+
MockServerStop server(io_service_, &done);
vector<pair<string, uint16_t> > empty_vector;
RecursiveQuery rq(*dns_service_, *nsas_, cache_, empty_vector,
@@ -913,7 +888,7 @@ TEST_F(RecursiveQueryTest, DISABLED_recursiveSendOk) {
Question q(Name("www.isc.org"), RRClass::IN(), RRType::A());
OutputBufferPtr buffer(new OutputBuffer(0));
MessagePtr answer(new Message(Message::RENDER));
- rq.resolve(q, answer, buffer, &server);
+ running_query_ = rq.resolve(q, answer, buffer, &server);
io_service_.run();
// Check that the answer we got matches the one we wanted
@@ -930,7 +905,7 @@ TEST_F(RecursiveQueryTest, DISABLED_recursiveSendOk) {
TEST_F(RecursiveQueryTest, DISABLED_recursiveSendNXDOMAIN) {
setDNSService(true, false);
bool done;
-
+
MockServerStop server(io_service_, &done);
vector<pair<string, uint16_t> > empty_vector;
RecursiveQuery rq(*dns_service_, *nsas_, cache_, empty_vector,
@@ -939,7 +914,7 @@ TEST_F(RecursiveQueryTest, DISABLED_recursiveSendNXDOMAIN) {
Question q(Name("wwwdoesnotexist.isc.org"), RRClass::IN(), RRType::A());
OutputBufferPtr buffer(new OutputBuffer(0));
MessagePtr answer(new Message(Message::RENDER));
- rq.resolve(q, answer, buffer, &server);
+ running_query_ = rq.resolve(q, answer, buffer, &server);
io_service_.run();
// Check that the answer we got matches the one we wanted
@@ -1003,9 +978,9 @@ TEST_F(RecursiveQueryTest, CachedNS) {
// Prepare the recursive query
vector<pair<string, uint16_t> > roots;
roots.push_back(pair<string, uint16_t>("192.0.2.2", 53));
-
+ vector<pair<string, uint16_t> > upstream;
RecursiveQuery rq(*dns_service_, *nsas_, cache_,
- vector<pair<string, uint16_t> >(), roots);
+ upstream, roots);
// Ask a question at the bottom. It should not use the lower NS, because
// it would lead to a loop in NS. But it can use the nsUpper one, it has
// an IP address and we can avoid asking root.
@@ -1015,7 +990,7 @@ TEST_F(RecursiveQueryTest, CachedNS) {
MessagePtr answer(new Message(Message::RENDER));
// The server is here so we have something to pass there
MockServer server(io_service_);
- rq.resolve(q, answer, buffer, &server);
+ running_query_ = rq.resolve(q, answer, buffer, &server);
// We don't need to run the service in this test. We are interested only
// in the place it starts resolving at
diff --git a/src/lib/resolve/tests/recursive_query_unittest_2.cc b/src/lib/resolve/tests/recursive_query_unittest_2.cc
index 2b3d129..0b38c59 100644
--- a/src/lib/resolve/tests/recursive_query_unittest_2.cc
+++ b/src/lib/resolve/tests/recursive_query_unittest_2.cc
@@ -76,14 +76,17 @@ using namespace std;
/// directed to one or other of the "servers" in the RecursiveQueryTest2 class,
/// regardless of the glue returned in referrals.
+namespace {
+const char* const TEST_ADDRESS = "127.0.0.1"; ///< Servers are on this address
+const uint16_t TEST_PORT = 5301; ///< ... and this port
+const size_t BUFFER_SIZE = 1024; ///< For all buffers
+const char* const WWW_EXAMPLE_ORG = "192.0.2.254";
+ ///< Address of www.example.org
+} //end anonymous namespace
+
namespace isc {
namespace asiodns {
-const std::string TEST_ADDRESS = "127.0.0.1"; ///< Servers are on this address
-const uint16_t TEST_PORT = 5301; ///< ... and this port
-const size_t BUFFER_SIZE = 1024; ///< For all buffers
-const char* WWW_EXAMPLE_ORG = "192.0.2.254"; ///< Address of www.example.org
-
// As the test is fairly long and complex, debugging "print" statements have
// been left in although they are disabled. Set the following to "true" to
// enable them.
@@ -146,6 +149,12 @@ public:
OutputBufferPtr udp_send_buffer_; ///< Send buffer for UDP I/O
udp::socket udp_socket_; ///< Socket used by UDP server
+ /// Some of the tests cause an 'active' running query to be created, but
+ /// don't complete the framework that makes that query delete itself.
+ /// This member can be used to store it so that it is deleted automatically
+ /// when the test is finished.
+ AbstractRunningQuery* running_query_;
+
/// \brief Constructor
RecursiveQueryTest2() :
debug_(DEBUG_PRINT),
@@ -167,8 +176,18 @@ public:
udp_length_(0),
udp_receive_buffer_(),
udp_send_buffer_(new OutputBuffer(BUFFER_SIZE)),
- udp_socket_(service_.get_io_service(), udp::v4())
- {
+ udp_socket_(service_.get_io_service(), udp::v4()),
+ running_query_(NULL)
+ {}
+
+ ~RecursiveQueryTest2() {
+ // It would delete itself, but after the io_service_, which could
+ // segfailt in case there were unhandled requests
+ resolver_.reset();
+ // In a similar note, we wait until the resolver has been cleaned up
+ // until deleting and active test running_query_
+ delete running_query_;
+ delete nsas_;
}
/// \brief Set Common Message Bits
@@ -683,7 +702,7 @@ TEST_F(RecursiveQueryTest2, Resolve) {
// Kick off the resolution process. We expect the first question to go to
// "root".
expected_ = UDP_ROOT;
- query.resolve(question_, resolver_callback);
+ running_query_ = query.resolve(question_, resolver_callback);
service_.run();
// Check what ran. (We have to cast the callback to ResolverCallback as we
diff --git a/src/lib/resolve/tests/recursive_query_unittest_3.cc b/src/lib/resolve/tests/recursive_query_unittest_3.cc
index 168ec80..92ec589 100644
--- a/src/lib/resolve/tests/recursive_query_unittest_3.cc
+++ b/src/lib/resolve/tests/recursive_query_unittest_3.cc
@@ -69,15 +69,16 @@ using namespace std;
/// By using the "test_server_" element of RecursiveQuery, all queries are
/// directed to one or other of the "servers" in the RecursiveQueryTest3 class.
-namespace isc {
-namespace asiodns {
-
-const std::string TEST_ADDRESS3 = "127.0.0.1";
- ///< Servers are on this address
+namespace {
+const char* const TEST_ADDRESS3 = "127.0.0.1"; ///< Servers are on this address
const uint16_t TEST_PORT3 = 5303; ///< ... and this port
-const size_t BUFFER_SIZE = 1024; ///< For all buffers
+const size_t BUFFER_SIZE = 1024; ///< For all buffers
-const std::string DUMMY_ADDR3 = "1.2.3.4"; ///< address to return as A
+const char* const DUMMY_ADDR3 = "1.2.3.4"; ///< address to return as A
+} // end anonymous namespace
+
+namespace isc {
+namespace asiodns {
class MockResolver3 : public isc::resolve::ResolverInterface {
public:
@@ -131,6 +132,12 @@ public:
OutputBufferPtr udp_send_buffer_; ///< Send buffer for UDP I/O
udp::socket udp_socket_; ///< Socket used by UDP server
+ /// Some of the tests cause an 'active' running query to be created, but
+ /// don't complete the framework that makes that query delete itself.
+ /// This member can be used to store it so that it is deleted automatically
+ /// when the test is finished.
+ AbstractRunningQuery* running_query_;
+
/// \brief Constructor
RecursiveQueryTest3() :
service_(),
@@ -153,10 +160,21 @@ public:
udp_length_(0),
udp_receive_buffer_(),
udp_send_buffer_(new OutputBuffer(BUFFER_SIZE)),
- udp_socket_(service_.get_io_service(), udp::v4())
+ udp_socket_(service_.get_io_service(), udp::v4()),
+ running_query_(NULL)
{
}
+ ~RecursiveQueryTest3() {
+ delete nsas_;
+ // It would delete itself, but after the io_service_, which could
+ // segfailt in case there were unhandled requests
+ resolver_.reset();
+ // In a similar note, we wait until the resolver has been cleaned up
+ // until deleting and active test running_query_
+ delete running_query_;
+ }
+
/// \brief Set Common Message Bits
///
/// Sets up the common bits of a response message returned by the handlers.
@@ -541,7 +559,7 @@ TEST_F(RecursiveQueryTest3, Resolve) {
// Kick off the resolution process.
expected_ = EDNS_UDP;
- query.resolve(question_, resolver_callback);
+ running_query_ = query.resolve(question_, resolver_callback);
service_.run();
// Check what ran. (We have to cast the callback to ResolverCallback3 as we
diff --git a/src/lib/server_common/client.h b/src/lib/server_common/client.h
index 8cafb1e..912e7a6 100644
--- a/src/lib/server_common/client.h
+++ b/src/lib/server_common/client.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __CLIENT_H
-#define __CLIENT_H 1
+#ifndef CLIENT_H
+#define CLIENT_H 1
#include <string>
#include <ostream>
@@ -147,7 +147,7 @@ std::ostream& operator<<(std::ostream& os, const Client& client);
}
}
-#endif // __CLIENT_H
+#endif // CLIENT_H
// Local Variables:
// mode: c++
diff --git a/src/lib/server_common/logger.h b/src/lib/server_common/logger.h
index 80bc81d..5d565bf 100644
--- a/src/lib/server_common/logger.h
+++ b/src/lib/server_common/logger.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SERVER_COMMON_LOGGER_H
-#define __SERVER_COMMON_LOGGER_H
+#ifndef SERVER_COMMON_LOGGER_H
+#define SERVER_COMMON_LOGGER_H
#include <log/macros.h>
#include <server_common/server_common_messages.h>
diff --git a/src/lib/server_common/socket_request.h b/src/lib/server_common/socket_request.h
index aac95d1..b532153 100644
--- a/src/lib/server_common/socket_request.h
+++ b/src/lib/server_common/socket_request.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SOCKET_REQUEST_H
-#define __SOCKET_REQUEST_H 1
+#ifndef SOCKET_REQUEST_H
+#define SOCKET_REQUEST_H 1
#include <exceptions/exceptions.h>
@@ -275,4 +275,4 @@ void cleanupSocketRequestor();
}
}
-#endif // __SOCKET_REQUEST_H
+#endif // SOCKET_REQUEST_H
diff --git a/src/lib/server_common/tests/portconfig_unittest.cc b/src/lib/server_common/tests/portconfig_unittest.cc
index ac880c0..0c971ee 100644
--- a/src/lib/server_common/tests/portconfig_unittest.cc
+++ b/src/lib/server_common/tests/portconfig_unittest.cc
@@ -18,6 +18,7 @@
#include <testutils/socket_request.h>
#include <testutils/mockups.h>
+#include <util/unittests/check_valgrind.h>
#include <util/unittests/resource.h>
#include <cc/data.h>
@@ -311,44 +312,48 @@ typedef InstallListenAddresses InstallListenAddressesDeathTest;
// We make the socket requestor throw a "fatal" exception, one where we can't be
// sure the state between processes is consistent. So we abort in that case.
TEST_F(InstallListenAddressesDeathTest, inconsistent) {
- AddressList deathAddresses;
- deathAddresses.push_back(AddressPair("192.0.2.3", 5288));
- // Make sure it actually kills the application (there should be an abort
- // in this case)
- EXPECT_DEATH({
- isc::util::unittests::dontCreateCoreDumps();
+ if (!isc::util::unittests::runningOnValgrind()) {
+ AddressList deathAddresses;
+ deathAddresses.push_back(AddressPair("192.0.2.3", 5288));
+ // Make sure it actually kills the application (there should be an abort
+ // in this case)
+ EXPECT_DEATH({
+ isc::util::unittests::dontCreateCoreDumps();
- try {
- installListenAddresses(deathAddresses, store_, dnss_);
- } catch (...) {
- // Prevent exceptions killing the application, we need
- // to make sure it dies the real hard way
- };
- }, "");
+ try {
+ installListenAddresses(deathAddresses, store_, dnss_);
+ } catch (...) {
+ // Prevent exceptions killing the application, we need
+ // to make sure it dies the real hard way
+ };
+ }, "");
+ }
}
// If we are unable to tell the boss we closed a socket, we abort, as we are
// not consistent with the boss most probably.
TEST_F(InstallListenAddressesDeathTest, cantClose) {
- installListenAddresses(valid_, store_, dnss_);
- AddressList empty;
- // Instruct it to fail on close
- sock_requestor_.break_release_ = true;
- EXPECT_DEATH({
- isc::util::unittests::dontCreateCoreDumps();
+ if (!isc::util::unittests::runningOnValgrind()) {
+ installListenAddresses(valid_, store_, dnss_);
+ AddressList empty;
+ // Instruct it to fail on close
+ sock_requestor_.break_release_ = true;
+ EXPECT_DEATH({
+ isc::util::unittests::dontCreateCoreDumps();
- try {
- // Setting to empty will close all current sockets.
- // And thanks to the break_release_, the close will
- // throw, which will make it crash.
- installListenAddresses(empty, store_, dnss_);
- } catch (...) {
- // To make sure it is killed by abort, not by some
- // (unhandled) exception
- };
- }, "");
- // And reset it back, so it can safely clean up itself.
- sock_requestor_.break_release_ = false;
+ try {
+ // Setting to empty will close all current sockets.
+ // And thanks to the break_release_, the close will
+ // throw, which will make it crash.
+ installListenAddresses(empty, store_, dnss_);
+ } catch (...) {
+ // To make sure it is killed by abort, not by some
+ // (unhandled) exception
+ };
+ }, "");
+ // And reset it back, so it can safely clean up itself.
+ sock_requestor_.break_release_ = false;
+ }
}
#endif // EXPECT_DEATH
diff --git a/src/lib/server_common/tests/socket_requestor_test.cc b/src/lib/server_common/tests/socket_requestor_test.cc
index 9878c63..ac1731f 100644
--- a/src/lib/server_common/tests/socket_requestor_test.cc
+++ b/src/lib/server_common/tests/socket_requestor_test.cc
@@ -410,7 +410,8 @@ private:
isc_throw(Unexpected,
"mkstemp() created a filename too long for sun_path");
}
- strncpy(socket_address.sun_path, path_, len);
+ strncpy(socket_address.sun_path, path_,
+ sizeof(socket_address.sun_path));
#ifdef HAVE_SA_LEN
socket_address.sun_len = len;
#endif
@@ -542,7 +543,6 @@ TEST_F(SocketRequestorTest, testSocketPassing) {
EXPECT_EQ("foo", socket_id.second);
EXPECT_EQ(0, close(socket_id.first));
}
-
// Create a second socket server, to test that multiple different
// domains sockets would work as well (even though we don't actually
// use that feature)
diff --git a/src/lib/statistics/counter.h b/src/lib/statistics/counter.h
index a5a1a1d..af52da4 100644
--- a/src/lib/statistics/counter.h
+++ b/src/lib/statistics/counter.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __COUNTER_H
-#define __COUNTER_H 1
+#ifndef COUNTER_H
+#define COUNTER_H 1
#include <exceptions/exceptions.h>
diff --git a/src/lib/statistics/counter_dict.h b/src/lib/statistics/counter_dict.h
index 863c0fb..e288dfe 100644
--- a/src/lib/statistics/counter_dict.h
+++ b/src/lib/statistics/counter_dict.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __COUNTER_DICT_H
-#define __COUNTER_DICT_H 1
+#ifndef COUNTER_DICT_H
+#define COUNTER_DICT_H 1
#include <statistics/counter.h>
#include <exceptions/exceptions.h>
diff --git a/src/lib/testutils/dnsmessage_test.h b/src/lib/testutils/dnsmessage_test.h
index fd1d51a..262d177 100644
--- a/src/lib/testutils/dnsmessage_test.h
+++ b/src/lib/testutils/dnsmessage_test.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ISC_TESTUTILS_DNSMESSAGETEST_H
-#define __ISC_TESTUTILS_DNSMESSAGETEST_H 1
+#ifndef ISC_TESTUTILS_DNSMESSAGETEST_H
+#define ISC_TESTUTILS_DNSMESSAGETEST_H 1
#include <algorithm>
#include <functional>
@@ -160,22 +160,6 @@ public:
private:
std::vector<isc::dns::ConstRRsetPtr>& rrsets_;
};
-
-class RRsetDumper {
-public:
- RRsetDumper(std::string& output) :
- output_(output)
- {}
- void operator()(isc::dns::ConstRRsetPtr rrset) {
- output_ += " " + rrset->toText();
-
- if (rrset->getRRsig()) {
- output_ += " " + rrset->getRRsig()->toText();
- }
- }
-private:
- std::string& output_;
-};
}
/// \brief A converter from a string to RRset.
@@ -201,6 +185,37 @@ isc::dns::RRsetPtr textToRRset(const std::string& text_rrset,
const isc::dns::Name& origin =
isc::dns::Name::ROOT_NAME());
+/// \brief Pull out signatures and convert to text
+///
+/// This is a helper function for rrsetsCheck.
+///
+/// It adds all the rrsets to the given vector. It also adds the
+/// signatures of those rrsets as separate rrsets into the vector
+/// (but does not modify the original rrset; i.e. technically the
+/// signatures are in the resulting vector twice).
+///
+/// Additionally, it adds the string representation of all rrsets
+/// and their signatures to the given string (for use in scoped_trace).
+///
+/// \param rrsets A vector to add the rrsets and signatures to
+/// \param text A string to add the rrsets string representations to
+/// \param begin The beginning of the rrsets iterator
+/// \param end The end of the rrsets iterator
+template <typename ITERATOR>
+void
+pullSigs(std::vector<isc::dns::ConstRRsetPtr>& rrsets,
+ std::string& text, ITERATOR begin, ITERATOR end)
+{
+ for (ITERATOR it = begin; it != end; ++it) {
+ rrsets.push_back(*it);
+ text += (*it)->toText();
+ if ((*it)->getRRsig()) {
+ rrsets.push_back((*it)->getRRsig());
+ text += (*it)->getRRsig()->toText();
+ }
+ }
+}
+
/// Set of unit tests to check if two sets of RRsets are identical.
///
/// This templated function takes two sets of sequences, each defined by
@@ -236,55 +251,50 @@ void
rrsetsCheck(EXPECTED_ITERATOR expected_begin, EXPECTED_ITERATOR expected_end,
ACTUAL_ITERATOR actual_begin, ACTUAL_ITERATOR actual_end)
{
- std::vector<isc::dns::ConstRRsetPtr> checked_rrsets; // for duplicate check
+ // Iterators can have their RRsig sets as separate RRsets,
+ // or they can have them attached to the RRset they cover.
+ // For ease of use of this method, we first flatten out both
+ // iterators, and pull out the signature sets, and add them as
+ // separate RRsets (rrsetCheck() later does not check signatures
+ // attached to rrsets)
+ std::vector<isc::dns::ConstRRsetPtr> expected_rrsets, actual_rrsets;
std::string expected_text, actual_text;
- std::for_each(expected_begin, expected_end,
- detail::RRsetDumper(expected_text));
- std::for_each(actual_begin, actual_end, detail::RRsetDumper(actual_text));
- unsigned int rrset_matched = 0;
- ACTUAL_ITERATOR it;
- for (it = actual_begin; it != actual_end; ++it) {
+
+ pullSigs(expected_rrsets, expected_text, expected_begin, expected_end);
+ pullSigs(actual_rrsets, actual_text, actual_begin, actual_end);
+
+ SCOPED_TRACE(std::string("Comparing two RRset lists:\n") +
+ "Actual:\n" + actual_text +
+ "Expected:\n" + expected_text);
+
+ // The vectors should have the same number of sets
+ ASSERT_EQ(expected_rrsets.size(), actual_rrsets.size());
+
+ // Now we check if all RRsets from the actual_rrsets are in
+ // expected_rrsets, and that actual_rrsets has no duplicates.
+ std::vector<isc::dns::ConstRRsetPtr> checked_rrsets; // for duplicate check
+
+ std::vector<isc::dns::ConstRRsetPtr>::const_iterator it;
+ for (it = actual_rrsets.begin(); it != actual_rrsets.end(); ++it) {
// Make sure there's no duplicate RRset in actual (using a naive
- // search). Since the actual set is guaranteed to be unique, we can
- // detect it if the expected data has a duplicate by the match/size
- // checks at the end of the function.
+ // search). By guaranteeing the actual set is unique, and the
+ // size of both vectors is the same, we can conclude that
+ // the two sets are identical after this loop.
// Note: we cannot use EXPECT_EQ for iterators
EXPECT_TRUE(checked_rrsets.end() ==
std::find_if(checked_rrsets.begin(), checked_rrsets.end(),
detail::RRsetMatch(*it)));
checked_rrsets.push_back(*it);
- EXPECTED_ITERATOR found_rrset_it =
- std::find_if(expected_begin, expected_end,
+ std::vector<isc::dns::ConstRRsetPtr>::const_iterator found_rrset_it =
+ std::find_if(expected_rrsets.begin(), expected_rrsets.end(),
detail::RRsetMatch(*it));
- if (found_rrset_it != expected_end) {
+ if (found_rrset_it != expected_rrsets.end()) {
rrsetCheck(*found_rrset_it, *it);
- ++rrset_matched;
- rrset_matched += (*it)->getRRsigDataCount();
+ } else {
+ FAIL() << (*it)->toText() << " not found in expected rrsets";
}
}
-
- {
- SCOPED_TRACE(std::string("Comparing two RRsets:\n") +
- "Actual:\n" + actual_text +
- "Expected:\n" + expected_text);
- // make sure all expected RRsets are in actual sets
- EXPECT_EQ(std::distance(expected_begin, expected_end), rrset_matched);
-
-#if (0)
- // TODO: see bug #2223. The following code was
- // disabled by #2165. The RRSIG RRsets are no longer directly
- // stored in the Message's rrsets, so the iterator will not find
- // them. The expected text used in many tests are flattened,
- // where the RRSIGs are inline. In other words, RRSIGs may occur
- // between (expected_begin, expected_end) but not between
- // (actual_begin, actual_end).
-
- // make sure rrsets only contains expected RRsets
- EXPECT_EQ(std::distance(expected_begin, expected_end),
- std::distance(actual_begin, actual_end));
-#endif
- }
}
/// Set of unit tests to check if two sets of RRsets are identical using
@@ -381,7 +391,7 @@ rrsetsCheck(const std::string& expected,
} // end of namespace testutils
} // end of namespace isc
-#endif // __ISC_TESTUTILS_DNSMESSAGETEST_H
+#endif // ISC_TESTUTILS_DNSMESSAGETEST_H
// Local Variables:
// mode: c++
diff --git a/src/lib/testutils/mockups.h b/src/lib/testutils/mockups.h
index 3028d7f..fc8a2e0 100644
--- a/src/lib/testutils/mockups.h
+++ b/src/lib/testutils/mockups.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ISC_TESTUTILS_MOCKUPS_H
-#define __ISC_TESTUTILS_MOCKUPS_H 1
+#ifndef ISC_TESTUTILS_MOCKUPS_H
+#define ISC_TESTUTILS_MOCKUPS_H 1
#include <config.h>
@@ -210,7 +210,7 @@ private:
} // end of testutils
} // end of isc
-#endif // __ISC_TESTUTILS_MOCKUPS_H
+#endif // ISC_TESTUTILS_MOCKUPS_H
// Local Variables:
// mode: c++
diff --git a/src/lib/testutils/portconfig.h b/src/lib/testutils/portconfig.h
index ce1bb39..8e8cab1 100644
--- a/src/lib/testutils/portconfig.h
+++ b/src/lib/testutils/portconfig.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ISC_TESTUTILS_PORTCONFIG_H
-#define __ISC_TESTUTILS_PORTCONFIG_H
+#ifndef ISC_TESTUTILS_PORTCONFIG_H
+#define ISC_TESTUTILS_PORTCONFIG_H
#include <gtest/gtest.h>
#include <cc/data.h>
@@ -186,4 +186,4 @@ invalidListenAddressConfig(Server& server) {
}
}
-#endif // __ISC_TESTUTILS_PORTCONFIG_H
+#endif // ISC_TESTUTILS_PORTCONFIG_H
diff --git a/src/lib/testutils/socket_request.h b/src/lib/testutils/socket_request.h
index 0ae15f3..d511401 100644
--- a/src/lib/testutils/socket_request.h
+++ b/src/lib/testutils/socket_request.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ISC_TESTUTILS_SOCKETREQUEST_H
-#define __ISC_TESTUTILS_SOCKETREQUEST_H 1
+#ifndef ISC_TESTUTILS_SOCKETREQUEST_H
+#define ISC_TESTUTILS_SOCKETREQUEST_H 1
#include <server_common/socket_request.h>
#include <server_common/portconfig.h>
@@ -216,4 +216,4 @@ private:
}
}
-#endif // __ISC_TESTUTILS_SOCKETREQUEST_H
+#endif // ISC_TESTUTILS_SOCKETREQUEST_H
diff --git a/src/lib/testutils/srv_test.h b/src/lib/testutils/srv_test.h
index a5c516e..e867595 100644
--- a/src/lib/testutils/srv_test.h
+++ b/src/lib/testutils/srv_test.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __ISC_TESTUTILS_SRVTEST_H
-#define __ISC_TESTUTILS_SRVTEST_H 1
+#ifndef ISC_TESTUTILS_SRVTEST_H
+#define ISC_TESTUTILS_SRVTEST_H 1
#include <util/buffer.h>
#include <dns/name.h>
@@ -112,7 +112,7 @@ protected:
};
} // end of namespace testutils
} // end of namespace isc
-#endif // __ISC_TESTUTILS_SRVTEST_H
+#endif // ISC_TESTUTILS_SRVTEST_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/Makefile.am b/src/lib/util/Makefile.am
index c56e4b8..13f8f7b 100644
--- a/src/lib/util/Makefile.am
+++ b/src/lib/util/Makefile.am
@@ -1,4 +1,4 @@
-SUBDIRS = . io unittests tests pyunittests python
+SUBDIRS = . io unittests tests pyunittests python threads
AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
AM_CPPFLAGS += -I$(top_srcdir)/src/lib/util -I$(top_builddir)/src/lib/util
@@ -33,3 +33,6 @@ EXTRA_DIST = python/pycppwrapper_util.h
libb10_util_la_LIBADD = $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
CLEANFILES = *.gcno *.gcda
+
+libb10_util_includedir = $(includedir)/$(PACKAGE_NAME)/util
+libb10_util_include_HEADERS = buffer.h
diff --git a/src/lib/util/buffer.h b/src/lib/util/buffer.h
index 7e88108..4800e99 100644
--- a/src/lib/util/buffer.h
+++ b/src/lib/util/buffer.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __BUFFER_H
-#define __BUFFER_H 1
+#ifndef BUFFER_H
+#define BUFFER_H 1
#include <stdlib.h>
#include <cstring>
@@ -535,7 +535,7 @@ typedef boost::shared_ptr<OutputBuffer> OutputBufferPtr;
} // namespace util
} // namespace isc
-#endif // __BUFFER_H
+#endif // BUFFER_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/encode/base32hex.h b/src/lib/util/encode/base32hex.h
index d7129d7..83fd0d3 100644
--- a/src/lib/util/encode/base32hex.h
+++ b/src/lib/util/encode/base32hex.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __BASE32HEX_H
-#define __BASE32HEX_H 1
+#ifndef BASE32HEX_H
+#define BASE32HEX_H 1
#include <stdint.h>
#include <string>
@@ -57,7 +57,7 @@ void decodeBase32Hex(const std::string& input, std::vector<uint8_t>& result);
} // namespace util
} // namespace isc
-#endif // __BASE32HEX_H
+#endif // BASE32HEX_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/encode/base64.h b/src/lib/util/encode/base64.h
index 6b1b346..1c7c74d 100644
--- a/src/lib/util/encode/base64.h
+++ b/src/lib/util/encode/base64.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __BASE64_H
-#define __BASE64_H 1
+#ifndef BASE64_H
+#define BASE64_H 1
#include <stdint.h>
#include <string>
@@ -72,7 +72,7 @@ void decodeBase64(const std::string& input, std::vector<uint8_t>& result);
} // namespace util
} // namespace isc
-#endif // __BASE64_H
+#endif // BASE64_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/encode/hex.h b/src/lib/util/encode/hex.h
index 5c806fc..32b5071 100644
--- a/src/lib/util/encode/hex.h
+++ b/src/lib/util/encode/hex.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __HEX_H
-#define __HEX_H 1
+#ifndef HEX_H
+#define HEX_H 1
#include <stdint.h>
#include <string>
@@ -58,7 +58,7 @@ void decodeHex(const std::string& input, std::vector<uint8_t>& result);
} // namespace util
} // namespace isc
-#endif // __HEX_H
+#endif // HEX_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/filename.h b/src/lib/util/filename.h
index f625938..a4ba47c 100644
--- a/src/lib/util/filename.h
+++ b/src/lib/util/filename.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __FILENAME_H
-#define __FILENAME_H
+#ifndef FILENAME_H
+#define FILENAME_H
#include <string>
@@ -170,4 +170,4 @@ private:
} // namespace util
} // namespace isc
-#endif // __FILENAME_H
+#endif // FILENAME_H
diff --git a/src/lib/util/hash/sha1.cc b/src/lib/util/hash/sha1.cc
index 091e293..1fdadfd 100644
--- a/src/lib/util/hash/sha1.cc
+++ b/src/lib/util/hash/sha1.cc
@@ -48,7 +48,7 @@
* merchantability of this software or the suitability of this
* software for any particular purpose. It is provided "as is"
* without express or implied warranty of any kind.
- *
+ *
*/
#include <util/hash/sha1.h>
@@ -79,7 +79,7 @@ SHA_Parity(const uint32_t x, const uint32_t y, const uint32_t z) {
return ((x) ^ (y) ^ (z));
}
-static inline int
+static inline int
SHA1CircularShift(uint8_t bits, uint32_t word) {
return ((word << bits) | (word >> (32 - bits)));
}
diff --git a/src/lib/util/hash/sha1.h b/src/lib/util/hash/sha1.h
index 6089ca8..165d93f 100644
--- a/src/lib/util/hash/sha1.h
+++ b/src/lib/util/hash/sha1.h
@@ -30,8 +30,8 @@
* without express or implied warranty of any kind.
*/
-#ifndef _SHA1_H_
-#define _SHA1_H_
+#ifndef SHA1_H
+#define SHA1_H
#include <stdint.h>
diff --git a/src/lib/util/interprocess_sync.h b/src/lib/util/interprocess_sync.h
index e4fa7af..f55f0ac 100644
--- a/src/lib/util/interprocess_sync.h
+++ b/src/lib/util/interprocess_sync.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __INTERPROCESS_SYNC_H__
-#define __INTERPROCESS_SYNC_H__
+#ifndef INTERPROCESS_SYNC_H
+#define INTERPROCESS_SYNC_H
#include <string>
@@ -146,4 +146,4 @@ protected:
} // namespace util
} // namespace isc
-#endif // __INTERPROCESS_SYNC_H__
+#endif // INTERPROCESS_SYNC_H
diff --git a/src/lib/util/interprocess_sync_file.h b/src/lib/util/interprocess_sync_file.h
index fd8da1b..153b391 100644
--- a/src/lib/util/interprocess_sync_file.h
+++ b/src/lib/util/interprocess_sync_file.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __INTERPROCESS_SYNC_FILE_H__
-#define __INTERPROCESS_SYNC_FILE_H__
+#ifndef INTERPROCESS_SYNC_FILE_H
+#define INTERPROCESS_SYNC_FILE_H
#include <util/interprocess_sync.h>
#include <exceptions/exceptions.h>
@@ -88,4 +88,4 @@ private:
} // namespace util
} // namespace isc
-#endif // __INTERPROCESS_SYNC_FILE_H__
+#endif // INTERPROCESS_SYNC_FILE_H
diff --git a/src/lib/util/interprocess_sync_null.h b/src/lib/util/interprocess_sync_null.h
index 6ac0322..be77514 100644
--- a/src/lib/util/interprocess_sync_null.h
+++ b/src/lib/util/interprocess_sync_null.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __INTERPROCESS_SYNC_NULL_H__
-#define __INTERPROCESS_SYNC_NULL_H__
+#ifndef INTERPROCESS_SYNC_NULL_H
+#define INTERPROCESS_SYNC_NULL_H
#include <util/interprocess_sync.h>
@@ -61,4 +61,4 @@ protected:
} // namespace util
} // namespace isc
-#endif // __INTERPROCESS_SYNC_NULL_H__
+#endif // INTERPROCESS_SYNC_NULL_H
diff --git a/src/lib/util/io/fd.h b/src/lib/util/io/fd.h
index bdd2d41..e90e16e 100644
--- a/src/lib/util/io/fd.h
+++ b/src/lib/util/io/fd.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_IO_FD_H
-#define __UTIL_IO_FD_H 1
+#ifndef UTIL_IO_FD_H
+#define UTIL_IO_FD_H 1
#include <unistd.h>
@@ -58,4 +58,4 @@ read_data(const int fd, void *buffer, const size_t length);
}
}
-#endif // __UTIL_IO_FD_H
+#endif // UTIL_IO_FD_H
diff --git a/src/lib/util/io/fd_share.cc b/src/lib/util/io/fd_share.cc
index 7adbbbe..8666441 100644
--- a/src/lib/util/io/fd_share.cc
+++ b/src/lib/util/io/fd_share.cc
@@ -142,6 +142,7 @@ send_fd(const int sock, const int fd) {
if (msghdr.msg_control == NULL) {
return (FD_OTHER_ERROR);
}
+ std::memset(msghdr.msg_control, 0, msghdr.msg_controllen);
struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msghdr);
cmsg->cmsg_len = cmsg_len(sizeof(int));
diff --git a/src/lib/util/io/pktinfo_utilities.h b/src/lib/util/io/pktinfo_utilities.h
index 9883c30..74dc37d 100644
--- a/src/lib/util/io/pktinfo_utilities.h
+++ b/src/lib/util/io/pktinfo_utilities.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PKTINFO_UTIL_H_
-#define __PKTINFO_UTIL_H_ 1
+#ifndef PKTINFO_UTIL_H
+#define PKTINFO_UTIL_H 1
#include <sys/socket.h>
#include <netinet/in.h>
@@ -48,4 +48,4 @@ convertPktInfo6(unsigned char* pktinfo) {
}
}
-#endif // __PKTINFO_UTIL_H_
+#endif // PKTINFO_UTIL_H
diff --git a/src/lib/util/io/sockaddr_util.h b/src/lib/util/io/sockaddr_util.h
index 0cd7c7b..847a0cb 100644
--- a/src/lib/util/io/sockaddr_util.h
+++ b/src/lib/util/io/sockaddr_util.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SOCKADDR_UTIL_H_
-#define __SOCKADDR_UTIL_H_ 1
+#ifndef SOCKADDR_UTIL_H
+#define SOCKADDR_UTIL_H 1
#include <sys/types.h>
#include <sys/socket.h>
@@ -77,7 +77,7 @@ convertSockAddr(struct sockaddr* sa) {
}
}
-#endif // __SOCKADDR_UTIL_H_
+#endif // SOCKADDR_UTIL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/io/socketsession.h b/src/lib/util/io/socketsession.h
index 48b7f19..023ef8e 100644
--- a/src/lib/util/io/socketsession.h
+++ b/src/lib/util/io/socketsession.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SOCKETSESSION_H_
-#define __SOCKETSESSION_H_ 1
+#ifndef SOCKETSESSION_H
+#define SOCKETSESSION_H 1
#include <boost/noncopyable.hpp>
@@ -492,7 +492,7 @@ private:
}
}
-#endif // __SOCKETSESSION_H_
+#endif // SOCKETSESSION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/io_utilities.h b/src/lib/util/io_utilities.h
index 61d4c9c..cd35364 100644
--- a/src/lib/util/io_utilities.h
+++ b/src/lib/util/io_utilities.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __IO_UTILITIES_H
-#define __IO_UTILITIES_H
+#ifndef IO_UTILITIES_H
+#define IO_UTILITIES_H
#include <cstddef>
@@ -101,4 +101,4 @@ writeUint32(uint32_t value, uint8_t* buffer) {
} // namespace util
} // namespace isc
-#endif // __ASIOLINK_UTILITIES_H
+#endif // IO_UTILITIES_H
diff --git a/src/lib/util/locks.h b/src/lib/util/locks.h
index da9e9cd..34296f2 100644
--- a/src/lib/util/locks.h
+++ b/src/lib/util/locks.h
@@ -23,8 +23,8 @@
/// to be set. we might want to enfore this at compile time with a check
/// (TODO)
-#ifndef __LOCKS_
-#define __LOCKS_
+#ifndef LOCKS
+#define LOCKS
namespace isc {
namespace util {
@@ -42,13 +42,17 @@ class upgradable_mutex {
template <typename T>
class sharable_lock {
public:
- sharable_lock(T) { }
+ sharable_lock(T) {}
};
template <typename T>
class scoped_lock {
public:
- scoped_lock(T) { }
+ scoped_lock(T) {}
+
+ // We need to define this explicitly. Some versions of clang++ would
+ // complain about this otherwise. See Trac ticket #2340
+ ~scoped_lock() {}
void lock() {}
void unlock() {}
@@ -58,4 +62,4 @@ public:
} // namespace util
} // namespace isc
-#endif // __LOCKS_
+#endif // LOCKS
diff --git a/src/lib/util/lru_list.h b/src/lib/util/lru_list.h
index 797c3c9..e5db869 100644
--- a/src/lib/util/lru_list.h
+++ b/src/lib/util/lru_list.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LRU_LIST_H
-#define __LRU_LIST_H
+#ifndef LRU_LIST_H
+#define LRU_LIST_H
#include <list>
#include <string>
@@ -257,4 +257,4 @@ void LruList<T>::clear() {
} // namespace util
} // namespace isc
-#endif // __LRU_LIST_H
+#endif // LRU_LIST_H
diff --git a/src/lib/util/memory_segment.h b/src/lib/util/memory_segment.h
index 97d2e02..664bd3c 100644
--- a/src/lib/util/memory_segment.h
+++ b/src/lib/util/memory_segment.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MEMORY_SEGMENT_H__
-#define __MEMORY_SEGMENT_H__
+#ifndef MEMORY_SEGMENT_H
+#define MEMORY_SEGMENT_H
#include <stdlib.h>
@@ -66,4 +66,4 @@ public:
} // namespace util
} // namespace isc
-#endif // __MEMORY_SEGMENT_H__
+#endif // MEMORY_SEGMENT_H
diff --git a/src/lib/util/memory_segment_local.h b/src/lib/util/memory_segment_local.h
index 5e43e53..de35b87 100644
--- a/src/lib/util/memory_segment_local.h
+++ b/src/lib/util/memory_segment_local.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __MEMORY_SEGMENT_LOCAL_H__
-#define __MEMORY_SEGMENT_LOCAL_H__
+#ifndef MEMORY_SEGMENT_LOCAL_H
+#define MEMORY_SEGMENT_LOCAL_H
#include <util/memory_segment.h>
@@ -73,4 +73,4 @@ private:
} // namespace util
} // namespace isc
-#endif // __MEMORY_SEGMENT_LOCAL_H__
+#endif // MEMORY_SEGMENT_LOCAL_H
diff --git a/src/lib/util/python/pycppwrapper_util.h b/src/lib/util/python/pycppwrapper_util.h
index 462e715..31041ba 100644
--- a/src/lib/util/python/pycppwrapper_util.h
+++ b/src/lib/util/python/pycppwrapper_util.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYCPPWRAPPER_UTIL_H
-#define __PYCPPWRAPPER_UTIL_H 1
+#ifndef PYCPPWRAPPER_UTIL_H
+#define PYCPPWRAPPER_UTIL_H 1
#include <Python.h>
@@ -328,7 +328,7 @@ installClassVariable(PyTypeObject& pyclass, const char* name, PyObject* obj) {
} // namespace python
} // namespace util
} // namespace isc
-#endif // __PYCPPWRAPPER_UTIL_H
+#endif // PYCPPWRAPPER_UTIL_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/python/wrapper_template.h b/src/lib/util/python/wrapper_template.h
index be701e1..787a296 100644
--- a/src/lib/util/python/wrapper_template.h
+++ b/src/lib/util/python/wrapper_template.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PYTHON_ at CPPCLASS@_H
-#define __PYTHON_ at CPPCLASS@_H 1
+#ifndef PYTHON_ at CPPCLASS@_H
+#define PYTHON_ at CPPCLASS@_H 1
#include <Python.h>
@@ -52,7 +52,7 @@ PyObject* create at CPPCLASS@Object(const @CPPCLASS@& source);
} // namespace python
} // namespace @MODULE@
} // namespace isc
-#endif // __PYTHON_ at CPPCLASS@_H
+#endif // PYTHON_ at CPPCLASS@_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/random/qid_gen.h b/src/lib/util/random/qid_gen.h
index 1af43c1..80f532f 100644
--- a/src/lib/util/random/qid_gen.h
+++ b/src/lib/util/random/qid_gen.h
@@ -18,8 +18,8 @@
// (and other parts where we need randomness, perhaps another thing
// for a general libutil?)
-#ifndef __QID_GEN_H
-#define __QID_GEN_H
+#ifndef QID_GEN_H
+#define QID_GEN_H
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
@@ -84,4 +84,4 @@ private:
} // namespace util
} // namespace isc
-#endif // __QID_GEN_H
+#endif // QID_GEN_H
diff --git a/src/lib/util/random/random_number_generator.h b/src/lib/util/random/random_number_generator.h
index 485ea7a..f0c0fb3 100644
--- a/src/lib/util/random/random_number_generator.h
+++ b/src/lib/util/random/random_number_generator.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __NSAS_RANDOM_NUMBER_GENERATOR_H
-#define __NSAS_RANDOM_NUMBER_GENERATOR_H
+#ifndef NSAS_RANDOM_NUMBER_GENERATOR_H
+#define NSAS_RANDOM_NUMBER_GENERATOR_H
#include <algorithm>
#include <cmath>
@@ -205,4 +205,4 @@ private:
} // namespace util
} // namespace isc
-#endif//__NSAS_RANDOM_NUMBER_GENERATOR_H
+#endif//NSAS_RANDOM_NUMBER_GENERATOR_H
diff --git a/src/lib/util/range_utilities.h b/src/lib/util/range_utilities.h
index 3f8b971..4d5b0bb 100644
--- a/src/lib/util/range_utilities.h
+++ b/src/lib/util/range_utilities.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __RANGE_UTIL_H_
-#define __RANGE_UTIL_H_ 1
+#ifndef RANGE_UTIL_H
+#define RANGE_UTIL_H 1
#include <stdlib.h>
#include <algorithm>
@@ -41,16 +41,17 @@ isRangeZero(Iterator begin, Iterator end) {
/// @brief Fill in specified range with a random data.
///
-/// Make sure that random number generator is initialized properly. Otherwise you
-/// will get a the same pseudo-random sequence after every start of your process.
-/// Calling srand() is enough. This method uses default rand(), which is usually
-/// a LCG pseudo-random number generator, so it is not suitable for security
-/// purposes. Please get a decent PRNG implementation, like mersene twister, if
-/// you are doing anything related with security.
+/// Make sure that random number generator is initialized
+/// properly. Otherwise you will get a the same pseudo-random sequence
+/// after every start of your process. Calling srand() is enough. This
+/// method uses default rand(), which is usually a LCG pseudo-random
+/// number generator, so it is not suitable for security
+/// purposes. Please get a decent PRNG implementation, like mersene
+/// twister, if you are doing anything related with security.
///
-/// PRNG initialization is left out of this function on purpose. It may be
-/// initialized to specific value on purpose, e.g. to repeat exactly the same
-/// sequence in a test.
+/// PRNG initialization is left out of this function on purpose. It may
+/// be initialized to specific value on purpose, e.g. to repeat exactly
+/// the same sequence in a test.
///
/// @param begin
/// @param end
@@ -65,4 +66,4 @@ fillRandom(Iterator begin, Iterator end) {
} // end of isc::util namespace
} // end of isc namespace
-#endif // __PKTINFO_UTIL_H_
+#endif // RANGE_UTIL_H
diff --git a/src/lib/util/strutil.h b/src/lib/util/strutil.h
index 0dbbe96..6b60009 100644
--- a/src/lib/util/strutil.h
+++ b/src/lib/util/strutil.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __STRUTIL_H
-#define __STRUTIL_H
+#ifndef STRUTIL_H
+#define STRUTIL_H
#include <algorithm>
#include <cctype>
@@ -206,4 +206,4 @@ tokenToNum(const std::string& num_token) {
} // namespace util
} // namespace isc
-#endif // __STRUTIL_H
+#endif // STRUTIL_H
diff --git a/src/lib/util/tests/buffer_unittest.cc b/src/lib/util/tests/buffer_unittest.cc
index 9af3d57..02ca83d 100644
--- a/src/lib/util/tests/buffer_unittest.cc
+++ b/src/lib/util/tests/buffer_unittest.cc
@@ -18,6 +18,7 @@
#ifdef EXPECT_DEATH
#include <util/unittests/resource.h>
+#include <util/unittests/check_valgrind.h>
#endif /* EXPECT_DEATH */
#include <util/buffer.h>
@@ -188,16 +189,18 @@ TEST_F(BufferTest, outputBufferReadat) {
}
#ifdef EXPECT_DEATH
// We use assert now, so we check it dies
- EXPECT_DEATH({
- isc::util::unittests::dontCreateCoreDumps();
-
- try {
- obuffer[sizeof(testdata)];
- } catch (...) {
- // Prevent exceptions killing the application, we need
- // to make sure it dies the real hard way
- }
- }, "");
+ if (!isc::util::unittests::runningOnValgrind()) {
+ EXPECT_DEATH({
+ isc::util::unittests::dontCreateCoreDumps();
+
+ try {
+ obuffer[sizeof(testdata)];
+ } catch (...) {
+ // Prevent exceptions killing the application, we need
+ // to make sure it dies the real hard way
+ }
+ }, "");
+ }
#endif
}
diff --git a/src/lib/util/tests/fd_tests.cc b/src/lib/util/tests/fd_tests.cc
index 6ba2766..b709405 100644
--- a/src/lib/util/tests/fd_tests.cc
+++ b/src/lib/util/tests/fd_tests.cc
@@ -34,7 +34,9 @@ class FDTest : public ::testing::Test {
// We do not care what is inside, we just need it to be the same
data(new unsigned char[TEST_DATA_SIZE]),
buffer(NULL)
- { }
+ {
+ memset(data, 0, TEST_DATA_SIZE);
+ }
~ FDTest() {
delete[] data;
delete[] buffer;
diff --git a/src/lib/util/tests/lru_list_unittest.cc b/src/lib/util/tests/lru_list_unittest.cc
index bfb3b4d..c0201ea 100644
--- a/src/lib/util/tests/lru_list_unittest.cc
+++ b/src/lib/util/tests/lru_list_unittest.cc
@@ -168,7 +168,7 @@ protected:
entry7_(new TestEntry("eta", 1))
{}
- virtual ~LruListTest()
+ virtual ~LruListTest()
{}
boost::shared_ptr<TestEntry> entry1_;
@@ -355,7 +355,7 @@ TEST_F(LruListTest, Dropped) {
lru.add(entry5_);
EXPECT_NE(0, (entry2_->getCode() & 0x8000));
- // Delete an entry and check that the handler does not run.
+ // Delete an entry and check that the handler does not run.
EXPECT_EQ(0, (entry3_->getCode() & 0x8000));
lru.remove(entry3_);
EXPECT_EQ(0, (entry3_->getCode() & 0x8000));
@@ -386,7 +386,7 @@ TEST_F(LruListTest, Clear) {
EXPECT_NE(0, (entry1_->getCode() & 0x8000));
EXPECT_NE(0, (entry2_->getCode() & 0x8000));
EXPECT_NE(0, (entry3_->getCode() & 0x8000));
-
+
EXPECT_EQ(0, lru.size());
}
diff --git a/src/lib/util/threads/Makefile.am b/src/lib/util/threads/Makefile.am
new file mode 100644
index 0000000..121e4ab
--- /dev/null
+++ b/src/lib/util/threads/Makefile.am
@@ -0,0 +1,12 @@
+SUBDIRS = . tests
+AM_CXXFLAGS = $(B10_CXXFLAGS)
+
+AM_CPPFLAGS = -I$(top_srcdir)/src/lib -I$(top_builddir)/src/lib
+AM_CPPFLAGS += $(BOOST_INCLUDES) $(MULTITHREADING_FLAG)
+
+lib_LTLIBRARIES = libb10-threads.la
+libb10_threads_la_SOURCES = sync.h sync.cc
+libb10_threads_la_SOURCES += thread.h thread.cc
+libb10_threads_la_LIBADD = $(top_builddir)/src/lib/exceptions/libb10-exceptions.la
+
+CLEANFILES = *.gcno *.gcda
diff --git a/src/lib/util/threads/sync.cc b/src/lib/util/threads/sync.cc
new file mode 100644
index 0000000..46a5646
--- /dev/null
+++ b/src/lib/util/threads/sync.cc
@@ -0,0 +1,240 @@
+// 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 "sync.h"
+
+#include <exceptions/exceptions.h>
+
+#include <cstring>
+#include <memory>
+#include <cerrno>
+#include <cassert>
+
+#include <pthread.h>
+
+using std::auto_ptr;
+
+namespace isc {
+namespace util {
+namespace thread {
+
+class Mutex::Impl {
+public:
+ Impl()
+#ifdef ENABLE_DEBUG
+ : locked_count(0)
+#endif // ENABLE_DEBUG
+ {}
+
+ pthread_mutex_t mutex;
+#ifdef ENABLE_DEBUG
+ size_t locked_count;
+#endif // ENABLE_DEBUG
+};
+
+namespace {
+
+struct Deinitializer {
+ Deinitializer(pthread_mutexattr_t& attributes):
+ attributes_(attributes)
+ {}
+ ~Deinitializer() {
+ const int result = pthread_mutexattr_destroy(&attributes_);
+ // This should never happen. According to the man page,
+ // if there's error, it's our fault.
+ assert(result == 0);
+ }
+ pthread_mutexattr_t& attributes_;
+};
+
+}
+
+Mutex::Mutex() :
+ impl_(NULL)
+{
+ pthread_mutexattr_t attributes;
+ int result = pthread_mutexattr_init(&attributes);
+ switch (result) {
+ case 0: // All 0K
+ break;
+ case ENOMEM:
+ throw std::bad_alloc();
+ default:
+ isc_throw(isc::InvalidOperation, std::strerror(result));
+ }
+ Deinitializer deinitializer(attributes);
+
+ // If debug mode is enabled in compilation, use the slower
+ // error-checking mutexes that detect deadlocks. Otherwise, use fast
+ // mutexes which don't. See the pthread_mutexattr_settype() POSIX
+ // documentation which describes these type attributes.
+#ifdef ENABLE_DEBUG
+ result = pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_ERRORCHECK);
+#else
+ result = pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_NORMAL);
+#endif // ENABLE_DEBUG
+ if (result != 0) {
+ isc_throw(isc::InvalidOperation, std::strerror(result));
+ }
+
+ auto_ptr<Impl> impl(new Impl);
+ result = pthread_mutex_init(&impl->mutex, &attributes);
+ switch (result) {
+ case 0: // All 0K
+ impl_ = impl.release();
+ break;
+ case ENOMEM:
+ case EAGAIN:
+ throw std::bad_alloc();
+ default:
+ isc_throw(isc::InvalidOperation, std::strerror(result));
+ }
+}
+
+Mutex::~Mutex() {
+ if (impl_ != NULL) {
+ const int result = pthread_mutex_destroy(&impl_->mutex);
+
+#ifdef ENABLE_DEBUG
+ const bool locked = impl_->locked_count != 0;
+#endif // ENABLE_DEBUG
+
+ delete impl_;
+ // We don't want to throw from the destructor. Also, if this ever
+ // fails, something is really screwed up a lot.
+ assert(result == 0);
+
+#ifdef ENABLE_DEBUG
+ // We should not try to destroy a locked mutex, bad threaded monsters
+ // could get loose if we ever do and it is also forbidden by pthreads.
+
+ // This should not be possible to happen, since the
+ // pthread_mutex_destroy should check for it already. But it seems
+ // there are systems that don't check it.
+ assert(!locked);
+#endif // ENABLE_DEBUG
+ }
+}
+
+#ifdef ENABLE_DEBUG
+
+void
+Mutex::postLockAction() {
+ assert(impl_->locked_count == 0);
+ ++impl_->locked_count;
+}
+
+void
+Mutex::preUnlockAction(bool throw_ok) {
+ if (impl_->locked_count == 0) {
+ if (throw_ok) {
+ isc_throw(isc::InvalidOperation,
+ "Unlock attempt for unlocked mutex");
+ } else {
+ assert(false);
+ }
+ }
+ --impl_->locked_count;
+}
+
+bool
+Mutex::locked() const {
+ return (impl_->locked_count != 0);
+}
+
+#endif // ENABLE_DEBUG
+
+void
+Mutex::lock() {
+ assert(impl_ != NULL);
+ const int result = pthread_mutex_lock(&impl_->mutex);
+ if (result != 0) {
+ isc_throw(isc::InvalidOperation, std::strerror(result));
+ }
+#ifdef ENABLE_DEBUG
+ postLockAction(); // Only in debug mode
+#endif // ENABLE_DEBUG
+}
+
+void
+Mutex::unlock() {
+ assert(impl_ != NULL);
+#ifdef ENABLE_DEBUG
+ preUnlockAction(false); // Only in debug mode. Ensure no throw.
+#endif // ENABLE_DEBUG
+ const int result = pthread_mutex_unlock(&impl_->mutex);
+ assert(result == 0); // This should never be possible
+}
+
+class CondVar::Impl {
+public:
+ Impl() {
+ const int result = pthread_cond_init(&cond_, NULL);
+ if (result != 0) {
+ isc_throw(isc::Unexpected, "pthread_cond_init failed: "
+ << std::strerror(result));
+ }
+ }
+ ~Impl() {
+ const int result = pthread_cond_destroy(&cond_);
+
+ // This can happen if we try to destroy cond_ while some other thread
+ // is waiting on it. assert() may be too strong for such a case,
+ // but we cannot safely destroy cond_ anyway. In order to avoid
+ // throwing from a destructor we simply let the process die.
+ assert(result == 0);
+ }
+
+ // For convenience allow the main class to access this directly.
+ pthread_cond_t cond_;
+};
+
+CondVar::CondVar() : impl_(new Impl)
+{}
+
+CondVar::~CondVar() {
+ delete impl_;
+}
+
+void
+CondVar::wait(Mutex& mutex) {
+#ifdef ENABLE_DEBUG
+ mutex.preUnlockAction(true); // Only in debug mode
+ const int result = pthread_cond_wait(&impl_->cond_, &mutex.impl_->mutex);
+ mutex.postLockAction(); // Only in debug mode
+#else
+ const int result = pthread_cond_wait(&impl_->cond_, &mutex.impl_->mutex);
+#endif
+ // pthread_cond_wait should normally succeed unless mutex is completely
+ // broken.
+ if (result != 0) {
+ isc_throw(isc::BadValue, "pthread_cond_wait failed unexpectedly: " <<
+ std::strerror(result));
+ }
+}
+
+void
+CondVar::signal() {
+ const int result = pthread_cond_signal(&impl_->cond_);
+
+ // pthread_cond_signal() can only fail when if cond_ is invalid. It
+ //should be impossible as long as this is a valid CondVar object.
+ assert(result == 0);
+}
+
+}
+}
+}
diff --git a/src/lib/util/threads/sync.h b/src/lib/util/threads/sync.h
new file mode 100644
index 0000000..87c78be
--- /dev/null
+++ b/src/lib/util/threads/sync.h
@@ -0,0 +1,229 @@
+// 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 B10_THREAD_SYNC_H
+#define B10_THREAD_SYNC_H
+
+#include <boost/noncopyable.hpp>
+
+#include <cstdlib> // for NULL.
+
+namespace isc {
+namespace util {
+namespace thread {
+class CondVar;
+
+/// \brief Mutex with very simple interface
+///
+/// Since mutexes are very system dependant, we create our own wrapper around
+/// whatever is available on the system and hide it.
+///
+/// To use this mutex, create it and then lock and unlock it by creating the
+/// Mutex::Locker object.
+///
+/// Also, as mutex is a low-level system object, an error might happen at any
+/// operation with it. We convert many errors to the isc::InvalidOperation,
+/// since the errors usually happen only when used in a wrong way. Any methods
+/// or constructors in this class can throw. Allocation errors are converted
+/// to std::bad_alloc (for example when OS-dependant limit of mutexes is
+/// exceeded). Some errors which usually mean a programmer error abort the
+/// program, since there could be no safe way to recover from them.
+///
+/// The current interface is somewhat minimalistic. If we ever need more, we
+/// can add it later.
+class Mutex : boost::noncopyable {
+public:
+ /// \brief Constructor.
+ ///
+ /// Creates a mutex. It is a non-recursive mutex (can be locked just once,
+ /// if the same threads tries to lock it again, Bad Things Happen).
+ ///
+ /// Depending on compilation parameters and OS, the mutex may or may not
+ /// do some error and sanity checking. However, such checking is meant
+ /// only to aid development, not rely on it as a feature.
+ ///
+ /// \throw std::bad_alloc In case allocation of something (memory, the
+ /// OS mutex) fails.
+ /// \throw isc::InvalidOperation Other unspecified errors around the mutex.
+ /// This should be rare.
+ Mutex();
+
+ /// \brief Destructor.
+ ///
+ /// Destroys the mutex. It is not allowed to destroy a mutex which is
+ /// currently locked. This means a Locker created with this Mutex must
+ /// never live longer than the Mutex itself.
+ ~Mutex();
+
+ /// \brief This holds a lock on a Mutex.
+ ///
+ /// To lock a mutex, create a locker. It'll get unlocked when the locker
+ /// is destroyed.
+ ///
+ /// If you create the locker on the stack or using some other "garbage
+ /// collecting" mechanism (auto_ptr, for example), it ensures exception
+ /// safety with regards to the mutex - it'll get released on the exit
+ /// of function no matter by what means.
+ class Locker : boost::noncopyable {
+ public:
+ /// \brief Constructor.
+ ///
+ /// Locks the mutex. May block for extended period of time.
+ ///
+ /// \throw isc::InvalidOperation when OS reports error. This usually
+ /// means an attempt to use the mutex in a wrong way (locking
+ /// a mutex second time from the same thread, for example).
+ Locker(Mutex& mutex) :
+ mutex_(mutex)
+ {
+ mutex.lock();
+ }
+
+ /// \brief Destructor.
+ ///
+ /// Unlocks the mutex.
+ ~Locker() {
+ mutex_.unlock();
+ }
+ private:
+ Mutex& mutex_;
+ };
+ /// \brief If the mutex is currently locked
+ ///
+ /// This is debug aiding method only. And it might be unavailable in
+ /// non-debug build (because keeping the state might be needlesly
+ /// slow).
+ ///
+ /// \todo Disable in non-debug build
+ bool locked() const;
+private:
+ friend class CondVar;
+
+ // Commonly called after acquiring the lock, checking and updating
+ // internal state for debug.
+ //
+ // Note that this method is only available when the build is
+ // configured with debugging support.
+ void postLockAction();
+
+ // Commonly called before releasing the lock, checking and updating
+ // internal state for debug.
+ //
+ // If throw_ok is true, it throws \c isc::InvalidOperation when the check
+ // fails; otherwise it aborts the process. This parameter must be set
+ // to false if the call to this shouldn't result in an exception (e.g.
+ // when called from a destructor).
+ //
+ // Note that this method is only available when the build is
+ // configured with debugging support.
+ void preUnlockAction(bool throw_ok);
+
+ class Impl;
+ Impl* impl_;
+ void lock();
+ void unlock();
+};
+
+/// \brief Encapsulation for a condition variable.
+///
+/// This class provides a simple encapsulation of condition variable for
+/// inter-thread synchronization. It has similar but simplified interface as
+/// that for \c pthread_cond_ variants.
+///
+/// It uses the \c Mutex class object for the mutex used with the condition
+/// variable. Since for normal applications the internal \c Mutex::Locker
+/// class is the only available interface to acquire a lock, sample code
+/// for waiting on a condition variable would look like this:
+/// \code
+/// CondVar cond;
+/// Mutex mutex;
+/// {
+/// Mutex::Locker locker(mutex);
+/// while (some_condition) {
+/// cond.wait(mutex);
+/// }
+/// // do something under the protection of locker
+/// } // lock is released here
+/// \endcode
+/// Note that \c mutex passed to the \c wait() method must be the same one
+/// used to construct the \c locker.
+///
+/// Right now there is no equivalent to pthread_cond_broadcast() or
+/// pthread_cond_timedwait() in this class, because this class is meant
+/// for internal development of BIND 10 and we don't need these at the
+/// moment. If and when we need these interfaces they can be added at that
+/// point.
+///
+/// \note This class is defined as a friend class of \c Mutex and directly
+/// refers to and modifies private internals of the \c Mutex class. It breaks
+/// the assumption that the lock is only acquired or released via the
+/// \c Locker class and breaks other integrity assumption on \c Mutex,
+/// thereby making it more fragile, but we couldn't find other way to
+/// implement a safe and still simple realization of condition variables.
+/// So, this is a kind of compromise. If this class is needed to be
+/// extended, first consider a way to use public interfaces of \c Mutex;
+/// do not easily rely on the fact that this class is a friend of it.
+class CondVar : boost::noncopyable {
+public:
+ /// \brief Constructor.
+ ///
+ /// \throw std::bad_alloc memory allocation failure
+ /// \throw isc::Unexpected other unexpected shortage of system resource
+ CondVar();
+
+ /// \brief Destructor.
+ ///
+ /// An object of this class must not be destroyed while some thread
+ /// is waiting on it. If this condition isn't met the destructor will
+ /// terminate the program.
+ ~CondVar();
+
+ /// \brief Wait on the condition variable.
+ ///
+ /// This method works like \c pthread_cond_wait(). For mutex it takes
+ /// an \c Mutex class object. A lock for the mutex must have been
+ /// acquired. If this condition isn't met, it can throw an exception
+ /// (in the debug mode build) or result in undefined behavior.
+ ///
+ /// The lock will be automatically released within this method, and
+ /// will be re-acquired on the exit of this method.
+ ///
+ /// \throw isc::InvalidOperation mutex isn't locked
+ /// \throw isc::BadValue mutex is not a valid \c Mutex object
+ ///
+ /// \param mutex A \c Mutex object to be released on wait().
+ void wait(Mutex& mutex);
+
+ /// \brief Unblock a thread waiting for the condition variable.
+ ///
+ /// This method wakes one of other threads (if any) waiting on this object
+ /// via the \c wait() call.
+ ///
+ /// This method never throws; if some unexpected low level error happens
+ /// it terminates the program.
+ void signal();
+private:
+ class Impl;
+ Impl* impl_;
+};
+
+} // namespace thread
+} // namespace util
+} // namespace isc
+
+#endif
+
+// Local Variables:
+// mode: c++
+// End:
diff --git a/src/lib/util/threads/tests/.gitignore b/src/lib/util/threads/tests/.gitignore
new file mode 100644
index 0000000..d6d1ec8
--- /dev/null
+++ b/src/lib/util/threads/tests/.gitignore
@@ -0,0 +1 @@
+/run_unittests
diff --git a/src/lib/util/threads/tests/Makefile.am b/src/lib/util/threads/tests/Makefile.am
new file mode 100644
index 0000000..a12d221
--- /dev/null
+++ b/src/lib/util/threads/tests/Makefile.am
@@ -0,0 +1,37 @@
+SUBDIRS = .
+
+AM_CPPFLAGS = -I$(top_builddir)/src/lib -I$(top_srcdir)/src/lib
+AM_CPPFLAGS += $(BOOST_INCLUDES) $(MULTITHREADING_FLAG)
+# XXX: we'll pollute the top builddir for creating a temporary test file
+# # used to bind a UNIX domain socket so we can minimize the risk of exceeding
+# # the limit of file name path size.
+AM_CPPFLAGS += -DTEST_DATA_TOPBUILDDIR=\"$(abs_top_builddir)\"
+AM_CXXFLAGS = $(B10_CXXFLAGS)
+
+if USE_STATIC_LINK
+AM_LDFLAGS = -static
+endif
+
+CLEANFILES = *.gcno *.gcda
+
+TESTS_ENVIRONMENT = \
+ $(LIBTOOL) --mode=execute $(VALGRIND_COMMAND)
+
+TESTS =
+if HAVE_GTEST
+TESTS += run_unittests
+run_unittests_SOURCES = run_unittests.cc
+run_unittests_SOURCES += thread_unittest.cc
+run_unittests_SOURCES += lock_unittest.cc
+run_unittests_SOURCES += condvar_unittest.cc
+
+run_unittests_CPPFLAGS = $(AM_CPPFLAGS) $(GTEST_INCLUDES)
+run_unittests_LDFLAGS = $(AM_LDFLAGS) $(GTEST_LDFLAGS) $(PTHREAD_LDFLAGS)
+
+run_unittests_LDADD = $(top_builddir)/src/lib/util/threads/libb10-threads.la
+run_unittests_LDADD += \
+ $(top_builddir)/src/lib/util/unittests/libutil_unittests.la
+run_unittests_LDADD += $(GTEST_LDADD)
+endif
+
+noinst_PROGRAMS = $(TESTS)
diff --git a/src/lib/util/threads/tests/condvar_unittest.cc b/src/lib/util/threads/tests/condvar_unittest.cc
new file mode 100644
index 0000000..1e04efa
--- /dev/null
+++ b/src/lib/util/threads/tests/condvar_unittest.cc
@@ -0,0 +1,169 @@
+// 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 <exceptions/exceptions.h>
+
+#include <util/threads/sync.h>
+#include <util/threads/thread.h>
+
+#include <gtest/gtest.h>
+
+#include <boost/bind.hpp>
+#include <boost/scoped_ptr.hpp>
+
+#include <cstring>
+
+#include <unistd.h>
+#include <signal.h>
+
+using namespace isc::util::thread;
+
+namespace {
+// Used as a signal handler below.
+volatile bool do_exit; // use for emergency escape
+void
+alarmHandler(int) {
+ do_exit = true;
+}
+
+class CondVarTest : public ::testing::Test {
+protected:
+ // We use a signal in case some of the thread synchronization tests
+ // unexpectedly cause a deadlock.
+ void SetUp() {
+ do_exit = false;
+
+ std::memset(&handler_, 0, sizeof(handler_));
+ handler_.sa_handler = alarmHandler;
+ if (sigaction(SIGALRM, &handler_, &original_) != 0) {
+ FAIL() << "Couldn't set alarm";
+ }
+ alarm(10); // 10sec duration: arbitrary choice
+ }
+ void TearDown() {
+ // Cancel the alarm and return the original handler
+ alarm(0);
+ if (sigaction(SIGALRM, &original_, NULL)) {
+ FAIL() << "Couldn't restore alarm";
+ }
+ }
+
+ CondVar condvar_;
+ Mutex mutex_;
+private:
+ struct sigaction handler_, original_;
+};
+
+TEST(CondVarTest0, create) {
+ // Just construct and destruct it. Nothing unusual should happen.
+ EXPECT_NO_THROW(CondVar condvar);
+}
+
+// Running on a separate thread, just updating the argument and waking up
+// the other thread via the condition variable passed.
+void
+ringSignal(CondVar* condvar, Mutex* mutex, int* arg) {
+ assert(*arg == 0);
+ Mutex::Locker locker(*mutex);
+ ++*arg;
+ condvar->signal();
+}
+
+// A simple wait-signal operation on a condition variable.
+TEST_F(CondVarTest, waitAndSignal) {
+ Mutex::Locker locker(mutex_);
+ int shared_var = 0; // let the other thread increment this
+ Thread t(boost::bind(&ringSignal, &condvar_, &mutex_, &shared_var));
+ condvar_.wait(mutex_);
+ t.wait();
+ EXPECT_EQ(1, shared_var);
+}
+
+// Thread's main code for the next test
+void
+signalAndWait(CondVar* condvar1, CondVar* condvar2, Mutex* mutex, int* arg) {
+ Mutex::Locker locker(*mutex);
+ ++*arg;
+ condvar2->signal(); // let the main thread know this one is ready
+ condvar1->wait(*mutex);
+ ++*arg;
+}
+
+// Similar to the previous test, but having two threads wait for a condvar.
+TEST_F(CondVarTest, multiWaits) {
+ boost::scoped_ptr<Mutex::Locker> locker(new Mutex::Locker(mutex_));
+ CondVar condvar2; // separate cond var for initial synchronization
+ int shared_var = 0; // let the other thread increment this
+ Thread t1(boost::bind(&signalAndWait, &condvar_, &condvar2, &mutex_,
+ &shared_var));
+ Thread t2(boost::bind(&signalAndWait, &condvar_, &condvar2, &mutex_,
+ &shared_var));
+
+ // Wait until both threads are waiting on condvar_.
+ while (shared_var < 2 && !do_exit) {
+ condvar2.wait(mutex_);
+ }
+ // Check we exited from the loop successfully.
+ ASSERT_FALSE(do_exit);
+ ASSERT_EQ(2, shared_var);
+
+ // release the lock, wake up both threads, wait for them to die, and
+ // confirm they successfully woke up.
+ locker.reset();
+ condvar_.signal();
+ condvar_.signal();
+ t1.wait();
+ t2.wait();
+ EXPECT_EQ(4, shared_var);
+}
+
+// Similar to the previous version of the same function, but just do
+// condvar operations. It will never wake up.
+void
+signalAndWait(CondVar* condvar, Mutex* mutex) {
+ Mutex::Locker locker(*mutex);
+ condvar->signal();
+ condvar->wait(*mutex);
+}
+
+#ifndef HAS_UNDEFINED_PTHREAD_BEHAVIOR
+TEST_F(CondVarTest, destroyWhileWait) {
+ // We'll destroy a CondVar object while the thread is still waiting
+ // on it. This will trigger an assertion failure.
+ EXPECT_DEATH_IF_SUPPORTED({
+ CondVar cond;
+ Mutex::Locker locker(mutex_);
+ Thread t(boost::bind(&signalAndWait, &cond, &mutex_));
+ cond.wait(mutex_);
+ }, "");
+}
+#endif // !HAS_UNDEFINED_PTHREAD_BEHAVIOR
+
+#ifdef ENABLE_DEBUG
+
+TEST_F(CondVarTest, badWait) {
+ // In our implementation, wait() requires acquiring the lock beforehand.
+ EXPECT_THROW(condvar_.wait(mutex_), isc::InvalidOperation);
+}
+
+#endif // ENABLE_DEBUG
+
+TEST_F(CondVarTest, emptySignal) {
+ // It's okay to call signal when no one waits.
+ EXPECT_NO_THROW(condvar_.signal());
+}
+
+}
diff --git a/src/lib/util/threads/tests/lock_unittest.cc b/src/lib/util/threads/tests/lock_unittest.cc
new file mode 100644
index 0000000..1abc3fa
--- /dev/null
+++ b/src/lib/util/threads/tests/lock_unittest.cc
@@ -0,0 +1,127 @@
+// 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 <gtest/gtest.h>
+
+#include <util/threads/sync.h>
+#include <util/threads/thread.h>
+#include <util/unittests/check_valgrind.h>
+
+#include <boost/bind.hpp>
+#include <unistd.h>
+#include <signal.h>
+
+using namespace isc::util::thread;
+
+namespace {
+
+#ifdef ENABLE_DEBUG
+
+// If we try to lock the debug mutex multiple times, it should
+// throw. This test will complete properly only when pthread debugging
+// facilities are enabled by configuring the code for debug build.
+TEST(MutexTest, lockMultiple) {
+ Mutex mutex;
+ EXPECT_FALSE(mutex.locked()); // Debug-only build
+
+ Mutex::Locker l1(mutex);
+ EXPECT_TRUE(mutex.locked()); // Debug-only build
+
+ EXPECT_THROW({
+ Mutex::Locker l2(mutex); // Attempt to lock again.
+ }, isc::InvalidOperation);
+ EXPECT_TRUE(mutex.locked()); // Debug-only build
+}
+
+#endif // ENABLE_DEBUG
+
+#ifndef HAS_UNDEFINED_PTHREAD_BEHAVIOR
+// Destroying a locked mutex is a bad idea as well
+TEST(MutexTest, destroyLocked) {
+ if (!isc::util::unittests::runningOnValgrind()) {
+ EXPECT_DEATH_IF_SUPPORTED({
+ Mutex* mutex = new Mutex;
+ new Mutex::Locker(*mutex);
+ delete mutex;
+ // This'll leak the locker, but inside the slave process, it should
+ // not be an issue.
+ }, "");
+ }
+}
+#endif // !HAS_UNDEFINED_PTHREAD_BEHAVIOR
+
+// In this test, we try to check if a mutex really locks. We could try that
+// with a deadlock, but that's not practical (the test would not end).
+//
+// Instead, we try do to some operation on the same data from multiple threads
+// that's likely to break if not locked. Also, the test must run for a while
+// to have an opportunity to manifest.
+//
+// Currently we try incrementing a double variable. That one is large enough
+// and complex enough so it should not be possible for the CPU to do it as an
+// atomic operation, at least on common architectures.
+const size_t iterations = 100000;
+
+void
+performIncrement(volatile double* canary, volatile bool* ready_me,
+ volatile bool* ready_other, Mutex* mutex)
+{
+ // Loosely (busy) wait for the other thread so both will start
+ // approximately at the same time.
+ *ready_me = true;
+ while (!*ready_other) {}
+
+ for (size_t i = 0; i < iterations; ++i) {
+ Mutex::Locker lock(*mutex);
+ *canary += 1;
+ }
+}
+
+void
+noHandler(int) {}
+
+TEST(MutexTest, swarm) {
+ // Create a timeout in case something got stuck here
+ struct sigaction ignored, original;
+ memset(&ignored, 0, sizeof(ignored));
+ ignored.sa_handler = noHandler;
+ if (sigaction(SIGALRM, &ignored, &original)) {
+ FAIL() << "Couldn't set alarm";
+ }
+ alarm(10);
+ // This type has a low chance of being atomic itself, further raising
+ // the chance of problems appearing.
+ double canary = 0;
+ Mutex mutex;
+ // Run two parallel threads
+ bool ready1 = false;
+ bool ready2 = false;
+ Thread t1(boost::bind(&performIncrement, &canary, &ready1, &ready2,
+ &mutex));
+ Thread t2(boost::bind(&performIncrement, &canary, &ready2, &ready1,
+ &mutex));
+ t1.wait();
+ t2.wait();
+ // Check it the sum is the expected value.
+ EXPECT_EQ(iterations * 2, canary) << "Threads are badly synchronized";
+ // Cancel the alarm and return the original handler
+ alarm(0);
+ if (sigaction(SIGALRM, &original, NULL)) {
+ FAIL() << "Couldn't restore alarm";
+ }
+}
+
+}
diff --git a/src/lib/util/threads/tests/run_unittests.cc b/src/lib/util/threads/tests/run_unittests.cc
new file mode 100644
index 0000000..6f71ad6
--- /dev/null
+++ b/src/lib/util/threads/tests/run_unittests.cc
@@ -0,0 +1,25 @@
+// 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 <gtest/gtest.h>
+#include <util/unittests/run_all.h>
+#include <stdlib.h>
+
+int
+main(int argc, char* argv[]) {
+ ::testing::InitGoogleTest(&argc, argv);
+
+ setenv("B10_LOCKFILE_DIR_FROM_BUILD", TEST_DATA_TOPBUILDDIR, 1);
+ return (isc::util::unittests::run_all());
+}
diff --git a/src/lib/util/threads/tests/thread_unittest.cc b/src/lib/util/threads/tests/thread_unittest.cc
new file mode 100644
index 0000000..5afdf3f
--- /dev/null
+++ b/src/lib/util/threads/tests/thread_unittest.cc
@@ -0,0 +1,98 @@
+// 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 <util/threads/thread.h>
+
+#include <boost/bind.hpp>
+
+#include <gtest/gtest.h>
+
+// This file tests the Thread class. It's hard to test an actual thread is
+// started, but we at least check the function is run and exceptions are
+// propagated as they should.
+//
+// We run some tests mutiple times to see if there happen to be a race
+// condition (then it would have better chance showing up).
+//
+// The detached tests are not run as many times to prevent many threads being
+// started in parallel (the other tests wait for the previous one to terminate
+// before starting new one).
+
+using namespace isc::util::thread;
+
+namespace {
+const size_t iterations = 200;
+const size_t detached_iterations = 25;
+
+void
+doSomething(int*) { }
+
+// We just test that we can forget about the thread and nothing
+// bad will happen on our side.
+TEST(ThreadTest, detached) {
+ int x;
+ for (size_t i = 0; i < detached_iterations; ++i) {
+ Thread thread(boost::bind(&doSomething, &x));
+ }
+}
+
+void
+markRun(bool* mark) {
+ EXPECT_FALSE(*mark);
+ *mark = true;
+}
+
+// Wait for a thread to end first. The variable must be set at the time.
+TEST(ThreadTest, wait) {
+ for (size_t i = 0; i < iterations; ++i) {
+ bool mark = false;
+ Thread thread(boost::bind(markRun, &mark));
+ thread.wait();
+ ASSERT_TRUE(mark) << "Not finished yet in " << i << "th iteration";
+ // Can't wait second time
+ ASSERT_THROW(thread.wait(), isc::InvalidOperation);
+ }
+}
+
+void
+throwSomething() {
+ throw 42; // Throw something really unusual, to see everything is caught.
+}
+
+void
+throwException() {
+ throw std::exception();
+}
+
+// Exception in the thread we forget about should not do anything to us
+TEST(ThreadTest, detachedException) {
+ for (size_t i = 0; i < detached_iterations; ++i) {
+ Thread thread(throwSomething);
+ }
+ for (size_t i = 0; i < detached_iterations; ++i) {
+ Thread thread(throwException);
+ }
+}
+
+// An uncaught exception in the thread should propagate through wait
+TEST(ThreadTest, exception) {
+ for (size_t i = 0; i < iterations; ++i) {
+ Thread thread(throwSomething);
+ Thread thread2(throwException);
+ ASSERT_THROW(thread.wait(), Thread::UncaughtException);
+ ASSERT_THROW(thread2.wait(), Thread::UncaughtException);
+ }
+}
+
+}
diff --git a/src/lib/util/threads/thread.cc b/src/lib/util/threads/thread.cc
new file mode 100644
index 0000000..5608e49
--- /dev/null
+++ b/src/lib/util/threads/thread.cc
@@ -0,0 +1,172 @@
+// 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 "thread.h"
+#include "sync.h"
+
+#include <memory>
+#include <string>
+#include <cstring>
+#include <cerrno>
+
+#include <pthread.h>
+
+#include <boost/scoped_ptr.hpp>
+
+using std::string;
+using std::exception;
+using std::auto_ptr;
+using boost::scoped_ptr;
+
+namespace isc {
+namespace util {
+namespace thread {
+
+// The implementation of the Thread class.
+//
+// This internal state is not deleted until the thread terminates and is either
+// waited for or detached. We could do this with shared_ptr (or, shared_ptr and
+// weak_ptr), but we plan on compiling boost without thread support, so it
+// might not be safe. Therefore we use an explicit mutex. It is being locked
+// only 2-3 times in the lifetime of the thread, which should be negligible
+// overhead anyway.
+class Thread::Impl {
+public:
+ Impl(const boost::function<void ()>& main) :
+ // Two things to happen before destruction - thread needs to terminate
+ // and the creating thread needs to release it.
+ waiting_(2),
+ main_(main),
+ exception_(false)
+ {}
+ // Another of the waiting events is done. If there are no more, delete
+ // impl.
+ static void done(Impl* impl) {
+ bool should_delete(false);
+ { // We need to make sure the mutex is unlocked before it is deleted
+ Mutex::Locker locker(impl->mutex_);
+ if (--impl->waiting_ == 0) {
+ should_delete = true;
+ }
+ }
+ if (should_delete) {
+ delete impl;
+ }
+ }
+ // Run the thread. The type of parameter is because the pthread API.
+ static void* run(void* impl_raw) {
+ Impl* impl = static_cast<Impl*>(impl_raw);
+ try {
+ impl->main_();
+ } catch (const exception& e) {
+ impl->exception_ = true;
+ impl->exception_text_ = e.what();
+ } catch (...) {
+ impl->exception_ = true;
+ impl->exception_text_ = "Uknown exception";
+ }
+ done(impl);
+ return (NULL);
+ }
+ // How many events are waiting? One is for the thread to finish, one
+ // for the destructor of Thread or wait. Once both happen, this is
+ // no longer needed.
+ size_t waiting_;
+ // The main function of the thread.
+ boost::function<void ()> main_;
+ // Was there an exception?
+ bool exception_;
+ string exception_text_;
+ // The mutex protects the waiting_ member, which ensures there are
+ // no race conditions and collisions when terminating. The other members
+ // should be safe, because:
+ // * tid_ is read only.
+ // * exception_ and exception_text_ is accessed outside of the thread
+ // only after join, by that time the thread must have terminated.
+ // * main_ is used in a read-only way here. If there are any shared
+ // resources used inside, it is up to the main_ itself to take care.
+ Mutex mutex_;
+ // Which thread are we talking about anyway?
+ pthread_t tid_;
+};
+
+Thread::Thread(const boost::function<void ()>& main) :
+ impl_(NULL)
+{
+ auto_ptr<Impl> impl(new Impl(main));
+ const int result = pthread_create(&impl->tid_, NULL, &Impl::run,
+ impl.get());
+ // Any error here?
+ switch (result) {
+ case 0: // All 0K
+ impl_ = impl.release();
+ break;
+ case EAGAIN:
+ throw std::bad_alloc();
+ default: // Other errors. They should not happen.
+ isc_throw(isc::InvalidOperation, std::strerror(result));
+ }
+}
+
+Thread::~Thread() {
+ if (impl_ != NULL) {
+ // In case we didn't call wait yet
+ const int result = pthread_detach(impl_->tid_);
+ Impl::done(impl_);
+ impl_ = NULL;
+ // If the detach ever fails, something is screwed rather badly.
+ assert(result == 0);
+ }
+}
+
+void
+Thread::wait() {
+ if (impl_ == NULL) {
+ isc_throw(isc::InvalidOperation,
+ "Wait called and no thread to wait for");
+ }
+
+ const int result = pthread_join(impl_->tid_, NULL);
+ if (result != 0) {
+ isc_throw(isc::InvalidOperation, std::strerror(result));
+ }
+
+ // Was there an exception in the thread?
+ scoped_ptr<UncaughtException> ex;
+ // Something here could in theory throw. But we already terminated the thread, so
+ // we need to make sure we are in consistent state even in such situation (like
+ // releasing the mutex and impl_).
+ try {
+ if (impl_->exception_) {
+ ex.reset(new UncaughtException(__FILE__, __LINE__,
+ impl_->exception_text_.c_str()));
+ }
+ } catch (...) {
+ Impl::done(impl_);
+ impl_ = NULL;
+ // We have eaten the UncaughtException by now, but there's another
+ // exception instead, so we have at least something.
+ throw;
+ }
+
+ Impl::done(impl_);
+ impl_ = NULL;
+ if (ex.get() != NULL) {
+ throw UncaughtException(*ex);
+ }
+}
+
+}
+}
+}
diff --git a/src/lib/util/threads/thread.h b/src/lib/util/threads/thread.h
new file mode 100644
index 0000000..9c6d20a
--- /dev/null
+++ b/src/lib/util/threads/thread.h
@@ -0,0 +1,112 @@
+// 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 B10_THREAD_H
+#define B10_THREAD_H
+
+#include <exceptions/exceptions.h>
+
+#include <boost/noncopyable.hpp>
+#include <boost/function.hpp>
+
+namespace isc {
+namespace util {
+/// \brief Wrappers for thread related functionality
+///
+/// We provide our own wrappers, currently around pthreads. We tried using
+/// the boost thread support, but it gave us some trouble, so we implemented
+/// in-house ones.
+namespace thread {
+
+/// \brief A separate thread.
+///
+/// A thread of execution. When created, starts running in the background.
+/// You can wait for it then or just forget it ever existed and leave it
+/// live peacefully.
+///
+/// The interface is minimalistic for now. We may need to extend it later.
+///
+/// \note While the objects of this class represent another thread, they
+/// are not thread-safe. You're not supposed to call wait() on the same
+/// object from multiple threads or so. They are reentrant (you can
+/// wait for different threads from different threads).
+class Thread : public boost::noncopyable {
+public:
+ /// \brief There's an uncaught exception in a thread.
+ ///
+ /// When a thread terminates because it the main function of the thread
+ /// throws, this one is re-thrown out of wait() and contains the what
+ /// of the original exception.
+ class UncaughtException : public isc::Exception {
+ public:
+ UncaughtException(const char* file, size_t line, const char* what) :
+ Exception(file, line, what)
+ {}
+ };
+
+ /// \brief Create and start a thread.
+ ///
+ /// Create a new thread and run body inside it.
+ ///
+ /// If you need to pass parameters to body, or return some result, you
+ /// may just want to use boost::bind or alike to store them within the
+ /// body functor.
+ ///
+ /// \note The main functor will be copied internally. You need to consider
+ /// this when returning the result.
+ ///
+ /// The body should terminate by exiting the function. If it throws, it
+ /// is considered an error. You should generally catch any exceptions form
+ /// within there and handle them somehow.
+ ///
+ /// \param main The code to run inside the thread.
+ ///
+ /// \throw std::bad_alloc if allocation of the new thread or other
+ /// resources fails.
+ /// \throw isc::InvalidOperation for other errors (should not happen).
+ Thread(const boost::function<void()>& main);
+
+ /// \brief Destructor.
+ ///
+ /// It is completely legitimate to destroy the thread without calling
+ /// wait() before. In such case, the thread will just live on until it
+ /// terminates. However, if the thread dies due to exception, for example,
+ /// it's up to you to detect that, no error is reported from this class.
+ ///
+ /// \throw isc::InvalidOperation in the rare case of OS reporting a
+ /// problem. This should not happen unless you messed up with the raw
+ /// thread by the low-level API.
+ ~Thread();
+
+ /// \brief Wait for the thread to terminate.
+ ///
+ /// Waits until the thread terminates. Must be called at most once.
+ ///
+ /// \throw isc::InvalidOperation if the OS API returns error. This usually
+ /// mean a programmer error (like two threads trying to wait on each
+ /// other).
+ /// \throw isc::InvalidOperation calling wait a second time.
+ /// \throw UncaughtException if the thread terminated by throwing an
+ /// exception instead of just returning from the function.
+ void wait();
+private:
+ class Impl;
+ Impl* impl_;
+};
+
+}
+}
+}
+
+#endif
diff --git a/src/lib/util/time_utilities.h b/src/lib/util/time_utilities.h
index a53089d..479f055 100644
--- a/src/lib/util/time_utilities.h
+++ b/src/lib/util/time_utilities.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TIME_UTILITIES_H
-#define __TIME_UTILITIES_H 1
+#ifndef TIME_UTILITIES_H
+#define TIME_UTILITIES_H 1
#include <string>
@@ -32,7 +32,7 @@ namespace isc {
namespace util {
///
-/// \brief A standard DNS (or ISC) module exception that is thrown if
+/// \brief A standard DNS (or ISC) module exception that is thrown if
/// a time conversion function encounters bad input
///
class InvalidTime : public Exception {
@@ -166,7 +166,7 @@ timeToText32(const uint32_t value);
}
}
-#endif // __DNSSECTIME_H
+#endif // TIME_UTILITIES_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/unittests/Makefile.am b/src/lib/util/unittests/Makefile.am
index 451ab4e..55e0372 100644
--- a/src/lib/util/unittests/Makefile.am
+++ b/src/lib/util/unittests/Makefile.am
@@ -7,6 +7,7 @@ libutil_unittests_la_SOURCES += newhook.h newhook.cc
libutil_unittests_la_SOURCES += testdata.h testdata.cc
if HAVE_GTEST
libutil_unittests_la_SOURCES += resource.h resource.cc
+libutil_unittests_la_SOURCES += check_valgrind.h check_valgrind.cc
libutil_unittests_la_SOURCES += run_all.h run_all.cc
libutil_unittests_la_SOURCES += textdata.h
libutil_unittests_la_SOURCES += wiredata.h wiredata.cc
diff --git a/src/lib/util/unittests/check_valgrind.cc b/src/lib/util/unittests/check_valgrind.cc
new file mode 100644
index 0000000..2951d25
--- /dev/null
+++ b/src/lib/util/unittests/check_valgrind.cc
@@ -0,0 +1,41 @@
+// 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>
+
+namespace isc {
+namespace util {
+namespace unittests {
+
+#if HAVE_VALGRIND_HEADERS
+#include <valgrind/valgrind.h>
+/// \brief Check if the program is run in valgrind
+///
+/// \return true if valgrind headers are available, and valgrind is running,
+/// false if the headers are not available, or if valgrind is not
+/// running
+bool
+runningOnValgrind() {
+ return (RUNNING_ON_VALGRIND != 0);
+}
+#else
+bool
+runningOnValgrind() {
+ return (false);
+}
+#endif // HAVE_VALGRIND_HEADERS
+
+} // end of namespace unittests
+} // end of namespace util
+} // end of namespace isc
diff --git a/src/lib/util/unittests/check_valgrind.h b/src/lib/util/unittests/check_valgrind.h
new file mode 100644
index 0000000..80f1f85
--- /dev/null
+++ b/src/lib/util/unittests/check_valgrind.h
@@ -0,0 +1,50 @@
+// 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.
+
+//
+// If we have the valgrind headers available, we can detect whether
+// valgrind is running. This should normally never be done, as you
+// want the to test the actual code in operation with valgrind.
+//
+// However, there is a limited set of operations where we want to
+// skip some tests if run under valgrind, most notably the
+// EXPECT_DEATH tests, as these would report memory leaks by
+// definition.
+//
+// If the valgrind headers are NOT available, the method checkValgrind()
+// always returns false; i.e. it always pretends the program is run
+// natively
+//
+
+#ifndef UTIL_UNITTESTS_CHECK_VALGRIND_H
+#define UTIL_UNITTESTS_CHECK_VALGRIND_H 1
+
+#include <config.h>
+
+namespace isc {
+namespace util {
+namespace unittests {
+
+/// \brief Check if the program is run in valgrind
+///
+/// \return true if valgrind headers are available, and valgrind is running,
+/// false if the headers are not available, or if valgrind is not
+/// running
+bool runningOnValgrind();
+
+} // end namespace unittests
+} // end namespace util
+} // end namespace isc
+
+#endif // UTIL_UNITTESTS_CHECK_VALGRIND_H
diff --git a/src/lib/util/unittests/fork.h b/src/lib/util/unittests/fork.h
index 2d27a11..d5623a7 100644
--- a/src/lib/util/unittests/fork.h
+++ b/src/lib/util/unittests/fork.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_UNITTESTS_FORK_H
-#define __UTIL_UNITTESTS_FORK_H 1
+#ifndef UTIL_UNITTESTS_FORK_H
+#define UTIL_UNITTESTS_FORK_H 1
#include <unistd.h>
@@ -49,4 +49,4 @@ check_output(int *write_pipe, const void *output, const size_t length);
}
}
-#endif // __UTIL_UNITTESTS_FORK_H
+#endif // UTIL_UNITTESTS_FORK_H
diff --git a/src/lib/util/unittests/mock_socketsession.h b/src/lib/util/unittests/mock_socketsession.h
index 8078265..01ca34f 100644
--- a/src/lib/util/unittests/mock_socketsession.h
+++ b/src/lib/util/unittests/mock_socketsession.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_UNITTESTS_MOCKSOCKETSESSION_H
-#define __UTIL_UNITTESTS_MOCKSOCKETSESSION_H 1
+#ifndef UTIL_UNITTESTS_MOCKSOCKETSESSION_H
+#define UTIL_UNITTESTS_MOCKSOCKETSESSION_H 1
#include <exceptions/exceptions.h>
@@ -147,7 +147,7 @@ private:
} // end of unittests
} // end of util
} // end of isc
-#endif // __UTIL_UNITTESTS_MOCKSOCKETSESSION_H
+#endif // UTIL_UNITTESTS_MOCKSOCKETSESSION_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/unittests/newhook.h b/src/lib/util/unittests/newhook.h
index c90751e..d2c1385 100644
--- a/src/lib/util/unittests/newhook.h
+++ b/src/lib/util/unittests/newhook.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_UNITTESTS_NEWHOOK_H
-#define __UTIL_UNITTESTS_NEWHOOK_H 1
+#ifndef UTIL_UNITTESTS_NEWHOOK_H
+#define UTIL_UNITTESTS_NEWHOOK_H 1
/**
* \file newhook.h
@@ -75,7 +75,7 @@ extern size_t throw_size_on_new;
}
}
-#endif // __UTIL_UNITTESTS_NEWHOOK_H
+#endif // UTIL_UNITTESTS_NEWHOOK_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/unittests/resource.h b/src/lib/util/unittests/resource.h
index 6430ab2..5a266b2 100644
--- a/src/lib/util/unittests/resource.h
+++ b/src/lib/util/unittests/resource.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_UNITTESTS_RESOURCE_H
-#define __UTIL_UNITTESTS_RESOURCE_H 1
+#ifndef UTIL_UNITTESTS_RESOURCE_H
+#define UTIL_UNITTESTS_RESOURCE_H 1
namespace isc {
namespace util {
@@ -32,7 +32,7 @@ void dontCreateCoreDumps();
} // end of namespace util
} // end of namespace isc
-#endif /* __UTIL_UNITTESTS_RESOURCE_H */
+#endif // UTIL_UNITTESTS_RESOURCE_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/unittests/run_all.h b/src/lib/util/unittests/run_all.h
index 94c7cb0..2335df7 100644
--- a/src/lib/util/unittests/run_all.h
+++ b/src/lib/util/unittests/run_all.h
@@ -14,8 +14,8 @@
-#ifndef __RUN_ALL_H
-#define __RUN_ALL_H
+#ifndef RUN_ALL_H
+#define RUN_ALL_H
// Avoid need for user to include this header file.
@@ -49,4 +49,4 @@ int run_all();
-#endif // __RUN_ALL_H
+#endif // RUN_ALL_H
diff --git a/src/lib/util/unittests/testdata.h b/src/lib/util/unittests/testdata.h
index a452dc6..c7ee707 100644
--- a/src/lib/util/unittests/testdata.h
+++ b/src/lib/util/unittests/testdata.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_UNITTESTS_TESTDATA_H
-#define __UTIL_UNITTESTS_TESTDATA_H 1
+#ifndef UTIL_UNITTESTS_TESTDATA_H
+#define UTIL_UNITTESTS_TESTDATA_H 1
/**
* \file testdata.h
@@ -47,7 +47,7 @@ void openTestData(const char* const datafile, std::ifstream& ifs);
}
}
-#endif // __UTIL_UNITTESTS_TESTDATA_H
+#endif // UTIL_UNITTESTS_TESTDATA_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/unittests/textdata.h b/src/lib/util/unittests/textdata.h
index 3e5fe0f..50d09ea 100644
--- a/src/lib/util/unittests/textdata.h
+++ b/src/lib/util/unittests/textdata.h
@@ -18,8 +18,8 @@
#include <gtest/gtest.h>
-#ifndef __UTIL_UNITTESTS_TEXTDATA_H
-#define __UTIL_UNITTESTS_TEXTDATA_H 1
+#ifndef UTIL_UNITTESTS_TEXTDATA_H
+#define UTIL_UNITTESTS_TEXTDATA_H 1
/**
* \file textdata.h
@@ -96,7 +96,7 @@ matchTextData(const std::string& expected_text,
}
}
-#endif // __UTIL_UNITTESTS_TEXTDATA_H
+#endif // UTIL_UNITTESTS_TEXTDATA_H
// Local Variables:
// mode: c++
diff --git a/src/lib/util/unittests/wiredata.h b/src/lib/util/unittests/wiredata.h
index a33a03a..a8c519e 100644
--- a/src/lib/util/unittests/wiredata.h
+++ b/src/lib/util/unittests/wiredata.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __UTIL_UNITTESTS_WIREDATA_H
-#define __UTIL_UNITTESTS_WIREDATA_H 1
+#ifndef UTIL_UNITTESTS_WIREDATA_H
+#define UTIL_UNITTESTS_WIREDATA_H 1
#include <cstddef>
@@ -38,7 +38,7 @@ void matchWireData(const void* expected_data, std::size_t expected_len,
}
}
-#endif // __UTIL_UNITTESTS_WIREDATA_H
+#endif // UTIL_UNITTESTS_WIREDATA_H
// Local Variables:
// mode: c++
diff --git a/src/lib/xfr/xfrout_client.h b/src/lib/xfr/xfrout_client.h
index bad963c..e691fb1 100644
--- a/src/lib/xfr/xfrout_client.h
+++ b/src/lib/xfr/xfrout_client.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef _XFROUT_CLIENT_H
-#define _XFROUT_CLIENT_H
+#ifndef XFROUT_CLIENT_H
+#define XFROUT_CLIENT_H
#include <stdint.h>
diff --git a/tests/lettuce/configurations/auth/.gitignore b/tests/lettuce/configurations/auth/.gitignore
new file mode 100644
index 0000000..07f1b7d
--- /dev/null
+++ b/tests/lettuce/configurations/auth/.gitignore
@@ -0,0 +1 @@
+/auth_basic.config
diff --git a/tests/lettuce/configurations/auth/auth_basic.config.orig b/tests/lettuce/configurations/auth/auth_basic.config.orig
new file mode 100644
index 0000000..4067fb1
--- /dev/null
+++ b/tests/lettuce/configurations/auth/auth_basic.config.orig
@@ -0,0 +1,22 @@
+{
+ "version": 2,
+ "Logging": {
+ "loggers": [ {
+ "debuglevel": 99,
+ "severity": "DEBUG",
+ "name": "*"
+ } ]
+ },
+ "Auth": {
+ "listen_on": [ {
+ "port": 47806,
+ "address": "127.0.0.1"
+ } ]
+ },
+ "Boss": {
+ "components": {
+ "b10-auth": { "kind": "needed", "special": "auth" },
+ "b10-cmdctl": { "special": "cmdctl", "kind": "needed" }
+ }
+ }
+}
diff --git a/tests/lettuce/features/auth_basic.feature b/tests/lettuce/features/auth_basic.feature
new file mode 100644
index 0000000..4667b64
--- /dev/null
+++ b/tests/lettuce/features/auth_basic.feature
@@ -0,0 +1,20 @@
+Feature: Basic Authoritative DNS server
+ This feature set is for testing the execution of the b10-auth
+ component using its default datasource configurations. This
+ will start it and perform queries against it.
+
+ Scenario: Query builtin bind zone
+ Given I have bind10 running with configuration auth/auth_basic.config
+ And wait for bind10 stderr message BIND10_STARTED_CC
+ And wait for bind10 stderr message CMDCTL_STARTED
+ And wait for bind10 stderr message AUTH_SERVER_STARTED
+
+ bind10 module Auth should be running
+ And bind10 module Resolver should not be running
+
+ A query for example.com should have rcode REFUSED
+ A query for version.bind type TXT class CH should have rcode NOERROR
+ A query for authors.bind type TXT class CH should have rcode NOERROR
+
+ # TODO: to be compatible with BIND 9
+ # A query for nonexistent.bind type TXT class CH should have rcode REFUSED
diff --git a/tests/lettuce/features/terrain/terrain.py b/tests/lettuce/features/terrain/terrain.py
index 8720e2d..2bfe7d4 100644
--- a/tests/lettuce/features/terrain/terrain.py
+++ b/tests/lettuce/features/terrain/terrain.py
@@ -49,6 +49,8 @@ copylist = [
"configurations/example.org.config"],
["configurations/bindctl/bindctl.config.orig",
"configurations/bindctl/bindctl.config"],
+ ["configurations/auth/auth_basic.config.orig",
+ "configurations/auth/auth_basic.config"],
["configurations/resolver/resolver_basic.config.orig",
"configurations/resolver/resolver_basic.config"],
["configurations/multi_instance/multi_auth.config.orig",
diff --git a/tests/tools/badpacket/command_options.h b/tests/tools/badpacket/command_options.h
index fc819e9..c6f2825 100644
--- a/tests/tools/badpacket/command_options.h
+++ b/tests/tools/badpacket/command_options.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __COMMAND_OPTIONS_H
-#define __COMMAND_OPTIONS_H
+#ifndef COMMAND_OPTIONS_H
+#define COMMAND_OPTIONS_H
#include <cstdlib>
#include <stdint.h>
@@ -159,4 +159,4 @@ private:
} // namespace badpacket
} // namespace isc
-#endif // __COMMAND_OPTIONS_H
+#endif // COMMAND_OPTIONS_H
diff --git a/tests/tools/badpacket/header_flags.h b/tests/tools/badpacket/header_flags.h
index 5d74e75..71aa64c 100644
--- a/tests/tools/badpacket/header_flags.h
+++ b/tests/tools/badpacket/header_flags.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __HEADER_FLAGS_H
-#define __HEADER_FLAGS_H
+#ifndef HEADER_FLAGS_H
+#define HEADER_FLAGS_H
#include <exceptions/exceptions.h>
#include "option_info.h"
@@ -99,4 +99,4 @@ private:
} // namespace badpacket
} // namespace isc
-#endif // __HEADER_FLAGS_H
+#endif // HEADER_FLAGS_H
diff --git a/tests/tools/badpacket/option_info.h b/tests/tools/badpacket/option_info.h
index a340c1d..aebeb66 100644
--- a/tests/tools/badpacket/option_info.h
+++ b/tests/tools/badpacket/option_info.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __OPTION_INFO_H
-#define __OPTION_INFO_H
+#ifndef OPTION_INFO_H
+#define OPTION_INFO_H
#include <stdint.h>
#include "exceptions/exceptions.h"
@@ -171,4 +171,4 @@ public:
} // namespace badpacket
} // namespace isc
-#endif // __OPTION_INFO_H
+#endif // OPTION_INFO_H
diff --git a/tests/tools/badpacket/scan.h b/tests/tools/badpacket/scan.h
index ca56646..40b5bf6 100644
--- a/tests/tools/badpacket/scan.h
+++ b/tests/tools/badpacket/scan.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __SCAN_H
-#define __SCAN_H
+#ifndef SCAN_H
+#define SCAN_H
#include <stdint.h>
@@ -195,4 +195,4 @@ private:
} // namespace test
} // namespace isc
-#endif // __SCAN_H
+#endif // SCAN_H
diff --git a/tests/tools/badpacket/version.h b/tests/tools/badpacket/version.h
index dc59b11..9f7f280 100644
--- a/tests/tools/badpacket/version.h
+++ b/tests/tools/badpacket/version.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __VERSION_H
-#define __VERSION_H
+#ifndef VERSION_H
+#define VERSION_H
namespace isc {
namespace badpacket {
@@ -23,4 +23,4 @@ static const char* BADPACKET_VERSION = "1.0-1";
} // namespace badpacket
} // namespace isc
-#endif // __VERSION_H
+#endif // VERSION_H
diff --git a/tests/tools/perfdhcp/command_options.h b/tests/tools/perfdhcp/command_options.h
index 4668f73..cbb6236 100644
--- a/tests/tools/perfdhcp/command_options.h
+++ b/tests/tools/perfdhcp/command_options.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __COMMAND_OPTIONS_H
-#define __COMMAND_OPTIONS_H
+#ifndef COMMAND_OPTIONS_H
+#define COMMAND_OPTIONS_H
#include <string>
#include <vector>
@@ -462,4 +462,4 @@ private:
} // namespace perfdhcp
} // namespace isc
-#endif // __COMMAND_OPTIONS_H
+#endif // COMMAND_OPTIONS_H
diff --git a/tests/tools/perfdhcp/localized_option.h b/tests/tools/perfdhcp/localized_option.h
index 336e083..2aa270a 100644
--- a/tests/tools/perfdhcp/localized_option.h
+++ b/tests/tools/perfdhcp/localized_option.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __LOCALIZED_OPTION_H
-#define __LOCALIZED_OPTION_H
+#ifndef LOCALIZED_OPTION_H
+#define LOCALIZED_OPTION_H
#include <dhcp/pkt6.h>
#include <dhcp/option6_ia.h>
@@ -147,4 +147,4 @@ private:
} // namespace isc::perfdhcp
} // namespace isc
-#endif // __LOCALIZED_OPTION_H
+#endif // LOCALIZED_OPTION_H
diff --git a/tests/tools/perfdhcp/perf_pkt4.h b/tests/tools/perfdhcp/perf_pkt4.h
index 87c7bb0..6f03193 100644
--- a/tests/tools/perfdhcp/perf_pkt4.h
+++ b/tests/tools/perfdhcp/perf_pkt4.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PERF_PKT4_H
-#define __PERF_PKT4_H
+#ifndef PERF_PKT4_H
+#define PERF_PKT4_H
#include <time.h>
#include <boost/shared_ptr.hpp>
@@ -136,4 +136,4 @@ typedef boost::shared_ptr<PerfPkt4> PerfPkt4Ptr;
} // namespace perfdhcp
} // namespace isc
-#endif // __PERF_PKT4_H
+#endif // PERF_PKT4_H
diff --git a/tests/tools/perfdhcp/perf_pkt6.h b/tests/tools/perfdhcp/perf_pkt6.h
index 25fb4e5..9a8d69b 100644
--- a/tests/tools/perfdhcp/perf_pkt6.h
+++ b/tests/tools/perfdhcp/perf_pkt6.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PERF_PKT6_H
-#define __PERF_PKT6_H
+#ifndef PERF_PKT6_H
+#define PERF_PKT6_H
#include <time.h>
#include <boost/shared_ptr.hpp>
@@ -136,4 +136,4 @@ typedef boost::shared_ptr<PerfPkt6> PerfPkt6Ptr;
} // namespace perfdhcp
} // namespace isc
-#endif // __PERF_PKT6_H
+#endif // PERF_PKT6_H
diff --git a/tests/tools/perfdhcp/pkt_transform.h b/tests/tools/perfdhcp/pkt_transform.h
index 1f57105..c94e9ba 100644
--- a/tests/tools/perfdhcp/pkt_transform.h
+++ b/tests/tools/perfdhcp/pkt_transform.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __PKT_TRANSFORM_H
-#define __PKT_TRANSFORM_H
+#ifndef PKT_TRANSFORM_H
+#define PKT_TRANSFORM_H
#include <dhcp/option.h>
@@ -166,4 +166,4 @@ private:
} // namespace perfdhcp
} // namespace isc
-#endif // __PKT_TRANSFORM_H
+#endif // PKT_TRANSFORM_H
diff --git a/tests/tools/perfdhcp/stats_mgr.h b/tests/tools/perfdhcp/stats_mgr.h
index 0c2b68c..537e81d 100644
--- a/tests/tools/perfdhcp/stats_mgr.h
+++ b/tests/tools/perfdhcp/stats_mgr.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __STATS_MGR_H
-#define __STATS_MGR_H
+#ifndef STATS_MGR_H
+#define STATS_MGR_H
#include <iostream>
#include <map>
@@ -1300,4 +1300,4 @@ private:
} // namespace perfdhcp
} // namespace isc
-#endif // __STATS_MGR_H
+#endif // STATS_MGR_H
diff --git a/tests/tools/perfdhcp/templates/.gitignore b/tests/tools/perfdhcp/templates/.gitignore
new file mode 100644
index 0000000..6f865da
--- /dev/null
+++ b/tests/tools/perfdhcp/templates/.gitignore
@@ -0,0 +1,5 @@
+/test1.hex
+/test2.hex
+/test3.hex
+/test4.hex
+/test5.hex
diff --git a/tests/tools/perfdhcp/test_control.h b/tests/tools/perfdhcp/test_control.h
index 2bd7871..245cf6d 100644
--- a/tests/tools/perfdhcp/test_control.h
+++ b/tests/tools/perfdhcp/test_control.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __TEST_CONTROL_H
-#define __TEST_CONTROL_H
+#ifndef TEST_CONTROL_H
+#define TEST_CONTROL_H
#include <string>
#include <vector>
@@ -97,7 +97,7 @@ static const size_t DHCPV6_IA_NA_OFFSET = 40;
/// accept 'start' and 'stop' arguments. The first time it is called, it is
/// called with the argument 'start' and the second time with the argument
/// 'stop'.
-///
+///
/// The application is executed by calling fork() to fork the current perfdhcp
/// process and then call execlp() to replace the current process image with
/// the new one.
@@ -987,4 +987,4 @@ private:
} // namespace perfdhcp
} // namespace isc
-#endif // __COMMAND_OPTIONS_H
+#endif // TEST_CONTROL_H
diff --git a/tests/tools/perfdhcp/tests/command_options_helper.h b/tests/tools/perfdhcp/tests/command_options_helper.h
index f9f6d36..7436bd7 100644
--- a/tests/tools/perfdhcp/tests/command_options_helper.h
+++ b/tests/tools/perfdhcp/tests/command_options_helper.h
@@ -12,8 +12,8 @@
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
-#ifndef __COMMAND_OPTIONS_HELPER_H
-#define __COMMAND_OPTIONS_HELPER_H
+#ifndef COMMAND_OPTIONS_HELPER_H
+#define COMMAND_OPTIONS_HELPER_H
#include <string>
#include <vector>
@@ -136,4 +136,4 @@ private:
} // namespace isc::perfdhcp
} // namespace isc
-#endif // __COMMAND_OPTIONS_HELPER_H
+#endif // COMMAND_OPTIONS_HELPER_H
More information about the bind10-changes
mailing list