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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..4503982d105a277e9f8fd3537bf17d73edc17bdf
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+#
+# Configuration file for the Sphinx documentation builder.
+#
+# This file does only contain a selection of the most common options. For a
+# full list see the documentation:
+# http://www.sphinx-doc.org/en/master/config
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+import os
+import sys
+
+loc = os.path.abspath(os.path.dirname(__file__))
+module_name = "localzone"
+module_loc = os.path.join(loc, "..")
+sys.path.insert(0, module_loc)
+
+about = {}
+with open(os.path.join(module_loc, module_name, "__version__.py")) as f:
+    exec(f.read(), about)
+
+
+# -- Project information -----------------------------------------------------
+
+project = 'localzone'
+copyright = '2018, Andrew Grant Spencer'
+author = 'Andrew Grant Spencer'
+
+# The short X.Y version
+version = about["__version__"]
+# The full version, including alpha/beta/rc tags
+release = about["__version__"]
+
+
+# -- General configuration ---------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#
+# needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+    'sphinx.ext.autodoc',
+    'sphinx.ext.doctest',
+    'sphinx.ext.todo',
+    'sphinx.ext.coverage',
+    'sphinx.ext.viewcode',
+    'sphinx.ext.githubpages',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+#
+# source_suffix = ['.rst', '.md']
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = None
+
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'sphinx_rtd_theme'
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#
+html_logo = "_static/localzone-light.svg"
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further.  For a list of options available for each theme, see the
+# documentation.
+#
+html_theme_options = {
+    'canonical_url': '/',
+}
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# Custom sidebar templates, must be a dictionary that maps document names
+# to template names.
+#
+# The default sidebars (for documents that don't match any pattern) are
+# defined by theme itself.  Builtin themes are using these templates by
+# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
+# 'searchbox.html']``.
+#
+# html_sidebars = {}
+
+html_context = {
+    "display_github": True, # Integrate GitHub
+    "github_user": "ags-slc", # Username
+    "github_repo": "localzone", # Repo name
+    "github_version": "master", # Version
+    "conf_py_path": "/docs/", # Path in the checkout to the docs root
+}
+
+# -- Options for HTMLHelp output ---------------------------------------------
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'localzonedoc'
+
+
+# -- Options for LaTeX output ------------------------------------------------
+
+latex_elements = {
+    # The paper size ('letterpaper' or 'a4paper').
+    #
+    # 'papersize': 'letterpaper',
+
+    # The font size ('10pt', '11pt' or '12pt').
+    #
+    # 'pointsize': '10pt',
+
+    # Additional stuff for the LaTeX preamble.
+    #
+    # 'preamble': '',
+
+    # Latex figure (float) alignment
+    #
+    # 'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+#  author, documentclass [howto, manual, or own class]).
+latex_documents = [
+    (master_doc, 'localzone.tex', 'localzone Documentation',
+     'Andrew Grant Spencer', 'manual'),
+]
+
+
+# -- Options for manual page output ------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+    (master_doc, 'localzone', 'localzone Documentation',
+     [author], 1)
+]
+
+
+# -- Options for Texinfo output ----------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+#  dir menu entry, description, category)
+texinfo_documents = [
+    (master_doc, 'localzone', 'localzone Documentation',
+     author, 'localzone', 'One line description of project.',
+     'Miscellaneous'),
+]
+
+
+# -- Options for Epub output -------------------------------------------------
+
+# Bibliographic Dublin Core info.
+epub_title = project
+
+# The unique identifier of the text. This can be a ISBN number
+# or the project homepage.
+#
+# epub_identifier = ''
+
+# A unique identification for the text.
+#
+# epub_uid = ''
+
+# A list of files that should not be packed into the epub file.
+epub_exclude_files = ['search.html']
+
+
+# -- Extension configuration -------------------------------------------------
+
+# -- Options for todo extension ----------------------------------------------
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = True
diff --git a/localzone/__init__.py b/localzone/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b93506ef32fab7223fee087d9a8480f022d696ca
--- /dev/null
+++ b/localzone/__init__.py
@@ -0,0 +1,48 @@
+#
+# You have entered the localzone.
+#
+
+"""
+The `localzone` DNS Library
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A simple DNS library, written in Python, for managing zone files.
+
+Basic usage:
+
+   >>> import localzone
+   >>> with localzone.manage("db.example.com") as z:
+   ...     r = z.add_record("greeting", "TXT", "hello, world!")
+   ...     r.name    # the record name, i.e. 'greeting'
+   ...     r.rdtype  # the record type, i.e. 'TXT'
+   ...     r.content # the record content, i.e. '"hello," "world!"'
+   ...
+
+Print the zone's resource records:
+
+   >>> import localzone
+   >>> with localzone.manage("db.example.com") as z:
+   ...     print(*z.records, sep="\\n")
+   ...
+   @ 3600 IN SOA ns username 2007120710 86400 7200 2419200 3600
+   @ 3600 IN NS ns
+   @ 3600 IN NS ns.somewhere.example.
+   @ 3600 IN MX 10 mail
+   @ ...
+
+or:
+
+   >>> import localzone
+   >>> with localzone.manage("db.example.com") as z:
+   >>>     for r in z.records:
+   >>>         print(r)
+   ...
+
+The full documentation is available at <https://localzone.iomaestro.com>.
+
+:copyright: (c) 2018 by Andrew Grant Spencer.
+:license: BSD, see LICENSE for more details.
+"""
+
+from .context import manage, load
+from .models import Zone, Record
diff --git a/localzone/__version__.py b/localzone/__version__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6853b7bb5a75dc2e65fe2c52feab60039b1adbb9
--- /dev/null
+++ b/localzone/__version__.py
@@ -0,0 +1,10 @@
+VERSION = (0, 9, 8)
+
+__title__ = "localzone"
+__description__ = "A simple library for managing DNS zones."
+__url__ = "https://localzone.iomaestro.com"
+__version__ = ".".join(map(str, VERSION))
+__author__ = "Andrew Grant Spencer"
+__author_email__ = "ags@iomaestro.com"
+__license__ = "BSD"
+__copyright__ = "Copyright (C) 2018 Andrew Grant Spencer"
diff --git a/localzone/context.py b/localzone/context.py
new file mode 100644
index 0000000000000000000000000000000000000000..7354c4a70fabe64e658a5f64b026c4cdba805af5
--- /dev/null
+++ b/localzone/context.py
@@ -0,0 +1,106 @@
+"""
+localzone.context
+~~~~~~~~~~~~~~~~~
+
+This module implements the methods for localzone context management.
+
+:copyright: (c) 2018 Andrew Grant Spencer
+:license: BSD, see LICENSE for more details.
+"""
+
+from contextlib import contextmanager
+import dns.name
+import dns.rdataclass
+import dns.tokenizer
+import dns.zone
+try:
+    # The api for the zonefile reader was exposed in dnspython 2.1
+    from dns.zonefile import Reader
+    DNSPYTHON21 = True
+except ImportError:
+    from dns.zone import _MasterReader
+    DNSPYTHON21 = False
+
+from .models import Zone
+
+
+@contextmanager
+def manage(filename, origin=None, autosave=False):
+    """
+    A context manager that yields a :class:`Zone <Zone>` object.
+
+    :param filename: The path to the zone's master file.
+    :type filename: string
+    :param origin: (optional) The zone's origin domain
+    :type origin: string
+    :param autosave: (optional) controls whether or not the zone's master file
+        is written to disk upon exit
+    :type autosave: bool
+    :return: :class:`Zone <Zone>` object
+    :rtype: localzone.models.Zone
+    """
+    if origin:
+        # perform basic validation/sanitization on origin
+        origin = dns.name.from_text(origin).to_text()
+
+    zone = load(filename, origin)
+
+    try:
+        yield zone
+    finally:
+        if autosave:
+            zone.save()
+
+
+def load(filename, origin=None):
+    """
+    Read a master zone file and construct a :class:`Zone <Zone>` object.
+
+    :param filename: The path to the zone's master file.
+    :type filename: string
+    :param origin: (optional) The zone's origin domain
+    :type origin: string
+    :return: :class:`Zone <Zone>` object
+    :rtype: localzone.Zone
+    """
+    with open(filename) as text:
+        tok = dns.tokenizer.Tokenizer(text, filename)
+        if DNSPYTHON21:
+            zone = Zone(
+                origin,
+                dns.rdataclass.IN,
+                relativize=True,
+                )
+            with zone.writer() as txn:
+                reader = Reader(
+                    tok,
+                    rdclass=dns.rdataclass.IN,
+                    txn=txn,
+                    allow_include=True,
+                )
+                reader.read()
+        else:
+            reader = _MasterReader(
+                tok,
+                origin=origin,
+                rdclass=dns.rdataclass.IN,
+                relativize=True,
+                zone_factory=Zone,
+                allow_include=True,
+                check_origin=True,
+            )
+            reader.read()
+            zone = reader.zone
+
+    # TODO: remember that any method using the zone.filename property should
+    # have it passed as a parameter
+    zone._filename = filename
+
+    # starting with dnspython v1.16.0, use default_ttl
+    try:
+        zone._ttl = reader.default_ttl
+    except AttributeError:
+        zone._ttl = reader.ttl
+
+    return zone
+
diff --git a/localzone/models.py b/localzone/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..44d93baea6bfe5decbfc5a7a8a0051c83a990037
--- /dev/null
+++ b/localzone/models.py
@@ -0,0 +1,372 @@
+"""
+localzone.models
+~~~~~~~~~~~~~~~~
+
+This module contains the primary objects that power localzone.
+
+:copyright: (c) 2018 Andrew Grant Spencer
+:license: BSD, see LICENSE for more details.
+"""
+
+from collections import namedtuple
+from time import strftime, localtime, time
+from dns.zone import Zone as DNSZone
+import dns.name
+import dns.rdata
+import dns.rdataclass
+import dns.rdatatype
+from .util import checksum
+
+
+class Zone(DNSZone):
+    """
+    Initialize a :class:`Zone <Zone>` object.
+
+    The Zone class extends its base class dns.zone.Zone with additional
+    abstractions (or denormalizations) for dealing with DNS zone records.
+
+    :param origin: The zone's origin.
+    :type origin: :class:`dns.name.Name <Name>` object or string
+    :param rdclass: The zone's rdata class; the default is class
+        `dns.rdataclass.IN`.
+    :type rdclass: int
+    :param relativize: Should the zone's names be relativized to the origin?
+    :type relativize: bool
+    """
+
+    def _increment_serial(self):
+        """
+        Increment the zone's serial.
+        Credit: https://bitbucket.org/chrismiles/easyzone/
+        """
+        next_serial = int(strftime("%Y%m%d00", localtime(time())))
+
+        if next_serial <= self.soa.rdata.serial:
+            next_serial = self.soa.rdata.serial + 1
+
+        # TODO: this is cheating a little bit, since record rdata is mutable.
+        # The immutable hashid of the SOA record will be out of sync until the
+        # record is released. Probably not a big deal, as there is really no
+        # reason to hold the record given the existence of the soa property.
+        # Should this implementation be reconsidered?
+        if hasattr(self.soa.rdata, 'replace'):
+            content = self.soa.rdata.replace(serial=next_serial).to_text()
+            self.update_record(self.soa.hashid, content)
+        else:
+            self.soa.rdata.serial = next_serial
+
+    def save(self, filename=None, autoserial=True):
+        """
+        Write the zone master file to disk. If `filename` is not provided, the
+        file from which the zone was originally loaded will be written.
+
+        NB: this will replace the file located at `filename`.
+
+        :param filename: The location to where the zone master file will be
+            written.
+        :type filename: string
+        :param autoserial: Should the zone's serial be updated automatically?
+        :type autoserial: bool
+        """
+        if not filename:
+            filename = self.filename
+
+        if autoserial:
+            self._increment_serial()
+
+        # TODO: investigate subclassing dns.zone.Zone.to_file() to support the
+        # `$ORIGIN` and `$TTL` directives, e.g. with_origin=True, with_ttl=True.
+        self.to_file(filename)
+
+    def get_record(self, hashid):
+        """
+        Get a resource record via ID. If no record is found, raise a `KeyError`.
+
+        :param hashid: The record's ID.
+        :type hashid: string
+        :return: :class:`Record <Record>` object
+        :rtype: localzone.models.Record
+        """
+        record = next((r for r in self.records if r.hashid == hashid), None)
+
+        if not record:
+            raise KeyError("The supplied hashid was not found in the zone")
+
+        return record
+
+    def get_records(self, rdtype):
+        """
+        Create and return a list of each resource record in the zone matching
+        the specified type. If rdtype is `"ANY"`, all zone records are returned.
+
+        :param rdtype: The record's type.
+        :type rdtype: string
+        :return: list of :class:`Record <Record>` objects
+        :rtype: list
+        """
+        result = []
+
+        for n in self.nodes:
+            for rds in self[n]:
+                for r in rds:
+                    if (
+                        r.rdtype == dns.rdatatype.from_text(rdtype)
+                        or rdtype.upper() == "ANY"
+                    ):
+                        record = Record(self.origin, n, self[n], rds, r)
+                        result.append(record)
+
+        return result
+
+    # TODO: was a default rdtype required because of lexicon?
+    # otherwise, remove the default.
+    def find_record(self, rdtype="ANY", name=None, content=None):
+        """
+        Create and return a list of each resource record in the zone matching
+        the search criteria.
+
+        :param rdtype: The record's type.
+        :type rdtype: string
+        :param name: The record's name.
+        :type name: string
+        :param content: The record's content.
+        :type content: string
+        :return: list of :class:`Record <Record>` objects
+        :rtype: list
+        """
+        result = []
+
+        # relativize the name
+        if name:
+            name_obj = dns.name.from_text(name, origin=self.origin)
+            name = name_obj.relativize(self.origin).to_text()
+
+        if rdtype.upper() == "TXT" and content:
+            # Content of record type `TXT` has enclosing quotes. See:
+            # https://git.io/fxART
+
+            # TODO: will this match for multiline records e.g. domainkeys?
+            # Maybe we should strip quotes instead? i.e. r.content.strip('\"')
+            content = '"%s"' % content
+
+        for r in self.get_records(rdtype):
+            if (
+                (r.name == name and r.content == content)
+                or (r.name == name and not content)
+                or (r.content == content and not name)
+                or (not name and not content)
+            ):
+                result.append(r)
+
+        return result
+
+    def add_record(self, name, rdtype, content, rdclass="IN", ttl=None):
+        """
+        Add a resource record to the zone.
+
+        :param name: The record's name.
+        :type name: string
+        :param rdtype: The record's type, e.g. "CNAME".
+        :type rdtype: string
+        :param content: The record's content.
+        :type content: string
+        :param rdclass: The record's class.
+        :type rdclass: string
+        :param ttl: The record's TTL.
+        :type ttl: ttl
+        :return: :class:`Record <Record>` object
+        :rtype: localzone.models.Record
+        """
+        # TODO: standardize on named params?
+
+        # convert string parameters to dnspython objects
+        name = dns.name.from_text(name, self.origin)
+        rdclass = dns.rdataclass.from_text(rdclass)
+        rdtype = dns.rdatatype.from_text(rdtype)
+
+        # TODO: won't this always be the case?
+        if name.is_subdomain(self.origin):
+            name = name.relativize(self.origin)
+
+        if not ttl:
+            ttl = self.ttl
+
+        # create the record data
+        rdata = dns.rdata.from_text(rdclass, rdtype, content, origin=self.origin)
+
+        # get or create the node and rdataset that will conatin the record
+        node = self.find_node(name, create=True)
+        rdataset = self.find_rdataset(name, rdtype, create=True)
+
+        # add the new rdata to the set
+        rdataset.add(rdata, ttl)
+
+        return Record(self.origin, name, node, rdataset, rdata)
+
+    def remove_record(self, hashid, cascade=True):
+        """
+        Remove a resource record from the zone. A `KeyError` is raised by the
+        `get_record()` method if the supplied `hashid` is not found in the zone.
+
+        If `cascade` is `True` and the`rdataset` is empty after removing the
+        record, the `rdataset` is also removed. If the `node` only contains the
+        empty `rdataset`, then the `node` is removed.
+
+        :param hashid: The record's ID.
+        :type hashid: string
+        :param cascade: (optional) Also remove the rdataset and node if empty?
+        :type cascade: bool
+        """
+        record = self.get_record(hashid)
+        rdata = record.rdata
+        rdataset = record.rdataset
+        node = record.node
+
+        rdataset.remove(rdata)
+
+        if cascade:
+            if not rdataset and len(node) == 1:
+                # the node contains only an empty rdataset; remove
+                self.delete_node(record.name)
+            elif not rdataset:
+                # the node contains other rdatasets; only remove empty set
+                self.delete_rdataset(record.name, record.rdtype)
+
+    def update_record(self, hashid, content):
+        """
+        Update the content of a resource record. A `KeyError` is raised by the
+        `get_record()` method if the supplied `hashid` is not found in the zone.
+
+        :param hashid: The record's ID.
+        :type hashid: string
+        :param content: The new content of the record.
+        :type content: string
+        """
+        record = self.get_record(hashid)
+        self.remove_record(hashid, cascade=False)
+        return self.add_record(record.name, record.rdtype, content)
+
+    @property
+    def filename(self):
+        return self._filename
+
+    @property
+    def ttl(self):
+        return self._ttl
+
+    @property
+    def soa(self):
+        """
+        Return the SOA record of the zone's origin.
+
+        :return: :class:`Record <Record>` object
+        :rtype: localzone.models.Record
+        """
+        return self.get_records("soa")[0]
+
+    @property
+    def records(self):
+        """
+        Return a list of :class:`Record <Record>` objects for each resource
+        record in the zone. If the zone is very large, be aware of memory
+        constraints.
+
+        :return: list of :class:`Record <Record>` objects
+        :rtype: list
+        """
+        return self.get_records("ANY")
+
+
+class Record(object):
+    """
+    Initialize a :class:`Record <Record>` object.
+
+    :param origin: The record's parent domain.
+    :type origin: :class:`dns.name.Name <Name>` object
+    :param name: The record's name.
+    :type name: :class:`dns.name.Name <Name>` object
+    :param node: The record's node.
+    :type node: :class:`dns.node.Node <Node>` object
+    :param rdataset: The record's rdataset.
+    :type rdataset: :class:`dns.rdataset.Rdataset <Rdataset>` object
+    :param rdata: The record's rdata.
+    :type rdata: :class:`dns.rdata.Rdata <Rdata>` object
+    """
+
+    def __init__(self, origin, name, node, rdataset, rdata):
+        RecordData = namedtuple(
+            "RecordData", ["hashid", "origin", "name", "node", "rdataset", "rdata"]
+        )
+
+        hashid = ""
+
+        # Pre-initialize the record so that a hash id can be created.
+        # Why not just use a dict instead? Because a tuple more clearly
+        # communicates the nature of the interface and the immutability of
+        # the (name, type, content) composite.
+        self._data = RecordData(hashid, origin, name, node, rdataset, rdata)
+
+        # Create the hash id and replace the tuple.
+        hashid = self.__hash__()
+        self._data = RecordData(hashid, origin, name, node, rdataset, rdata)
+
+    def __repr__(self):
+        s = "<DNS {rdtype} record: {name}>"
+        return s.format(rdtype=self.rdtype, name=self.name)
+
+    def __str__(self):
+        return self.to_text()
+
+    def __hash__(self):
+        # TODO: convert to md5?
+        return checksum(self.to_text())
+
+    def to_text(self):
+        s = "{name} {ttl} {rdclass} {rdtype} {content}"
+        return s.format(
+            name=self.name,
+            ttl=self.ttl,
+            rdclass=self.rdclass,
+            rdtype=self.rdtype,
+            content=self.content,
+        )
+
+    @property
+    def hashid(self):
+        return self._data.hashid
+
+    @property
+    def name(self):
+        return self._data.name.to_text()
+
+    @property
+    def origin(self):
+        return self._data.origin.to_text()
+
+    @property
+    def ttl(self):
+        return self._data.rdataset.ttl
+
+    @property
+    def content(self):
+        return self._data.rdata.to_text()
+
+    @property
+    def rdata(self):
+        return self._data.rdata
+
+    @property
+    def rdclass(self):
+        return dns.rdataclass.to_text(self._data.rdata.rdclass)
+
+    @property
+    def rdtype(self):
+        return dns.rdatatype.to_text(self._data.rdata.rdtype)
+
+    @property
+    def rdataset(self):
+        return self._data.rdataset
+
+    @property
+    def node(self):
+        return self._data.node
diff --git a/localzone/util.py b/localzone/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..60332762215459855adc3a9cc49fe08f30a9cfc6
--- /dev/null
+++ b/localzone/util.py
@@ -0,0 +1,77 @@
+"""
+localzone.util
+~~~~~~~~~~~~~~
+
+This module contains general purpose utilities used by localzone.
+"""
+
+from itertools import chain, repeat
+
+
+def group(iterable, n, padvalue=None):
+    """
+    Create n-length sets from an iterable.
+
+    :param iterable: An iterable object.
+    :type iterable: iterable
+    :param n: The number of items in the set.
+    :type n: int
+    :param padvalue: The value used, if necessary, to pad the last set.
+    :type n: int
+    :return: An iterable set.
+    :rtype: iterator
+    """
+    return zip(*[chain(iterable, repeat(padvalue, n - 1))] * n)
+
+
+def pack(tup):
+    """
+    Packs a tuple of 8-bit integers.
+
+    :param tup: Tuple of 8-bit integers.
+    :type tup: tuple
+    :return: The packed n-bit value, where n is len(tup) * 8.
+    :rtype: int
+    """
+    size = len(tup)
+    result = 0
+    for i in range(size):
+        result = tup[i] << (i * 8) | result
+    return result
+
+
+def checksum(word, size=32):
+    """
+    Implements Fletcher's checksum to create 16, 32, or 64-bit checksums.
+
+    :param word: The data to checksum.
+    :type word: string
+    :param size: The checksum's size.
+    :type size: int
+    :return: Fletcher's checksum represented as a hexadecimal digest.
+    :rtype: string
+    """
+    if size not in [16, 32, 64]:
+        raise ValueError("Valid checksum sizes are 16, 32 and 64")
+
+    bits = int(size / 2)
+    block_size = int(bits / 8)
+    modulus = int(2 ** bits - 1)
+    pad = 0
+    ordinals = map(ord, word)
+
+    if size == 16:
+        blocks = ordinals
+    else:
+        blocks = map(pack, group(ordinals, block_size, pad))
+
+    a = b = 0
+
+    for block in blocks:
+        a += block
+        b += a
+
+    a %= modulus
+    b %= modulus
+
+    return format((b << bits) | a, "x").zfill(4)
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e1384fb4b6c0712786f931a331ca531f8dc88b6
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1 @@
+"""localzone test package initialization"""
diff --git a/tests/test_context.py b/tests/test_context.py
new file mode 100644
index 0000000000000000000000000000000000000000..baac0841e341b5cdb30a4d3abbe0c96dedbfc28c
--- /dev/null
+++ b/tests/test_context.py
@@ -0,0 +1,29 @@
+import pytest
+import localzone
+try:
+    from dns.zonefile import UnknownOrigin
+except ImportError:
+    from dns.zone import UnknownOrigin
+
+ZONEFILE = "tests/zonefiles/db.example.com"
+ORIGIN = "example.com."
+TTL = 3600
+
+
+def test_load():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    assert z.filename == ZONEFILE
+    assert z.ttl == TTL
+    assert len(z.records) == 16
+
+
+def test_load_missing_origin():
+    with pytest.raises(UnknownOrigin):
+        localzone.load("tests/zonefiles/db.no-origin.com")
+
+
+def test_manage():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        assert z.filename == ZONEFILE
+        assert z.ttl == TTL
+        assert len(z.records) == 16
diff --git a/tests/test_models.py b/tests/test_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4e868785958d2915ae3b285fc041198b891b83f
--- /dev/null
+++ b/tests/test_models.py
@@ -0,0 +1,126 @@
+from dns.rdatatype import UnknownRdatatype
+from dns.exception import SyntaxError as DNSSyntaxError
+import pytest
+import localzone
+
+ZONEFILE = "tests/zonefiles/db.example.com"
+ORIGIN = "example.com."
+HASHID = "dd03d449"
+
+#
+# readers
+#
+
+
+def test_get_all_records():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    records = z.get_records("ANY")
+    assert len(records) == 16
+
+
+def test_get_record():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    record = z.get_record(HASHID)
+    assert record.name == "@"
+    assert record.rdtype == "A"
+    assert record.content == "192.0.2.1"
+    assert record.ttl == 3600
+
+
+def test_get_record_not_found():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    with pytest.raises(KeyError):
+        z.get_record("deadbeef")
+
+
+def test_find_records_by_type():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    records = z.find_record("MX")
+    assert len(records) == 3
+
+
+def test_find_record_by_name():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    records = z.find_record("CNAME", "www")
+    assert len(records) == 1
+    assert records[0].content == "@"
+
+
+def test_find_record_by_content():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    records = z.find_record("A", content="192.0.2.2")
+    assert len(records) == 1
+    assert records[0].name == "ns"
+
+
+def test_zone_records_property():
+    z = localzone.load(ZONEFILE, ORIGIN)
+    records = z.records
+    assert len(records) == 16
+
+
+#
+# writers
+#
+
+
+def test_zone_add_record():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        record = z.add_record("test", "txt", "testing")
+        assert record.hashid == "28c9e108"
+
+
+def test_zone_add_record_unknown_type():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        with pytest.raises(UnknownRdatatype):
+            z.add_record("test", "err", "testing")
+
+
+def test_zone_add_record_no_content():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        with pytest.raises((AttributeError, DNSSyntaxError, ValueError)):
+            z.add_record("test", "txt", None)
+
+
+def test_zone_remove_record():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        z.remove_record(HASHID)
+        with pytest.raises(KeyError):
+            z.get_record(HASHID)
+
+
+def test_zone_remove_record_not_found():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        with pytest.raises(KeyError):
+            z.remove_record("deadbeef")
+
+
+def test_zone_update_record():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        record = z.update_record(HASHID, "192.0.2.100")
+        assert record.hashid == "117e047a"
+        assert record.name == "@"
+        assert record.rdtype == "A"
+        assert record.content == "192.0.2.100"
+        assert record.ttl == 3600
+
+
+def test_zone_update_record_not_found():
+    with localzone.manage(ZONEFILE, ORIGIN) as z:
+        with pytest.raises(KeyError):
+            z.update_record("deadbeef", "eat mor chikin")
+
+
+def test_zone_save():
+    savefile = "tests/db.example.com.saved"
+    z = localzone.load(ZONEFILE, ORIGIN)
+    serial = z.soa.rdata.serial
+    record = z.update_record(HASHID, "192.0.2.100")
+    z.save(savefile)
+    z = localzone.load(savefile, ORIGIN)
+    record = z.find_record("A", content="192.0.2.100")[0]
+    assert z.soa.rdata.serial > serial
+    assert record.name == "@"
+    assert record.rdtype == "A"
+    assert record.content == "192.0.2.100"
+    assert record.ttl == 3600
diff --git a/tests/test_util.py b/tests/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..3804bb4228b2077aad007e9b48b0288d06304d79
--- /dev/null
+++ b/tests/test_util.py
@@ -0,0 +1,28 @@
+import pytest
+from localzone.util import checksum
+
+# Test vectors
+WORD = "abcde"
+CS16 = "c8f0"
+CS32 = "f04fc729"
+CS64 = "c8c6c527646362c6"
+
+
+def test_checksum_16():
+    cs = checksum(WORD, 16)
+    assert cs == CS16
+
+
+def test_checksum_32():
+    cs = checksum(WORD)
+    assert cs == CS32
+
+
+def test_checksum_64():
+    cs = checksum(WORD, 64)
+    assert cs == CS64
+
+
+def test_checksum_invalid_size():
+    with pytest.raises(ValueError):
+        cs = checksum(WORD, 128)
diff --git a/tests/zonefiles/db.example.com b/tests/zonefiles/db.example.com
new file mode 100644
index 0000000000000000000000000000000000000000..51057c9e0dca8f9642eaa944ea5ed5959c6977e8
--- /dev/null
+++ b/tests/zonefiles/db.example.com
@@ -0,0 +1,18 @@
+$ORIGIN example.com.     ; designates the start of this zone file in the namespace
+$TTL 1h                  ; default expiration time of all resource records without their own TTL value
+example.com.  IN  SOA   ns.example.com. username.example.com. ( 2007120710 1d 2h 4w 1h )
+example.com.  IN  NS    ns                    ; ns.example.com is a nameserver for example.com
+example.com.  IN  NS    ns.somewhere.example. ; ns.somewhere.example is a backup nameserver for example.com
+example.com.  IN  MX    10 mail.example.com.  ; mail.example.com is the mailserver for example.com
+@             IN  MX    20 mail2.example.com. ; equivalent to above line, "@" represents zone origin
+@             IN  MX    50 mail3              ; equivalent to above line, but using a relative host name
+example.com.  IN  A     192.0.2.1             ; IPv4 address for example.com
+              IN  AAAA  2001:db8:10::1        ; IPv6 address for example.com
+ns            IN  A     192.0.2.2             ; IPv4 address for ns.example.com
+              IN  AAAA  2001:db8:10::2        ; IPv6 address for ns.example.com
+www           IN  CNAME example.com.          ; www.example.com is an alias for example.com
+wwwtest       IN  CNAME www                   ; wwwtest.example.com is another alias for www.example.com
+mail          IN  A     192.0.2.3             ; IPv4 address for mail.example.com
+mail2         IN  A     192.0.2.4             ; IPv4 address for mail2.example.com
+mail3         IN  A     192.0.2.5             ; IPv4 address for mail3.example.com
+@             IN  TXT   "v=spf1 mx ~all"      ; SPFv1 record for example.com
diff --git a/tests/zonefiles/db.no-origin.com b/tests/zonefiles/db.no-origin.com
new file mode 100644
index 0000000000000000000000000000000000000000..6202c696dab1b0c24070234e5b193e4286987dbf
--- /dev/null
+++ b/tests/zonefiles/db.no-origin.com
@@ -0,0 +1,2 @@
+islegit.com.  IN  SOA   ns.islegit.com. ags.islegit.com. ( 2019010100 1d 2h 4w 1h )
+@             IN  TXT   "coming2019"