summaryrefslogtreecommitdiffstats
path: root/lib/resolv.rb
blob: e55bb726547a0b69862cce0f23d91ca0737942b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
=begin
= resolv library
resolv.rb is a resolver library written in Ruby.
Since it is written in Ruby, it is thread-aware.
I.e. it can resolv many hostnames concurrently.

It is possible to lookup various resources of DNS using DNS module directly.

== example
  p Resolv.getaddress("www.ruby-lang.org")
  p Resolv.getname("210.251.121.214")

  Resolv::DNS.open {|dns|
    p dns.getresources("www.ruby-lang.org", Resolv::DNS::Resource::IN::A).collect {|r| r.address}
    p dns.getresources("ruby-lang.org", Resolv::DNS::Resource::IN::MX).collect {|r| [r.exchange.to_s, r.preference]}
  }

== Resolv class

=== class methods
--- Resolv.getaddress(name)
--- Resolv.getaddresses(name)
--- Resolv.each_address(name) {|address| ...}
    They lookups IP addresses of ((|name|)) which represents a hostname
    as a string by default resolver.

    getaddress returns first entry of lookupped addresses.
    getaddresses returns lookupped addresses as an array.
    each_address iterates over lookupped addresses.

--- Resolv.getname(address)
--- Resolv.getnames(address)
--- Resolv.each_name(address) {|name| ...}
    lookups hostnames of ((|address|)) which represents IP address as a string.

    getname returns first entry of lookupped names.
    getnames returns lookupped names as an array.
    each_names iterates over lookupped names.

== Resolv::Hosts class
hostname resolver using /etc/hosts format.

=== class methods
--- Resolv::Hosts.new(hosts='/etc/hosts')

=== methods
--- Resolv::Hosts#getaddress(name)
--- Resolv::Hosts#getaddresses(name)
--- Resolv::Hosts#each_address(name) {|address| ...}
    address lookup methods.

--- Resolv::Hosts#getname(address)
--- Resolv::Hosts#getnames(address)
--- Resolv::Hosts#each_name(address) {|name| ...}
    hostnames lookup methods.

== Resolv::DNS class
DNS stub resolver.

=== class methods
--- Resolv::DNS.new(config_info=nil)

    ((|config_info|)) should be nil, a string or a hash.
    If nil is given, /etc/resolv.conf and platform specific information is used.
    If a string is given, it should be a filename which format is same as /etc/resolv.conf.
    If a hash is given, it may contains information for nameserver, search and ndots as follows.

      Resolv::DNS.new({:nameserver=>["210.251.121.21"], :search=>["ruby-lang.org"], :ndots=>1})

--- Resolv::DNS.open(config_info=nil)
--- Resolv::DNS.open(config_info=nil) {|dns| ...}

=== methods
--- Resolv::DNS#close

--- Resolv::DNS#getaddress(name)
--- Resolv::DNS#getaddresses(name)
--- Resolv::DNS#each_address(name) {|address| ...}
    address lookup methods.

    ((|name|)) must be a instance of Resolv::DNS::Name or String.  Lookupped
    address is represented as an instance of Resolv::IPv4 or Resolv::IPv6.

--- Resolv::DNS#getname(address)
--- Resolv::DNS#getnames(address)
--- Resolv::DNS#each_name(address) {|name| ...}
    hostnames lookup methods.

    ((|address|)) must be a instance of Resolv::IPv4, Resolv::IPv6 or String.
    Lookupped name is represented as an instance of Resolv::DNS::Name.

--- Resolv::DNS#getresource(name, typeclass)
--- Resolv::DNS#getresources(name, typeclass)
--- Resolv::DNS#each_resource(name, typeclass) {|resource| ...}
    They lookup DNS resources of ((|name|)).
    ((|name|)) must be a instance of Resolv::Name or String.

    ((|typeclass|)) should be one of follows:
    * Resolv::DNS::Resource::IN::ANY
    * Resolv::DNS::Resource::IN::NS
    * Resolv::DNS::Resource::IN::CNAME
    * Resolv::DNS::Resource::IN::SOA
    * Resolv::DNS::Resource::IN::HINFO
    * Resolv::DNS::Resource::IN::MINFO
    * Resolv::DNS::Resource::IN::MX
    * Resolv::DNS::Resource::IN::TXT
    * Resolv::DNS::Resource::IN::ANY
    * Resolv::DNS::Resource::IN::A
    * Resolv::DNS::Resource::IN::WKS
    * Resolv::DNS::Resource::IN::PTR
    * Resolv::DNS::Resource::IN::AAAA

    Lookupped resource is represented as an instance of (a subclass of)
    Resolv::DNS::Resource. 
    (Resolv::DNS::Resource::IN::A, etc.)

== Resolv::DNS::Resource::IN::NS class
--- name
== Resolv::DNS::Resource::IN::CNAME class
--- name
== Resolv::DNS::Resource::IN::SOA class
--- mname
--- rname
--- serial
--- refresh
--- retry
--- expire
--- minimum
== Resolv::DNS::Resource::IN::HINFO class
--- cpu
--- os
== Resolv::DNS::Resource::IN::MINFO class
--- rmailbx
--- emailbx
== Resolv::DNS::Resource::IN::MX class
--- preference
--- exchange
== Resolv::DNS::Resource::IN::TXT class
--- data
== Resolv::DNS::Resource::IN::A class
--- address
== Resolv::DNS::Resource::IN::WKS class
--- address
--- protocol
--- bitmap
== Resolv::DNS::Resource::IN::PTR class
--- name
== Resolv::DNS::Resource::IN::AAAA class
--- address

== Resolv::DNS::Name class

=== class methods
--- Resolv::DNS::Name.create(name)

=== methods
--- Resolv::DNS::Name#to_s

== Resolv::DNS::Resource class

== Resolv::IPv4 class
=== class methods
--- Resolv::IPv4.create(address)

=== methods
--- Resolv::IPv4#to_s
--- Resolv::IPv4#to_name

=== constants
--- Resolv::IPv4::Regex
    regular expression for IPv4 address.

== Resolv::IPv6 class
=== class methods
--- Resolv::IPv6.create(address)

=== methods
--- Resolv::IPv6#to_s
--- Resolv::IPv6#to_name

=== constants
--- Resolv::IPv6::Regex
    regular expression for IPv6 address.

== Bugs
* NIS is not supported.
* /etc/nsswitch.conf is not supported.
* IPv6 is not supported.

=end

require 'socket'
require 'fcntl'
require 'timeout'
require 'thread'

class Resolv
  def self.getaddress(name)
    DefaultResolver.getaddress(name)
  end

  def self.getaddresses(name)
    DefaultResolver.getaddresses(name)
  end

  def self.each_address(name, &block)
    DefaultResolver.each_address(name, &block)
  end

  def self.getname(address)
    DefaultResolver.getname(address)
  end

  def self.getnames(address)
    DefaultResolver.getnames(address)
  end

  def self.each_name(address, &proc)
    DefaultResolver.each_name(address, &proc)
  end

  def initialize(resolvers=[Hosts.new, DNS.new])
    @resolvers = resolvers
  end

  def getaddress(name)
    each_address(name) {|address| return address}
    raise ResolvError.new("no address for #{name}")
  end

  def getaddresses(name)
    ret = []
    each_address(name) {|address| ret << address}
    return ret
  end

  def each_address(name)
    if AddressRegex =~ name
      yield name
      return
    end
    yielded = false
    @resolvers.each {|r|
      r.each_address(name) {|address|
        yield address.to_s
        yielded = true
      }
      return if yielded
    }
  end

  def getname(address)
    each_name(address) {|name| return name}
    raise ResolvError.new("no name for #{address}")
  end

  def getnames(address)
    ret = []
    each_name(address) {|name| ret << name}
    return ret
  end

  def each_name(address)
    yielded = false
    @resolvers.each {|r|
      r.each_name(address) {|name|
        yield name.to_s
        yielded = true
      }
      return if yielded
    }
  end

  class ResolvError < StandardError
  end

  class ResolvTimeout < TimeoutError
  end

  class Hosts
    if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
      require 'win32/resolv'
      DefaultFileName = Win32::Resolv.get_hosts_path
    else
      DefaultFileName = '/etc/hosts'
    end

    def initialize(filename = DefaultFileName)
      @filename = filename
      @mutex = Mutex.new
      @initialized = nil
    end

    def lazy_initialize
      @mutex.synchronize {
        unless @initialized
          @name2addr = {}
          @addr2name = {}
          open(@filename) {|f|
            f.each {|line|
              line.sub!(/#.*/, '')
              addr, hostname, *aliases = line.split(/\s+/)
              next unless addr
              addr.untaint
              hostname.untaint
              @addr2name[addr] = [] unless @addr2name.include? addr
              @addr2name[addr] << hostname
              @addr2name[addr] += aliases
              @name2addr[hostname] = [] unless @name2addr.include? hostname
              @name2addr[hostname] << addr
              aliases.each {|n|
                n.untaint
                @name2addr[n] = [] unless @name2addr.include? n
                @name2addr[n] << addr
              }
            }
          }
          @name2addr.each {|name, arr| arr.reverse!}
          @initialized = true
        end
      }
      self
    end

    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("#{@filename} has no name: #{name}")
    end

    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end

    def each_address(name, &proc)
      lazy_initialize
      if @name2addr.include?(name)
        @name2addr[name].each(&proc)
      end
    end

    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("#{@filename} has no address: #{address}")
    end

    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end

    def each_name(address, &proc)
      lazy_initialize
      if @addr2name.include?(address)
        @addr2name[address].each(&proc)
      end
    end
  end

  class DNS
    # STD0013 (RFC 1035, etc.)
    # ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters

    Port = 53
    UDPSize = 512

    DNSThreadGroup = ThreadGroup.new

    def self.open(*args)
      dns = new(*args)
      return dns unless block_given?
      begin
        yield dns
      ensure
        dns.close
      end
    end

    def initialize(config_info=nil)
      @mutex = Mutex.new
      @config = Config.new(config_info)
      @initialized = nil
    end

    def lazy_initialize
      @mutex.synchronize {
        unless @initialized
          @config.lazy_initialize

          if nameserver = @config.single?
            @requester = Requester::ConnectedUDP.new(nameserver)
          else
            @requester = Requester::UnconnectedUDP.new
          end

          @initialized = true
        end
      }
      self
    end

    def close
      @mutex.synchronize {
        if @initialized
          @requester.close if @requester
          @requester = nil
          @initialized = false
        end
      }
    end

    def getaddress(name)
      each_address(name) {|address| return address}
      raise ResolvError.new("DNS result has no information for #{name}")
    end

    def getaddresses(name)
      ret = []
      each_address(name) {|address| ret << address}
      return ret
    end

    def each_address(name)
      each_resource(name, Resource::IN::A) {|resource| yield resource.address}
    end

    def getname(address)
      each_name(address) {|name| return name}
      raise ResolvError.new("DNS result has no information for #{address}")
    end

    def getnames(address)
      ret = []
      each_name(address) {|name| ret << name}
      return ret
    end

    def each_name(address)
      case address
      when Name
        ptr = address
      when IPv4::Regex
        ptr = IPv4.create(address).to_name
      when IPv6::Regex
        ptr = IPv6.create(address).to_name
      else
        raise ResolvError.new("cannot interpret as address: #{address}")
      end
      each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
    end

    def getresource(name, typeclass)
      each_resource(name, typeclass) {|resource| return resource}
      raise ResolvError.new("DNS result has no information for #{name}")
    end

    def getresources(name, typeclass)
      ret = []
      each_resource(name, typeclass) {|resource| ret << resource}
      return ret
    end

    def each_resource(name, typeclass, &proc)
      lazy_initialize
      q = Queue.new
      senders = {}
      begin
        @config.resolv(name) {|candidate, tout, nameserver|
          msg = Message.new
          msg.rd = 1
          msg.add_question(candidate, typeclass)
          unless sender = senders[[candidate, nameserver]]
            sender = senders[[candidate, nameserver]] =
              @requester.sender(msg, candidate, q, nameserver)
          end
          sender.send
          reply = reply_name = nil
          timeout(tout, ResolvTimeout) { reply, reply_name = q.pop }
          case reply.rcode
          when RCode::NoError
            extract_resources(reply, reply_name, typeclass, &proc)
            return
          when RCode::NXDomain
            raise Config::NXDomain.new(reply_name.to_s)
          else
            raise Config::OtherResolvError.new(reply_name.to_s)
          end
        }
      ensure
        @requester.delete(q)
      end
    end

    def extract_resources(msg, name, typeclass)
      if typeclass < Resource::ANY
        n0 = Name.create(name)
        msg.each_answer {|n, ttl, data|
          yield data if n0 == n
        }
      end
      yielded = false
      n0 = Name.create(name)
      msg.each_answer {|n, ttl, data|
        if n0 == n
          case data
          when typeclass
            yield data
            yielded = true
          when Resource::CNAME
            n0 = data.name
          end
        end
      }
      return if yielded
      msg.each_answer {|n, ttl, data|
        if n0 == n
          case data
          when typeclass
            yield data
          end
        end
      }
    end

    class Requester
      def initialize
        @senders = {}
      end

      def close
        thread, sock, @thread, @sock = @thread, @sock
        begin
          if thread
            thread.kill
            thread.join
          end
        ensure
          sock.close if sock
        end
      end

      def delete(arg)
        case arg
        when Sender
          @senders.delete_if {|k, s| s == arg }
        when Queue
          @senders.delete_if {|k, s| s.queue == arg }
        else
          raise ArgumentError.new("neither Sender or Queue: #{arg}")
        end
      end

      class Sender
        def initialize(msg, data, sock, queue)
          @msg = msg
          @data = data
          @sock = sock
          @queue = queue
        end
        attr_reader :queue

        def recv(msg)
          @queue.push([msg, @data])
        end
      end

      class UnconnectedUDP < Requester
        def initialize
          super()
          @sock = UDPSocket.new
          @sock.fcntl(Fcntl::F_SETFD, 1) if defined? Fcntl::F_SETFD
          @id = {}
          @id.default = -1
          @thread = Thread.new {
            DNSThreadGroup.add Thread.current
            loop {
              reply, from = @sock.recvfrom(UDPSize)
              msg = begin
                Message.decode(reply)
              rescue DecodeError
                STDERR.print("DNS message decoding error: #{reply.inspect}\n")
                next
              end
              if s = @senders[[[from[3],from[1]],msg.id]]
                s.recv msg
              else
                #STDERR.print("non-handled DNS message: #{msg.inspect} from #{from.inspect}\n")
              end
            }
          }
        end

        def sender(msg, data, queue, host, port=Port)
          service = [host, port]
          id = Thread.exclusive {
            @id[service] = (@id[service] + 1) & 0xffff
          }
          request = msg.encode
          request[0,2] = [id].pack('n')
          return @senders[[service, id]] =
            Sender.new(request, data, @sock, host, port, queue)
        end

        class Sender < Requester::Sender
          def initialize(msg, data, sock, host, port, queue)
            super(msg, data, sock, queue)
            @host = host
            @port = port
          end

          def send
            @sock.send(@msg, 0, @host, @port)
          end
        end
      end

      class ConnectedUDP < Requester
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          @sock = UDPSocket.new
          @sock.connect(host, port)
          @sock.fcntl(Fcntl::F_SETFD, 1) if defined? Fcntl::F_SETFD
          @id = -1
          @thread = Thread.new {
            DNSThreadGroup.add Thread.current
            loop {
              reply = @sock.recv(UDPSize)
              msg = begin
                Message.decode(reply)
              rescue DecodeError
                STDERR.print("DNS message decoding error: #{reply.inspect}")
                next
              end
              if s = @senders[msg.id]
                s.recv msg
              else
                #STDERR.print("non-handled DNS message: #{msg.inspect}")
              end
            }
          }
        end

        def sender(msg, data, queue, host=@host, port=@port)
          unless host == @host && port == @port
            raise RequestError.new("host/port don't match: #{host}:#{port}")
          end
          id = Thread.exclusive { @id = (@id + 1) & 0xffff }
          request = msg.encode
          request[0,2] = [id].pack('n')
          return @senders[id] = Sender.new(request, data, @sock, queue)
        end

        class Sender < Requester::Sender
          def send
            @sock.send(@msg, 0)
          end
        end
      end

      class TCP < Requester
        def initialize(host, port=Port)
          super()
          @host = host
          @port = port
          @sock = TCPSocket.new
          @sock.connect(host, port)
          @sock.fcntl(Fcntl::F_SETFD, 1) if defined? Fcntl::F_SETFD
          @id = -1
          @senders = {}
          @thread = Thread.new {
            DNSThreadGroup.add Thread.current
            loop {
              len = @sock.read(2).unpack('n')
              reply = @sock.read(len)
              msg = begin
                Message.decode(reply)
              rescue DecodeError
                STDERR.print("DNS message decoding error: #{reply.inspect}")
                next
              end
              if s = @senders[msg.id]
                s.push msg
              else
                #STDERR.print("non-handled DNS message: #{msg.inspect}")
              end
            }
          }
        end

        def sender(msg, data, queue, host=@host, port=@port)
          unless host == @host && port == @port
            raise RequestError.new("host/port don't match: #{host}:#{port}")
          end
          id = Thread.exclusive { @id = (@id + 1) & 0xffff }
          request = msg.encode
          request[0,2] = [request.length, id].pack('nn')
          return @senders[id] = Sender.new(request, data, @sock, queue)
        end

        class Sender < Requester::Sender
          def send
            @sock.print(@msg)
            @sock.flush
          end
        end
      end

      class RequestError < StandardError
      end
    end

    class Config
      def initialize(config_info=nil)
        @mutex = Mutex.new
        @config_info = config_info
        @initialized = nil
      end

      def Config.parse_resolv_conf(filename)
        nameserver = []
        search = nil
        ndots = 1
        open(filename) {|f|
          f.each {|line|
            line.sub!(/[#;].*/, '')
            keyword, *args = line.split(/\s+/)
            args.each { |arg|
              arg.untaint
            }
            next unless keyword
            case keyword
            when 'nameserver'
              nameserver += args
            when 'domain'
              next if args.empty?
              search = [args[0]]
            when 'search'
              next if args.empty?
              search = args
            when 'options'
              args.each {|arg|
                case arg
                when /\Andots:(\d+)\z/
                  ndots = $1.to_i
                end
              }
            end
          }
        }
        return { :nameserver => nameserver, :search => search, :ndots => ndots }
      end

      def Config.default_config_hash(filename="/etc/resolv.conf")
        if File.exist? filename
          config_hash = Config.parse_resolv_conf(filename)
        else
          if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
            search, nameserver = Win32::Resolv.get_resolv_info
            config_hash = {}
            config_hash[:nameserver] = nameserver if nameserver
            config_hash[:search] = [search].flatten if search
          end
        end
        config_hash
      end

      def lazy_initialize
        @mutex.synchronize {
          unless @initialized
            @nameserver = []
            @search = nil
            @ndots = 1
            case @config_info
            when nil
              config_hash = Config.default_config_hash
            when String
              config_hash = Config.parse_resolv_conf(@config_info)
            when Hash
              config_hash = @config_info.dup
              if String === config_hash[:nameserver]
                config_hash[:nameserver] = [config_hash[:nameserver]]
              end
              if String === config_hash[:search]
                config_hash[:search] = [config_hash[:search]]
              end
            else
              raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}")
            end
            @nameserver = config_hash[:nameserver] if config_hash.include? :nameserver
            @search = config_hash[:search] if config_hash.include? :search
            @ndots = config_hash[:ndots] if config_hash.include? :ndots

            @nameserver = ['0.0.0.0'] if @nameserver.empty?
            if @search
              @search = @search.map {|arg| Label.split(arg) }
            else
              hostname = Socket.gethostname
              if /\./ =~ hostname
                @search = [Label.split($')]
              else
                @search = [[]]
              end
            end

            if !@nameserver.kind_of?(Array) ||
               !@nameserver.all? {|ns| String === ns }
              raise ArgumentError.new("invalid nameserver config: #{@nameserver.inspect}")
            end

            if !@search.kind_of?(Array) ||
               !@search.all? {|ls| ls.all? {|l| Label::Str === l } }
              raise ArgumentError.new("invalid search config: #{@search.inspect}")
            end

            if !@ndots.kind_of?(Integer)
              raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}")
            end

            @initialized = true
          end
        }
        self
      end

      def single?
        lazy_initialize
        if @nameserver.length == 1
          return @nameserver[0]
        else
          return nil
        end
      end

      def generate_candidates(name)
        candidates = nil
        name = Name.create(name)
        if name.absolute?
          candidates = [name]
        else
          if @ndots <= name.length - 1
            candidates = [Name.new(name.to_a)]
          else
            candidates = []
          end
          candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
        end
        return candidates
      end

      InitialTimeout = 5

      def generate_timeouts
        ts = [InitialTimeout]
        ts << ts[-1] * 2 / @nameserver.length
        ts << ts[-1] * 2
        ts << ts[-1] * 2
        return ts
      end

      def resolv(name)
        candidates = generate_candidates(name)
        timeouts = generate_timeouts
        begin
          candidates.each {|candidate|
            begin
              timeouts.each {|tout|
                @nameserver.each {|nameserver|
                  begin
                    yield candidate, tout, nameserver
                  rescue ResolvTimeout
                  end
                }
              }
              raise ResolvError.new("DNS resolv timeout: #{name}")
            rescue NXDomain
            end
          }
        rescue ResolvError
        end
      end

      class NXDomain < ResolvError
      end

      class OtherResolvError < ResolvError
      end
    end

    module OpCode
      Query = 0
      IQuery = 1
      Status = 2
      Notify = 4
      Update = 5
    end

    module RCode
      NoError = 0
      FormErr = 1
      ServFail = 2
      NXDomain = 3
      NotImp = 4
      Refused = 5
      YXDomain = 6
      YXRRSet = 7
      NXRRSet = 8
      NotAuth = 9
      NotZone = 10
      BADVERS = 16
      BADSIG = 16
      BADKEY = 17
      BADTIME = 18
      BADMODE = 19
      BADNAME = 20
      BADALG = 21
    end

    class DecodeError < StandardError
    end

    class EncodeError < StandardError
    end

    module Label
      def self.split(arg)
        labels = []
        arg.scan(/[^\.]+/) {labels << Str.new($&)}
        return labels
      end

      class Str
        def initialize(string)
          @string = string
          @downcase = string.downcase
        end
        attr_reader :string, :downcase

        def to_s
          return @string
        end

        def inspect
          return "#<#{self.class} #{self.to_s}>"
        end

        def ==(other)
          return @downcase == other.downcase
        end

        def eql?(other)
          return self == other
        end

        def hash
          return @downcase.hash
        end
      end
    end

    class Name
      def self.create(arg)
        case arg
        when Name
          return arg
        when String
          return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
        else
          raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
        end
      end

      def initialize(labels, absolute=true)
        @labels = labels
        @absolute = absolute
      end

      def inspect
        "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
      end

      def absolute?
        return @absolute
      end

      def ==(other)
        return false unless Name === other
        return @labels == other.to_a && @absolute == other.absolute?
      end
      alias eql? ==

      # tests subdomain-of relation.
      #
      #   domain = Resolv::DNS::Name.create("y.z")
      #   p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
      #   p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
      #   p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
      #   p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
      #   p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
      #   p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
      #
      def subdomain_of?(other)
        raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
        return false if @absolute != other.absolute?
        other_len = other.length
        return false if @labels.length <= other_len
        return @labels[-other_len, other_len] == other.to_a
      end

      def hash
        return @labels.hash ^ @absolute.hash
      end

      def to_a
        return @labels
      end

      def length
        return @labels.length
      end

      def [](i)
        return @labels[i]
      end

      # returns the domain name as a string.
      #
      # The domain name doesn't have a trailing dot even if the name object is
      # absolute.
      #
      #   p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
      #   p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"
      #
      def to_s
        return @labels.join('.')
      end
    end

    class Message
      @@identifier = -1

      def initialize(id = (@@identifier += 1) & 0xffff)
        @id = id
        @qr = 0
        @opcode = 0
        @aa = 0
        @tc = 0
        @rd = 0 # recursion desired
        @ra = 0 # recursion available
        @rcode = 0
        @question = []
        @answer = []
        @authority = []
        @additional = []
      end

      attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode
      attr_reader :question, :answer, :authority, :additional

      def ==(other)
        return @id == other.id &&
               @qr == other.qr &&
               @opcode == other.opcode &&
               @aa == other.aa &&
               @tc == other.tc &&
               @rd == other.rd &&
               @ra == other.ra &&
               @rcode == other.rcode &&
               @question == other.question &&
               @answer == other.answer &&
               @authority == other.authority &&
               @additional == other.additional
      end

      def add_question(name, typeclass)
        @question << [Name.create(name), typeclass]
      end

      def each_question
        @question.each {|name, typeclass|
          yield name, typeclass
        }
      end

      def add_answer(name, ttl, data)
        @answer << [Name.create(name), ttl, data]
      end

      def each_answer
        @answer.each {|name, ttl, data|
          yield name, ttl, data
        }
      end

      def add_authority(name, ttl, data)
        @authority << [Name.create(name), ttl, data]
      end

      def each_authority
        @authority.each {|name, ttl, data|
          yield name, ttl, data
        }
      end

      def add_additional(name, ttl, data)
        @additional << [Name.create(name), ttl, data]
      end

      def each_additional
        @additional.each {|name, ttl, data|
          yield name, ttl, data
        }
      end

      def each_resource
        each_answer {|name, ttl, data| yield name, ttl, data}
        each_authority {|name, ttl, data| yield name, ttl, data}
        each_additional {|name, ttl, data| yield name, ttl, data}
      end

      def encode
        return MessageEncoder.new {|msg|
          msg.put_pack('nnnnnn',
            @id,
            (@qr & 1) << 15 |
            (@opcode & 15) << 11 |
            (@aa & 1) << 10 |
            (@tc & 1) << 9 |
            (@rd & 1) << 8 |
            (@ra & 1) << 7 |
            (@rcode & 15),
            @question.length,
            @answer.length,
            @authority.length,
            @additional.length)
          @question.each {|q|
            name, typeclass = q
            msg.put_name(name)
            msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
          }
          [@answer, @authority, @additional].each {|rr|
            rr.each {|r|
              name, ttl, data = r
              msg.put_name(name)
              msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
              msg.put_length16 {data.encode_rdata(msg)}
            }
          }
        }.to_s
      end

      class MessageEncoder
        def initialize
          @data = ''
          @names = {}
          yield self
        end

        def to_s
          return @data
        end

        def put_bytes(d)
          @data << d
        end

        def put_pack(template, *d)
          @data << d.pack(template)
        end

        def put_length16
          length_index = @data.length
          @data << "\0\0"
          data_start = @data.length
          yield
          data_end = @data.length
          @data[length_index, 2] = [data_end - data_start].pack("n")
        end

        def put_string(d)
          self.put_pack("C", d.length)
          @data << d
        end

        def put_string_list(ds)
          ds.each {|d|
            self.put_string(d)
          }
        end

        def put_name(d)
          put_labels(d.to_a)
        end

        def put_labels(d)
          d.each_index {|i|
            domain = d[i..-1]
            if idx = @names[domain]
              self.put_pack("n", 0xc000 | idx)
              return
            else
              @names[domain] = @data.length
              self.put_label(d[i])
            end
          }
          @data << "\0"
        end

        def put_label(d)
          self.put_string(d.string)
        end
      end

      def Message.decode(m)
        o = Message.new(0)
        MessageDecoder.new(m) {|msg|
          id, flag, qdcount, ancount, nscount, arcount =
            msg.get_unpack('nnnnnn')
          o.id = id
          o.qr = (flag >> 15) & 1
          o.opcode = (flag >> 11) & 15
          o.aa = (flag >> 10) & 1
          o.tc = (flag >> 9) & 1
          o.rd = (flag >> 8) & 1
          o.ra = (flag >> 7) & 1
          o.rcode = flag & 15
          (1..qdcount).each {
            name, typeclass = msg.get_question
            o.add_question(name, typeclass)
          }
          (1..ancount).each {
            name, ttl, data = msg.get_rr
            o.add_answer(name, ttl, data)
          }
          (1..nscount).each {
            name, ttl, data = msg.get_rr
            o.add_authority(name, ttl, data)
          }
          (1..arcount).each {
            name, ttl, data = msg.get_rr
            o.add_additional(name, ttl, data)
          }
        }
        return o
      end

      class MessageDecoder
        def initialize(data)
          @data = data
          @index = 0
          @limit = data.length
          yield self
        end

        def get_length16
          len, = self.get_unpack('n')
          save_limit = @limit
          @limit = @index + len
          d = yield(len)
          if @index < @limit
            raise DecodeError.new("junk exists")
          elsif @limit < @index
            raise DecodeError.new("limit exceeded")
          end
          @limit = save_limit
          return d
        end

        def get_bytes(len = @limit - @index)
          d = @data[@index, len]
          @index += len
          return d
        end

        def get_unpack(template)
          len = 0
          template.each_byte {|byte|
            case byte
            when ?c, ?C
              len += 1
            when ?n
              len += 2
            when ?N
              len += 4
            else
              raise StandardError.new("unsupported template: '#{byte.chr}' in '#{template}'")
            end
          }
          raise DecodeError.new("limit exceeded") if @limit < @index + len
          arr = @data.unpack("@#{@index}#{template}")
          @index += len
          return arr
        end

        def get_string
          len = @data[@index]
          raise DecodeError.new("limit exceeded") if @limit < @index + 1 + len
          d = @data[@index + 1, len]
          @index += 1 + len
          return d
        end

        def get_string_list
          strings = []
          while @index < @limit
            strings << self.get_string
          end
          strings
        end

        def get_name
          return Name.new(self.get_labels)
        end

        def get_labels(limit=nil)
          limit = @index if !limit || @index < limit
          d = []
          while true
            case @data[@index]
            when 0
              @index += 1
              return d
            when 192..255
              idx = self.get_unpack('n')[0] & 0x3fff
              if limit <= idx
                raise DecodeError.new("non-backward name pointer")
              end
              save_index = @index
              @index = idx
              d += self.get_labels(limit)
              @index = save_index
              return d
            else
              d << self.get_label
            end
          end
          return d
        end

        def get_label
          return Label::Str.new(self.get_string)
        end

        def get_question
          name = self.get_name
          type, klass = self.get_unpack("nn")
          return name, Resource.get_class(type, klass)
        end

        def get_rr
          name = self.get_name
          type, klass, ttl = self.get_unpack('nnN')
          typeclass = Resource.get_class(type, klass)
          return name, ttl, self.get_length16 {typeclass.decode_rdata(self)}
        end
      end
    end

    class Query
      def encode_rdata(msg)
        raise EncodeError.new("#{self.class} is query.") 
      end

      def self.decode_rdata(msg)
        raise DecodeError.new("#{self.class} is query.") 
      end
    end

    class Resource < Query
      ClassHash = {}

      def encode_rdata(msg)
        raise NotImplementedError.new
      end

      def self.decode_rdata(msg)
        raise NotImplementedError.new
      end

      def ==(other)
        return self.class == other.class &&
          self.instance_variables == other.instance_variables &&
          self.instance_variables.collect {|name| self.instance_eval name} ==
            other.instance_variables.collect {|name| other.instance_eval name}
      end

      def eql?(other)
        return self == other
      end

      def hash
        h = 0
        self.instance_variables.each {|name|
          h ^= self.instance_eval("#{name}.hash")
        }
        return h
      end

      def self.get_class(type_value, class_value)
        return ClassHash[[type_value, class_value]] ||
               Generic.create(type_value, class_value)
      end

      class Generic < Resource
        def initialize(data)
          @data = data
        end
        attr_reader :data

        def encode_rdata(msg)
          msg.put_bytes(data)
        end

        def self.decode_rdata(msg)
          return self.new(msg.get_bytes)
        end

        def self.create(type_value, class_value)
          c = Class.new(Generic)
          c.const_set(:TypeValue, type_value)
          c.const_set(:ClassValue, class_value)
          Generic.const_set("Type#{type_value}_Class#{class_value}", c)
          ClassHash[[type_value, class_value]] = c
          return c
        end
      end

      class DomainName < Resource
        def initialize(name)
          @name = name
        end
        attr_reader :name

        def encode_rdata(msg)
          msg.put_name(@name)
        end

        def self.decode_rdata(msg)
          return self.new(msg.get_name)
        end
      end

      # Standard (class generic) RRs
      ClassValue = nil

      class NS < DomainName
        TypeValue = 2
      end

      class CNAME < DomainName
        TypeValue = 5
      end

      class SOA < Resource
        TypeValue = 6

        def initialize(mname, rname, serial, refresh, retry_, expire, minimum)
          @mname = mname
          @rname = rname
          @serial = serial
          @refresh = refresh
          @retry = retry_
          @expire = expire
          @minimum = minimum
        end
        attr_reader :mname, :rname, :serial, :refresh, :retry, :expire, :minimum

        def encode_rdata(msg)
          msg.put_name(@mname)
          msg.put_name(@rname)
          msg.put_pack('NNNNN', @serial, @refresh, @retry, @expire, @minimum)
        end

        def self.decode_rdata(msg)
          mname = msg.get_name
          rname = msg.get_name
          serial, refresh, retry_, expire, minimum = msg.get_unpack('NNNNN')
          return self.new(
            mname, rname, serial, refresh, retry_, expire, minimum)
        end
      end

      class PTR < DomainName
        TypeValue = 12
      end

      class HINFO < Resource
        TypeValue = 13

        def initialize(cpu, os)
          @cpu = cpu
          @os = os
        end
        attr_reader :cpu, :os

        def encode_rdata(msg)
          msg.put_string(@cpu)
          msg.put_string(@os)
        end

        def self.decode_rdata(msg)
          cpu = msg.get_string
          os = msg.get_string
          return self.new(cpu, os)
        end
      end

      class MINFO < Resource
        TypeValue = 14

        def initialize(rmailbx, emailbx)
          @rmailbx = rmailbx
          @emailbx = emailbx
        end
        attr_reader :rmailbx, :emailbx

        def encode_rdata(msg)
          msg.put_name(@rmailbx)
          msg.put_name(@emailbx)
        end

        def self.decode_rdata(msg)
          rmailbx = msg.get_string
          emailbx = msg.get_string
          return self.new(rmailbx, emailbx)
        end
      end

      class MX < Resource
        TypeValue= 15

        def initialize(preference, exchange)
          @preference = preference
          @exchange = exchange
        end
        attr_reader :preference, :exchange

        def encode_rdata(msg)
          msg.put_pack('n', @preference)
          msg.put_name(@exchange)
        end

        def self.decode_rdata(msg)
          preference, = msg.get_unpack('n')
          exchange = msg.get_name
          return self.new(preference, exchange)
        end
      end

      class TXT < Resource
        TypeValue = 16

        def initialize(first_string, *rest_strings)
          @strings = [first_string, *rest_strings]
        end
        attr_reader :strings

        def data
          @strings[0]
        end

        def encode_rdata(msg)
          msg.put_string_list(@strings)
        end

        def self.decode_rdata(msg)
          strings = msg.get_string_list
          return self.new(*strings)
        end
      end

      class ANY < Query
        TypeValue = 255
      end

      ClassInsensitiveTypes = [
        NS, CNAME, SOA, PTR, HINFO, MINFO, MX, TXT, ANY
      ]

      # ARPA Internet specific RRs
      module IN
        ClassValue = 1

        ClassInsensitiveTypes.each {|s|
          c = Class.new(s)
          c.const_set(:TypeValue, s::TypeValue)
          c.const_set(:ClassValue, ClassValue)
          ClassHash[[s::TypeValue, ClassValue]] = c
          self.const_set(s.name.sub(/.*::/, ''), c)
        }

        class A < Resource
          ClassHash[[TypeValue = 1, ClassValue = ClassValue]] = self

          def initialize(address)
            @address = IPv4.create(address)
          end
          attr_reader :address

          def encode_rdata(msg)
            msg.put_bytes(@address.address)
          end

          def self.decode_rdata(msg)
            return self.new(IPv4.new(msg.get_bytes(4)))
          end
        end

        class WKS < Resource
          ClassHash[[TypeValue = 11, ClassValue = ClassValue]] = self

          def initialize(address, protocol, bitmap)
            @address = IPv4.create(address)
            @protocol = protocol
            @bitmap = bitmap
          end
          attr_reader :address, :protocol, :bitmap

          def encode_rdata(msg)
            msg.put_bytes(@address.address)
            msg.put_pack("n", @protocol)
            msg.put_bytes(@bitmap)
          end

          def self.decode_rdata(msg)
            address = IPv4.new(msg.get_bytes(4))
            protocol, = msg.get_unpack("n")
            bitmap = msg.get_bytes
            return self.new(address, protocol, bitmap)
          end
        end

        class AAAA < Resource
          ClassHash[[TypeValue = 28, ClassValue = ClassValue]] = self

          def initialize(address)
            @address = IPv6.create(address)
          end
          attr_reader :address

          def encode_rdata(msg)
            msg.put_bytes(@address.address)
          end

          def self.decode_rdata(msg)
            return self.new(IPv6.new(msg.get_bytes(16)))
          end
        end

        # SRV resource record defined in RFC 2782
        # 
        # These records identify the hostname and port that a service is
        # available at.
        # 
        # The format is:
        #   _Service._Proto.Name TTL Class SRV Priority Weight Port Target
        #
        # The fields specific to SRV are defined in RFC 2782 as meaning:
        # - +priority+ The priority of this target host.  A client MUST attempt
        #   to contact the target host with the lowest-numbered priority it can
        #   reach; target hosts with the same priority SHOULD be tried in an
        #   order defined by the weight field.  The range is 0-65535.  Note that
        #   it is not widely implemented and should be set to zero.
        # 
        # - +weight+ A server selection mechanism.  The weight field specifies
        #   a relative weight for entries with the same priority. Larger weights
        #   SHOULD be given a proportionately higher probability of being
        #   selected. The range of this number is 0-65535.  Domain administrators
        #   SHOULD use Weight 0 when there isn't any server selection to do, to
        #   make the RR easier to read for humans (less noisy). Note that it is
        #   not widely implemented and should be set to zero.
        #
        # - +port+  The port on this target host of this service.  The range is 0-
        #   65535.
        # 
        # - +target+ The domain name of the target host. A target of "." means
        #   that the service is decidedly not available at this domain.
        class SRV < Resource
          ClassHash[[TypeValue = 33, ClassValue = ClassValue]] = self

          # Create a SRV resource record.
          def initialize(priority, weight, port, target)
            @priority = priority.to_int
            @weight = weight.to_int
            @port = port.to_int
            @target = Name.create(target)
          end

          attr_reader :priority, :weight, :port, :target

          def encode_rdata(msg)
            msg.put_pack("n", @priority)
            msg.put_pack("n", @weight)
            msg.put_pack("n", @port)
            msg.put_name(@target)
          end

          def self.decode_rdata(msg)
            priority, = msg.get_unpack("n")
            weight,   = msg.get_unpack("n")
            port,     = msg.get_unpack("n")
            target    = msg.get_name
            return self.new(priority, weight, port, target)
          end
        end

      end
    end
  end

  class IPv4
    Regex = /\A(\d+)\.(\d+)\.(\d+)\.(\d+)\z/

    def self.create(arg)
      case arg
      when IPv4
        return arg
      when Regex
        if (0..255) === (a = $1.to_i) &&
           (0..255) === (b = $2.to_i) &&
           (0..255) === (c = $3.to_i) &&
           (0..255) === (d = $4.to_i)
          return self.new([a, b, c, d].pack("CCCC"))
        else
          raise ArgumentError.new("IPv4 address with invalid value: " + arg)
        end
      else
        raise ArgumentError.new("cannot interpret as IPv4 address: #{arg.inspect}")
      end
    end

    def initialize(address)
      unless address.kind_of?(String) && address.length == 4
        raise ArgumentError.new('IPv4 address must be 4 bytes')
      end
      @address = address
    end
    attr_reader :address

    def to_s
      return sprintf("%d.%d.%d.%d", *@address.unpack("CCCC"))
    end

    def inspect
      return "#<#{self.class} #{self.to_s}>"
    end

    def to_name
      return DNS::Name.create(
        '%d.%d.%d.%d.in-addr.arpa.' % @address.unpack('CCCC').reverse)
    end

    def ==(other)
      return @address == other.address
    end

    def eql?(other)
      return self == other
    end

    def hash
      return @address.hash
    end
  end

  class IPv6
    Regex_8Hex = /\A
      (?:[0-9A-Fa-f]{1,4}:){7}
         [0-9A-Fa-f]{1,4}
      \z/x

    Regex_CompressedHex = /\A
      ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
      ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)
      \z/x

    Regex_6Hex4Dec = /\A
      ((?:[0-9A-Fa-f]{1,4}:){6,6})
      (\d+)\.(\d+)\.(\d+)\.(\d+)
      \z/x

    Regex_CompressedHex4Dec = /\A
      ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
      ((?:[0-9A-Fa-f]{1,4}:)*)
      (\d+)\.(\d+)\.(\d+)\.(\d+)
      \z/x

    Regex = /
      (?:#{Regex_8Hex}) |
      (?:#{Regex_CompressedHex}) |
      (?:#{Regex_6Hex4Dec}) |
      (?:#{Regex_CompressedHex4Dec})/x

    def self.create(arg)
      case arg
      when IPv6
        return arg
      when String
        address = ''
        if Regex_8Hex =~ arg
          arg.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
        elsif Regex_CompressedHex =~ arg
          prefix = $1
          suffix = $2
          a1 = ''
          a2 = ''
          prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
          suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
          omitlen = 16 - a1.length - a2.length
          address << a1 << "\0" * omitlen << a2
        elsif Regex_6Hex4Dec =~ arg
          prefix, a, b, c, d = $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i
          if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
            prefix.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
            address << [a, b, c, d].pack('CCCC')
          else
            raise ArgumentError.new("not numeric IPv6 address: " + arg)
          end
        elsif Regex_CompressedHex4Dec =~ arg
          prefix, suffix, a, b, c, d = $1, $2, $3.to_i, $4.to_i, $5.to_i, $6.to_i
          if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
            a1 = ''
            a2 = ''
            prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
            suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
            omitlen = 12 - a1.length - a2.length
            address << a1 << "\0" * omitlen << a2 << [a, b, c, d].pack('CCCC')
          else
            raise ArgumentError.new("not numeric IPv6 address: " + arg)
          end
        else
          raise ArgumentError.new("not numeric IPv6 address: " + arg)
        end
        return IPv6.new(address)
      else
        raise ArgumentError.new("cannot interpret as IPv6 address: #{arg.inspect}")
      end
    end

    def initialize(address)
      unless address.kind_of?(String) && address.length == 16
        raise ArgumentError.new('IPv6 address must be 16 bytes')
      end
      @address = address
    end
    attr_reader :address

    def to_s
      address = sprintf("%X:%X:%X:%X:%X:%X:%X:%X", *@address.unpack("nnnnnnnn"))
      unless address.sub!(/(^|:)0(:0)+(:|$)/, '::')
        address.sub!(/(^|:)0(:|$)/, '::')
      end
      return address
    end

    def inspect
      return "#<#{self.class} #{self.to_s}>"
    end

    def to_name
      # ip6.arpa should be searched too. [RFC3152]
      return DNS::Name.new(
        @address.unpack("H32")[0].split(//).reverse + ['ip6', 'int'])
    end

    def ==(other)
      return @address == other.address
    end

    def eql?(other)
      return self == other
    end

    def hash
      return @address.hash
    end
  end

  DefaultResolver = self.new
  AddressRegex = /(?:#{IPv4::Regex})|(?:#{IPv6::Regex})/
end