diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,1 @@
+0.1.1: First release
diff --git a/COPYING b/COPYING
new file mode 100644
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/Certificate.hs b/Certificate.hs
new file mode 100644
--- /dev/null
+++ b/Certificate.hs
@@ -0,0 +1,46 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+module Certificate where
+
+import           Crypto.Hash
+import           Data.ASN1.BinaryEncoding (DER (..))
+import           Data.ASN1.Encoding       (encodeASN1')
+import           Data.ASN1.Types          (ASN1Object (..))
+import           Data.ByteArray           (convert)
+
+import qualified Data.ByteString          as BS
+import qualified Data.Text                as TS
+import qualified Data.Text.Encoding       as TS
+import qualified Data.X509                as X
+
+import           Fingerprint
+
+newtype Certificate = Certificate X.SignedCertificate
+    deriving (Eq, Show)
+
+takeTailCert :: X.CertificateChain -> Maybe Certificate
+takeTailCert (X.CertificateChain (c:_)) = Just $ Certificate c
+takeTailCert _                          = Nothing
+
+-- |First 16 bytes of sha256 hash of DER encoding of SPKI field
+-- (as suggested by RFC7469).
+spkiFingerprint :: Certificate -> Fingerprint
+spkiFingerprint (Certificate signed) = truncateFP 16 . Fingerprint . convert . hashWith SHA256 .
+        encodeDER . X.certPubKey . X.signedObject $ X.getSigned signed
+    where
+    truncateFP :: Int -> Fingerprint -> Fingerprint
+    truncateFP n (Fingerprint fp) = Fingerprint $ BS.take n fp
+    encodeDER :: ASN1Object o => o -> BS.ByteString
+    encodeDER = encodeASN1' DER . (`toASN1` [])
+
+certCN :: Certificate -> String
+certCN (Certificate signed) = maybe "" (TS.unpack . TS.decodeUtf8 . X.getCharacterStringRawData)
+    . X.getDnElement X.DnCommonName . X.certIssuerDN $ X.getCertificate signed
diff --git a/Config.hs b/Config.hs
new file mode 100644
--- /dev/null
+++ b/Config.hs
@@ -0,0 +1,77 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+module Config where
+
+import           System.Directory (doesFileExist)
+import           System.Exit      (exitFailure)
+import           System.FilePath  ((</>))
+
+import           Util
+
+data Config = Config
+    { listen_host        :: String
+    , listen_port        :: Int
+    , accept_unnamed     :: Bool
+    , curses_local_top   :: Bool
+    , curses_log         :: Bool
+    , interactive_client :: [String]
+    } deriving (Read)
+
+confFilePath :: FilePath -> FilePath
+confFilePath = (</> "htalkat.conf")
+
+defaultConfigFile :: String
+defaultConfigFile = unlines
+    [ "Config"
+    , "    { listen_host = \"\"  # Empty means bind all available hosts"
+    , "    , listen_port = 5518"
+    , "    , accept_unnamed = True  # Accept connections even from unnamed users"
+    , ""
+    , "    , curses_local_top = True  # Display you above remote in curses client"
+    , "    , curses_log = False  # Log conversations to files in ~/.htalkat/logs/"
+    , ""
+    , "    # interactive_client: if non-empty, run in place of built-in client."
+    , "    # First string is the command to run, and subsequent strings are arguments."
+    , "    # It will be executed with two further arguments:"
+    , "    # the name of the remote user,"
+    , "    # and the path to a unix domain socket to interact with."
+    , "    # Minimal example:"
+    , "    #, interactive_client = [\"sh\", \"-c\","
+    , "    #    \"socat unix-connect:\\\"$2\\\" stdio\", \"talkatc\"]"
+    , "    , interactive_client = []"
+    , "    }"
+    ]
+
+createConfigFileIfNecessary :: FilePath -> IO ()
+createConfigFileIfNecessary ddir =
+    let cpath = confFilePath ddir
+    in doesFileExist cpath >>! writeFile cpath defaultConfigFile
+
+loadConfig :: FilePath -> IO Config
+loadConfig ddir = do
+    createConfigFileIfNecessary ddir
+    s <- readFile (confFilePath ddir)
+    case readReadConfig (confFilePath ddir) s of
+        Left err   -> putStrLn err >> exitFailure >> undefined
+        Right conf -> pure conf
+
+readReadConfig :: FilePath -> String -> Either String Config
+readReadConfig path s =
+    -- Based on https://hackage.haskell.org/package/tce-conf by Dino Morelli
+    case reads $ removeComments s of
+        [(c, _)    ] -> Right c
+        ((_, x) : _) -> Left $ "ERROR parsing config file: " <> x <> hint
+        [          ] -> Left $ "ERROR parsing config file" <> hint
+    where
+    hint = "; to recreate, remove " <> path <> " and try again."
+    removeComments :: String -> String
+    removeComments = unlines . map removeComment . lines
+    removeComment = takeWhile (/= '#')
diff --git a/CursesClient.hs b/CursesClient.hs
new file mode 100644
--- /dev/null
+++ b/CursesClient.hs
@@ -0,0 +1,466 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE BangPatterns      #-}
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module CursesClient (cursesClient) where
+
+import           Prelude                        hiding (lines)
+
+import           Control.Concurrent
+import           Control.Exception              (bracket, bracket_)
+import           Control.Monad.State
+import           Data.Char                      (isSpace)
+import           Data.Function                  (on)
+import           Data.Int                       (Int64)
+import           Data.List                      (uncons, (\\))
+import           Data.Maybe                     (fromMaybe)
+import           Safe                           (headMay)
+import           System.Exit                    (exitFailure)
+import           System.IO                      (Handle, hFlush)
+import           UI.HSCurses.Curses             hiding (ls)
+
+import qualified Data.ByteString.Lazy.Char8     as BLC
+import qualified Data.Text.Encoding.Error       as T
+import qualified Data.Text.Lazy                 as T
+import qualified Data.Text.Lazy.Encoding        as T
+import qualified Data.Text.Lazy.IO              as T
+import qualified Network.Socket                 as S
+import qualified Network.Socket.ByteString.Lazy as SL
+import           UI.HSCurses.CursesHelper       as CH
+
+import           Mundanities
+import           Util
+import           WCWidth
+
+#ifndef WINDOWS
+import           System.Posix.Signals
+#endif
+
+newtype Reversed = Reversed {getReversed :: T.Text}
+
+data StreamState = StreamState
+    { streamWin     :: Window
+    , streamLines   :: [T.Text]
+    , streamHeights :: [Int]
+    , streamCurLine :: Reversed
+    , streamView    :: Int
+    }
+
+resetSS :: Int -> Window -> StreamState -> StreamState
+resetSS w win ss = ss
+    { streamWin = win
+    , streamHeights = lineHeight w <$> streamLines ss
+    , streamView = 0
+    }
+
+curLineHeight :: Int -> StreamState -> Int
+curLineHeight w = lineHeight w . T.reverse . getReversed . streamCurLine
+
+mapCurLine :: (T.Text -> T.Text) -> StreamState -> StreamState
+mapCurLine f s = s { streamCurLine = Reversed . f . getReversed $ streamCurLine s }
+
+allHeights :: Int -> StreamState -> [Int]
+allHeights w ss = curLineHeight w ss : streamHeights ss
+
+allLines :: StreamState -> [T.Text]
+allLines ss = (T.reverse . getReversed $ streamCurLine ss) : streamLines ss
+
+data TalkStream = OutStream | InStream
+    deriving Eq
+
+data CState = CState
+    { otherName        :: String
+    , connectionClosed :: Bool
+    , monitor          :: Bool
+    , logHandle        :: Maybe Handle
+    , lastMoved        :: TalkStream
+    , onTop            :: TalkStream
+    , outStream        :: StreamState
+    , inStream         :: StreamState
+    }
+
+initCState :: String -> TalkStream -> Maybe Handle -> (Window,Window) -> CState
+initCState name top mLog (w,w') = CState
+    { otherName = name
+    , connectionClosed = False
+    , monitor = False
+    , lastMoved = OutStream
+    , onTop = top
+    , logHandle = mLog
+    , outStream = emptySS $ if top == OutStream then w else w'
+    , inStream = emptySS $ if top == InStream then w else w'
+    } where emptySS x = StreamState x [] [] (Reversed "") 0
+
+resetWindows :: Int -> TalkStream -> (Window,Window) -> CState -> CState
+resetWindows ww top (w,w') =
+    mapSS OutStream (resetSS ww $ winOf OutStream) .
+    mapSS InStream (resetSS ww $ winOf InStream)
+    where winOf str = if str == top then w else w'
+
+getSS :: TalkStream -> CState -> StreamState
+getSS OutStream = outStream
+getSS InStream  = inStream
+
+mapSS :: TalkStream -> (StreamState -> StreamState) -> CState -> CState
+mapSS OutStream f ss = ss { outStream = f $ outStream ss }
+mapSS InStream f ss  = ss { inStream = f $ inStream ss }
+
+
+wcwidthNonNeg :: Char -> Int
+wcwidthNonNeg = max 0 . wcwidth
+
+wcLength :: T.Text -> Int
+wcLength = sum . (wcwidthNonNeg <$>) . T.unpack
+
+
+resetTerm :: IO ()
+resetTerm = nl True >> raw False >> cBreak True
+
+getGeom :: IO ((Int,Int),Int)
+getGeom = do
+    (lines,cols) <- scrSize
+    let (d,m) = divMod lines 2
+    pure ((d + m - 1, d), cols)
+
+getWidth :: IO Int
+getWidth = snd <$> getGeom
+
+getDividerY :: IO Int
+getDividerY = fst . fst <$> getGeom
+
+checkSize :: IO ()
+checkSize = do
+    dy <- getDividerY
+    ww <- getWidth
+    when (dy == 0 || ww <= maxWCWidth) $
+        CH.end >> putStrLn "Terminal too small." >> exitFailure
+    where maxWCWidth = 2
+
+initWindows :: IO (Window,Window)
+initWindows = do
+    ((wh,wh'),ww) <- getGeom
+    liftM2 (,)
+        (newWin wh (ww + 1) 0 0)
+        (newWin wh' (ww + 1) (wh+1) 0)
+
+data Event = InCharEv Char | KeyEv Key | ConnectionClosed | NeedReset | Quit
+    deriving (Eq)
+
+isQuit :: Event -> Bool
+isQuit =
+    -- Handle ^C, in case it doesn't generate a signal (as on windows?)
+    (`elem` [Quit, KeyEv (KeyChar '\ETX')])
+
+connectingNamedSocket :: FilePath -> (S.Socket -> IO a) -> IO a
+connectingNamedSocket path =
+    (`bracket` (`S.gracefulClose` 1000)) $ do
+        sock <- S.socket S.AF_UNIX S.Stream 0
+        S.connect sock $ S.SockAddrUnix path
+        pure sock
+
+cursesClient :: Bool -> Maybe Handle -> String -> FilePath -> IO ()
+cursesClient localTop mLog name path = connectingNamedSocket path $ \sock -> do
+    charStream <- T.unpack . T.decodeUtf8With T.lenientDecode <$> SL.getContents sock
+    putStrLn "Waiting for answer..."
+    case uncons charStream of
+        Nothing -> putStrLn "Connection closed."
+        Just ('T', charStream') -> bracket_ CH.start CH.end $ do
+            checkSize
+            resetTerm
+            eventChan <- newChan
+#ifndef WINDOWS
+            let suspHandler = CatchOnce $ do
+                    raiseSignal sigTSTP
+                    void installTSTP
+                    writeChan eventChan NeedReset
+                installTSTP = installHandler sigTSTP suspHandler Nothing
+            _ <- installTSTP
+            _ <- installHandler sigINT (Catch $ writeChan eventChan Quit) Nothing
+#endif
+            let top = if localTop then OutStream else InStream
+            st <- initCState name top mLog <$> initWindows
+            _ <- forkIO $ do
+                mapM_ (writeChan eventChan . InCharEv) charStream'
+                writeChan eventChan ConnectionClosed
+            _ <- forkIO $ writeList2Chan eventChan . (KeyEv <$>) =<< getContentsCurses
+            void . (`runStateT` st) $ do
+                redrawAll
+                mapM_ (handleEvent sock) . takeWhile (not . isQuit) =<<
+                    liftIO (getChanContents eventChan)
+        _ -> error "Impossible handshake char!"
+
+-- hscurses doesn't bind get_wch, so we do utf8 decoding by hand.
+getContentsCurses :: IO [Key]
+getContentsCurses = do
+    cChan <- newChan
+    kChan <- newChan
+    _ <- forkIO . forever $ getCh >>= \case
+        (KeyChar c) -> writeChan cChan c
+        k           -> writeChan kChan k
+    _ <- forkIO . writeList2Chan kChan . (KeyChar <$>) .
+        T.unpack . T.decodeUtf8With T.lenientDecode . BLC.concat . (BLC.singleton <$>) =<<
+            getChanContents cChan
+    getChanContents kChan
+
+handleEvent :: S.Socket -> Event -> StateT CState IO ()
+handleEvent _ (InCharEv c) = do
+    gets monitor >>? do
+        liftIO beep
+        modify $ \cs -> cs { monitor = False }
+        redrawIndicators
+    addCharToStream InStream $ if allowedTalkatChar c then c else '?'
+handleEvent _ (KeyEv (KeyChar '\DLE')) = -- ^P
+    viewAddPg InStream 1
+handleEvent _ (KeyEv (KeyChar '\SO')) = -- ^N
+    viewAddPg InStream $ -1
+handleEvent _ (KeyEv KeyPPage) = viewAddPg OutStream 1
+handleEvent _ (KeyEv KeyNPage) = viewAddPg OutStream $ -1
+handleEvent _ (KeyEv KeyUp) = modView InStream (+1)
+handleEvent _ (KeyEv KeyDown) = modView InStream (+ (-1))
+handleEvent _ (KeyEv KeyLeft) = modView OutStream (+1)
+handleEvent _ (KeyEv KeyRight) = modView OutStream (+ (-1))
+handleEvent sock (KeyEv (KeyChar '\ETB')) = do -- ^W
+    l <- gets $ getReversed . streamCurLine . getSS OutStream
+    let (spaces, rest) = break (> 0) . (fromIntegral . T.length <$>) $ T.split isSpace l
+        n = length spaces + fromMaybe 0 (headMay rest)
+    replicateM_ n $ handleEvent sock (KeyEv (KeyChar '\b'))
+handleEvent _ (KeyEv (KeyChar '\a')) = do
+    modify $ \cs -> cs { monitor = not $ monitor cs }
+    redrawIndicators
+handleEvent _ (KeyEv (KeyChar '\f')) = redrawAll
+handleEvent sock (KeyEv k) | k `elem` [KeyBackspace, KeyDC, KeyChar '\DEL'] =
+    handleEvent sock (KeyEv (KeyChar '\b'))
+handleEvent sock (KeyEv KeyEnter) =
+    handleEvent sock (KeyEv (KeyChar '\n'))
+handleEvent _ (KeyEv KeyResize) = do
+    liftIO checkSize
+    forM_ [InStream,OutStream] $ \strm -> liftIO . delWin =<< gets (streamWin . getSS strm)
+    ww <- liftIO $ CH.resizeui >> getWidth
+    top <- gets onTop
+    modify . resetWindows ww top =<< liftIO initWindows
+    redrawAll
+handleEvent sock (KeyEv (KeyChar c)) | allowedTalkatChar c =
+    gets connectionClosed >>! do
+        addCharToStream OutStream c
+        liftIO . ignoreIOErr . SL.sendAll sock . T.encodeUtf8 $ T.singleton c
+handleEvent _ (KeyEv _) = liftIO showHelp
+handleEvent _ ConnectionClosed = do
+    modify $ \cs -> cs { connectionClosed = True }
+    redrawIndicators
+handleEvent _ NeedReset = do
+    liftIO resetTerm
+    redrawAll
+handleEvent _ _ = pure ()
+
+allowedTalkatChar :: Char -> Bool
+allowedTalkatChar c =
+    -- disallow C0 control chars without special meaning
+    -- (curses displays them with the wrong width)
+    c `notElem` (['\0'..'\31'] \\ "\b\NAK\n")
+
+addCharToStream :: TalkStream -> Char -> StateT CState IO ()
+addCharToStream strm c = do
+    modify (\cs -> cs { lastMoved = strm })
+    case c of
+        '\b' -> eraseLast strm 1
+        '\NAK' -> do
+            n <- gets $ T.length . getReversed . streamCurLine . getSS strm
+            eraseLast strm n
+        '\n' -> do
+            ww <- liftIO getWidth
+            curLine <- gets $ T.reverse . getReversed . streamCurLine . getSS strm
+            modify . mapSS strm $ \ss -> ss
+                { streamLines = curLine : streamLines ss
+                , streamHeights = curLineHeight ww ss : streamHeights ss
+                , streamCurLine = Reversed ""
+                }
+            maybe (pure ()) (liftIO . logLine strm curLine) =<< gets logHandle
+            redrawStream strm
+        _ -> do
+            modify . mapSS strm $ mapCurLine (T.cons c)
+            p <- gets (streamView . getSS strm)
+            win <- gets $ streamWin . getSS strm
+            (_,x) <- liftIO $ getYX win
+            ww <- liftIO getWidth
+            if x + wcwidthNonNeg c <= ww
+                then when (p == 0) . liftIO $
+                    wAddStr win [c] >> wRefresh win
+                else redrawStream strm
+    placeCursor
+
+logLine :: TalkStream -> T.Text -> Handle -> IO ()
+logLine strm s h = (>> hFlush h) . T.hPutStrLn h . (<> s) $ case strm of
+    InStream  -> "<< "
+    OutStream -> ">> "
+
+redrawAll :: StateT CState IO ()
+redrawAll = do
+    liftIO $ wclear stdScr >> refresh
+    forM_ [InStream,OutStream] redrawStream
+    redrawIndicators
+    placeCursor
+
+placeCursor :: StateT CState IO ()
+placeCursor = do
+    lst <- gets lastMoved
+    scrolled <- gets $ (>0) . streamView . getSS lst
+    closed <- gets connectionClosed
+    if scrolled || closed
+        then liftIO $ do
+            dy <- getDividerY
+            wMove stdScr dy 0
+        else
+            liftIO . wRefresh =<< gets (streamWin . getSS lst)
+
+redrawIndicators :: StateT CState IO ()
+redrawIndicators = do
+    ov <- gets $ streamView . getSS OutStream
+    iv <- gets $ streamView . getSS InStream
+    name <- gets otherName
+    closed <- gets connectionClosed
+    mtr <- gets monitor
+    let os = if ov > 0 then "[you ^ " <> show ov <> "]" else ""
+        is = "[" <> name <> (if iv > 0 then " ^ " <> show iv else "") <>
+            (if mtr then "*" else "") <> "]"
+        cs = "[Connection lost; ^C to quit]"
+        csShort = "[Closed]"
+    liftIO $ do
+        ww <- getWidth
+        dy <- getDividerY
+        mvWAddStr stdScr dy 0 $ replicate ww '─'
+        when closed $ do
+            let drawCentred s = mvWAddStr stdScr dy ((ww - length s) `div` 2) s
+            if ww > length cs + 4 then drawCentred cs
+            else when (ww > length csShort + 4) $ drawCentred csShort
+        when (ww > 12 + length is + length os + (if closed then length cs + 2 else 0)) $
+            sequence_ [ unless (null s) $ mvWAddStr stdScr dy p s
+                | (s,p) <- [(is,5), (os, ww - 5 - length os)] ]
+        wMove stdScr dy 0
+        refresh
+
+showHelp :: IO ()
+showHelp = do
+    ww <- liftIO getWidth
+    dy <- liftIO getDividerY
+    mvWAddStr stdScr dy 0 $ replicate ww '─'
+    mvWAddStr stdScr dy (max 1 ((ww - length helpStr) `div` 2)) $
+        take (ww - 2) helpStr
+    wMove stdScr dy 0
+    refresh
+    where helpStr = "^P/^N,PgUp/PgDn,arrows scroll; ^W/^U erase; ^C quit; ^G monitor; ^L redraw"
+
+
+getStreamHeight :: TalkStream -> StateT CState IO Int
+getStreamHeight strm = do
+    top <- gets onTop
+    ((wh,wh'),_) <- liftIO getGeom
+    pure $ if top == strm then wh else wh'
+
+redrawStream :: TalkStream -> StateT CState IO ()
+redrawStream strm = do
+    ww <- liftIO getWidth
+    wh <- getStreamHeight strm
+    ss <- gets $ getSS strm
+    let v = streamView ss
+        (len,n) = lenToSum (wh + v) $ allHeights ww ss
+        ls = reverse . take len $ allLines ss
+        pls = take wh . drop (n - (wh + v)) . concat $
+            reverse . zip (False:repeat True) . reverse .
+            wrap ww <$> ls
+        win = streamWin ss
+    liftIO $ do
+        werase win
+        sequence_ [ do
+                mvWAddStr win y 0 $ T.unpack s
+                when isWrap $ do
+                    CH.wSetStyle win $ CH.mkCursesStyle [CH.Reverse]
+                    mvWAddStr win y (ww-1) " "
+                    CH.wResetStyle win
+            | ((isWrap,s),y) <- zip pls [(wh - length pls) ..] ]
+        wRefresh win
+    where
+    lenToSum :: (Num n, Ord n) => n -> [n] -> (Int,n)
+    lenToSum m = go 0 0 where
+        go l n (a:as) | n < m = go (l + 1) (n + a) as
+        go l n _ = (l,n)
+
+
+wrap :: Int -> T.Text -> [T.Text]
+wrap wrapWidth _ | wrapWidth < 2 = error "Tried to wrap with too small width!"
+wrap wrapWidth line = wrap' "" 0 . mergeSpaces $ T.groupBy ((==) `on` isSpace) line
+    where
+    mergeSpaces (s:ws) | isSpace (T.head s) = s : mergeSpaces ws
+    mergeSpaces (w:s:ws) = (w <> s) : mergeSpaces ws
+    mergeSpaces ws = ws
+
+    wrap' l n ws | n > wrapWidth =
+        let (a,b) = splitAtWC (wrapWidth - 1) l in a : wrap' b (n - wcLength a) ws
+    wrap' l _ [] = [l]
+    wrap' l n (w:ws) =
+        let l' = l <> w
+            nw = wcLength w
+            n' = n + nw
+        in if n' > wrapWidth
+            then (if T.null l then id else (l:)) $ wrap' w nw ws
+            else wrap' l' n' ws
+
+    splitAtWC :: Int -> T.Text -> (T.Text,T.Text)
+    splitAtWC m s = go m T.empty s where
+        go !n !acc t
+            | Just (c,r) <- T.uncons t = let w = max 0 $ wcwidth c in
+                if w > max 0 n then (T.reverse acc,t)
+                else go (n - w) (T.cons c acc) r
+            | otherwise = (T.reverse acc, T.empty)
+
+lineHeight :: Int -> T.Text -> Int
+lineHeight w = length . wrap w
+
+eraseLast :: TalkStream -> Int64 -> StateT CState IO ()
+eraseLast strm n = do
+    ss <- gets $ getSS strm
+    ww <- liftIO getWidth
+    let cur = getReversed $ streamCurLine ss
+        mightDecreaseHeight =
+            -- +1 to handle case of wrapping at double-width char
+            wcLength cur + 1 > ww
+        wErase = wcLength $ T.take n cur
+    modify . mapSS strm . mapCurLine $ T.drop n
+    if mightDecreaseHeight
+        then redrawStream strm
+        else liftIO $ do
+            let win = streamWin ss
+            (y,x) <- getYX win
+            mvWAddStr win y (x - wErase) (replicate wErase ' ')
+            wMove win y $ x - wErase
+            wRefresh win
+
+
+viewAddPg :: TalkStream -> Int -> StateT CState IO ()
+viewAddPg strm n = do
+    wh <- getStreamHeight strm
+    modView strm (+ (n * wh))
+
+modView :: TalkStream -> (Int -> Int) -> StateT CState IO ()
+modView strm f = do
+    ww <- liftIO getWidth
+    wh <- getStreamHeight strm
+    ss <- gets $ getSS strm
+    let h = (+ (-wh)) . sum . allHeights ww $ ss
+        oldView = streamView ss
+        newView = max 0 . min h $ f oldView
+    when (newView /= oldView) $ do
+        modify . mapSS strm $ \s -> s { streamView = newView }
+        redrawStream strm
+        redrawIndicators
+        placeCursor
diff --git a/DumbClient.hs b/DumbClient.hs
new file mode 100644
--- /dev/null
+++ b/DumbClient.hs
@@ -0,0 +1,69 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+module DumbClient (dumbClient) where
+
+import           Control.Concurrent             (forkIO)
+import           Control.Exception              (bracket)
+import           Control.Monad                  (foldM_)
+import           System.IO
+import           System.IO.Unsafe               (unsafeInterleaveIO)
+
+import qualified Data.ByteString                as BS
+import qualified Data.ByteString.Lazy           as BL
+import qualified Data.Text.Encoding.Error       as T
+import qualified Data.Text.Lazy                 as T
+import qualified Data.Text.Lazy.Encoding        as T
+import qualified Network.Socket                 as S
+import qualified Network.Socket.ByteString      as SS
+import qualified Network.Socket.ByteString.Lazy as SL
+
+import           WCWidth
+
+connectingNamedSocket :: FilePath -> (S.Socket -> IO a) -> IO a
+connectingNamedSocket path =
+    (`bracket` S.close) $ do
+        sock <- S.socket S.AF_UNIX S.Stream 0
+        S.connect sock $ S.SockAddrUnix path
+        pure sock
+
+getContentsBS :: IO [BS.ByteString]
+getContentsBS = unsafeInterleaveIO $ do
+    s <- BS.hGetSome stdin 256
+    if BS.null s then pure []
+        else (s :) <$> getContentsBS
+
+dumbClient :: FilePath -> IO ()
+dumbClient path = connectingNamedSocket path $ \sock -> do
+    _ <- forkIO $ do
+        printWithErasures . T.decodeUtf8With T.lenientDecode . BL.drop 1 =<<
+            SL.getContents sock
+        putStrLn "\n[Connection closed; ^C to quit]"
+    hSetBuffering stdin NoBuffering
+    hSetEcho stdin False
+    hSetBuffering stdout NoBuffering
+    mapM_ (SS.sendAll sock) =<< getContentsBS
+
+printWithErasures :: T.Text -> IO ()
+printWithErasures = mapM_ (doLine . T.unpack) . T.lines where
+    doLine :: String -> IO ()
+    doLine = foldM_ go []
+
+    go [] '\b'    = pure []
+    go (h:t) '\b' = erase (charWidth h) >> pure t
+    go s '\NAK'   = (erase . sum $ charWidth <$> s) >> pure []
+    go s c        = putChar c >> pure (c:s)
+
+    -- This doesn't correctly erase wide characters which are wrapped onto the
+    -- next line earlier than a normal char would have been.
+    -- I don't see how to deal with that dumbly.
+    erase n = putStr . concat $ replicate n "\b \b"
+
+    charWidth = max 0 . wcwidth
diff --git a/Fingerprint.hs b/Fingerprint.hs
new file mode 100644
--- /dev/null
+++ b/Fingerprint.hs
@@ -0,0 +1,31 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Fingerprint where
+
+import           Control.Monad   (guard)
+
+import qualified Data.ByteString as BS
+
+import           HexString
+
+-- | 16-byte SHA256/128 fingerprint
+newtype Fingerprint = Fingerprint BS.ByteString
+    deriving (Eq,Ord,Show)
+
+parseFingerprint :: String -> Maybe Fingerprint
+parseFingerprint s = do
+    guard $ length s == 32
+    Fingerprint <$> parseHexString s
+
+showFingerprint :: Fingerprint -> String
+showFingerprint (Fingerprint fp) = showHexString fp
diff --git a/HexString.hs b/HexString.hs
new file mode 100644
--- /dev/null
+++ b/HexString.hs
@@ -0,0 +1,56 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module HexString where
+
+import           Data.ByteString (ByteString, pack, unpack)
+
+parseHexString :: String -> Maybe ByteString
+parseHexString s = pack <$> parseHexString' s
+    where
+    parseHexString' (a:b:c) = do
+        ha <- fromHex a
+        hb <- fromHex b
+        (16 * ha + hb :) <$> parseHexString' c
+        where
+        fromHex '0' = Just 0
+        fromHex '1' = Just 1
+        fromHex '2' = Just 2
+        fromHex '3' = Just 3
+        fromHex '4' = Just 4
+        fromHex '5' = Just 5
+        fromHex '6' = Just 6
+        fromHex '7' = Just 7
+        fromHex '8' = Just 8
+        fromHex '9' = Just 9
+        fromHex 'a' = Just 10
+        fromHex 'b' = Just 11
+        fromHex 'c' = Just 12
+        fromHex 'd' = Just 13
+        fromHex 'e' = Just 14
+        fromHex 'f' = Just 15
+        fromHex 'A' = Just 10
+        fromHex 'B' = Just 11
+        fromHex 'C' = Just 12
+        fromHex 'D' = Just 13
+        fromHex 'E' = Just 14
+        fromHex 'F' = Just 15
+        fromHex _   = Nothing
+    parseHexString' [] = Just []
+    parseHexString' _ = Nothing
+
+showHexString :: ByteString -> String
+showHexString = concat . (showHexWord8 <$>) . unpack
+    where showHexWord8 w =
+            let (a,b) = quotRem w 16
+                hex = ("0123456789abcdef" !!) . fromIntegral
+            in hex a : hex b : ""
diff --git a/Host.hs b/Host.hs
new file mode 100644
--- /dev/null
+++ b/Host.hs
@@ -0,0 +1,43 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Host where
+
+import           Control.Monad (msum)
+import           Data.List     (elemIndices)
+import           Data.Maybe    (fromMaybe)
+import           Safe          (lastMay, readMay)
+
+data Host = Host {hostName :: String, hostPort :: Int}
+    deriving (Eq,Ord,Show)
+
+defaultTalkatPort :: Int
+defaultTalkatPort = 5518
+
+showHost :: Host -> String
+showHost (Host name port) = name ++
+    (if port == defaultTalkatPort then "" else ":" ++ show port)
+
+parseHost :: String -> Maybe Host
+parseHost s = msum
+    [ (`Host` defaultTalkatPort) <$> decodeIPv6 s
+    , do
+        i <- lastMay $ elemIndices ':' s
+        let (h, ':':portStr) = splitAt i s
+            h' = fromMaybe h $ decodeIPv6 h
+        Host h' <$> readMay portStr
+    , pure $ Host s defaultTalkatPort
+    ]
+    where
+    decodeIPv6 :: String -> Maybe String
+    decodeIPv6 ('[':rest) | Just ']' <- lastMay rest = Just $ init rest
+    decodeIPv6 _ = Nothing
diff --git a/Identity.hs b/Identity.hs
new file mode 100644
--- /dev/null
+++ b/Identity.hs
@@ -0,0 +1,145 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Identity where
+
+import           Network.TLS              (Credential, credentialLoadX509)
+import           System.FilePath          ((<.>), (</>))
+
+import           Data.ASN1.BinaryEncoding (DER (..))
+import           Data.ASN1.Encoding       (encodeASN1')
+import           Data.ASN1.OID
+import           Data.ASN1.Types          (ASN1Object (..))
+import           Data.ASN1.Types.String   (ASN1StringEncoding (UTF8))
+import           Data.Hourglass
+import           Data.PEM
+import           Data.X509                as X
+
+#ifndef WINDOWS
+import           System.Posix.Files       (ownerReadMode, ownerWriteMode,
+                                           setFileMode, unionFileModes)
+#endif
+
+import qualified Crypto.PubKey.Ed25519    as Ed25519
+import qualified Data.ByteArray           as BA
+import qualified Data.ByteString          as BS
+import qualified Data.Text                as TS
+import qualified Data.Text.Encoding       as TS
+
+import           Certificate
+import           Fingerprint
+import           Host
+import           Mundanities
+import           Petname
+import           Prompt
+import           User
+import           Util
+
+data IdentityType = IdConnect | IdListen deriving Eq
+
+loadIdentity :: FilePath -> IdentityType -> IO (Maybe Credential)
+loadIdentity ddir tp = do
+    let base = ddir </> "id"
+        certpath = base <> (if tp == IdConnect then "-connect" else "-listen") <.> "crt"
+        keypath = base <.> "key"
+    ignoreIOErrAlt $ eitherToMaybe <$> credentialLoadX509 certpath keypath
+
+saveIdentity :: FilePath -> PrivKey -> CertificateChain -> CertificateChain -> IO ()
+saveIdentity ddir secKey connectChain listenChain = do
+    let base = ddir </> "id"
+        connectCertpath = base <> "-connect" <.> "crt"
+        listenCertpath = base <> "-listen" <.> "crt"
+        keypath = base <.> "key"
+    ignoreIOErr $ do
+        writeChain connectCertpath connectChain
+        writeChain listenCertpath listenChain
+        BS.writeFile keypath . pemWriteBS . PEM "PRIVATE KEY" [] . encodeDER $ secKey
+#ifndef WINDOWS
+        setFileMode keypath $ unionFileModes ownerReadMode ownerWriteMode -- chmod 600
+#endif
+    where
+    writeChain certpath chain =
+        let CertificateChainRaw rawCerts = encodeCertificateChain chain
+            chainPEMs = map (pemWriteBS . PEM "CERTIFICATE" []) rawCerts
+        in BS.writeFile certpath $ BS.intercalate "\n" chainPEMs
+    encodeDER :: ASN1Object o => o -> BS.ByteString
+    encodeDER = encodeASN1' DER . (`toASN1` [])
+
+createOrShowIdentity :: FilePath -> Maybe String -> IO ()
+createOrShowIdentity ddir mCN =
+    mapM (loadIdentity ddir) [IdConnect,IdListen] >>= \case
+        [Just (connectChain,_), Just (_,_)]
+                | Just cert <- takeTailCert connectChain
+                , Nothing <- mCN -> do
+            mapM_ putStrLn
+                [ "Your fingerprint: talkat:" <> showFingerprint (spkiFingerprint cert)
+                , "Your public name: " <> certCN cert
+                ]
+        [Just (_,key), Just (listenChain,_)]
+                | Just cn <- mCN ->
+            case key of
+                PrivKeyEd25519 secKey -> do
+                    connectChain' <- generateSelfSigned secKey cn
+                    saveIdentity ddir key connectChain' listenChain
+                _ -> putStrLn "Error: Can't regenerate non-ED25519 key!"
+        _ -> do
+            putStrLn "Generating new identity."
+            secKey <- Ed25519.generateSecretKey
+            let promptCN = do
+                    putStrLn "Enter a public name for this identity (can be blank)."
+                    putStrLn "This will be shown to anyone you connect to, and only to them."
+                    putStrLn "(You can change this later by rerunning this command)"
+                    promptLine "Public name: "
+            cn <- maybe promptCN pure mCN
+            connectChain <- generateSelfSigned secKey cn
+            listenChain <- generateSelfSigned secKey ""
+            saveIdentity ddir (PrivKeyEd25519 secKey) connectChain listenChain
+            let Just cert = takeTailCert connectChain
+                fp = spkiFingerprint cert
+            putStrLn $ "Your fingerprint: talkat:" <> showFingerprint fp
+            writeName ddir (User fp (parseHost "localhost")) $ Named "self"
+
+generateSelfSigned :: Ed25519.SecretKey -> String -> IO CertificateChain
+generateSelfSigned secKey cn =
+    let dn = DistinguishedName [(getObjectID DnCommonName,
+            ASN1CharacterString UTF8 . TS.encodeUtf8 $ TS.pack cn)]
+        sigAlg = SignatureALG_IntrinsicHash PubKeyALG_Ed25519
+        -- RFC5280: To indicate that a certificate has no well-defined expiration
+        -- date, the notAfter SHOULD be assigned the GeneralizedTime value of
+        -- 99991231235959Z.
+        notAfterMax :: DateTime
+        notAfterMax = DateTime (Date 9999 December 31) (TimeOfDay 23 59 59 0)
+
+        -- RFC5280 has no corresponding prescription for notBefore.
+        -- 19500101000000Z seems the canonical choice, but it seems to get
+        -- loaded as 2050 for some reason. So we use 1970.
+        notBeforeMin :: DateTime
+        notBeforeMin = DateTime (Date 1970 January 1) (TimeOfDay 0 0 0 0)
+
+        cert pubKey = X.Certificate
+            { certVersion = 2
+            , certSerial = 0
+            , certSignatureAlg = sigAlg
+            , certIssuerDN = dn
+            , certSubjectDN = dn
+            , certValidity = (timeConvert notBeforeMin, timeConvert notAfterMax)
+            , certPubKey = pubKey
+            , certExtensions = Extensions Nothing
+            }
+    in do
+        let pubKey = Ed25519.toPublic secKey
+        let signed = fst $ objectToSignedExact
+                (\b -> (BS.pack . BA.unpack $ Ed25519.sign secKey pubKey b, sigAlg, ()))
+                (cert $ PubKeyEd25519 pubKey)
+        pure $ CertificateChain [signed]
diff --git a/Incoming.hs b/Incoming.hs
new file mode 100644
--- /dev/null
+++ b/Incoming.hs
@@ -0,0 +1,96 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+module Incoming where
+
+import           Control.Monad    (filterM, forM, forM_)
+import           Data.List        ((\\))
+import           Data.Maybe       (catMaybes)
+import           Safe             (maximumMay, readMay)
+import           System.Directory
+import           System.FileLock  (SharedExclusive (..), withFileLock)
+import           System.FilePath  ((</>))
+
+import           Certificate
+import           Fingerprint
+import           LookupPetname
+import           Mundanities
+import           Petname
+import           Util
+
+type Incoming = Int
+
+addIncoming :: FilePath -> Certificate -> FilePath -> Int -> IO Incoming
+addIncoming ddir cert sockPath serial = do
+    let idir = incomingDir ddir
+    createDirectoryIfMissing True idir
+    withFileLock (idir </> ".lock") Exclusive $ \_ -> do
+        ns <- incomingNs ddir
+        let n = head $ [1..] \\ ns
+        let ndir = idir </> show n
+        createDirectoryIfMissing False ndir
+        writeFile (ndir </> "fp") . showFingerprint $ spkiFingerprint cert
+        writeFile (ndir </> "publicName") $ certCN cert
+        writeFile (ndir </> "sock") sockPath
+        writeFile (ndir </> "serial") $ show serial
+        pure n
+
+cleanAllIncoming :: FilePath -> IO ()
+cleanAllIncoming ddir = do
+    ns <- incomingNs ddir
+    forM_ ns $ cleanIncoming ddir Nothing
+
+cleanIncoming :: FilePath -> Maybe Int -> Incoming -> IO ()
+cleanIncoming ddir mSerial n =
+    let path = incomingPath ddir n
+        serialOk | Just s <- mSerial =
+                (== Just s) <$> ignoreIOErrAlt (readMay <$> readFile (path </> "serial"))
+            | otherwise = pure True
+    in doesDirectoryExist path >>? serialOk >>? removeDirectoryRecursive path
+
+incomingDir :: FilePath -> FilePath
+incomingDir = (</> "incoming")
+
+incomingNs :: FilePath -> IO [Int]
+incomingNs ddir = catMaybes . (readMay <$>) <$>
+    listDirectory (incomingDir ddir)
+
+incomingPath :: FilePath -> Incoming -> FilePath
+incomingPath ddir n = incomingDir ddir </> show n
+
+lastIncoming :: FilePath -> Maybe Fingerprint -> IO (Maybe Incoming)
+lastIncoming ddir mFp = do
+    ns <- incomingNs ddir
+    maximumMay <$> filterM checkFp ns
+    where
+    checkFp _ | Nothing <- mFp = pure True
+    checkFp n | Just fp <- mFp = (== Just fp) . parseFingerprint <$>
+        readFile (incomingPath ddir n </> "fp")
+
+listIncoming :: FilePath -> IO [String]
+listIncoming ddir = do
+    ns <- incomingNs ddir
+    forM ns $ \n -> do
+        let idir = incomingPath ddir n
+        t <- getModificationTime idir
+        petname <- incomingPetname ddir n
+        ((show t <> ": " <> showPetname petname) <>) <$> case petname of
+            Named _ -> pure ""
+            _ -> do
+                Just fp <- parseFingerprint <$> readFile (idir </> "fp")
+                cn <- readFile (idir </> "publicName")
+                pure $ " " <> showFingerprint fp <>
+                    if null cn then "" else " \"" <> cn <> "\""
+
+
+incomingPetname :: FilePath -> Incoming -> IO Petname
+incomingPetname ddir n = do
+    Just fp <- parseFingerprint <$> readFile (incomingPath ddir n </> "fp")
+    lookupOrAddPetname ddir fp
diff --git a/LookupPetname.hs b/LookupPetname.hs
new file mode 100644
--- /dev/null
+++ b/LookupPetname.hs
@@ -0,0 +1,68 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe          #-}
+{-# LANGUAGE TupleSections #-}
+
+module LookupPetname (lookupPetname, lookupOrAddPetname) where
+
+import           Data.List        (sortBy, (\\))
+import           Data.Maybe       (catMaybes)
+import           Data.Ord         (Down (..))
+import           Data.Traversable (forM)
+import           System.FileLock  (SharedExclusive (..), withFileLock)
+import           System.FilePath  ((</>))
+
+import qualified Data.Map.Strict  as MS
+
+import           Fingerprint
+import           Petname
+import           User
+
+newtype NameMap = NameMap (MS.Map Fingerprint Petname)
+
+loadNameMap :: FilePath -> IO NameMap
+loadNameMap ddir = do
+    names <- loadNames ddir
+    NameMap . MS.fromList
+        . (onFst userFP <$>)
+        . sortBy pref
+        . catMaybes
+        <$> forM names (\name ->
+            ((,name) <$>) <$> lookupName ddir name)
+    where
+    -- |prefer named to unnamed, then without host to with host, then shortest
+    pref (User _ Nothing,_) (User _ (Just _),_) = GT
+    pref (User _ (Just _),_) (User _ Nothing,_) = LT
+    pref (_,n) (_,n')                           = compare (Down n) (Down n')
+    onFst f (a,b) = (f a,b)
+
+nameMapLookup :: Fingerprint -> NameMap -> Maybe Petname
+nameMapLookup fp (NameMap nm) = MS.lookup fp nm
+
+nameMapNextUnnamed :: NameMap -> Petname
+nameMapNextUnnamed (NameMap nm) = head $ (Unnamed <$> [1..]) \\ MS.elems nm
+
+lookupPetname :: FilePath -> Fingerprint -> IO (Maybe Petname)
+lookupPetname ddir fp = do
+    (nameMapLookup fp <$>) . withFileLock (namesDir ddir </> ".lock") Shared $ \_ ->
+        loadNameMap ddir
+
+lookupOrAddPetname :: FilePath -> Fingerprint -> IO Petname
+lookupOrAddPetname ddir fp = do
+    nm <- withFileLock (namesDir ddir </> ".lock") Shared $ \_ ->
+        loadNameMap ddir
+    case nameMapLookup fp nm of
+        Nothing -> do
+            let next = nameMapNextUnnamed nm
+            writeName ddir (User fp Nothing) next
+            pure next
+        Just name ->
+            pure name
diff --git a/Mundanities.hs b/Mundanities.hs
new file mode 100644
--- /dev/null
+++ b/Mundanities.hs
@@ -0,0 +1,35 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Mundanities where
+
+import           Control.Applicative    (Alternative, empty)
+import           Control.Monad.Catch    (MonadMask, handle)
+import           Control.Monad.IO.Class (MonadIO, liftIO)
+import           System.Directory
+import           System.FilePath
+
+-- |returns true iff path is contained within the directory dir
+isSubPath :: FilePath -> FilePath -> IO Bool
+isSubPath dir path = isRelative . makeRelative dir <$> canonicalizePath path
+
+ignoreIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
+ignoreIOErr = handle ((\_ -> return mempty) :: (Monad m, Monoid a) => IOError -> m a)
+
+warnIOErr :: (MonadIO m, MonadMask m, Monoid a) => m a -> m a
+warnIOErr = handle ((\e -> liftIO (print e) >> return mempty) :: (MonadIO m, Monoid a) => IOError -> m a)
+
+ignoreIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
+ignoreIOErrAlt = handle ((\_ -> return empty) :: (Monad m, Alternative f) => IOError -> m (f a))
+
+warnIOErrAlt :: (MonadIO m, MonadMask m, Alternative f) => m (f a) -> m (f a)
+warnIOErrAlt = handle ((\e -> liftIO (print e) >> return empty) :: (MonadIO m, Alternative f) => IOError -> m (f a))
diff --git a/Notify.hs b/Notify.hs
new file mode 100644
--- /dev/null
+++ b/Notify.hs
@@ -0,0 +1,72 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE CPP #-}
+
+module Notify where
+
+import           Control.Monad      (void)
+import           System.Directory   (doesFileExist)
+import           System.FilePath    ((</>))
+import           System.Process
+
+#ifndef WINDOWS
+import           System.Posix.Files (ownerModes, setFileMode)
+#endif
+
+import           Certificate
+import           Fingerprint
+import           Petname
+import           Util
+
+notifyOfIncoming :: FilePath -> Certificate -> Petname -> IO ()
+notifyOfIncoming ddir cert petname = do
+    case petname of
+        Named name -> putStrLn $ "Talk request from '" <> name <> "'; accept with: htalkat a "<> shellQuotePetname (Named name) <>""
+        p@(Unnamed _) -> do
+            putStrLn $ "Talk request from unknown caller " <> showPetname p
+            putStrLn $ "  Fingerprint: " <> showFingerprint (spkiFingerprint cert)
+            putStrLn $ "  Public name: " <> certCN cert
+            putStrLn $ "Accept with: htalkat a " <> shellQuotePetname p
+    createNotifyScriptIfNecessary ddir
+    void $ rawSystem (notifyScriptPath ddir)
+        [ showPetname petname
+        , showFingerprint $ spkiFingerprint cert
+        , certCN cert
+        ]
+
+notifyScriptPath :: FilePath -> FilePath
+notifyScriptPath = (</> "notify.sh")
+
+createNotifyScriptIfNecessary :: FilePath -> IO ()
+createNotifyScriptIfNecessary ddir =
+    let spath = notifyScriptPath ddir
+    in doesFileExist spath >>! do
+        writeFile spath defaultNotifyScript
+#ifndef WINDOWS
+        setFileMode spath ownerModes -- chmod 700
+#endif
+
+defaultNotifyScript :: String
+defaultNotifyScript = unlines
+    [ "#!/usr/bin/env bash"
+    , "# This script is called when someone connects to the talkat server."
+    , "# The following positional arguments are given to this script:"
+    , "# $1: assigned name of caller, or +N for an unknown caller"
+    , "# $2: fingerprint of caller's public key"
+    , "# $3: \"public name\" set in CN field of caller's certificate"
+    , ""
+    , "# Example:"
+    , "#announce=\"$(echo -n \"Talkat request from $1\"; \\"
+    , "#    [[ \"$1\" =~ ^\\+ ]] && echo -n \" $2 (\\\"$3\\\")\")\""
+    , "#write $USER <<<\"$announce\""
+    , "#mail -s \"$announce\" $USER <<<\"Answer with htalkat a '$1'\""
+    , "#notify-send \"$announce\""
+    ]
diff --git a/Opts.hs b/Opts.hs
new file mode 100644
--- /dev/null
+++ b/Opts.hs
@@ -0,0 +1,41 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Opts (help, parseArgs, Opt(..)) where
+
+import           System.Console.GetOpt
+
+data Opt
+    = DataDir FilePath
+    | SocksHost String
+    | SocksPort String
+    | Help
+    | Version
+    deriving (Eq, Ord, Show)
+
+options :: [OptDescr Opt]
+options =
+    [ Option ['d'] ["datadir"] (ReqArg DataDir "PATH") "default: ~/.htalkat, or $HTALKAT_DIR if set"
+    , Option ['S'] ["socks-host"] (ReqArg SocksHost "HOST") "use SOCKS5 proxy"
+    , Option ['P'] ["socks-port"] (ReqArg SocksPort "PORT") "port for SOCKS5 proxy (default: 1080)"
+    , Option ['v'] ["version"] (NoArg Version) "show version information"
+    , Option ['h'] ["help"] (NoArg Help) "show usage information"
+    ]
+
+help :: String -> String
+help = (`usageInfo` options)
+
+parseArgs :: [String] -> IO ([Opt],[String])
+parseArgs argv =
+    case getOpt RequireOrder options argv of
+        (o,n,[])   -> return (o,n)
+        (_,_,errs) -> ioError . userError $ concat errs
diff --git a/Petname.hs b/Petname.hs
new file mode 100644
--- /dev/null
+++ b/Petname.hs
@@ -0,0 +1,100 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Petname where
+
+import           Control.Monad             (msum)
+import           Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT)
+import           Data.Char                 (isAlphaNum)
+import           Data.List                 (elemIndices)
+import           Data.Maybe                (catMaybes)
+import           Safe                      (lastMay, readMay)
+import           System.Directory          (createDirectoryIfMissing,
+                                            listDirectory)
+import           System.FileLock           (SharedExclusive (..), withFileLock)
+import           System.FilePath           (isValid, takeFileName, (</>))
+
+import           Host
+import           Mundanities
+import           User
+
+data Petname = Named String | Unnamed Int
+    deriving (Eq)
+
+instance Ord Petname where
+    compare (Named _) (Unnamed _)    = LT
+    compare (Unnamed _) (Named _)    = GT
+    compare (Named n) (Named n')
+        | c <- compare (length n) (length n')
+        , c /= EQ                    = c
+    compare (Named n) (Named n')     = compare n n'
+    compare (Unnamed n) (Unnamed n') = compare n n'
+
+parsePetname :: String -> Maybe Petname
+parsePetname ('+':s) | Just n <- readMay s, n > 0 = Just $ Unnamed n
+parsePetname s | isValidPetname s = Just $ Named s
+parsePetname _ = Nothing
+
+isValidPetname :: String -> Bool
+isValidPetname ('.':_) = False
+isValidPetname s       = shellQuotable s && isValid s && s == takeFileName s
+    where shellQuotable = notElem '\''
+
+showPetname :: Petname -> String
+showPetname (Named s)   = s
+showPetname (Unnamed n) = '+':show n
+
+shellQuotePetname :: Petname -> String
+shellQuotePetname = shellQuote . showPetname where
+    shellQuote s
+        | all shellSafe s && not (null s) = s
+        | otherwise = '\'' : s <> "'"
+    shellSafe c = isAlphaNum c || c `elem` ".,_-+="
+
+namesDir :: FilePath -> FilePath
+namesDir = (</> "names")
+
+lookupName :: FilePath -> Petname -> IO (Maybe User)
+lookupName ddir name = do
+    let ndir = namesDir ddir
+        path = ndir </> showPetname name
+    createDirectoryIfMissing True ndir
+    ignoreIOErrAlt . withFileLock (ndir </> ".lock") Shared $ \_ ->
+        parseUser <$> readFile path
+
+resolveTarget :: FilePath -> String -> IO (Maybe User)
+resolveTarget ddir target
+    | Just user <- parseUser target = pure $ Just user
+    | otherwise = runMaybeT $ msum
+        [ do
+            name <- MaybeT . pure $ parsePetname target
+            MaybeT $ lookupName ddir name
+        , do
+            i <- MaybeT . pure . lastMay $ elemIndices '@' target
+            let (n, '@':h) = splitAt i target
+            name <- MaybeT . pure $ parsePetname n
+            host <- MaybeT . pure $ parseHost h
+            MaybeT $ ((\u -> u { userHost = Just host }) <$>) <$>
+                lookupName ddir name
+        ]
+
+writeName :: FilePath -> User -> Petname -> IO ()
+writeName ddir user name = do
+    let ndir = namesDir ddir
+        path = ndir </> showPetname name
+    createDirectoryIfMissing True ndir
+    withFileLock (ndir </> ".lock") Exclusive $ \_ ->
+        writeFile path $ showUser user
+
+loadNames :: FilePath -> IO [Petname]
+loadNames ddir = catMaybes . (parsePetname <$>) <$>
+    listDirectory (namesDir ddir)
diff --git a/Prompt.hs b/Prompt.hs
new file mode 100644
--- /dev/null
+++ b/Prompt.hs
@@ -0,0 +1,16 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+module Prompt where
+
+import           System.IO (hFlush, stdout)
+
+promptLine :: String -> IO String
+promptLine p = putStr p >> hFlush stdout >> getLine
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,42 @@
+# htalkat: Haskell client and server for talkat (Talk Across TLS)
+
+## Building from source
+Install the haskell package manager cabal; e.g. on a debian system:
+```
+$ sudo apt-get install cabal-install
+```
+Then in the htalkat directory, run:
+```
+$ cabal update && cabal install
+```
+The resulting binary will be installed by default as `~/.cabal/bin/htalkat`.
+
+### Compile-time options
+* `cabal install -f -curses`: compile without curses; a very simple dumb client is used instead.
+
+## Basic usage
+```
+# Create your cryptographic identity:
+htalkat i
+# Connect to a talkat URI:
+htalkat c talkat:1fb3034c92e2b5d32f78739995abf31b@example.invalid
+# Give it a short name:
+htalkat n talkat:1fb3034c92e2b5d32f78739995abf31b@example.invalid bob
+htalkat c bob
+
+# Host your own talkat server; by default this will run on port 5518.
+htalkat l
+# Wait for someone to connect, then answer:
+htalkat a
+
+# Get further help
+htalkat h
+```
+
+## Configuration
+After first run, you can edit ~/.htalkat/htalkat.conf for general configuration options, and ~/.htalkat/notify.sh to set how the server notifies you of incoming connections.
+
+## Portability
+htalkat was written with POSIX systems in mind, and has only been tested on them, but it may also be possible to compile and run it on Windows. Please let me know if you try.
+
+-- mbays@sdf.org
diff --git a/RelayStream.hs b/RelayStream.hs
new file mode 100644
--- /dev/null
+++ b/RelayStream.hs
@@ -0,0 +1,146 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module RelayStream where
+
+import           Control.Concurrent
+import           Control.Exception              (SomeException, handle)
+import           Control.Monad                  (foldM_, forever, unless, void,
+                                                 when)
+import           System.Timeout                 (timeout)
+
+import qualified Data.ByteString                as BS
+import qualified Data.ByteString.Lazy           as BL
+import qualified Data.Text.Encoding.Error       as T
+import qualified Data.Text.Lazy                 as T
+import qualified Data.Text.Lazy.Encoding        as T
+import qualified Network.Socket                 as S
+import qualified Network.Socket.ByteString.Lazy as SL
+import qualified Network.TLS                    as TLS
+import qualified Time.System                    as TM
+import qualified Time.Types                     as TM
+
+import           Mundanities
+import           TimedText
+
+data WriteOrder = WriteFirst | WriteSecond
+    deriving (Eq,Ord,Show)
+
+relayStream :: TLS.Context -> WriteOrder -> S.Socket -> IO ()
+relayStream ctxt ord dSock = do
+    receivedHandshake <- newEmptyMVar
+    finished <- newEmptyMVar
+    rawInChan <- newChan
+    let abort = putMVar finished ()
+        abortOnErr = handle abortHandler where
+            abortHandler :: Monoid a => SomeException -> IO a
+            abortHandler _ = abort >> pure mempty
+        recvAll = do
+            b <- TLS.recvData ctxt
+            case BS.uncons b of
+                Nothing -> abort
+                Just (h,_) -> do
+                    ok <- tryReadMVar receivedHandshake >>= \case
+                        Just ok -> pure ok
+                        Nothing -> do
+                            let isHandshakeByte = h == introByte
+                            putMVar receivedHandshake isHandshakeByte
+                            if isHandshakeByte
+                                then pure True
+                                else abort >> pure False
+                    if ok then writeChan rawInChan b >> recvAll
+                        else writeChan rawInChan BS.empty
+        sendHandshake = do
+            when (ord == WriteSecond) . void $ readMVar receivedHandshake
+            TLS.sendData ctxt $ BL.singleton introByte
+
+    sockMV <- newEmptyMVar
+    sockThread <- forkIO $ putMVar sockMV . fst =<< S.accept dSock
+
+    _ <- forkIO $ do
+        sock <- readMVar sockMV
+        abortOnErr sendHandshake
+        tsOutChan <- newChan
+        rawOutChan <- newChan
+        _ <- forkIO . abortOnErr $ do
+            writeList2Chan rawOutChan . T.unpack . T.decodeUtf8With T.lenientDecode =<<
+                SL.getContents sock
+            abort
+        pausesThread <- forkIO $ insertPauses rawOutChan tsOutChan
+        abortOnErr $ sendAll tsOutChan
+        killThread pausesThread
+
+    _ <- forkIO $ do
+        tsInChan <- newChan
+        decodeTTThread <- forkIO $
+            writeList2Chan tsInChan . decodeTimedText . BL.fromChunks =<< getChanContents rawInChan
+        _ <- forkIO . abortOnErr $ relayTimed tsInChan =<< readMVar sockMV
+        abortOnErr recvAll
+        killThread decodeTTThread
+
+    _ <- takeMVar finished
+    TLS.bye ctxt
+    ignoreIOErr $ killThread sockThread
+    tryTakeMVar sockMV >>= \case
+        Nothing   -> pure ()
+        Just sock -> S.gracefulClose sock 1000
+    where
+    introByte = fromIntegral $ fromEnum 'T'
+
+    insertPauses rawChan ttChan = TM.timeCurrentP >>= insertPauses'
+        where
+        insertPauses' e = do
+            c <- readChan rawChan
+            e' <- TM.timeCurrentP
+            let ms = elapsedPToMS $ e' - e
+            when (ms > 0) . writeChan ttChan . Left $ fromIntegral ms
+            writeChan ttChan $ Right c
+            insertPauses' e'
+
+    sendAll ttChan = forever $ do
+        readBufMV <- newMVar []
+        _ <- timeout sendTimeout . forever $
+            modifyMVar_ readBufMV . (pure .) . (:) =<< readChan ttChan
+        rtt <- readMVar readBufMV
+        unless (null rtt) . TLS.sendData ctxt . rechunk . encodeTimedText $ reverse rtt
+        where
+        rechunk =
+            -- TLS.sendData sends one packet per chunk, while encodeTimedText
+            -- returns a chunk per char, so it's important to rechunk.
+            BL.fromStrict . BL.toStrict
+        sendTimeout = 1000 * 300
+
+    relayTimed chan sock = foldM_ sendTimed' Nothing =<< getChanContents chan where
+        sendTimed' :: Maybe TM.ElapsedP -> Either Int Char -> IO (Maybe TM.ElapsedP)
+        sendTimed' Nothing (Right c) = do
+            threadDelay bufferTime
+            e <- TM.timeCurrentP
+            sendTimed' (Just e) (Right c)
+        sendTimed' Nothing _ = pure Nothing
+        sendTimed' (Just e) (Right c) = do
+            SL.sendAll sock . T.encodeUtf8 $ T.singleton c
+            pure $ Just e
+        sendTimed' (Just e) (Left n) = do
+            delayed <- elapsedPToMS . flip (-) e <$> TM.timeCurrentP
+            when (n > delayed) . threadDelay . (1000 *) $ n - delayed
+            pure $ if n == pauseMax && n < delayed
+                then Nothing
+                else Just $ e + msToElapsedP n
+        bufferTime = 1000 * 300
+
+    msToElapsedP :: Int -> TM.ElapsedP
+    msToElapsedP ms | (s,ms') <- fromIntegral ms `divMod` 1000 =
+        TM.ElapsedP (TM.Elapsed (TM.Seconds s)) (TM.NanoSeconds $ 1000000 * ms')
+    elapsedPToMS :: TM.ElapsedP -> Int
+    elapsedPToMS (TM.ElapsedP (TM.Elapsed (TM.Seconds s)) (TM.NanoSeconds ns)) =
+        fromIntegral $ s*1000 + ns `div` 1000000
diff --git a/TLSTalk.hs b/TLSTalk.hs
new file mode 100644
--- /dev/null
+++ b/TLSTalk.hs
@@ -0,0 +1,238 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE CPP               #-}
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module TLSTalk
+    ( SocksProxy(..)
+    , answerLast
+    , connect
+    , serve
+    , spawnDefaultInteractiveClient
+    ) where
+
+import           Control.Concurrent
+import           Control.Exception
+import           Control.Monad            (void, (<=<))
+import           Data.Default.Class       (def)
+import           Data.X509.Validation     (FailedReason (..), defaultChecks,
+                                           defaultHooks, validate)
+import           Network.Simple.TCP       (connectSock, connectSockSOCKS5)
+import           Network.TLS              as TLS
+import           Network.TLS.Extra.Cipher
+import           System.Directory         (createDirectoryIfMissing)
+import           System.Exit              (exitFailure)
+import           System.FileLock          (SharedExclusive (..), withFileLock,
+                                           withTryFileLock)
+import           System.FilePath
+import           System.IO                (IOMode (..), openFile)
+import           System.IO.Temp           (withSystemTempDirectory)
+import           System.Process           (rawSystem)
+import           Time.System              (timeCurrent)
+import           Time.Types               (Elapsed (..), Seconds (..))
+
+import qualified Data.ByteString          as BS
+
+import qualified Data.Text                as TS
+import qualified Data.Text.Encoding       as TS
+import qualified Data.X509                as X
+import qualified Network.Simple.TCP       as TCP
+import qualified Network.Socket           as S
+
+import           Certificate
+import           Config
+import           Fingerprint
+import           Host
+import           Incoming
+import           LookupPetname
+import           Notify
+import           Petname
+import           RelayStream
+
+#ifdef CURSES
+import           CursesClient
+#else
+import           DumbClient
+#endif
+
+bindingNamedSocket :: FilePath -> (S.Socket -> IO a) -> IO a
+bindingNamedSocket path =
+    (`bracket` S.close) $ do
+        sock <- S.socket S.AF_UNIX S.Stream 0
+        S.bind sock $ S.SockAddrUnix path
+        S.listen sock 1
+        pure sock
+
+serve :: FilePath -> Credential -> IO ()
+serve ddir cred = errorOnNoLock <=< withTryFileLock listenLockPath Exclusive $ \_ -> do
+    conf <- loadConfig ddir
+    let params = def
+                { serverShared = def { sharedCredentials = Credentials [cred] }
+                , serverSupported = def
+                    { supportedCiphers = talkatCiphersuite
+                    , supportedVersions = [TLS13] }
+                , serverHooks = def
+                    { onUnverifiedClientCert = pure True
+                    , onClientCertificate = \_ -> pure CertificateUsageAccept
+                    }
+                , serverWantClientCert = True
+                }
+    let port = show $ listen_port conf
+        hostPref = case listen_host conf of
+            [] -> TCP.HostAny
+            h  -> TCP.Host h
+        Just fp = spkiFingerprint <$> takeTailCert (fst cred)
+    putStrLn $ "Listening on "
+        <> (case hostPref of
+            TCP.Host h -> "host " <> h
+            _          -> "all available hosts")
+        <> ", port " <> port <> "."
+    putStrLn $ "URI: talkat:"
+        <> showFingerprint fp <> "@"
+        <> (let portBit = if port /= show defaultTalkatPort
+                    then ":" <> port else ""
+            in case hostPref of
+                TCP.Host h -> h <> portBit
+                _          -> "[host]" <> portBit <>
+                    "\n       (replace [host] with your hostname or IP address)")
+    cleanAllIncoming ddir
+    serialMVar <- newMVar 0
+    TCP.serve hostPref port $ \(sock,_) -> do
+        S.setSocketOption sock S.NoDelay 1
+        context <- contextNew sock params
+        handshake context
+        Just cert <- (takeTailCert =<<) <$> getClientCertificateChain context
+        (if accept_unnamed conf then ((Just <$>) .) . lookupOrAddPetname else lookupPetname)
+                ddir (spkiFingerprint cert) >>= \case
+            Nothing -> pure ()
+            Just petname -> withSystemTempDirectory "htalkat" $ \tdir -> do
+                let sockPath = tdir </> "sock"
+                bindingNamedSocket sockPath $ \dSock -> do
+                    -- Serial numbers ensure we don't delete the wrong dir
+                    serial <- modifyMVar serialMVar $ \n -> pure (n+1,n)
+                    incoming <- addIncoming ddir cert sockPath serial
+                    notifyOfIncoming ddir cert petname
+                    relayStream context WriteFirst dSock
+                    withFileLock (incomingDir ddir </> ".lock") Exclusive $ \_ ->
+                        cleanIncoming ddir (Just serial) incoming
+    where
+    listenLockPath = ddir </> ".listen_lock"
+    errorOnNoLock :: Maybe a -> IO ()
+    errorOnNoLock Nothing = do
+        putStrLn $ "Error: " <> listenLockPath <> " locked by another process."
+        exitFailure
+    errorOnNoLock _ = pure ()
+
+data SocksProxy
+    = NoSocksProxy
+    | Socks5Proxy String String
+
+connect :: FilePath -> Credential -> String -> SocksProxy -> Host -> Fingerprint -> IO ()
+connect ddir cred name socksProxy (Host hostname port) fp = do
+    let serverId = if port == defaultTalkatPort
+            then BS.empty
+            else TS.encodeUtf8 . TS.pack . (':':) $ show port
+        params = (TLS.defaultParamsClient hostname serverId)
+            { clientSupported = def
+                { supportedCiphers = talkatCiphersuite
+                , supportedVersions = [TLS13] }
+            , clientHooks = def
+                { onServerCertificate = checkServerCert
+                , onCertificateRequest = \(_,_,_) ->
+                    pure $ Just cred
+                }
+            }
+    context <- do
+        sock <- openSocket
+        S.setSocketOption sock S.NoDelay 1
+        c <- TLS.contextNew sock params
+        handshake c >> pure c
+    withSystemTempDirectory "htalkat" $ \tdir -> do
+        let path = tdir </> "sock"
+        bindingNamedSocket path $ \dSock -> do
+            _ <- forkIO $ relayStream context WriteSecond dSock
+            conf <- loadConfig ddir
+            spawnInteractiveClient ddir conf name path
+    where
+    openSocket :: IO S.Socket
+    openSocket = case socksProxy of
+        NoSocksProxy -> fst <$> connectSock hostname (show port)
+        Socks5Proxy socksHostname socksPort -> do
+            sock <- fst <$> connectSock socksHostname socksPort
+            _ <- connectSockSOCKS5 sock hostname (show port)
+            pure sock
+
+    checkServerCert store cache service chain | Just cert <- takeTailCert chain = do
+        errors <- filter (not . ignoreError) <$> validate X.HashSHA256 defaultHooks
+            (defaultChecks { checkExhaustive = True , checkLeafV3 = False }) store cache service chain
+        if fp == spkiFingerprint cert then pure errors
+            else do
+                putStrLn "Server provides an unexpected certificate!"
+                putStrLn $ "Expected: " <> showFingerprint fp
+                putStrLn $ "Received: " <> showFingerprint (spkiFingerprint cert)
+                pure $ UnknownCA : errors
+        where
+        ignoreError UnknownCA        = True
+        ignoreError SelfSigned       = True
+        ignoreError NotAnAuthority   = True
+        ignoreError (NameMismatch _) = True
+        ignoreError _                = False
+    checkServerCert _ _ _ _ = pure [ EmptyChain ]
+
+talkatCiphersuite :: [Cipher]
+talkatCiphersuite =
+    [ cipher_TLS13_AES128GCM_SHA256
+    , cipher_TLS13_AES256GCM_SHA384
+    , cipher_TLS13_CHACHA20POLY1305_SHA256
+    , cipher_TLS13_AES128CCM_SHA256
+    ]
+
+answerLast :: FilePath -> Maybe Fingerprint -> IO ()
+answerLast ddir mFp = do
+    mInfo <- withFileLock (incomingDir ddir </> ".lock") Exclusive $ \_ -> do
+        lastIncoming ddir mFp >>= \case
+            Just incoming -> do
+                petname <- incomingPetname ddir incoming
+                sockPath <- readFile (incomingPath ddir incoming </> "sock")
+                cleanIncoming ddir Nothing incoming
+                pure $ Just (petname, sockPath)
+            Nothing -> pure Nothing
+    case mInfo of
+        Just (petname, sockPath) -> do
+            conf <- loadConfig ddir
+            spawnInteractiveClient ddir conf (showPetname petname) sockPath
+        Nothing -> putStrLn "Nothing to answer."
+
+spawnInteractiveClient :: FilePath -> Config -> String -> FilePath -> IO ()
+spawnInteractiveClient ddir conf name sockPath
+    | command:args <- interactive_client conf =
+        void . rawSystem command $ args ++ [name, sockPath]
+    | otherwise =
+#ifdef CURSES
+        do
+            mLog <- if curses_log conf
+                then do
+                    createDirectoryIfMissing True $ ddir </> "logs"
+                    Elapsed (Seconds epochSecs) <- timeCurrent
+                    Just <$> openFile (ddir </> "logs" </> name <>
+                        "-" <> show epochSecs <.> "log") AppendMode
+                else pure Nothing
+            cursesClient (curses_local_top conf) mLog name sockPath
+#else
+        dumbClient sockPath
+#endif
+
+spawnDefaultInteractiveClient :: FilePath -> String -> FilePath -> IO ()
+spawnDefaultInteractiveClient ddir name sockPath = do
+    conf <- loadConfig ddir
+    spawnInteractiveClient ddir (conf { interactive_client = [] })
+        name sockPath
diff --git a/Talkat.hs b/Talkat.hs
new file mode 100644
--- /dev/null
+++ b/Talkat.hs
@@ -0,0 +1,227 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE CPP        #-}
+{-# LANGUAGE LambdaCase #-}
+
+module Main where
+
+import           Control.Monad      (forM_, mplus, when)
+import           Data.Char          (toLower)
+import           Data.List          (isPrefixOf, sort)
+import           Data.Maybe         (fromMaybe, isJust)
+import           Safe               (headMay)
+import           System.Directory   (createDirectoryIfMissing,
+                                     doesDirectoryExist, getHomeDirectory)
+import           System.Environment (getArgs, lookupEnv)
+import           System.Exit        (exitFailure, exitSuccess)
+import           System.FilePath    ((</>))
+
+#ifndef WINDOWS
+import           System.Posix.Files (ownerModes, setFileMode)
+#endif
+
+import           Config
+import           Fingerprint
+import           Host
+import           Identity
+import           Incoming
+import           Notify
+import           Petname
+import           Prompt
+import           TLSTalk
+import           User
+import           Util
+import           Version
+
+import qualified Opts
+
+data Command
+    = Help
+    | Identity
+    | Name
+    | Answer
+    | Connect
+    | Listen
+    deriving (Eq,Ord,Show,Enum)
+
+commands :: [Command]
+commands = enumFrom Help
+
+cmdOfStr :: String -> Maybe Command
+cmdOfStr s = headMay [ c
+    | c <- commands
+    , s `isPrefixOf` (toLower <$> show c) ]
+
+die :: String -> IO ()
+die s = putStrLn s >> exitFailure
+
+main :: IO ()
+main = do
+    (opts,args) <- Opts.parseArgs =<< getArgs
+    when (Opts.Version `elem` opts) $ putStrLn version >> exitSuccess
+
+    ddir <- do
+        let optDir = headMay [ path | Opts.DataDir path <- opts ]
+        envDir <- lookupEnv "HTALKAT_DIR"
+        defDir <- (</> ".htalkat") <$> getHomeDirectory
+        pure . fromMaybe defDir $ optDir `mplus` envDir
+    doesDirectoryExist ddir >>! do
+        createDirectoryIfMissing True ddir
+#ifndef WINDOWS
+        setFileMode ddir ownerModes -- chmod 700
+#endif
+        createDirectoryIfMissing True $ ddir </> "incoming"
+        createDirectoryIfMissing True $ ddir </> "names"
+        createConfigFileIfNecessary ddir
+        createNotifyScriptIfNecessary ddir
+
+    let socksProxy = maybe (const NoSocksProxy) Socks5Proxy
+            (headMay [ h | Opts.SocksHost h <- opts ])
+            . fromMaybe "1080" $ headMay [ p | Opts.SocksPort p <- opts ]
+
+    let (mcmd,args') = if Opts.Help `elem` opts then (Just Help, args)
+            else (cmdOfStr =<< headMay args, drop 1 args)
+
+    case mcmd of
+        Nothing -> do
+            isConnectArg <- case args of
+                [target] -> isJust <$> resolveTarget ddir target
+                _        -> pure False
+            if isConnectArg
+                then doCmd ddir socksProxy args Connect
+                else die "Unknown command/name. Use 'htalkat h' for help."
+        Just cmd -> doCmd ddir socksProxy args' cmd
+
+doCmd :: [Char] -> SocksProxy -> [String] -> Command -> IO ()
+doCmd ddir socksProxy args = \case
+    Help -> case args of
+        [] -> putStr . Opts.help . init . concat $ (<>"\n") <$>
+            [ "Usage: htalkat [OPTION...] COMMAND [ARG...]"
+            , ""
+            , "Commands:"
+            , "  htalkat i[dentity] [PUBLIC_NAME]          create/show identity"
+            , "  htalkat c[onnect] [talkat:]FP@HOST        connect to host"
+            , "  htalkat c[onnect] NAME                    connect to named user"
+            , "  htalkat n[ame] [talkat:]FP[@HOST] [NAME]  set name for user [at host]"
+            , "  htalkat l[isten]                          start server"
+            , "  htalkat a[nswer] [NAME]                   accept connection [from user]"
+            , "  htalkat a[nswer] --list                   list unanswered connections"
+            , "  htalkat n[ame] +N NAME                    set name for unnamed caller"
+            , "  htalkat h[elp] [COMMAND]                  show help [on command]"
+            , ""
+            , "FP is a 32 hex character public key fingerprint."
+            , "HOST can specify a nonstandard port as \"HOSTNAME:PORT\""
+            , ""
+            , "Options:"
+            ]
+        [c] | Just cmd <- cmdOfStr c -> mapM_ putStrLn $ case cmd of
+            Help -> [ "htalkat h[elp] [COMMAND]"
+                , "  Show help [on command]." ]
+            Identity ->
+                [ "htalkat i[dentity] [PUBLIC_NAME]"
+                , "  Create new identity (prompting for public name if omitted),"
+                , "  or show existing identity."
+                , "  If PUBLIC_NAME is given and identity exists, change public name in identity."
+                ]
+            Name ->
+                [ "htalkat n[ame] [talkat:]FP[@HOST] [NAME]"
+                , "  Set NAME as a synonym for the user identified by the given fingerprint."
+                , "  The name will be shown when receiving a call from the user."
+                , "  If a host is specified, then NAME can be used with the c[onnect] command."
+                , "  If NAME already exists, it will be overwritten."
+                , "  If NAME is omitted, it will be prompted for; this makes a good URI handler."
+                , "htalkat n[ame] NAME1 NAME2:"
+                , "  As above, but setting NAME2 to whatever NAME1 is currently set to."
+                , "  NAME1 may be of the form +N (+1, +2 etc); these pseudonames are"
+                , "  automatically assigned to unknown incoming callers."
+                , "htalkat n[ame]:"
+                , "  List known names."
+                , ""
+                , "Names are saved as files in " <> show ddir </> "names" <> "."
+                , "To delete, rename, or copy names, manipulate these files directly." ]
+            Connect ->
+                [ "htalkat c[onnect] NAME"
+                , "  Connect to user at host as previously named with the n[ame] command."
+                , "htalkat c[onnect] [talkat:]FP@HOST"
+                , "  Call host. It is important to obtain the correct fingerprint of the person"
+                , "  you intend to call, not just give whatever fingerprint is served by the host."
+                , ""
+                , "The command 'c[onnect]' can normally be omitted."
+                , "NAME@HOST also works."
+                ]
+            Answer -> [ "htalkat a[nswer] [NAME]"
+                , "  Answer most recent incoming call, restricting to calls from NAME if given."
+                , ""
+                , "htalkat a[nswer] --list"
+                , "  List unanswered incoming connections."
+                , ""
+                , "htalkat a[nswer] --interactive-client NAME SOCKET_PATH"
+                , "  Directly invoke interactive client,"
+                , "  for use with the interactive_client config option."
+                ]
+            Listen -> [ "htalkat l[isten]"
+                , "  Start server process which will listen for calls and announce them."
+                , "  Other users will be able to connect to you at talkat:FP@HOST[:PORT],"
+                , "  where FP is as given by i[dentity], HOST is your hostname or IP address,"
+                , "  and PORT is a non-standard port if you set one."
+                , "  See " <> ddir </> "listen.conf" <> " for configuration options,"
+                , "  and " <> ddir </> "notify.sh" <> " to set up notifications." ]
+        _ -> pure ()
+
+    Identity -> createOrShowIdentity ddir $ headMay args
+
+    Name -> case args of
+        target:args' | length args' <= 1 ->
+            resolveTarget ddir target >>= \case
+                Nothing   -> die $ "Unknown: " <> target
+                Just user -> case args' of
+                    name:_ | Just pet <- parsePetname name ->
+                        writeName ddir user pet
+                    name:_ -> die $ "Invalid name: " <> name
+                    [] -> do
+                        name <- promptLine $ "Enter name to assign to " <> showUser user <> ": "
+                        doCmd ddir socksProxy [target,name] Name
+        [] -> do
+            names <- sort <$> loadNames ddir
+            forM_ names $ \name -> do
+                mUser <- lookupName ddir name
+                putStrLn $ showPetname name <> ": " <> case mUser of
+                    Nothing -> "[unparseable name file!]"
+                    Just (User fp mh) -> showFingerprint fp <>
+                        maybe "" (("@" <>) . showHost) mh
+        _ -> die "Usage: htalkat n [talkat:]FP[@HOST[:PORT]] NAME; htalkat n NAME1 NAME2"
+    Answer -> case args of
+        s:_ | s `elem` ["-l","--list"] -> mapM_ putStrLn =<< listIncoming ddir
+        [s,name,sockPath] | s `elem` ["-i","--interactive-client"] ->
+            spawnDefaultInteractiveClient ddir name sockPath
+        [target] ->
+            resolveTarget ddir target >>= \case
+                Nothing          -> die $ "Unknown: " <> target
+                Just (User fp _) -> answerLast ddir (Just fp)
+        [] -> answerLast ddir Nothing
+        _ -> die "Usage: htalkat a [--list] [NAME]"
+    Listen -> loadIdentity ddir IdListen >>= \case
+        Nothing   -> die "You must first create an identity with 'htalkat i'."
+        Just cred -> serve ddir cred
+    Connect -> loadIdentity ddir IdConnect >>= \case
+        Nothing -> die "You must first create an identity with 'htalkat i'."
+        Just cred -> case args of
+            [target] -> resolveTarget ddir target >>= \case
+                Nothing ->
+                    die $ "Unknown: " <> target
+                Just (User _ Nothing) ->
+                    die $ "No host associated with '" <> target <> "'."
+                Just (User fp (Just host)) ->
+                    connect ddir cred name socksProxy host fp
+                    where
+                    name | Just pet <- parsePetname target = showPetname pet
+                        | otherwise = showHost host
+            _ -> die "Usage: htalkat c NAME[@HOST]; htalkat c [talkat:]FP@HOST"
diff --git a/TimedText.hs b/TimedText.hs
new file mode 100644
--- /dev/null
+++ b/TimedText.hs
@@ -0,0 +1,62 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE OverloadedStrings #-}
+
+module TimedText where
+
+import qualified Data.Array                 as A
+import qualified Data.ByteString.Lazy       as BL
+import qualified Data.ByteString.Lazy.Char8 as BLC
+import qualified Data.Text.Encoding.Error   as T
+import qualified Data.Text.Lazy             as T
+import qualified Data.Text.Lazy.Encoding    as T
+
+type TimedText = [ Either Int Char ]
+
+pauseMax :: Int
+pauseMax = 64 * 64 - 1
+
+encodeTimedText :: TimedText -> BL.ByteString
+encodeTimedText = pad . BL.concat . (encode <$>)
+    where
+    encode (Left n) | n <= 0 = BL.empty
+    encode (Left n) | n >= pauseMax = "~//"
+    encode (Left n) | (a,b) <- n `divMod` 64 = "~" <> base64BC a <> base64BC b
+        where
+        base64BC = BLC.singleton . (base64Array A.!)
+        base64Array = A.listArray (0,63) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+    encode (Right '~') = "~~"
+    encode (Right c) = T.encodeUtf8 $ T.singleton c
+    pad b = b <> BL.pack (replicate (fromIntegral $ (- BL.length b) `mod` padLength) 0)
+    padLength = 24
+
+decodeTimedText :: BL.ByteString -> TimedText
+decodeTimedText = decode . T.unpack . T.decodeUtf8With T.lenientDecode. unpad
+    where
+    decode [] = []
+    decode ('~':'~':s) = Right '~' : decode s
+    decode ('~':a:b:s) | Just n <- decodePause a b = Left n : decode s
+    decode ('~':s) = decode s  -- unparseable sequence
+    decode (c:s) = Right c : decode s
+
+    decodePause a b
+        | Just n <- fromIntegral <$> decodeBase64Char a
+        , Just m <- fromIntegral <$> decodeBase64Char b
+        = Just $ 64*n + m
+    decodePause _ _ = Nothing
+    decodeBase64Char :: Char -> Maybe Int
+    decodeBase64Char a | n <- fromEnum a - fromEnum 'A', 0 <= n && n < 26 = Just n
+    decodeBase64Char a | n <- fromEnum a - fromEnum 'a', 0 <= n && n < 26 = Just $ 26 + n
+    decodeBase64Char a | n <- fromEnum a - fromEnum '0', 0 <= n && n < 10 = Just $ 52 + n
+    decodeBase64Char '+' = Just 62
+    decodeBase64Char '/' = Just 63
+    decodeBase64Char _ = Nothing
+    unpad = BL.filter (/= 0)
diff --git a/User.hs b/User.hs
new file mode 100644
--- /dev/null
+++ b/User.hs
@@ -0,0 +1,45 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module User
+    ( User(..)
+    , parseUser
+    , showUser
+    ) where
+
+import           Control.Monad (guard, msum)
+import           Data.List     (stripPrefix)
+
+import           Fingerprint
+import           Host
+
+data User = User
+    { userFP   :: Fingerprint
+    , userHost :: Maybe Host
+    }
+
+parseUser,parseUser' :: String -> Maybe User
+parseUser s | Just s' <- stripPrefix "talkat:" s = parseUser' s'
+parseUser s = parseUser' s
+parseUser' s = do
+    let (fpStr,rest) = splitAt 32 s
+    fp <- parseFingerprint fpStr
+    msum [ guard (null rest) >> pure (User fp Nothing)
+        , do
+            '@':hostStr <- pure rest
+            host <- parseHost hostStr
+            pure . User fp $ Just host
+        ]
+
+showUser :: User -> String
+showUser (User fp Nothing)     = showFingerprint fp
+showUser (User fp (Just host)) = showFingerprint fp <> "@" <> showHost host
diff --git a/Util.hs b/Util.hs
new file mode 100644
--- /dev/null
+++ b/Util.hs
@@ -0,0 +1,31 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Util where
+import           Control.Monad (unless, when)
+
+-- nice tip from one joeyh:
+whenM,unlessM,(>>?),(>>!) :: Monad m => m Bool -> m () -> m ()
+whenM c a = c >>= flip when a
+unlessM c a = c >>= flip unless a
+(>>?) = whenM
+(>>!) = unlessM
+-- same precedence as ($), allowing e.g. foo bar >>! error $ "failed " ++ meep
+infixr 0 >>?
+infixr 0 >>!
+
+maybeToEither :: e -> Maybe a -> Either e a
+maybeToEither e = maybe (Left e) Right
+
+eitherToMaybe :: Either e a -> Maybe a
+eitherToMaybe (Left _)  = Nothing
+eitherToMaybe (Right a) = Just a
diff --git a/Version.hs b/Version.hs
new file mode 100644
--- /dev/null
+++ b/Version.hs
@@ -0,0 +1,19 @@
+-- This file is part of htalkat
+-- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
+--
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of version 3 of the GNU General Public License as
+-- published by the Free Software Foundation, or any later version.
+--
+-- You should have received a copy of the GNU General Public License
+-- along with this program.  If not, see http://www.gnu.org/licenses/.
+
+{-# LANGUAGE Safe #-}
+
+module Version where
+
+programName :: String
+programName = "htalkat"
+
+version :: String
+version = "0.1.1"
diff --git a/WCWidth.hs b/WCWidth.hs
new file mode 100644
--- /dev/null
+++ b/WCWidth.hs
@@ -0,0 +1,429 @@
+-- Adapted from a pure haskell port of wcwidth by agentm, released under the
+-- "Unlicense" licence, taken from:
+-- https://raw.githubusercontent.com/agentm/project-m36/master/src/lib/ProjectM36/WCWidth.hs
+
+module WCWidth (wcwidth) where
+import           Data.Char
+import           Data.Set.Range
+
+wIDEEASTASIAN :: RangeSet Int
+wIDEEASTASIAN = foldr insertRange empty [
+    (0x1100, 0x115f),  -- Hangul Choseong Kiyeok  ..Hangul Choseong Filler
+    (0x231a, 0x231b),  -- Watch                   ..Hourglass
+    (0x2329, 0x232a),  -- Left-pointing Angle Brac..Right-pointing Angle Bra
+    (0x23e9, 0x23ec),  -- Black Right-pointing Dou..Black Down-pointing Doub
+    (0x23f0, 0x23f0),  -- Alarm Clock             ..Alarm Clock
+    (0x23f3, 0x23f3),  -- Hourglass With Flowing S..Hourglass With Flowing S
+    (0x25fd, 0x25fe),  -- White Medium Small Squar..Black Medium Small Squar
+    (0x2614, 0x2615),  -- Umbrella With Rain Drops..Hot Beverage
+    (0x2648, 0x2653),  -- Aries                   ..Pisces
+    (0x267f, 0x267f),  -- Wheelchair Symbol       ..Wheelchair Symbol
+    (0x2693, 0x2693),  -- Anchor                  ..Anchor
+    (0x26a1, 0x26a1),  -- High Voltage Sign       ..High Voltage Sign
+    (0x26aa, 0x26ab),  -- Medium White Circle     ..Medium Black Circle
+    (0x26bd, 0x26be),  -- Soccer Ball             ..Baseball
+    (0x26c4, 0x26c5),  -- Snowman Without Snow    ..Sun Behind Cloud
+    (0x26ce, 0x26ce),  -- Ophiuchus               ..Ophiuchus
+    (0x26d4, 0x26d4),  -- No Entry                ..No Entry
+    (0x26ea, 0x26ea),  -- Church                  ..Church
+    (0x26f2, 0x26f3),  -- Fountain                ..Flag In Hole
+    (0x26f5, 0x26f5),  -- Sailboat                ..Sailboat
+    (0x26fa, 0x26fa),  -- Tent                    ..Tent
+    (0x26fd, 0x26fd),  -- Fuel Pump               ..Fuel Pump
+    (0x2705, 0x2705),  -- White Heavy Check Mark  ..White Heavy Check Mark
+    (0x270a, 0x270b),  -- Raised Fist             ..Raised Hand
+    (0x2728, 0x2728),  -- Sparkles                ..Sparkles
+    (0x274c, 0x274c),  -- Cross Mark              ..Cross Mark
+    (0x274e, 0x274e),  -- Negative Squared Cross M..Negative Squared Cross M
+    (0x2753, 0x2755),  -- Black Question Mark Orna..White Exclamation Mark O
+    (0x2757, 0x2757),  -- Heavy Exclamation Mark S..Heavy Exclamation Mark S
+    (0x2795, 0x2797),  -- Heavy Plus Sign         ..Heavy Division Sign
+    (0x27b0, 0x27b0),  -- Curly Loop              ..Curly Loop
+    (0x27bf, 0x27bf),  -- Double Curly Loop       ..Double Curly Loop
+    (0x2b1b, 0x2b1c),  -- Black Large Square      ..White Large Square
+    (0x2b50, 0x2b50),  -- White Medium Star       ..White Medium Star
+    (0x2b55, 0x2b55),  -- Heavy Large Circle      ..Heavy Large Circle
+    (0x2e80, 0x2e99),  -- Cjk Radical Repeat      ..Cjk Radical Rap
+    (0x2e9b, 0x2ef3),  -- Cjk Radical Choke       ..Cjk Radical C-simplified
+    (0x2f00, 0x2fd5),  -- Kangxi Radical One      ..Kangxi Radical Flute
+    (0x2ff0, 0x2ffb),  -- Ideographic Description ..Ideographic Description
+    (0x3000, 0x303e),  -- Ideographic Space       ..Ideographic Variation In
+    (0x3041, 0x3096),  -- Hiragana Letter Small A ..Hiragana Letter Small Ke
+    (0x3099, 0x30ff),  -- Combining Katakana-hirag..Katakana Digraph Koto
+    (0x3105, 0x312d),  -- Bopomofo Letter B       ..Bopomofo Letter Ih
+    (0x3131, 0x318e),  -- Hangul Letter Kiyeok    ..Hangul Letter Araeae
+    (0x3190, 0x31ba),  -- Ideographic Annotation L..Bopomofo Letter Zy
+    (0x31c0, 0x31e3),  -- Cjk Stroke T            ..Cjk Stroke Q
+    (0x31f0, 0x321e),  -- Katakana Letter Small Ku..Parenthesized Korean Cha
+    (0x3220, 0x3247),  -- Parenthesized Ideograph ..Circled Ideograph Koto
+    (0x3250, 0x32fe),  -- Partnership Sign        ..Circled Katakana Wo
+    (0x3300, 0x4dbf),  -- Square Apaato           ..
+    (0x4e00, 0xa48c),  -- Cjk Unified Ideograph-4e..Yi Syllable Yyr
+    (0xa490, 0xa4c6),  -- Yi Radical Qot          ..Yi Radical Ke
+    (0xa960, 0xa97c),  -- Hangul Choseong Tikeut-m..Hangul Choseong Ssangyeo
+    (0xac00, 0xd7a3),  -- Hangul Syllable Ga      ..Hangul Syllable Hih
+    (0xf900, 0xfaff),  -- Cjk Compatibility Ideogr..
+    (0xfe10, 0xfe19),  -- Presentation Form For Ve..Presentation Form For Ve
+    (0xfe30, 0xfe52),  -- Presentation Form For Ve..Small Full Stop
+    (0xfe54, 0xfe66),  -- Small Semicolon         ..Small Equals Sign
+    (0xfe68, 0xfe6b),  -- Small Reverse Solidus   ..Small Commercial At
+    (0xff01, 0xff60),  -- Fullwidth Exclamation Ma..Fullwidth Right White Pa
+    (0xffe0, 0xffe6),  -- Fullwidth Cent Sign     ..Fullwidth Won Sign
+    (0x16fe0, 0x16fe0),  -- (nil)                   ..
+    (0x17000, 0x187ec),  -- (nil)                   ..
+    (0x18800, 0x18af2),  -- (nil)                   ..
+    (0x1b000, 0x1b001),  -- Katakana Letter Archaic ..Hiragana Letter Archaic
+    (0x1f004, 0x1f004),  -- Mahjong Tile Red Dragon ..Mahjong Tile Red Dragon
+    (0x1f0cf, 0x1f0cf),  -- Playing Card Black Joker..Playing Card Black Joker
+    (0x1f18e, 0x1f18e),  -- Negative Squared Ab     ..Negative Squared Ab
+    (0x1f191, 0x1f19a),  -- Squared Cl              ..Squared Vs
+    (0x1f200, 0x1f202),  -- Square Hiragana Hoka    ..Squared Katakana Sa
+    (0x1f210, 0x1f23b),  -- Squared Cjk Unified Ideo..
+    (0x1f240, 0x1f248),  -- Tortoise Shell Bracketed..Tortoise Shell Bracketed
+    (0x1f250, 0x1f251),  -- Circled Ideograph Advant..Circled Ideograph Accept
+    (0x1f300, 0x1f320),  -- Cyclone                 ..Shooting Star
+    (0x1f32d, 0x1f335),  -- Hot Dog                 ..Cactus
+    (0x1f337, 0x1f37c),  -- Tulip                   ..Baby Bottle
+    (0x1f37e, 0x1f393),  -- Bottle With Popping Cork..Graduation Cap
+    (0x1f3a0, 0x1f3ca),  -- Carousel Horse          ..Swimmer
+    (0x1f3cf, 0x1f3d3),  -- Cricket Bat And Ball    ..Table Tennis Paddle And
+    (0x1f3e0, 0x1f3f0),  -- House Building          ..European Castle
+    (0x1f3f4, 0x1f3f4),  -- Waving Black Flag       ..Waving Black Flag
+    (0x1f3f8, 0x1f43e),  -- Badminton Racquet And Sh..Paw Prints
+    (0x1f440, 0x1f440),  -- Eyes                    ..Eyes
+    (0x1f442, 0x1f4fc),  -- Ear                     ..Videocassette
+    (0x1f4ff, 0x1f53d),  -- Prayer Beads            ..Down-pointing Small Red
+    (0x1f54b, 0x1f54e),  -- Kaaba                   ..Menorah With Nine Branch
+    (0x1f550, 0x1f567),  -- Clock Face One Oclock   ..Clock Face Twelve-thirty
+    (0x1f57a, 0x1f57a),  -- (nil)                   ..
+    (0x1f595, 0x1f596),  -- Reversed Hand With Middl..Raised Hand With Part Be
+    (0x1f5a4, 0x1f5a4),  -- (nil)                   ..
+    (0x1f5fb, 0x1f64f),  -- Mount Fuji              ..Person With Folded Hands
+    (0x1f680, 0x1f6c5),  -- Rocket                  ..Left Luggage
+    (0x1f6cc, 0x1f6cc),  -- Sleeping Accommodation  ..Sleeping Accommodation
+    (0x1f6d0, 0x1f6d2),  -- Place Of Worship        ..
+    (0x1f6eb, 0x1f6ec),  -- Airplane Departure      ..Airplane Arriving
+    (0x1f6f4, 0x1f6f6),  -- (nil)                   ..
+    (0x1f910, 0x1f91e),  -- Zipper-mouth Face       ..
+    (0x1f920, 0x1f927),  -- (nil)                   ..
+    (0x1f930, 0x1f930),  -- (nil)                   ..
+    (0x1f933, 0x1f93e),  -- (nil)                   ..
+    (0x1f940, 0x1f94b),  -- (nil)                   ..
+    (0x1f950, 0x1f95e),  -- (nil)                   ..
+    (0x1f980, 0x1f991),  -- Crab                    ..
+    (0x1f9c0, 0x1f9c0),  -- Cheese Wedge            ..Cheese Wedge
+    (0x20000, 0x2fffd),  -- Cjk Unified Ideograph-20..
+    (0x30000, 0x3fffd)  -- (nil)                   ..
+    ]
+
+zEROWIDTH :: RangeSet Int
+zEROWIDTH = foldr insertRange empty [
+    (0x0300, 0x036f),  -- Combining Grave Accent  ..Combining Latin Small Le
+    (0x0483, 0x0489),  -- Combining Cyrillic Titlo..Combining Cyrillic Milli
+    (0x0591, 0x05bd),  -- Hebrew Accent Etnahta   ..Hebrew Point Meteg
+    (0x05bf, 0x05bf),  -- Hebrew Point Rafe       ..Hebrew Point Rafe
+    (0x05c1, 0x05c2),  -- Hebrew Point Shin Dot   ..Hebrew Point Sin Dot
+    (0x05c4, 0x05c5),  -- Hebrew Mark Upper Dot   ..Hebrew Mark Lower Dot
+    (0x05c7, 0x05c7),  -- Hebrew Point Qamats Qata..Hebrew Point Qamats Qata
+    (0x0610, 0x061a),  -- Arabic Sign Sallallahou ..Arabic Small Kasra
+    (0x064b, 0x065f),  -- Arabic Fathatan         ..Arabic Wavy Hamza Below
+    (0x0670, 0x0670),  -- Arabic Letter Superscrip..Arabic Letter Superscrip
+    (0x06d6, 0x06dc),  -- Arabic Small High Ligatu..Arabic Small High Seen
+    (0x06df, 0x06e4),  -- Arabic Small High Rounde..Arabic Small High Madda
+    (0x06e7, 0x06e8),  -- Arabic Small High Yeh   ..Arabic Small High Noon
+    (0x06ea, 0x06ed),  -- Arabic Empty Centre Low ..Arabic Small Low Meem
+    (0x0711, 0x0711),  -- Syriac Letter Superscrip..Syriac Letter Superscrip
+    (0x0730, 0x074a),  -- Syriac Pthaha Above     ..Syriac Barrekh
+    (0x07a6, 0x07b0),  -- Thaana Abafili          ..Thaana Sukun
+    (0x07eb, 0x07f3),  -- Nko Combining Short High..Nko Combining Double Dot
+    (0x0816, 0x0819),  -- Samaritan Mark In       ..Samaritan Mark Dagesh
+    (0x081b, 0x0823),  -- Samaritan Mark Epentheti..Samaritan Vowel Sign A
+    (0x0825, 0x0827),  -- Samaritan Vowel Sign Sho..Samaritan Vowel Sign U
+    (0x0829, 0x082d),  -- Samaritan Vowel Sign Lon..Samaritan Mark Nequdaa
+    (0x0859, 0x085b),  -- Mandaic Affrication Mark..Mandaic Gemination Mark
+    (0x08d4, 0x08e1),  -- (nil)                   ..
+    (0x08e3, 0x0902),  -- Arabic Turned Damma Belo..Devanagari Sign Anusvara
+    (0x093a, 0x093a),  -- Devanagari Vowel Sign Oe..Devanagari Vowel Sign Oe
+    (0x093c, 0x093c),  -- Devanagari Sign Nukta   ..Devanagari Sign Nukta
+    (0x0941, 0x0948),  -- Devanagari Vowel Sign U ..Devanagari Vowel Sign Ai
+    (0x094d, 0x094d),  -- Devanagari Sign Virama  ..Devanagari Sign Virama
+    (0x0951, 0x0957),  -- Devanagari Stress Sign U..Devanagari Vowel Sign Uu
+    (0x0962, 0x0963),  -- Devanagari Vowel Sign Vo..Devanagari Vowel Sign Vo
+    (0x0981, 0x0981),  -- Bengali Sign Candrabindu..Bengali Sign Candrabindu
+    (0x09bc, 0x09bc),  -- Bengali Sign Nukta      ..Bengali Sign Nukta
+    (0x09c1, 0x09c4),  -- Bengali Vowel Sign U    ..Bengali Vowel Sign Vocal
+    (0x09cd, 0x09cd),  -- Bengali Sign Virama     ..Bengali Sign Virama
+    (0x09e2, 0x09e3),  -- Bengali Vowel Sign Vocal..Bengali Vowel Sign Vocal
+    (0x0a01, 0x0a02),  -- Gurmukhi Sign Adak Bindi..Gurmukhi Sign Bindi
+    (0x0a3c, 0x0a3c),  -- Gurmukhi Sign Nukta     ..Gurmukhi Sign Nukta
+    (0x0a41, 0x0a42),  -- Gurmukhi Vowel Sign U   ..Gurmukhi Vowel Sign Uu
+    (0x0a47, 0x0a48),  -- Gurmukhi Vowel Sign Ee  ..Gurmukhi Vowel Sign Ai
+    (0x0a4b, 0x0a4d),  -- Gurmukhi Vowel Sign Oo  ..Gurmukhi Sign Virama
+    (0x0a51, 0x0a51),  -- Gurmukhi Sign Udaat     ..Gurmukhi Sign Udaat
+    (0x0a70, 0x0a71),  -- Gurmukhi Tippi          ..Gurmukhi Addak
+    (0x0a75, 0x0a75),  -- Gurmukhi Sign Yakash    ..Gurmukhi Sign Yakash
+    (0x0a81, 0x0a82),  -- Gujarati Sign Candrabind..Gujarati Sign Anusvara
+    (0x0abc, 0x0abc),  -- Gujarati Sign Nukta     ..Gujarati Sign Nukta
+    (0x0ac1, 0x0ac5),  -- Gujarati Vowel Sign U   ..Gujarati Vowel Sign Cand
+    (0x0ac7, 0x0ac8),  -- Gujarati Vowel Sign E   ..Gujarati Vowel Sign Ai
+    (0x0acd, 0x0acd),  -- Gujarati Sign Virama    ..Gujarati Sign Virama
+    (0x0ae2, 0x0ae3),  -- Gujarati Vowel Sign Voca..Gujarati Vowel Sign Voca
+    (0x0b01, 0x0b01),  -- Oriya Sign Candrabindu  ..Oriya Sign Candrabindu
+    (0x0b3c, 0x0b3c),  -- Oriya Sign Nukta        ..Oriya Sign Nukta
+    (0x0b3f, 0x0b3f),  -- Oriya Vowel Sign I      ..Oriya Vowel Sign I
+    (0x0b41, 0x0b44),  -- Oriya Vowel Sign U      ..Oriya Vowel Sign Vocalic
+    (0x0b4d, 0x0b4d),  -- Oriya Sign Virama       ..Oriya Sign Virama
+    (0x0b56, 0x0b56),  -- Oriya Ai Length Mark    ..Oriya Ai Length Mark
+    (0x0b62, 0x0b63),  -- Oriya Vowel Sign Vocalic..Oriya Vowel Sign Vocalic
+    (0x0b82, 0x0b82),  -- Tamil Sign Anusvara     ..Tamil Sign Anusvara
+    (0x0bc0, 0x0bc0),  -- Tamil Vowel Sign Ii     ..Tamil Vowel Sign Ii
+    (0x0bcd, 0x0bcd),  -- Tamil Sign Virama       ..Tamil Sign Virama
+    (0x0c00, 0x0c00),  -- Telugu Sign Combining Ca..Telugu Sign Combining Ca
+    (0x0c3e, 0x0c40),  -- Telugu Vowel Sign Aa    ..Telugu Vowel Sign Ii
+    (0x0c46, 0x0c48),  -- Telugu Vowel Sign E     ..Telugu Vowel Sign Ai
+    (0x0c4a, 0x0c4d),  -- Telugu Vowel Sign O     ..Telugu Sign Virama
+    (0x0c55, 0x0c56),  -- Telugu Length Mark      ..Telugu Ai Length Mark
+    (0x0c62, 0x0c63),  -- Telugu Vowel Sign Vocali..Telugu Vowel Sign Vocali
+    (0x0c81, 0x0c81),  -- Kannada Sign Candrabindu..Kannada Sign Candrabindu
+    (0x0cbc, 0x0cbc),  -- Kannada Sign Nukta      ..Kannada Sign Nukta
+    (0x0cbf, 0x0cbf),  -- Kannada Vowel Sign I    ..Kannada Vowel Sign I
+    (0x0cc6, 0x0cc6),  -- Kannada Vowel Sign E    ..Kannada Vowel Sign E
+    (0x0ccc, 0x0ccd),  -- Kannada Vowel Sign Au   ..Kannada Sign Virama
+    (0x0ce2, 0x0ce3),  -- Kannada Vowel Sign Vocal..Kannada Vowel Sign Vocal
+    (0x0d01, 0x0d01),  -- Malayalam Sign Candrabin..Malayalam Sign Candrabin
+    (0x0d41, 0x0d44),  -- Malayalam Vowel Sign U  ..Malayalam Vowel Sign Voc
+    (0x0d4d, 0x0d4d),  -- Malayalam Sign Virama   ..Malayalam Sign Virama
+    (0x0d62, 0x0d63),  -- Malayalam Vowel Sign Voc..Malayalam Vowel Sign Voc
+    (0x0dca, 0x0dca),  -- Sinhala Sign Al-lakuna  ..Sinhala Sign Al-lakuna
+    (0x0dd2, 0x0dd4),  -- Sinhala Vowel Sign Ketti..Sinhala Vowel Sign Ketti
+    (0x0dd6, 0x0dd6),  -- Sinhala Vowel Sign Diga ..Sinhala Vowel Sign Diga
+    (0x0e31, 0x0e31),  -- Thai Character Mai Han-a..Thai Character Mai Han-a
+    (0x0e34, 0x0e3a),  -- Thai Character Sara I   ..Thai Character Phinthu
+    (0x0e47, 0x0e4e),  -- Thai Character Maitaikhu..Thai Character Yamakkan
+    (0x0eb1, 0x0eb1),  -- Lao Vowel Sign Mai Kan  ..Lao Vowel Sign Mai Kan
+    (0x0eb4, 0x0eb9),  -- Lao Vowel Sign I        ..Lao Vowel Sign Uu
+    (0x0ebb, 0x0ebc),  -- Lao Vowel Sign Mai Kon  ..Lao Semivowel Sign Lo
+    (0x0ec8, 0x0ecd),  -- Lao Tone Mai Ek         ..Lao Niggahita
+    (0x0f18, 0x0f19),  -- Tibetan Astrological Sig..Tibetan Astrological Sig
+    (0x0f35, 0x0f35),  -- Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
+    (0x0f37, 0x0f37),  -- Tibetan Mark Ngas Bzung ..Tibetan Mark Ngas Bzung
+    (0x0f39, 0x0f39),  -- Tibetan Mark Tsa -phru  ..Tibetan Mark Tsa -phru
+    (0x0f71, 0x0f7e),  -- Tibetan Vowel Sign Aa   ..Tibetan Sign Rjes Su Nga
+    (0x0f80, 0x0f84),  -- Tibetan Vowel Sign Rever..Tibetan Mark Halanta
+    (0x0f86, 0x0f87),  -- Tibetan Sign Lci Rtags  ..Tibetan Sign Yang Rtags
+    (0x0f8d, 0x0f97),  -- Tibetan Subjoined Sign L..Tibetan Subjoined Letter
+    (0x0f99, 0x0fbc),  -- Tibetan Subjoined Letter..Tibetan Subjoined Letter
+    (0x0fc6, 0x0fc6),  -- Tibetan Symbol Padma Gda..Tibetan Symbol Padma Gda
+    (0x102d, 0x1030),  -- Myanmar Vowel Sign I    ..Myanmar Vowel Sign Uu
+    (0x1032, 0x1037),  -- Myanmar Vowel Sign Ai   ..Myanmar Sign Dot Below
+    (0x1039, 0x103a),  -- Myanmar Sign Virama     ..Myanmar Sign Asat
+    (0x103d, 0x103e),  -- Myanmar Consonant Sign M..Myanmar Consonant Sign M
+    (0x1058, 0x1059),  -- Myanmar Vowel Sign Vocal..Myanmar Vowel Sign Vocal
+    (0x105e, 0x1060),  -- Myanmar Consonant Sign M..Myanmar Consonant Sign M
+    (0x1071, 0x1074),  -- Myanmar Vowel Sign Geba ..Myanmar Vowel Sign Kayah
+    (0x1082, 0x1082),  -- Myanmar Consonant Sign S..Myanmar Consonant Sign S
+    (0x1085, 0x1086),  -- Myanmar Vowel Sign Shan ..Myanmar Vowel Sign Shan
+    (0x108d, 0x108d),  -- Myanmar Sign Shan Counci..Myanmar Sign Shan Counci
+    (0x109d, 0x109d),  -- Myanmar Vowel Sign Aiton..Myanmar Vowel Sign Aiton
+    (0x135d, 0x135f),  -- Ethiopic Combining Gemin..Ethiopic Combining Gemin
+    (0x1712, 0x1714),  -- Tagalog Vowel Sign I    ..Tagalog Sign Virama
+    (0x1732, 0x1734),  -- Hanunoo Vowel Sign I    ..Hanunoo Sign Pamudpod
+    (0x1752, 0x1753),  -- Buhid Vowel Sign I      ..Buhid Vowel Sign U
+    (0x1772, 0x1773),  -- Tagbanwa Vowel Sign I   ..Tagbanwa Vowel Sign U
+    (0x17b4, 0x17b5),  -- Khmer Vowel Inherent Aq ..Khmer Vowel Inherent Aa
+    (0x17b7, 0x17bd),  -- Khmer Vowel Sign I      ..Khmer Vowel Sign Ua
+    (0x17c6, 0x17c6),  -- Khmer Sign Nikahit      ..Khmer Sign Nikahit
+    (0x17c9, 0x17d3),  -- Khmer Sign Muusikatoan  ..Khmer Sign Bathamasat
+    (0x17dd, 0x17dd),  -- Khmer Sign Atthacan     ..Khmer Sign Atthacan
+    (0x180b, 0x180d),  -- Mongolian Free Variation..Mongolian Free Variation
+    (0x1885, 0x1886),  -- Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
+    (0x18a9, 0x18a9),  -- Mongolian Letter Ali Gal..Mongolian Letter Ali Gal
+    (0x1920, 0x1922),  -- Limbu Vowel Sign A      ..Limbu Vowel Sign U
+    (0x1927, 0x1928),  -- Limbu Vowel Sign E      ..Limbu Vowel Sign O
+    (0x1932, 0x1932),  -- Limbu Small Letter Anusv..Limbu Small Letter Anusv
+    (0x1939, 0x193b),  -- Limbu Sign Mukphreng    ..Limbu Sign Sa-i
+    (0x1a17, 0x1a18),  -- Buginese Vowel Sign I   ..Buginese Vowel Sign U
+    (0x1a1b, 0x1a1b),  -- Buginese Vowel Sign Ae  ..Buginese Vowel Sign Ae
+    (0x1a56, 0x1a56),  -- Tai Tham Consonant Sign ..Tai Tham Consonant Sign
+    (0x1a58, 0x1a5e),  -- Tai Tham Sign Mai Kang L..Tai Tham Consonant Sign
+    (0x1a60, 0x1a60),  -- Tai Tham Sign Sakot     ..Tai Tham Sign Sakot
+    (0x1a62, 0x1a62),  -- Tai Tham Vowel Sign Mai ..Tai Tham Vowel Sign Mai
+    (0x1a65, 0x1a6c),  -- Tai Tham Vowel Sign I   ..Tai Tham Vowel Sign Oa B
+    (0x1a73, 0x1a7c),  -- Tai Tham Vowel Sign Oa A..Tai Tham Sign Khuen-lue
+    (0x1a7f, 0x1a7f),  -- Tai Tham Combining Crypt..Tai Tham Combining Crypt
+    (0x1ab0, 0x1abe),  -- Combining Doubled Circum..Combining Parentheses Ov
+    (0x1b00, 0x1b03),  -- Balinese Sign Ulu Ricem ..Balinese Sign Surang
+    (0x1b34, 0x1b34),  -- Balinese Sign Rerekan   ..Balinese Sign Rerekan
+    (0x1b36, 0x1b3a),  -- Balinese Vowel Sign Ulu ..Balinese Vowel Sign Ra R
+    (0x1b3c, 0x1b3c),  -- Balinese Vowel Sign La L..Balinese Vowel Sign La L
+    (0x1b42, 0x1b42),  -- Balinese Vowel Sign Pepe..Balinese Vowel Sign Pepe
+    (0x1b6b, 0x1b73),  -- Balinese Musical Symbol ..Balinese Musical Symbol
+    (0x1b80, 0x1b81),  -- Sundanese Sign Panyecek ..Sundanese Sign Panglayar
+    (0x1ba2, 0x1ba5),  -- Sundanese Consonant Sign..Sundanese Vowel Sign Pan
+    (0x1ba8, 0x1ba9),  -- Sundanese Vowel Sign Pam..Sundanese Vowel Sign Pan
+    (0x1bab, 0x1bad),  -- Sundanese Sign Virama   ..Sundanese Consonant Sign
+    (0x1be6, 0x1be6),  -- Batak Sign Tompi        ..Batak Sign Tompi
+    (0x1be8, 0x1be9),  -- Batak Vowel Sign Pakpak ..Batak Vowel Sign Ee
+    (0x1bed, 0x1bed),  -- Batak Vowel Sign Karo O ..Batak Vowel Sign Karo O
+    (0x1bef, 0x1bf1),  -- Batak Vowel Sign U For S..Batak Consonant Sign H
+    (0x1c2c, 0x1c33),  -- Lepcha Vowel Sign E     ..Lepcha Consonant Sign T
+    (0x1c36, 0x1c37),  -- Lepcha Sign Ran         ..Lepcha Sign Nukta
+    (0x1cd0, 0x1cd2),  -- Vedic Tone Karshana     ..Vedic Tone Prenkha
+    (0x1cd4, 0x1ce0),  -- Vedic Sign Yajurvedic Mi..Vedic Tone Rigvedic Kash
+    (0x1ce2, 0x1ce8),  -- Vedic Sign Visarga Svari..Vedic Sign Visarga Anuda
+    (0x1ced, 0x1ced),  -- Vedic Sign Tiryak       ..Vedic Sign Tiryak
+    (0x1cf4, 0x1cf4),  -- Vedic Tone Candra Above ..Vedic Tone Candra Above
+    (0x1cf8, 0x1cf9),  -- Vedic Tone Ring Above   ..Vedic Tone Double Ring A
+    (0x1dc0, 0x1df5),  -- Combining Dotted Grave A..Combining Up Tack Above
+    (0x1dfb, 0x1dff),  -- (nil)                   ..Combining Right Arrowhea
+    (0x20d0, 0x20f0),  -- Combining Left Harpoon A..Combining Asterisk Above
+    (0x2cef, 0x2cf1),  -- Coptic Combining Ni Abov..Coptic Combining Spiritu
+    (0x2d7f, 0x2d7f),  -- Tifinagh Consonant Joine..Tifinagh Consonant Joine
+    (0x2de0, 0x2dff),  -- Combining Cyrillic Lette..Combining Cyrillic Lette
+    (0x302a, 0x302d),  -- Ideographic Level Tone M..Ideographic Entering Ton
+    (0x3099, 0x309a),  -- Combining Katakana-hirag..Combining Katakana-hirag
+    (0xa66f, 0xa672),  -- Combining Cyrillic Vzmet..Combining Cyrillic Thous
+    (0xa674, 0xa67d),  -- Combining Cyrillic Lette..Combining Cyrillic Payer
+    (0xa69e, 0xa69f),  -- Combining Cyrillic Lette..Combining Cyrillic Lette
+    (0xa6f0, 0xa6f1),  -- Bamum Combining Mark Koq..Bamum Combining Mark Tuk
+    (0xa802, 0xa802),  -- Syloti Nagri Sign Dvisva..Syloti Nagri Sign Dvisva
+    (0xa806, 0xa806),  -- Syloti Nagri Sign Hasant..Syloti Nagri Sign Hasant
+    (0xa80b, 0xa80b),  -- Syloti Nagri Sign Anusva..Syloti Nagri Sign Anusva
+    (0xa825, 0xa826),  -- Syloti Nagri Vowel Sign ..Syloti Nagri Vowel Sign
+    (0xa8c4, 0xa8c5),  -- Saurashtra Sign Virama  ..
+    (0xa8e0, 0xa8f1),  -- Combining Devanagari Dig..Combining Devanagari Sig
+    (0xa926, 0xa92d),  -- Kayah Li Vowel Ue       ..Kayah Li Tone Calya Plop
+    (0xa947, 0xa951),  -- Rejang Vowel Sign I     ..Rejang Consonant Sign R
+    (0xa980, 0xa982),  -- Javanese Sign Panyangga ..Javanese Sign Layar
+    (0xa9b3, 0xa9b3),  -- Javanese Sign Cecak Telu..Javanese Sign Cecak Telu
+    (0xa9b6, 0xa9b9),  -- Javanese Vowel Sign Wulu..Javanese Vowel Sign Suku
+    (0xa9bc, 0xa9bc),  -- Javanese Vowel Sign Pepe..Javanese Vowel Sign Pepe
+    (0xa9e5, 0xa9e5),  -- Myanmar Sign Shan Saw   ..Myanmar Sign Shan Saw
+    (0xaa29, 0xaa2e),  -- Cham Vowel Sign Aa      ..Cham Vowel Sign Oe
+    (0xaa31, 0xaa32),  -- Cham Vowel Sign Au      ..Cham Vowel Sign Ue
+    (0xaa35, 0xaa36),  -- Cham Consonant Sign La  ..Cham Consonant Sign Wa
+    (0xaa43, 0xaa43),  -- Cham Consonant Sign Fina..Cham Consonant Sign Fina
+    (0xaa4c, 0xaa4c),  -- Cham Consonant Sign Fina..Cham Consonant Sign Fina
+    (0xaa7c, 0xaa7c),  -- Myanmar Sign Tai Laing T..Myanmar Sign Tai Laing T
+    (0xaab0, 0xaab0),  -- Tai Viet Mai Kang       ..Tai Viet Mai Kang
+    (0xaab2, 0xaab4),  -- Tai Viet Vowel I        ..Tai Viet Vowel U
+    (0xaab7, 0xaab8),  -- Tai Viet Mai Khit       ..Tai Viet Vowel Ia
+    (0xaabe, 0xaabf),  -- Tai Viet Vowel Am       ..Tai Viet Tone Mai Ek
+    (0xaac1, 0xaac1),  -- Tai Viet Tone Mai Tho   ..Tai Viet Tone Mai Tho
+    (0xaaec, 0xaaed),  -- Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
+    (0xaaf6, 0xaaf6),  -- Meetei Mayek Virama     ..Meetei Mayek Virama
+    (0xabe5, 0xabe5),  -- Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
+    (0xabe8, 0xabe8),  -- Meetei Mayek Vowel Sign ..Meetei Mayek Vowel Sign
+    (0xabed, 0xabed),  -- Meetei Mayek Apun Iyek  ..Meetei Mayek Apun Iyek
+    (0xfb1e, 0xfb1e),  -- Hebrew Point Judeo-spani..Hebrew Point Judeo-spani
+    (0xfe00, 0xfe0f),  -- Variation Selector-1    ..Variation Selector-16
+    (0xfe20, 0xfe2f),  -- Combining Ligature Left ..Combining Cyrillic Titlo
+    (0x101fd, 0x101fd),  -- Phaistos Disc Sign Combi..Phaistos Disc Sign Combi
+    (0x102e0, 0x102e0),  -- Coptic Epact Thousands M..Coptic Epact Thousands M
+    (0x10376, 0x1037a),  -- Combining Old Permic Let..Combining Old Permic Let
+    (0x10a01, 0x10a03),  -- Kharoshthi Vowel Sign I ..Kharoshthi Vowel Sign Vo
+    (0x10a05, 0x10a06),  -- Kharoshthi Vowel Sign E ..Kharoshthi Vowel Sign O
+    (0x10a0c, 0x10a0f),  -- Kharoshthi Vowel Length ..Kharoshthi Sign Visarga
+    (0x10a38, 0x10a3a),  -- Kharoshthi Sign Bar Abov..Kharoshthi Sign Dot Belo
+    (0x10a3f, 0x10a3f),  -- Kharoshthi Virama       ..Kharoshthi Virama
+    (0x10ae5, 0x10ae6),  -- Manichaean Abbreviation ..Manichaean Abbreviation
+    (0x11001, 0x11001),  -- Brahmi Sign Anusvara    ..Brahmi Sign Anusvara
+    (0x11038, 0x11046),  -- Brahmi Vowel Sign Aa    ..Brahmi Virama
+    (0x1107f, 0x11081),  -- Brahmi Number Joiner    ..Kaithi Sign Anusvara
+    (0x110b3, 0x110b6),  -- Kaithi Vowel Sign U     ..Kaithi Vowel Sign Ai
+    (0x110b9, 0x110ba),  -- Kaithi Sign Virama      ..Kaithi Sign Nukta
+    (0x11100, 0x11102),  -- Chakma Sign Candrabindu ..Chakma Sign Visarga
+    (0x11127, 0x1112b),  -- Chakma Vowel Sign A     ..Chakma Vowel Sign Uu
+    (0x1112d, 0x11134),  -- Chakma Vowel Sign Ai    ..Chakma Maayyaa
+    (0x11173, 0x11173),  -- Mahajani Sign Nukta     ..Mahajani Sign Nukta
+    (0x11180, 0x11181),  -- Sharada Sign Candrabindu..Sharada Sign Anusvara
+    (0x111b6, 0x111be),  -- Sharada Vowel Sign U    ..Sharada Vowel Sign O
+    (0x111ca, 0x111cc),  -- Sharada Sign Nukta      ..Sharada Extra Short Vowe
+    (0x1122f, 0x11231),  -- Khojki Vowel Sign U     ..Khojki Vowel Sign Ai
+    (0x11234, 0x11234),  -- Khojki Sign Anusvara    ..Khojki Sign Anusvara
+    (0x11236, 0x11237),  -- Khojki Sign Nukta       ..Khojki Sign Shadda
+    (0x1123e, 0x1123e),  -- (nil)                   ..
+    (0x112df, 0x112df),  -- Khudawadi Sign Anusvara ..Khudawadi Sign Anusvara
+    (0x112e3, 0x112ea),  -- Khudawadi Vowel Sign U  ..Khudawadi Sign Virama
+    (0x11300, 0x11301),  -- Grantha Sign Combining A..Grantha Sign Candrabindu
+    (0x1133c, 0x1133c),  -- Grantha Sign Nukta      ..Grantha Sign Nukta
+    (0x11340, 0x11340),  -- Grantha Vowel Sign Ii   ..Grantha Vowel Sign Ii
+    (0x11366, 0x1136c),  -- Combining Grantha Digit ..Combining Grantha Digit
+    (0x11370, 0x11374),  -- Combining Grantha Letter..Combining Grantha Letter
+    (0x11438, 0x1143f),  -- (nil)                   ..
+    (0x11442, 0x11444),  -- (nil)                   ..
+    (0x11446, 0x11446),  -- (nil)                   ..
+    (0x114b3, 0x114b8),  -- Tirhuta Vowel Sign U    ..Tirhuta Vowel Sign Vocal
+    (0x114ba, 0x114ba),  -- Tirhuta Vowel Sign Short..Tirhuta Vowel Sign Short
+    (0x114bf, 0x114c0),  -- Tirhuta Sign Candrabindu..Tirhuta Sign Anusvara
+    (0x114c2, 0x114c3),  -- Tirhuta Sign Virama     ..Tirhuta Sign Nukta
+    (0x115b2, 0x115b5),  -- Siddham Vowel Sign U    ..Siddham Vowel Sign Vocal
+    (0x115bc, 0x115bd),  -- Siddham Sign Candrabindu..Siddham Sign Anusvara
+    (0x115bf, 0x115c0),  -- Siddham Sign Virama     ..Siddham Sign Nukta
+    (0x115dc, 0x115dd),  -- Siddham Vowel Sign Alter..Siddham Vowel Sign Alter
+    (0x11633, 0x1163a),  -- Modi Vowel Sign U       ..Modi Vowel Sign Ai
+    (0x1163d, 0x1163d),  -- Modi Sign Anusvara      ..Modi Sign Anusvara
+    (0x1163f, 0x11640),  -- Modi Sign Virama        ..Modi Sign Ardhacandra
+    (0x116ab, 0x116ab),  -- Takri Sign Anusvara     ..Takri Sign Anusvara
+    (0x116ad, 0x116ad),  -- Takri Vowel Sign Aa     ..Takri Vowel Sign Aa
+    (0x116b0, 0x116b5),  -- Takri Vowel Sign U      ..Takri Vowel Sign Au
+    (0x116b7, 0x116b7),  -- Takri Sign Nukta        ..Takri Sign Nukta
+    (0x1171d, 0x1171f),  -- Ahom Consonant Sign Medi..Ahom Consonant Sign Medi
+    (0x11722, 0x11725),  -- Ahom Vowel Sign I       ..Ahom Vowel Sign Uu
+    (0x11727, 0x1172b),  -- Ahom Vowel Sign Aw      ..Ahom Sign Killer
+    (0x11c30, 0x11c36),  -- (nil)                   ..
+    (0x11c38, 0x11c3d),  -- (nil)                   ..
+    (0x11c3f, 0x11c3f),  -- (nil)                   ..
+    (0x11c92, 0x11ca7),  -- (nil)                   ..
+    (0x11caa, 0x11cb0),  -- (nil)                   ..
+    (0x11cb2, 0x11cb3),  -- (nil)                   ..
+    (0x11cb5, 0x11cb6),  -- (nil)                   ..
+    (0x16af0, 0x16af4),  -- Bassa Vah Combining High..Bassa Vah Combining High
+    (0x16b30, 0x16b36),  -- Pahawh Hmong Mark Cim Tu..Pahawh Hmong Mark Cim Ta
+    (0x16f8f, 0x16f92),  -- Miao Tone Right         ..Miao Tone Below
+    (0x1bc9d, 0x1bc9e),  -- Duployan Thick Letter Se..Duployan Double Mark
+    (0x1d167, 0x1d169),  -- Musical Symbol Combining..Musical Symbol Combining
+    (0x1d17b, 0x1d182),  -- Musical Symbol Combining..Musical Symbol Combining
+    (0x1d185, 0x1d18b),  -- Musical Symbol Combining..Musical Symbol Combining
+    (0x1d1aa, 0x1d1ad),  -- Musical Symbol Combining..Musical Symbol Combining
+    (0x1d242, 0x1d244),  -- Combining Greek Musical ..Combining Greek Musical
+    (0x1da00, 0x1da36),  -- Signwriting Head Rim    ..Signwriting Air Sucking
+    (0x1da3b, 0x1da6c),  -- Signwriting Mouth Closed..Signwriting Excitement
+    (0x1da75, 0x1da75),  -- Signwriting Upper Body T..Signwriting Upper Body T
+    (0x1da84, 0x1da84),  -- Signwriting Location Hea..Signwriting Location Hea
+    (0x1da9b, 0x1da9f),  -- Signwriting Fill Modifie..Signwriting Fill Modifie
+    (0x1daa1, 0x1daaf),  -- Signwriting Rotation Mod..Signwriting Rotation Mod
+    (0x1e000, 0x1e006),  -- (nil)                   ..
+    (0x1e008, 0x1e018),  -- (nil)                   ..
+    (0x1e01b, 0x1e021),  -- (nil)                   ..
+    (0x1e023, 0x1e024),  -- (nil)                   ..
+    (0x1e026, 0x1e02a),  -- (nil)                   ..
+    (0x1e8d0, 0x1e8d6),  -- Mende Kikakui Combining ..Mende Kikakui Combining
+    (0x1e944, 0x1e94a),  -- (nil)                   ..
+    (0xe0100, 0xe01ef)  -- Variation Selector-17   ..Variation Selector-256
+    ]
+
+
+basicZero :: RangeSet Int
+basicZero = foldr insertRange empty [
+  (0, 0),
+  (0x034f, 0x034f),
+  (0x200b, 0x200f),
+  (0x2028, 0x2029),
+  (0x202a, 0x202e),
+  (0x2060, 0x2063)
+  ]
+
+ctrlChars :: RangeSet Int
+ctrlChars = foldr insertRange empty [
+  (1, 31),
+  (0x07f, 0x09F)
+  ]
+
+wcwidth :: Char -> Int
+wcwidth c | queryPoint v basicZero = 0
+          | queryPoint v ctrlChars = -1
+          | queryPoint v wIDEEASTASIAN = 2
+          | queryPoint v zEROWIDTH = 0
+          | otherwise = 1
+  where v = ord c
diff --git a/htalkat.1 b/htalkat.1
new file mode 100644
--- /dev/null
+++ b/htalkat.1
@@ -0,0 +1,126 @@
+.\" Automatically generated by Pandoc 2.14.2
+.\"
+.TH "HTALKAT" "1" "" "Version 0.1.1" "htalkat"
+.hy
+.SH NAME
+.PP
+htalkat - talkat client and server
+.SH SYNOPSIS
+.PP
+talkat [OPTION]\&... COMMAND [ARG]\&...
+.SH DESCRIPTION
+.PP
+htalkat is a client and server for the talkat real-time text protocol,
+with a curses interactive client.
+Similar to talk(1) but running over a TLS connection.
+.SH COMMANDS
+.TP
+h[elp] [COMMAND]
+Give detailed usage information.
+.TP
+i[dentity] [PUBLIC_NAME]
+Create/show/modify cryptographic identity (public and secret keys, and
+certificates), setting public name to PUBLIC_NAME if given.
+.TP
+c[onnect] ( [talkat:]FP\[at]HOST | NAME[\[at]HOST] )
+Connect to remote host, checking the public key agrees with the
+fingerprint provided.
+Waits for the connection to be \[lq]answered\[rq], then starts
+the interactive curses client (or a user-configured client)
+.TP
+n[ame] ( [talkat:]FP\[at]HOST | NAME[\[at]HOST] ) NAME
+Set short name (\[lq]petname\[rq]) for fingerprint and optional host.
+This can be
+used with the c[onnect] command, and will be used when referring to the
+fingerprint.
+If the name to set is omitted, it will be prompted for.
+.TP
+l[isten]
+Start server process.
+This will listen for connections on the configured
+port (default: 5518), and notify by writing information to stdout and
+executing the \[ti]/.htalkat/notify.sh script.
+If the public key provided on an
+incoming connection does not have a name associated, it will be assigned
+an
+automatic name +N where N is the next available positive integer.
+.TP
+a[nswer] [--list|-l] NAME
+Answer incoming connection, starting the interactive curses client (or
+a user-configured client), or list pending unanswered connections.
+.TP
+a[nswer] [--interactive-client|-i] NAME SOCKET_PATH
+Directly spawn default (curses) client.
+NAME is the name of remote to
+display.
+SOCKET_PATH is the path to a unix domain socket to interact with;
+characters read from this socket are displayed as coming from remote,
+and user input is written to the socket.
+.SH OPTIONS
+.TP
+-d, --datadir \f[I]PATH\f[R]
+Directory for data and configuration.
+Default: \[ti]/.htalkat
+.TP
+-S, --socks-host \f[I]HOST\f[R]
+Use SOCKS5 proxy for all connections (including DNS resolution).
+.TP
+-P, --socks-port \f[I]PORT\f[R]
+Port to use for SOCKS5 proxy.
+Default: 1080.
+.TP
+-v, --version
+Show version information.
+.TP
+-h, --help
+Show usage information.
+.SH FILES
+.TP
+\[ti]/.htalkat
+Default \f[I]datadir\f[R].
+The paths given below assume that this is used.
+.TP
+\[ti]/.htalkat/id.key
+Secret key used in certificates.
+The user hash is derived from the
+corresponding public key.
+.TP
+\[ti]/.htalkat/id-connect.crt
+X509 certificate used for outgoing connections.
+.TP
+\[ti]/.htalkat/id-listen.crt
+X509 certificate used for incoming connections.
+Unlike id-connect.crt, this will typically have empty Common Name field,
+for privacy reasons.
+.TP
+\[ti]/.htalkat/htalkat.conf
+Configuration file.
+.TP
+\[ti]/.htalkat/notify.sh
+Executable script which is run when the server accepts an incoming
+connection.
+.TP
+\[ti]/.htalkat/names/
+Short names (\[lq]petnames\[rq]) for user hashes, optionally with hosts,
+are stored
+here.
+These files may be manipulated directly.
+.TP
+\[ti]/.htalkat/incoming/
+Information on unanswered incoming connections is stored here.
+.TP
+\[ti]/.htalkat/logs/
+Communication logs are optionally written here, one file per connection.
+.SH ENVIRONMENT
+.TP
+HTALKAT_DIR
+Path to directory to use in place of \[ti]/.htalkat/ (can be overridden
+by -d).
+.SH LICENCE
+.PP
+htalkat is free software, released under the terms of the GNU GPL v3 or
+later.
+You should have obtained a copy of the licence as the file COPYING.
+.SH AUTHORS
+.PP
+Martin Bays <mbays@sdf.org>
diff --git a/htalkat.cabal b/htalkat.cabal
new file mode 100644
--- /dev/null
+++ b/htalkat.cabal
@@ -0,0 +1,95 @@
+cabal-version:      >=1.18
+name:               htalkat
+version:            0.1.1
+license:            GPL-3
+license-file:       COPYING
+maintainer:         mbays@sdf.org
+author:             Martin Bays
+homepage:           https://mbays.sdf.org/htalkat
+synopsis:           Talk across TLS
+description:
+    Server and curses client for the "talkat" (Talk Across TLS) real-time text communication protocol.
+
+category:           Network
+build-type:         Simple
+extra-doc-files:
+    CHANGELOG.md
+    README.md
+    htalkat.1
+    spec.html
+
+source-repository head
+    type:     git
+    location: https://repo.or.cz/htalkat.git
+
+flag curses
+    description: Enable Curses UI
+
+executable htalkat
+    main-is:          Talkat.hs
+    other-modules:
+        Certificate
+        Config
+        DumbClient
+        Fingerprint
+        HexString
+        Host
+        Identity
+        Incoming
+        Mundanities
+        LookupPetname
+        Notify
+        Opts
+        Petname
+        Prompt
+        RelayStream
+        TimedText
+        TLSTalk
+        User
+        Util
+        Version
+        WCWidth
+
+    default-language: Haskell2010
+    ghc-options:      -threaded -Wall
+    build-depends:
+        base >=4.6 && <5,
+        array >=0.3 && <0.6,
+        asn1-encoding <0.10,
+        asn1-types >=0.3.4 && <0.4,
+        bytestring >=0.10.4.0 && <0.12,
+        containers >=0.5.5.1 && <0.7,
+        cryptonite >=0.26 && <0.30,
+        data-default-class >=0.1.2.0 && <0.2,
+        data-hash >=0.2.0.1 && <0.3,
+        directory >=1.2.1.0 && <1.4,
+        exceptions >=0.10.4 && <0.11,
+        filelock <0.2,
+        filepath >=1.3.0.2 && <1.5,
+        hourglass >=0.2.12 && <0.3,
+        memory >=0.14 && <0.17,
+        mtl >=2.0 && <2.3,
+        network >=2.4.2.3 && <3.2,
+        network-simple >=0.4.3 && <0.5,
+        pem >=0.2.4 && <0.3,
+        process >=1.2.0.0 && <1.7,
+        rset <1.1,
+        safe >=0.3.19 && <0.4,
+        temporary >= 1.2 && <1.4,
+        text >=1.1.0.0 && <1.3,
+        time <1.13,
+        tls >=1.5.4 && <1.6,
+        transformers >=0.3.0.0 && <0.6,
+        x509 >=1.7.5 && <1.8,
+        x509-validation >=1.6.11 && <1.7
+
+    if os(windows)
+        cpp-options: -DWINDOWS
+    else
+        build-depends: unix >=2.7.0.1 && <2.8
+
+    if flag(curses)
+        cpp-options: -DCURSES
+        other-modules: CursesClient
+        build-depends: hscurses <1.5
+        pkgconfig-depends: ncursesw -any
diff --git a/spec.html b/spec.html
new file mode 100644
--- /dev/null
+++ b/spec.html
@@ -0,0 +1,74 @@
+<!DOCTYPE html>
+<html>
+<head><title>talkat speculative specification</title></head>
+<body>
+<h1>talkat speculative specification</h1>
+<h1>Introduction</h1>
+<p>talkat (&quot;talk across TLS&quot;) is a minimalist protocol for real-time textual bilateral communication, similar to talk(1). It updates talk(1) by using encrypted authenticated connections with traffic-analysis countermeasures, and by being unicode-aware.</p>
+
+<h1>Protocol</h1>
+<p>A talkat server listens on a tcp port, 5518 by default, and accepts TLS 1.3 or later connections. The connecting client provides a client certificate, and uses Server Name Indication (SNI).</p>
+
+<p>The application data in each direction consists entirely of a single stream of UTF-8 characters, interpreted as a handshake character followed by a timed character stream as described below.</p>
+
+<p>If no client certificate is presented, the server MUST reject the connection.</p>
+
+<p>Either party may close the TLS connection at any time.</p>
+
+<p>TLS 1.2 (and earlier) connections MUST be rejected. TLS 1.2 is inappropriate, as it sends client certificates unencrypted.</p>
+
+<h1>Authentication</h1>
+<p>The server and client certificates are intended to identify the individual users involved.</p>
+
+<p>In particular, a server process is intended to belong to a single user. Multiple users on a single host can use different ports. Alternatively, SNI may be used to disambiguate between multiple users, bearing in mind the privacy consequences of the fact that the SNI is sent unencrypted.</p>
+
+<p>Each user is identified by a single public key, which they use as the subject public key of the tail certificates of the server and client certificate chains they provide. For out-of-band confirmation of identity, the SHA256/128 hash (i.e. the first 16 bytes of the SHA256 hash) of the binary DER encoding of the Subject Public Key Info (SPKI) field of such an X509 certificate (as in RFC 7469) should be used. A 128-bit truncated hash is sufficient, since only pre-image resistance rather than collision resistance is required.</p>
+
+<p>The Common Name field of the tail client certificate may be used to indicate the identity of the user it claims to identify.</p>
+
+<p>For communicating hashes and host information, we define the URI scheme &quot;talkat:HASH[@HOST[:PORT]]&quot;, where HASH is the hexadecimal encoding (case-insensitive) of the SHA256/128 hash. For futureproofing purposes, other hash algorithms may be specified, so the full format is &quot;talkat:[HASHALG:]HASH[@HOST[:PORT]]&quot;, with any truncation to initial bytes of the hash indicated by the length, so HASHALG defaults to &quot;sha256&quot;.</p>
+
+<p>Further details of authentication are left up to the user agent, but the intended primary mode of operation is as follows. A single key pair is generated by a user and self-signed certificates generated from it are used both for the server certificate when running a server and for the client certificate when connecting to another server. Users use out-of-band means to verify key hashes. It does not make sense to limit the validity of these certificates, so it is recommended to create it with undefined validity (notAfter value of 99991231235959Z, as per RFC5280). Since including the user's name in a server certificate provided to anyone connecting to the appropriate port could be a privacy/security concern, it is recommended to use a server certificate with empty Common Name, and one or more client certificates each with the Common Name set to an appropriate name for the user, all generated from the same public key.</p>
+
+<h1>Handshake</h1>
+<p>The first character sent in each direction is the 1-byte handshake character 'T'. This is to be sent once the sender is ready for conversation to begin. The TLS client MUST NOT send the handshake character until having received the handshake character from the TLS server.</p>
+
+<h1>Timed character streams</h1>
+<p>Each character stream is parsed as a sequence of lines terminated by \n or \r\n. Each line consists of a sequence of unicode characters, erasures, and pauses, encoded as follows:</p>
+
+<ul><li>'\b' (0x08, ^H) is interpreted as erasing the last character of the current line. If the current line is empty, this is a no-op.</li>
+<li>'\NAK' (0x15, ^U) is interpreted as erasing the entire current line.</li>
+<li>'\n' is interpreted as terminating the current line and beginning a new empty line.</li>
+<li>'~' followed by a 12-bit integer N encoded as a big-endian 2-character base64 sequence (using the character mapping of RFC4648) is interpreted as a pause of N milliseconds, except that the maximum value '~//' is interpreted as a pause of 4095ms or more.</li>
+<li>&quot;~~&quot; is interpreted as the character '~'.</li>
+<li>Null bytes are ignored; they can be used for padding.</li>
+<li>All other unicode characters are interpreted as themselves.</li>
+</ul>
+
+<h2>Example</h2>
+<p>&quot;今~A+日わ!~DI\b\bは~~\n&quot; denotes &quot;今&quot; followed by a 62ms pause, then &quot;日わ!&quot;, then a 200ms pause, then the erasure of the last two characters (&quot;わ!&quot;) followed by &quot;は~&quot; and a newline. The final resulting string is &quot;今日は~&quot;.</p>
+
+<h2>Chunking and padding</h2>
+<p>When transmitting over a network which might be surveilled by an adversary, such as the open internet, appropriate means MUST be used to mitigate the ability to fingerprint a user, and/or gain information on communication contents, through timing information (see RFC6973 for context on surveillance and traffic analysis). In particular, the naive approach of sending a packet immediately after each keystroke of a typing user MUST NOT be used on such a network. Instead, multiple quickly typed keystrokes are to be sent together, with the timing of the keystrokes indicated by the encoded pauses. Furthermore, packets MUST be padded to obscure the length of their contents; this can be done either with TLS record padding or by inserting null bytes in the timed character streams.</p>
+
+<p>As a rough guide (non-normative), the stream could be chunked into 300ms intervals, with each sent (if any character/erasure is typed in the interval) padded to have length divisible by 24, with no chunk ending with a pause. Note that regular chunking is necessary even if the Nagle algorithm is in effect (i.e. if TCP_NODELAY is not set), to ensure that typing speed is not revealed by packet sizes.</p>
+
+<h2>Recommendations for display</h2>
+<p>This subsection is not normative.</p>
+
+<p>A client attempting to display in real-time an incoming stream which includes pauses has to deal with the problem that network delays may exceed the pauses specified in the stream. There are two conflicting goals:</p>
+
+<ul><li>1. Minimise the delay between data being received and being displayed.</li>
+<li>2. Faithfully reproduce the pauses specified in the stream.</li>
+</ul>
+
+<p>Goal 1 can be achieved at the expense of goal 2 by immediately beginning display of the data in a packet when we receive it, compressing to zero any pauses in the part of the stream we were in the process of rendering. Alternatively, we can get as close as possible to achieving goal 2, at the expense of goal 1, by always rendering all pauses as specified, except when pauses are unavoidably lengthened or introduced due to a network delay in receiving the next part of the stream.</p>
+
+<p>The latter strategy is likely to be unacceptable in context of real-time communication, since it means that the delay between a packet being sent and being displayed is the maximum of the network delays for all packets sent so far. The former strategy might be acceptable, but an implementation may prefer a compromise strategy which handles small variations in network delay more smoothly.</p>
+
+<h1>Other real-time text protocols</h1>
+<ul><li>RFC4103: lossy protocol using RTP over UDP, for use with SIP.</li>
+<li>XEP-0301: XMPP extension. Doesn't seem to be used.</li>
+</ul>
+</body>
+</html>
