Merge pull request #1 from katmore/master

new tlds.csv based on latest info from IANA
This commit is contained in:
nico 2018-06-23 14:18:54 +02:00 committed by GitHub
commit 7be88990e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
50 changed files with 46800 additions and 288 deletions

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.*
!/.gitignore
/vendor/
/node_modules/
composer.lock
package-lock.json
*.log
!**.gitkeep
/*-backup.csv
/formats/**/*-backup.*

679
GPLv3 Normal file
View File

@ -0,0 +1,679 @@
THIS DOCUMENT APPLIES TO ALL SOURCE FILES IN THE PROJECT:
"TLD Enumerations" AS FOUND IN https://github.com/katmore/tld-enum
UNLESS SOURCE FILE CONTAINS TEXT EXPLICITLY STATING OTHERWISE.
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.
The flat framework. https://github.com/katmore/flat
Copyright (C) 2012-2015 Doug Bird. All Rights Reserved.
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:
The flat framework. https://github.com/katmore/flat
Copyright (C) 2012-2015 Doug Bird. All Rights Reserved.
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>.

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017-2018 Doug Bird. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

276
README.md
View File

@ -1,6 +1,274 @@
list-of-top-level-domains # TLD Enumerations
========================= Lists of every [IANA TLD](http://data.iana.org/TLD/tlds-alpha-by-domain.txt) in various formats. The lists may be continuously updated using the included [update utility](#updating-the-tld-format-files) that pulls the latest data from IANA.
A (almost complete) list of top level domains (TLDs) in CSV-format. * [CSV Format](./tlds.csv)
* [All Format Files](#tld-list-formats)
* [Updating the Format Files](#updating-the-tld-format-files)
* [Node Usage](#node-usage)
* [PHP Usage](#php-usage)
## Usage
Because the lists are provided in universial CSV and JSON formats, they can be easily utilitized in most programming environments.
Additionally, for convenience, some native programming language formats have also been provided.
* [Node Usage](#node-usage)
* [More Node Examples](#more-node-examples)
* [PHP Usage](#php-usage)
* [More PHP Examples](#more-php-examples)
Missing IDN-TLDs. ### Node Usage
* use npm to add the `tld-enum` package to your project
```sh
$ npm install tld-enum --save
```
* add the module to your source
```js
const tldEnum = require('tld-enum');
```
* access the list by using the `tldEnum.tldList` array
```js
const tldEnum = require('tld-enum');
console.log(tldEnum.list); //an array with every IANA TLD
```
The following example...
```js
const tldEnum = require('tld-enum');
console.log("There are " + tldEnum.list.length + " IANA TLDs");
let tldCheck;
tldCheck = "com";
console.log("Is '" + tldCheck + "' a real TLD?");
if (tldEnum.list.indexOf(tldCheck.toLowerCase()) != -1) {
console.log(" yes");
} else {
console.log(" no");
}
tldCheck = "somethingWeird";
console.log("Is '" + tldCheck + "' a real TLD?");
if (tldEnum.list.indexOf(tldCheck.toLowerCase()) != -1) {
console.log(" yes");
} else {
console.log(" no");
}
```
Should produce the following output...
```txt
There are 1577 IANA TLDs
Is 'com' a real TLD?
yes
Is 'somethingWeird' a real TLD?
no
```
#### More Node Examples
* [js-demo.js](/examples/js-demo.js) Demo using the simple array of every TLD in JavaScript.
* [js-desc-demo.js](/examples/js-desc-demo.js) Demo using the TLD description hashmap in JavaScript.
* [js-type-demo.js](/examples/js-type-demo.js) Demo using the TLD type hashmap in JavaScript.
* [js-info-demo.js](/examples/js-info-demo.js) Demo using the array of TLD info hashmaps in JavaScript.
### PHP Usage
* use composer to add the `katmore/tld-enum` package to your project
```sh
$ composer require katmore/tld-enum
```
* access the list by using the `\TldEnum\TldList::TLD_LIST` class constant array
```php
<?php
print_r(\TldEnum\TldList::TLD_LIST); //an array with every IANA TLD
```
The following example...
```php
<?php
use TldEnum\TldList;
echo "There are " . count(TldList::TLD_LIST) . " IANA TLDs\n";
$tldCheck = "com";
echo "Is '$tldCheck' a real TLD?\n";
if (in_array(strtolower($tldCheck), TldList::TLD_LIST)) {
echo " yes\n";
} else {
echo " no\n";
}
$tldCheck = "somethingWeird";
echo "Is '$tldCheck' a real TLD?\n";
if (in_array(strtolower($tldCheck), TldList::TLD_LIST)) {
echo " yes\n";
} else {
echo " no\n";
}
```
Should produce the following output...
```txt
There are 1577 IANA TLDs
Is 'com' a real TLD?
yes
Is 'somethingWeird' a real TLD?
no
```
#### More PHP Examples
* [php-demo.php](/examples/php-demo.php) Demo using the simple array of every TLD in PHP.
* [php-TldDesc-demo.php](/examples/php-TldDesc-demo.php) Demo using the TLD description hashmap in PHP.
* [php-TldType-demo.php](/examples/php-TldType-demo.php) Demo using the TLD type hashmap in PHP.
* [php-TldInfo-demo.php](/examples/php-TldInfo-demo.php) Demo using the array of TLD info hashmaps in PHP.
## TLD List Formats
* **CSV**: [tlds.csv](/tlds.csv)
A CSV file providing a row for every IANA TLD with the following three columns: *domain* (TLD), *description*, and *type*.
* **PHP**
* [TldList.php](/formats/php/TldEnum/TldList.php)
A PHP source file providing a class constant array comprised of every IANA TLD.
* [TldDesc.php](/formats/php/TldEnum/TldDesc.php)
A PHP source file providing a class constant assoc array with a key for every IANA TLD and the corresponding TLD's "description" as the value.
* [TldType.php](/formats/php/TldEnum/TldType.php)
A PHP source file providing a class constant assoc array with a key for every IANA TLD and the corresponding TLD's "type" as the value.
* [TldInfo.php](/formats/php/TldEnum/TldInfo.php)
A PHP source file providing a class constant array of "info" assoc array elements of every IANA TLD.
* **JSON**
* [tld-list.json](/formats/json/tld-list.json)
A JSON formatted array comprised of every IANA TLD.
* [tld-desc.json](/formats/json/tld-desc.json)
A JSON formatted object with a property for every IANA TLD and the corresponding TLD's "description" as the value.
* [tld-type.json](/formats/json/tld-type.json)
A JSON formatted object with a property for every IANA TLD and the corresponding TLD's "type" as the value.
* [tld-info.json](/formats/json/tld-info.json)
A JSON formatted array of "info" object elements of every IANA TLD.
* **JavaScript**
* [list.js](/formats/js/tld-enum/list.js)
An export module with an array comprised of every IANA TLD.
* [desc.js](/formats/js/tld-enum/desc.js)
An export module with an object containing a property for every IANA TLD and the corresponding TLD's "description" as the value.
* [type.js](/formats/js/tld-enum/type.js)
An export module with an object containing a property for every IANA TLD and the corresponding TLD's "type" as the value.
* [info.js](/formats/js/tld-enum/info.js)
An export module with an array comprised of "info" object elements of every IANA TLD.
## Updating the TLD format files
All [TLD List Formats](#tld-list-formats) can be updated with the latest data from IANA by using the [**TLD Update Utility**](/bin/devel/update-formats.sh).
```sh
$ bin/devel/update-formats.sh
```
### TLD Update Utility Prerequisites
* Node.js version 8.11 or higher.
* (Optional) PHP command-line version 7.2 or higher, to re-generate the [PHP format files](#tld-list-formats).
* The *devDependencies* from [*package.json*](./package.json) must be available.
* If **tld-enum** was installed in an outside project using npm, then the *tld-enum* dev dependencies must be installed manually, as in the following example:
```sh
npm install async-request --save-dev
npm install cheerio --save-dev
npm install commander --save-dev
npm install country-data --save-dev
npm install countryjs --save-dev
npm install csv-parse --save-dev
npm install csv-stringify --save-dev
npm install es6-promisify --save-dev
npm install fs --save-dev
npm install fs-extra --save-dev
npm install md5-file --save-dev
npm install pathinfo --save-dev
npm install request --save-dev
npm install tmp --save-dev
```
* If **tld-enum** was installed in an outside project using npm, then the **TLD Update Utility** can be executed from the *node_module* directory, as in the following example:
```sh
node_modules/tld-enum/bin/devel/update-formats.sh
```
### TLD Update Utility Usage
```txt
usage:
update-formats.sh [-h]|[-q][format file options...]
-h,--help: Print a help message and exit.
-q,--quiet: Print only critical messages.
format file options:
--force-php: Creating the PHP format files is mandatory.
--skip-php: Always skip creating the PHP format files.
--skip-csv: Use existing tlds.csv and do not download new data from IANA.
```
### TLD Update Helpers
Internally, the *TLD Update Utility* uses multiple *"helper" scripts* to generate the full set of native format lists.
These individual *"helper" scripts* should not be directly executed except for development and troubleshooting purposes.
## Legal
The source code in this project is based on a fork of certain source code originally from the [incognico/list-of-top-level-domains](https://github.com/incognico/list-of-top-level-domains) project, as retrieved on 2017-12-04, which was published to the public domain.
### Copyright
TLD Enumerations - https://github.com/katmore/tld-enum
The following copyright notice applies to all resources in this project unless specifically noted otherwise:
Copyright (c) 2017-2018 Doug Bird. All Rights Reserved.
### License
All resources in the *TLD Enumerations* project are copyrighted free software unless specifically noted otherwise.
You may redistribute and modify it under either the terms and conditions of the
"The MIT License (MIT)"; or the terms and conditions of the "GPL v3 License".
See [LICENSE](/LICENSE) and [GPLv3](/GPLv3).
These licensing conditions do not apply to any resources that have been released into the public domain; which are listed in the [**"Public Domain Resources"**](/README.md#public-domain-resources) section of the *TLD Enumerations* project's [README](/README.md) document.
### Public Domain Resources
The following resources of this project are hereby released into the public domain:
* [tlds.csv](/tlds.csv)
* [formats/js/tld-enum/list.js](/formats/js/tld-enum/list.js)
* [formats/js/tld-enum/desc.js](/formats/js/tld-enum/desc.js)
* [formats/js/tld-enum/info.js](/formats/js/tld-enum/info.js)
* [formats/js/tld-enum/type.js](/formats/js/tld-enum/type.js)
* [formats/json/tld-list.json](/formats/json/tld-list.json)
* [formats/json/tld-desc.json](/formats/json/tld-desc.json)
* [formats/json/tld-info.json](/formats/json/tld-info.json)
* [formats/json/tld-type.json](/formats/json/tld-type.json)
* [formats/php/TldEnum/TldList.php](/formats/php/TldEnum/TldList.php)
* [formats/php/TldEnum/TldDesc.php](/formats/php/TldEnum/TldDesc.php)
* [formats/php/TldEnum/TldInfo.php](/formats/php/TldEnum/TldInfo.php)
* [formats/php/TldEnum/TldType.php](/formats/php/TldEnum/TldType.php)
* [assets/tld-desc.csv](/assets/tld-desc.csv)

284
assets/tld-desc.csv Normal file
View File

@ -0,0 +1,284 @@
ac,Ascension Island
ad,Andorra (Principality of)
ae,United Arab Emirates
aero,Air-transport industry
af,Afghanistan (Islamic Republic of)
ag,Antigua and Barbuda
ai,Anguilla
al,Albania (Republic of)
am,Armenia (Republic of)
an,Netherlands Antilles
ao,Angola (Republic of)
aq,Antarctica
ar,Argentina (Argentine Republic)
arpa,Address and Routing Parameter Area
as,American Samoa
asia,Organisations and individuals in the Asia-Pacific region
at,Austria (Republic of)
au,Australia (Commonwealth of)
aw,Aruba
ax,Åland Islands
az,Azerbaijan (Republic of)
ba,Bosnia and Herzegovina
bb,Barbados
bd,Bangladesh (People's Republic of)
be,Belgium (Kingdom of)
bf,Burkina Faso
bg,Bulgaria (Republic of)
bh,Bahrain (Kingdom of)
bi,Burundi (Republic of)
biz,Business
bj,Benin (Republic of)
bl,Saint Barthélemy (Collectivity of) {unassigned - see also: .gp and .fr}
bm,Bermuda
bn,Brunei (Nation of Brunei - the Abode of Peace) [Negara Brunei Darussalam]
bo,Bolivia (Plurinational State of)
bq,Caribbean Netherlands [Bonaire - Sint Eustatius and Saba] {unassigned - see also: .an and .nl}
br,Brazil (Federative Republic of)
bs,Bahamas (Commonwealth of the)
bt,Bhutan (Kingdom of)
bv,Bouvet Island
bw,Botswana (Republic of)
by,Belarus (Republic of)
bz,Belize
ca,Canada
cat,Catalan
cc,Cocos (Keeling) Islands (Territory of the)
cd,Congo (Democratic Republic of the) [Congo-Kinshasa]
cf,Central African Republic
cg,Congo (Republic of) [Congo-Brazzaville]
ch,Switzerland (Swiss Confederation)
ci,Ivory Coast (Republic of Côte d'Ivoire)
ck,Cook Islands
cl,Chile (Republic of)
cm,Cameroon (Republic of)
cn,China (People's Republic of)
co,Colombia (Republic of)
com,Commercial organizations
coop,Cooperatives
cr,Costa Rica (Republic of)
cs,Czechoslovakia {formerly - retired 1995 - see also: .cz and .sk}
cu,Cuba (Republic of)
cv,Cape Verde (Republic of)
cw,Curaçao (Country of)
cx,Christmas Island (Territory of)
cy,Cyprus (Republic of)
cz,Czech Republic
dd,German Democratic Republic [East Germany] {formerly - retired}
de,Germany (Federal Republic of)
dj,Djibouti (Republic of)
dk,Denmark (Kingdom of)
dm,Dominica (Commonwealth of)
do,Dominican Republic
dz,Algeria (People's Democratic Republic of)
ec,Ecuador (Republic of)
edu,Educational establishments
ee,Estonia (Republic of)
eg,Egypt (Arab Republic of)
eh,Western Sahara {reserved}
er,Eritrea (State of)
es,Spain (Kingdom of)
et,Ethiopia (Federal Democratic Republic of)
eu,European Union
fi,Finland (Republic of)
fj,Fiji (Republic of)
fk,Falkland Islands (Malvinas)
fm,Micronesia (Federated States of)
fo,Faroe Islands
fr,France (French Republic)
ga,Gabon (Gabonese Republic)
gb,United Kingdom (United Kingdom of Great Britain and Northern Ireland)
gd,Grenada
ge,Georgia
gf,French Guiana
gg,Guernsey (Bailiwick of)
gh,Ghana (Republic of)
gi,Gibraltar
gl,Greenland
gm,Gambia (Republic of The)
gn,Guinea (Republic of)
gov,US government
gp,Guadeloupe
gq,Equatorial Guinea (Republic of)
gr,Greece (Hellenic Republic)
gs,South Georgia and the South Sandwich Islands
gt,Guatemala (Republic of)
gu,Guam
gw,Guinea-Bissau (Republic of)
gy,Guyana (Co-operative Republic of)
hk,Hong Kong (Hong Kong Special Administrative Region of the People's Republic of China)
hm,Heard Island and McDonald Islands
hn,Honduras (Republic of)
hr,Croatia (Republic of)
ht,Haiti (Republic of)
hu,Hungary
id,Indonesia (Republic of)
ie,Ireland (Republic of)
il,Israel (State of)
im,Isle of Man
in,India (Republic of)
info,Informational sites
int,International treaty-based organizations
io,British Indian Ocean Territory
iq,Iraq (Republic of)
ir,Iran (Islamic Republic of)
is,Iceland
it,Italy (Italian Republic)
je,Jersey (Bailiwick of)
jm,Jamaica (Commonwealth of)
jo,Jordan (Hashemite Kingdom of)
jobs,Employment-related sites
jp,Japan
ke,Kenya (Republic of)
kg,Kyrgyzstan (Kyrgyz Republic)
kh,Cambodia (Kingdom of)
ki,Kiribati (Republic of)
km,Comoros (Union of the)
kn,Saint Kitts and Nevis (Federation of)
kp,Korea (Democratic People's Republic of) [North Korea]
kr,Korea (Republic of) [South Korea]
kw,Kuwait (State of Kuwait)
ky,Cayman Islands
kz,Kazakhstan (Republic of)
la,Laos (Lao People's Democratic Republic)
lb,Lebanon (Lebanese Republic)
lc,Saint Lucia
li,Liechtenstein (Principality of)
lk,Sri Lanka (Democratic Socialist Republic of)
local,Pseudo-Domain for Multicast DNS
lr,Liberia (Republic of)
ls,Lesotho (Kingdom of)
lt,Lithuania (Republic of)
lu,Luxembourg (Grand Duchy of)
lv,Latvia (Republic of)
ly,Libya
ma,Morocco
mc,Monaco (Principality of)
md,Moldova (Republic of)
me,Montenegro
mf,Saint Martin (Collectivity of) {unassigned - see also: .gp and .fr}
mg,Madagascar (Republic of)
mh,Marshall Islands (Republic of the)
mil,US military
mk,Macedonia (Republic of)
ml,Mali (Republic of)
mm,Myanmar (Republic of the Union of) [Burma]
mn,Mongolia
mo,Macau (Macau Special Administrative Region of the People's Republic of China) [Macao]
mobi,Mobile
mp,Northern Mariana Islands (Commonwealth of the)
mq,Martinique
mr,Mauritania (Islamic Republic of)
ms,Montserrat
mt,Malta (Republic of)
mu,Mauritius (Republic of)
museum,Museums
mv,Maldives (Republic of)
mw,Malawi (Republic of)
mx,Mexico (United Mexican States)
my,Malaysia
mz,Mozambique (Republic of)
na,Namibia (Republic of)
name,Individuals
nato,NATO sites and operations {formerly - retired 1996 - never used}
nc,New Caledonia
ne,Niger (Republic of)
net,Network
nf,Norfolk Island (Territory of)
ng,Nigeria (Federal Republic of)
ni,Nicaragua (Republic of)
nl,Netherlands
no,Norway (Kingdom of)
np,Nepal (Federal Democratic Republic of)
nr,Nauru (Republic of)
nu,Niue
nz,New Zealand
om,Oman (Sultanate of)
onion,Pseudo-Domain for TOR (The Onion Router)
org,Non-profit organizations
pa,Panama (Republic of)
pe,Peru (Republic of)
pf,French Polynesia and Clipperton Island
pg,Papua New Guinea (Independent State of)
ph,Philippines (Republic of the)
pk,Pakistan (Islamic Republic of)
pl,Poland (Republic of)
pm,Saint Pierre and Miquelon
pn,Pitcairn Islands (Pitcairn - Henderson - Ducie and Oeno Islands)
pr,Puerto Rico (Commonwealth of)
pro,Profession
ps,Palestine (State of)
pt,Portugal (Portuguese Republic)
pw,Palau (Republic of)
py,Paraguay (Republic of)
qa,Qatar (State of)
re,Réunion
ro,Romania
rs,Serbia (Republic of)
ru,Russia (Russian Federation)
rw,Rwanda (Republic of)
sa,Saudi Arabia (Kingdom of)
sb,Solomon Islands
sc,Seychelles (Republic of)
sd,Sudan (Republic of)
se,Sweden (Kingdom of)
sg,Singapore (Republic of)
sh,Saint Helena
si,Slovenia (Republic of)
sj,Svalbard and Jan Mayen {not in use - see also: .no}
sk,Slovakia (Slovak Republic)
sl,Sierra Leone (Republic of)
sm,San Marino (Republic of)
sn,Senegal (Republic of)
so,Somalia (Federal Republic of)
sr,Suriname (Republic of)
ss,South Sudan (Republic of)
st,São Tomé and Príncipe (Democratic Republic of)
su,Soviet Union (Union of Soviet Socialist Republics)
sv,El Salvador (Republic of)
sx,Sint Maarten
sy,Syria (Syrian Arab Republic)
sz,Swaziland (Kingdom of)
tc,Turks and Caicos Islands
td,Chad (Republic of)
tel,Telephone
tf,French Southern and Antarctic Lands (Territory of the)
tg,Togo (Togolese Republic)
th,Thailand (Kingdom of)
tj,Tajikistan (Republic of)
tk,Tokelau
tl,Timor-Leste (Democratic Republic of) [East Timor]
tm,Turkmenistan
tn,Tunisia (Republic of)
to,Tonga (Kingdom of)
tp,Timor-Leste (Democratic Republic of) [East Timor] {being phased out - also see: .tl}
tr,Turkey (Republic of)
travel,Travel
tt,Trinidad and Tobago (Republic of)
tv,Tuvalu
tw,Taiwan (Republic of China)
tz,Tanzania (United Republic of)
ua,Ukraine
ug,Uganda (Republic of)
uk,United Kingdom (United Kingdom of Great Britain and Northern Ireland)
um,United States Minor Outlying Islands {formerly - retired 2010 - see also: .us}
us,United States of America and United States Minor Outlying Islands
uy,Uruguay (Oriental Republic of)
uz,Uzbekistan (Republic of)
va,Vatican City (Vatican City State)
vc,Saint Vincent and the Grenadines
ve,Venezuela (Bolivarian Republic of)
vg,British Virgin Islands (Virgin Islands)
vi,United States Virgin Islands (United States Virgin Islands)
vn,Vietnam (Socialist Republic of)
vu,Vanuatu (Republic of)
wf,Wallis and Futuna (Territory of the Wallis and Futuna Islands)
ws,Samoa (Independent State of)
xxx,Adult entertainment
ye,Yemen (Republic of)
yt,Mayotte (Department of)
yu,Yugoslavia and Serbia and Montenegro {formerly - retired 2010 - see also: .me and .rs}
za,South Africa (Republic of)
zm,Zambia (Republic of)
zr,Zaire (Republic of) {formerly - retired 2001 - see also: .cd}
zw,Zimbabwe (Republic of)
1 ac Ascension Island
2 ad Andorra (Principality of)
3 ae United Arab Emirates
4 aero Air-transport industry
5 af Afghanistan (Islamic Republic of)
6 ag Antigua and Barbuda
7 ai Anguilla
8 al Albania (Republic of)
9 am Armenia (Republic of)
10 an Netherlands Antilles
11 ao Angola (Republic of)
12 aq Antarctica
13 ar Argentina (Argentine Republic)
14 arpa Address and Routing Parameter Area
15 as American Samoa
16 asia Organisations and individuals in the Asia-Pacific region
17 at Austria (Republic of)
18 au Australia (Commonwealth of)
19 aw Aruba
20 ax Åland Islands
21 az Azerbaijan (Republic of)
22 ba Bosnia and Herzegovina
23 bb Barbados
24 bd Bangladesh (People's Republic of)
25 be Belgium (Kingdom of)
26 bf Burkina Faso
27 bg Bulgaria (Republic of)
28 bh Bahrain (Kingdom of)
29 bi Burundi (Republic of)
30 biz Business
31 bj Benin (Republic of)
32 bl Saint Barthélemy (Collectivity of) {unassigned - see also: .gp and .fr}
33 bm Bermuda
34 bn Brunei (Nation of Brunei - the Abode of Peace) [Negara Brunei Darussalam]
35 bo Bolivia (Plurinational State of)
36 bq Caribbean Netherlands [Bonaire - Sint Eustatius and Saba] {unassigned - see also: .an and .nl}
37 br Brazil (Federative Republic of)
38 bs Bahamas (Commonwealth of the)
39 bt Bhutan (Kingdom of)
40 bv Bouvet Island
41 bw Botswana (Republic of)
42 by Belarus (Republic of)
43 bz Belize
44 ca Canada
45 cat Catalan
46 cc Cocos (Keeling) Islands (Territory of the)
47 cd Congo (Democratic Republic of the) [Congo-Kinshasa]
48 cf Central African Republic
49 cg Congo (Republic of) [Congo-Brazzaville]
50 ch Switzerland (Swiss Confederation)
51 ci Ivory Coast (Republic of Côte d'Ivoire)
52 ck Cook Islands
53 cl Chile (Republic of)
54 cm Cameroon (Republic of)
55 cn China (People's Republic of)
56 co Colombia (Republic of)
57 com Commercial organizations
58 coop Cooperatives
59 cr Costa Rica (Republic of)
60 cs Czechoslovakia {formerly - retired 1995 - see also: .cz and .sk}
61 cu Cuba (Republic of)
62 cv Cape Verde (Republic of)
63 cw Curaçao (Country of)
64 cx Christmas Island (Territory of)
65 cy Cyprus (Republic of)
66 cz Czech Republic
67 dd German Democratic Republic [East Germany] {formerly - retired}
68 de Germany (Federal Republic of)
69 dj Djibouti (Republic of)
70 dk Denmark (Kingdom of)
71 dm Dominica (Commonwealth of)
72 do Dominican Republic
73 dz Algeria (People's Democratic Republic of)
74 ec Ecuador (Republic of)
75 edu Educational establishments
76 ee Estonia (Republic of)
77 eg Egypt (Arab Republic of)
78 eh Western Sahara {reserved}
79 er Eritrea (State of)
80 es Spain (Kingdom of)
81 et Ethiopia (Federal Democratic Republic of)
82 eu European Union
83 fi Finland (Republic of)
84 fj Fiji (Republic of)
85 fk Falkland Islands (Malvinas)
86 fm Micronesia (Federated States of)
87 fo Faroe Islands
88 fr France (French Republic)
89 ga Gabon (Gabonese Republic)
90 gb United Kingdom (United Kingdom of Great Britain and Northern Ireland)
91 gd Grenada
92 ge Georgia
93 gf French Guiana
94 gg Guernsey (Bailiwick of)
95 gh Ghana (Republic of)
96 gi Gibraltar
97 gl Greenland
98 gm Gambia (Republic of The)
99 gn Guinea (Republic of)
100 gov US government
101 gp Guadeloupe
102 gq Equatorial Guinea (Republic of)
103 gr Greece (Hellenic Republic)
104 gs South Georgia and the South Sandwich Islands
105 gt Guatemala (Republic of)
106 gu Guam
107 gw Guinea-Bissau (Republic of)
108 gy Guyana (Co-operative Republic of)
109 hk Hong Kong (Hong Kong Special Administrative Region of the People's Republic of China)
110 hm Heard Island and McDonald Islands
111 hn Honduras (Republic of)
112 hr Croatia (Republic of)
113 ht Haiti (Republic of)
114 hu Hungary
115 id Indonesia (Republic of)
116 ie Ireland (Republic of)
117 il Israel (State of)
118 im Isle of Man
119 in India (Republic of)
120 info Informational sites
121 int International treaty-based organizations
122 io British Indian Ocean Territory
123 iq Iraq (Republic of)
124 ir Iran (Islamic Republic of)
125 is Iceland
126 it Italy (Italian Republic)
127 je Jersey (Bailiwick of)
128 jm Jamaica (Commonwealth of)
129 jo Jordan (Hashemite Kingdom of)
130 jobs Employment-related sites
131 jp Japan
132 ke Kenya (Republic of)
133 kg Kyrgyzstan (Kyrgyz Republic)
134 kh Cambodia (Kingdom of)
135 ki Kiribati (Republic of)
136 km Comoros (Union of the)
137 kn Saint Kitts and Nevis (Federation of)
138 kp Korea (Democratic People's Republic of) [North Korea]
139 kr Korea (Republic of) [South Korea]
140 kw Kuwait (State of Kuwait)
141 ky Cayman Islands
142 kz Kazakhstan (Republic of)
143 la Laos (Lao People's Democratic Republic)
144 lb Lebanon (Lebanese Republic)
145 lc Saint Lucia
146 li Liechtenstein (Principality of)
147 lk Sri Lanka (Democratic Socialist Republic of)
148 local Pseudo-Domain for Multicast DNS
149 lr Liberia (Republic of)
150 ls Lesotho (Kingdom of)
151 lt Lithuania (Republic of)
152 lu Luxembourg (Grand Duchy of)
153 lv Latvia (Republic of)
154 ly Libya
155 ma Morocco
156 mc Monaco (Principality of)
157 md Moldova (Republic of)
158 me Montenegro
159 mf Saint Martin (Collectivity of) {unassigned - see also: .gp and .fr}
160 mg Madagascar (Republic of)
161 mh Marshall Islands (Republic of the)
162 mil US military
163 mk Macedonia (Republic of)
164 ml Mali (Republic of)
165 mm Myanmar (Republic of the Union of) [Burma]
166 mn Mongolia
167 mo Macau (Macau Special Administrative Region of the People's Republic of China) [Macao]
168 mobi Mobile
169 mp Northern Mariana Islands (Commonwealth of the)
170 mq Martinique
171 mr Mauritania (Islamic Republic of)
172 ms Montserrat
173 mt Malta (Republic of)
174 mu Mauritius (Republic of)
175 museum Museums
176 mv Maldives (Republic of)
177 mw Malawi (Republic of)
178 mx Mexico (United Mexican States)
179 my Malaysia
180 mz Mozambique (Republic of)
181 na Namibia (Republic of)
182 name Individuals
183 nato NATO sites and operations {formerly - retired 1996 - never used}
184 nc New Caledonia
185 ne Niger (Republic of)
186 net Network
187 nf Norfolk Island (Territory of)
188 ng Nigeria (Federal Republic of)
189 ni Nicaragua (Republic of)
190 nl Netherlands
191 no Norway (Kingdom of)
192 np Nepal (Federal Democratic Republic of)
193 nr Nauru (Republic of)
194 nu Niue
195 nz New Zealand
196 om Oman (Sultanate of)
197 onion Pseudo-Domain for TOR (The Onion Router)
198 org Non-profit organizations
199 pa Panama (Republic of)
200 pe Peru (Republic of)
201 pf French Polynesia and Clipperton Island
202 pg Papua New Guinea (Independent State of)
203 ph Philippines (Republic of the)
204 pk Pakistan (Islamic Republic of)
205 pl Poland (Republic of)
206 pm Saint Pierre and Miquelon
207 pn Pitcairn Islands (Pitcairn - Henderson - Ducie and Oeno Islands)
208 pr Puerto Rico (Commonwealth of)
209 pro Profession
210 ps Palestine (State of)
211 pt Portugal (Portuguese Republic)
212 pw Palau (Republic of)
213 py Paraguay (Republic of)
214 qa Qatar (State of)
215 re Réunion
216 ro Romania
217 rs Serbia (Republic of)
218 ru Russia (Russian Federation)
219 rw Rwanda (Republic of)
220 sa Saudi Arabia (Kingdom of)
221 sb Solomon Islands
222 sc Seychelles (Republic of)
223 sd Sudan (Republic of)
224 se Sweden (Kingdom of)
225 sg Singapore (Republic of)
226 sh Saint Helena
227 si Slovenia (Republic of)
228 sj Svalbard and Jan Mayen {not in use - see also: .no}
229 sk Slovakia (Slovak Republic)
230 sl Sierra Leone (Republic of)
231 sm San Marino (Republic of)
232 sn Senegal (Republic of)
233 so Somalia (Federal Republic of)
234 sr Suriname (Republic of)
235 ss South Sudan (Republic of)
236 st São Tomé and Príncipe (Democratic Republic of)
237 su Soviet Union (Union of Soviet Socialist Republics)
238 sv El Salvador (Republic of)
239 sx Sint Maarten
240 sy Syria (Syrian Arab Republic)
241 sz Swaziland (Kingdom of)
242 tc Turks and Caicos Islands
243 td Chad (Republic of)
244 tel Telephone
245 tf French Southern and Antarctic Lands (Territory of the)
246 tg Togo (Togolese Republic)
247 th Thailand (Kingdom of)
248 tj Tajikistan (Republic of)
249 tk Tokelau
250 tl Timor-Leste (Democratic Republic of) [East Timor]
251 tm Turkmenistan
252 tn Tunisia (Republic of)
253 to Tonga (Kingdom of)
254 tp Timor-Leste (Democratic Republic of) [East Timor] {being phased out - also see: .tl}
255 tr Turkey (Republic of)
256 travel Travel
257 tt Trinidad and Tobago (Republic of)
258 tv Tuvalu
259 tw Taiwan (Republic of China)
260 tz Tanzania (United Republic of)
261 ua Ukraine
262 ug Uganda (Republic of)
263 uk United Kingdom (United Kingdom of Great Britain and Northern Ireland)
264 um United States Minor Outlying Islands {formerly - retired 2010 - see also: .us}
265 us United States of America and United States Minor Outlying Islands
266 uy Uruguay (Oriental Republic of)
267 uz Uzbekistan (Republic of)
268 va Vatican City (Vatican City State)
269 vc Saint Vincent and the Grenadines
270 ve Venezuela (Bolivarian Republic of)
271 vg British Virgin Islands (Virgin Islands)
272 vi United States Virgin Islands (United States Virgin Islands)
273 vn Vietnam (Socialist Republic of)
274 vu Vanuatu (Republic of)
275 wf Wallis and Futuna (Territory of the Wallis and Futuna Islands)
276 ws Samoa (Independent State of)
277 xxx Adult entertainment
278 ye Yemen (Republic of)
279 yt Mayotte (Department of)
280 yu Yugoslavia and Serbia and Montenegro {formerly - retired 2010 - see also: .me and .rs}
281 za South Africa (Republic of)
282 zm Zambia (Republic of)
283 zr Zaire (Republic of) {formerly - retired 2001 - see also: .cd}
284 zw Zimbabwe (Republic of)

View File

@ -0,0 +1,119 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-desc.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldDescJs = path.dirname(require.main.filename) + '/../../../formats/js/tld-enum/desc.js';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JavaScript format file 'desc.js' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tldDescStartTldDesc = 'module.exports = ';
const tldDescEndTldDesc = ';';
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldDescJs = tmpDir.name + '/desc.js';
let existingMd5 = null;
if (fs.existsSync(fileTldDescJs)) {
existingMd5 = md5File.sync(fileTldDescJs);
const pathinfoTlds = pathinfo(fileTldDescJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldDescJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldDesc = {};
let i = 0;
parser.on('readable', function() {
let row, domain, desc;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[1] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 2 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
if (!domain) {
console.error(meName + ": (FATAL) invalid 'tlds.csv', empty column 1 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
desc=row[1];
tldDesc[domain]=desc;
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'desc.js' file...");
fs.writeFileSync(fileNewTldDescJs, tldDescStartTldDesc);
fs.appendFileSync(fileNewTldDescJs, JSON.stringify(tldDesc, null, 2));
fs.appendFileSync(fileNewTldDescJs, tldDescEndTldDesc);
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldDescJs);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'desc.js' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldDescJs + ")");
return;
}
}
fs.copySync(fileNewTldDescJs, fileTldDescJs);
console.log("saved new 'desc.js' file");
});
})();

View File

@ -0,0 +1,119 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-info.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldInfoJs = path.dirname(require.main.filename) + '/../../../formats/js/tld-enum/info.js';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JavaScript format file 'info.js' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tldInfoStartTldInfo = 'module.exports = ';
const tldInfoEndTldInfo = ';';
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldInfoJs = tmpDir.name + '/info.js';
let existingMd5 = null;
if (fs.existsSync(fileTldInfoJs)) {
existingMd5 = md5File.sync(fileTldInfoJs);
const pathinfoTlds = pathinfo(fileTldInfoJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldInfoJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldInfo = [];
let i = 0;
parser.on('readable', function() {
let row, domain, desc, type;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[1] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 2 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[2] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 3 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
desc=row[1];
type=row[2];
tldInfo.push({
'domain' : domain,
'description' : desc,
'type' : type,
});
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'info.js' file...");
fs.writeFileSync(fileNewTldInfoJs, tldInfoStartTldInfo);
fs.appendFileSync(fileNewTldInfoJs, JSON.stringify(tldInfo, null, 2));
fs.appendFileSync(fileNewTldInfoJs, tldInfoEndTldInfo);
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldInfoJs);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'info.js' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldInfoJs + ")");
return;
}
}
fs.copySync(fileNewTldInfoJs, fileTldInfoJs);
console.log("saved new 'info.js' file");
});
})();

View File

@ -0,0 +1,102 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-list.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
const fileTldListJs = path.dirname(require.main.filename) + '/../../../formats/js/tld-enum/list.js';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-list#readme");
console.log("");
console.log(" Generates new JavaScript format file 'list.js' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tldEnumStartTldList = 'module.exports = ';
const tldEnumEndTldList = ';';
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldListJs = tmpDir.name + '/list.js';
let existingMd5 = null;
if (fs.existsSync(fileTldListJs)) {
existingMd5 = md5File.sync(fileTldListJs);
const pathinfoTlds = pathinfo(fileTldListJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldListJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldEnum = [];
let i = 0;
parser.on('readable', function() {
let row;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + ": " + fileTldsCsv);
process.exit(1);
}
tldEnum.push(row[0]);
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'list.js' file...");
fs.writeFileSync(fileNewTldListJs, tldEnumStartTldList);
fs.appendFileSync(fileNewTldListJs, JSON.stringify(tldEnum, null, 2));
fs.appendFileSync(fileNewTldListJs, tldEnumEndTldList);
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldListJs);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'list.js' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldListJs + ")");
return;
}
}
fs.copySync(fileNewTldListJs, fileTldListJs);
console.log("saved new 'list.js' file");
});
})();

View File

@ -0,0 +1,110 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-type.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldTypeJs = path.dirname(require.main.filename) + '/../../../formats/js/tld-enum/type.js';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JavaScript format file 'type.js' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tldTypeStartTldType = 'module.exports = ';
const tldTypeEndTldType = ';';
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldTypeJs = tmpDir.name + '/type.js';
let existingMd5 = null;
if (fs.existsSync(fileTldTypeJs)) {
existingMd5 = md5File.sync(fileTldTypeJs);
const pathinfoTlds = pathinfo(fileTldTypeJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldTypeJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldType = {};
let i = 0;
parser.on('readable', function() {
let row, domain, type;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[2] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 3 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
type=row[2];
tldType[domain]=type;
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'type.js' file...");
fs.writeFileSync(fileNewTldTypeJs, tldTypeStartTldType);
fs.appendFileSync(fileNewTldTypeJs, JSON.stringify(tldType, null, 2));
fs.appendFileSync(fileNewTldTypeJs, tldTypeEndTldType);
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldTypeJs);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'type.js' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldTypeJs + ")");
return;
}
}
fs.copySync(fileNewTldTypeJs, fileTldTypeJs);
console.log("saved new 'type.js' file");
});
})();

View File

@ -0,0 +1,103 @@
#!/usr/bin/env node
const meName = 'generate-json-tld-desc.json';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldDescJs = path.dirname(require.main.filename) + '/../../../formats/json/tld-desc.json';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JSON format file 'tld-desc.json' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldDescJson = tmpDir.name + '/tld-desc.json';
let existingMd5 = null;
if (fs.existsSync(fileTldDescJs)) {
existingMd5 = md5File.sync(fileTldDescJs);
const pathinfoTlds = pathinfo(fileTldDescJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldDescJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldDesc = {};
let i = 0;
parser.on('readable', function() {
let row, domain, desc;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[1] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 2 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
desc=row[1];
tldDesc[domain]=desc;
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'tld-desc.json' file...");
fs.appendFileSync(fileNewTldDescJson, JSON.stringify(tldDesc, null, 2));
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldDescJson);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'tld-desc.json' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldDescJs + ")");
return;
}
}
fs.copySync(fileNewTldDescJson, fileTldDescJs);
console.log("saved new 'tld-desc.json' file");
});
})();

View File

@ -0,0 +1,112 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-info.json';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldInfoJs = path.dirname(require.main.filename) + '/../../../formats/json/tld-info.json';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JSON format file 'tld-info.json' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldInfoJs = tmpDir.name + '/tld-info.json';
let existingMd5 = null;
if (fs.existsSync(fileTldInfoJs)) {
existingMd5 = md5File.sync(fileTldInfoJs);
const pathinfoTlds = pathinfo(fileTldInfoJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldInfoJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldInfo = [];
let i = 0;
parser.on('readable', function() {
let row, domain, desc, type;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[1] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 2 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[2] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 3 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
desc=row[1];
type=row[2];
tldInfo.push({
'domain' : domain,
'description' : desc,
'type' : type,
});
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'tld-info.json' file...");
fs.appendFileSync(fileNewTldInfoJs, JSON.stringify(tldInfo, null, 2));
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldInfoJs);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'tld-info.json' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldInfoJs + ")");
return;
}
}
fs.copySync(fileNewTldInfoJs, fileTldInfoJs);
console.log("saved new 'tld-info.json' file");
});
})();

View File

@ -0,0 +1,96 @@
#!/usr/bin/env node
const meName = 'generate-json-tld-enum.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
tmp.setGracefulCleanup();
const fileTldListJson = path.dirname(require.main.filename) + '/../../../formats/json/tld-list.json';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JSON format file 'tld-list.json' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldListJson = tmpDir.name + '/tld-list.json';
let existingMd5 = null;
if (fs.existsSync(fileTldListJson)) {
existingMd5 = md5File.sync(fileTldListJson);
const pathinfoTlds = pathinfo(fileTldListJson);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.json';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldListJson, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldEnum = [];
let i = 0;
parser.on('readable', function() {
let row;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + ": " + fileTldsCsv);
process.exit(1);
}
tldEnum.push(row[0]);
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'tld-list.json' file...");
fs.writeFileSync(fileNewTldListJson, JSON.stringify(tldEnum, null, 2));
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldListJson);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'tld-list.json' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldListJson + ")");
return;
}
}
fs.copySync(fileNewTldListJson, fileTldListJson);
console.log("saved new 'tld-list.json' file");
});
})();

View File

@ -0,0 +1,103 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-type.json';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldTypeJs = path.dirname(require.main.filename) + '/../../../formats/json/tld-type.json';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new JSON format file 'tld-type.json' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldTypeJson = tmpDir.name + '/tld-type.json';
let existingMd5 = null;
if (fs.existsSync(fileTldTypeJs)) {
existingMd5 = md5File.sync(fileTldTypeJs);
const pathinfoTlds = pathinfo(fileTldTypeJs);
const fileBackupTlds = pathinfoTlds.dirname + pathinfoTlds.sep + pathinfoTlds.basename + '-' + existingMd5 + '-backup.js';
if (!fs.existsSync(fileBackupTlds)) {
fs.copySync(fileTldTypeJs, fileBackupTlds);
}
}
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldType = {};
let i = 0;
parser.on('readable', function() {
let row, domain, type;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[2] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 3 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
type=row[2];
tldType[domain]=type;
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
process.stdout.write("generating new 'tld-type.json' file...");
fs.appendFileSync(fileNewTldTypeJson, JSON.stringify(tldType, null, 2));
console.log("done");
if (existingMd5) {
const newMd5 = md5File.sync(fileNewTldTypeJson);
if (newMd5 == existingMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'tld-type.json' file that is identical to the existing file (md5: " + existingMd5 + ", path: " + fileTldTypeJs + ")");
return;
}
}
fs.copySync(fileNewTldTypeJson, fileTldTypeJs);
console.log("saved new 'tld-type.json' file");
});
})();

View File

@ -0,0 +1,177 @@
#!/usr/bin/env php
<?php
new class() {
const ME_NAME = 'generate-php-tld-desc.php';
const TLDS_CSV_PATH = __DIR__ . '/../../../tlds.csv';
const TLD_DESC_PATH = __DIR__ . '/../../../formats/php/TldEnum/TldDesc.php';
private static $_quietMode = false;
public function __construct() {
$opt = getopt ( "q",['quiet']);
if (isset($opt['q']) || isset($opt['quiet'])) {
static::$_quietMode = true;
}
if (!static::$_quietMode) {
echo static::ME_NAME."\n";
echo " (c) 2017 Doug Bird, All Rights Reserved.\n";
echo " see README.md for licensing and other information\n";
echo " https://github.com/katmore/tld-enum#readme\n";
echo "\n";
echo " Generates new PHP format file 'TldDesc.php' from the 'tlds.csv' file\n";
echo "\n";
}
$fileTldsCsv = static::TLDS_CSV_PATH;
if (!is_file($fileTldsCsv) || !is_readable($fileTldsCsv)) {
static::_echo_error("(FATAL) not a readable path to 'tlds.csv': $fileTldsCsv",1);
}
$tldDescFile = static::TLD_DESC_PATH;
$tldDescDir = pathinfo($tldDescFile,\PATHINFO_DIRNAME);
if (file_exists($tldDescFile)) {
if (!is_file($tldDescFile)) {
static::_echo_error("(FATAL) existing path for 'TldDesc.php' was not a file as expected: $tldDescFile",1);
}
if (!is_writable($tldDescFile)) {
static::_echo_error("(FATAL) existing path for 'TldDesc.php' is not writable: $tldDescFile",1);
}
} else {
if (!file_exists($tldDescDir) || !is_dir($tldDescDir)) {
static::_echo_error("(FATAL) path for 'TldDesc.php' directory does not exist as expected: $tldDescDir",1);
}
if (!is_writable($tldDescDir)) {
static::_echo_error("(FATAL) path for 'TldDesc.php' directory is not writeable: $tldDescDir",1);
}
}
$existingMd5 = null;
if (file_exists($tldDescFile)) {
$existingMd5 = md5_file($tldDescFile);
$tldDescBasename = pathinfo($tldDescFile,\PATHINFO_FILENAME);
$backupTldDescFile = $tldDescDir . \DIRECTORY_SEPARATOR . "$tldDescBasename-$existingMd5-backup.php";
if (!file_exists($backupTldDescFile)) {
if (!copy($tldDescFile,$backupTldDescFile)) {
static::_echo_error("(FATAL) failed to create backup for 'TldDesc.php' (source: $tldDescFile, dest: $backupTldDescFile)",1);
}
}
}
if (false === ($newTldDescFile = tempnam ( sys_get_temp_dir() , 'tld-enum-' ))) {
static::_echo_error("(FATAL) unable to initialize new 'TldDesc.php' file",1);
}
register_shutdown_function(function() use($newTldDescFile) {
if (is_file($newTldDescFile) && is_writable($newTldDescFile)) {
unlink($newTldDescFile);
}
});
$tldDesc = [];
if (($handle = fopen($fileTldsCsv, "r")) === false) {
static::_echo_error("(FATAL) unable to open 'tlds.csv' in read mode: $fileTldsCsv",1);
} else {
echo "reading 'tlds.csv'...";
$i=0;
while (($row = fgetcsv($handle, 1000, ",")) !== false) {
if (!count($row)) {
static::_echo_error("(FATAL) invalid 'tlds.csv' row #$i: $fileTldsCsv",1);
}
if (!isset($row[1])) {
static::_echo_error("(FATAL) invalid 'tlds.csv', missing column 2 on row #$i: $fileTldsCsv",1);
}
$domain = $row[0];
$desc = $row[1];
$tldDesc[$domain] = $desc;
$i++;
}
fclose($handle);
echo "done\n";
}
echo "generating new 'TldDesc.php' file...";
if (false === file_put_contents($newTldDescFile,static::TLD_DESC_SOURCE_START_CLASS)) {
static::_echo_error("(FATAL) failed to write to new 'TldDesc.php' file",1);
}
if (false === file_put_contents($newTldDescFile,static::TLD_DESC_SOURCE_START_TLD_DESC_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldDesc.php' file",1);
}
$tldDescExport = var_export($tldDesc, true);
$tldDescExport = substr($tldDescExport,strlen("array ("));
$tldDescExport = substr($tldDescExport,0,-1);
$tldDescExport = ' ['.$tldDescExport.']';
if (false === file_put_contents($newTldDescFile, $tldDescExport,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldDesc.php' file",1);
}
if (false === file_put_contents($newTldDescFile,static::TLD_DESC_SOURCE_END_TLD_DESC_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldDesc.php' file",1);
}
if (false === file_put_contents($newTldDescFile,static::TLD_DESC_SOURCE_END_CLASS,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldDesc.php' file",1);
}
echo "done\n";
if ($existingMd5!==null) {
$newTldDescMd5 = md5_file($newTldDescFile);
if ($existingMd5 == $newTldDescMd5) {
static::_echo_error("(NOTICE) ignoring newly generated 'TldDesc.php' file that is identical to the existing file (md5: $existingMd5, path: $tldDescFile)");
return;
}
if (!unlink($tldDescFile)) {
static::_echo_error("(FATAL) failed to remove stale 'TldDesc.php': $tldDescFile",1);
}
}
if (!copy($newTldDescFile,$tldDescFile)) {
static::_echo_error("(FATAL) failed to save new 'TldDesc.php': $tldDescFile",1);
}
echo "saved new 'TldDesc.php' file\n";
}
private static function _echo_error(string $str, int $fatal_exit_status=null) : void {
if (substr($str,0,1)!=="\n") {
$str .= "\n";
}
$str = static::ME_NAME . ": ".$str;
if (\PHP_SAPI=='cli') {
fwrite(\STDERR,$str);
} else {
echo $str ;
}
if (is_int($fatal_exit_status)) {
exit($fatal_exit_status);
}
}
const TLD_DESC_SOURCE_START_CLASS = <<<SOURCE
<?php
namespace TldEnum;
class TldDesc {
SOURCE;
const TLD_DESC_SOURCE_START_TLD_DESC_CONST = <<<SOURCE
const TLD_DESC =
SOURCE;
const TLD_DESC_SOURCE_END_TLD_DESC_CONST = <<<SOURCE
;
SOURCE;
const TLD_DESC_SOURCE_END_CLASS = <<<SOURCE
}
SOURCE;
};

View File

@ -0,0 +1,211 @@
#!/usr/bin/env php
<?php
new class() {
const ME_NAME = 'generate-php-tld-info.php';
const TLDS_CSV_PATH = __DIR__ . '/../../../tlds.csv';
const TLD_INFO_PATH = __DIR__ . '/../../../formats/php/TldEnum/TldInfo.php';
private static $_quietMode = false;
public function __construct() {
$opt = getopt ( "q",['quiet']);
if (isset($opt['q']) || isset($opt['quiet'])) {
static::$_quietMode = true;
}
if (!static::$_quietMode) {
echo static::ME_NAME."\n";
echo " (c) 2017 Doug Bird, All Rights Reserved.\n";
echo " see README.md for licensing and other information\n";
echo " https://github.com/katmore/tld-enum#readme\n";
echo "\n";
echo " Generates new PHP format file 'TldInfo.php' from the 'tlds.csv' file\n";
echo "\n";
}
$fileTldsCsv = static::TLDS_CSV_PATH;
if (!is_file($fileTldsCsv) || !is_readable($fileTldsCsv)) {
static::_echo_error("(FATAL) not a readable path to 'tlds.csv': $fileTldsCsv",1);
}
$tldInfoFile = static::TLD_INFO_PATH;
$tldInfoDir = pathinfo($tldInfoFile,\PATHINFO_DIRNAME);
if (file_exists($tldInfoFile)) {
if (!is_file($tldInfoFile)) {
static::_echo_error("(FATAL) existing path for 'TldInfo.php' was not a file as expected: $tldInfoFile",1);
}
if (!is_writable($tldInfoFile)) {
static::_echo_error("(FATAL) existing path for 'TldInfo.php' is not writable: $tldInfoFile",1);
}
} else {
if (!file_exists($tldInfoDir) || !is_dir($tldInfoDir)) {
static::_echo_error("(FATAL) path for 'TldInfo.php' directory does not exist as expected: $tldInfoDir",1);
}
if (!is_writable($tldInfoDir)) {
static::_echo_error("(FATAL) path for 'TldInfo.php' directory is not writeable: $tldInfoDir",1);
}
}
$existingMd5 = null;
if (file_exists($tldInfoFile)) {
$existingMd5 = md5_file($tldInfoFile);
$tldInfoBasename = pathinfo($tldInfoFile,\PATHINFO_FILENAME);
$backupTldInfoFile = $tldInfoDir . \DIRECTORY_SEPARATOR . "$tldInfoBasename-$existingMd5-backup.php";
if (!file_exists($backupTldInfoFile)) {
if (!copy($tldInfoFile,$backupTldInfoFile)) {
static::_echo_error("(FATAL) failed to create backup for 'TldInfo.php' (source: $tldInfoFile, dest: $backupTldInfoFile)",1);
}
}
}
if (false === ($newTldInfoFile = tempnam ( sys_get_temp_dir() , 'tld-enum-' ))) {
static::_echo_error("(FATAL) unable to initialize new 'TldInfo.php' file",1);
}
register_shutdown_function(function() use($newTldInfoFile)
{
if (is_file($newTldInfoFile) && is_writable($newTldInfoFile)) {
unlink($newTldInfoFile);
}
});
echo "generating new 'TldInfo.php' file...";
if (false === file_put_contents($newTldInfoFile,static::TLD_INFO_SOURCE_START_CLASS)) {
static::_echo_error("(FATAL) failed to write to new 'TldInfo.php' file",1);
}
if (false === file_put_contents($newTldInfoFile,static::TLD_INFO_SOURCE_START_TLD_INFO_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldInfo.php' file",1);
}
if (($handle = fopen($fileTldsCsv, "r")) === false) {
static::_echo_error("(FATAL) unable to open 'tlds.csv' in read mode: $fileTldsCsv",1);
} else {
echo "reading 'tlds.csv'...";
$i=0;
while (($row = fgetcsv($handle, 1000, ",")) !== false) {
if (!count($row)) {
static::_echo_error("(FATAL) invalid 'tlds.csv' row #$i: $fileTldsCsv",1);
}
if (!isset($row[1])) {
static::_echo_error("(FATAL) invalid 'tlds.csv', missing column 2 on row #$i: $fileTldsCsv",1);
}
if (!isset($row[2])) {
static::_echo_error("(FATAL) invalid 'tlds.csv', missing column 3 on row #$i: $fileTldsCsv",1);
}
$domain = $row[0];
$desc = $row[1];
$type = $row[2];
$tldInfoElem = [
'domain'=>$domain,
'description'=>$desc,
'type'=>$type,
];
$tldInfoElem = var_export($tldInfoElem, true);
$tldInfoElem = substr($tldInfoElem,strlen("array ("));
$tldInfoElem = substr($tldInfoElem,0,-1);
$tldInfoElem = ' ['.$tldInfoElem.']';
if ($i!=0) {
$tldInfoElem = ",\n$tldInfoElem";
}
if (false === file_put_contents($newTldInfoFile, $tldInfoElem,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldInfo.php' file",1);
}
$i++;
}
fclose($handle);
echo "done\n";
}
//echo "new TldInfo.php: $newTldInfoFile\n";
if (false === file_put_contents($newTldInfoFile,static::TLD_INFO_SOURCE_END_TLD_INFO_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldInfo.php' file",1);
}
if (false === file_put_contents($newTldInfoFile,static::TLD_INFO_SOURCE_END_CLASS,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldInfo.php' file",1);
}
echo "done\n";
if ($existingMd5!==null) {
$newTldInfoMd5 = md5_file($newTldInfoFile);
if ($existingMd5 == $newTldInfoMd5) {
static::_echo_error("(NOTICE) ignoring newly generated 'TldInfo.php' file that is identical to the existing file (md5: $existingMd5, path: $tldInfoFile)");
return;
}
if (!unlink($tldInfoFile)) {
static::_echo_error("(FATAL) failed to remove stale 'TldInfo.php': $tldInfoFile",1);
}
}
if (!copy($newTldInfoFile,$tldInfoFile)) {
static::_echo_error("(FATAL) failed to save new 'TldInfo.php': $tldInfoFile",1);
}
echo "saved new 'TldInfo.php' file\n";
}
private static function _echo_error(string $str, int $fatal_exit_status=null) : void {
if (substr($str,0,1)!=="\n") {
$str .= "\n";
}
$str = static::ME_NAME . ": ".$str;
if (\PHP_SAPI=='cli') {
fwrite(\STDERR,$str);
} else {
echo $str ;
}
if (is_int($fatal_exit_status)) {
exit($fatal_exit_status);
}
}
const TLD_INFO_SOURCE_START_CLASS = <<<SOURCE
<?php
namespace TldEnum;
class TldInfo {
SOURCE;
const TLD_INFO_SOURCE_START_TLD_INFO_CONST = <<<SOURCE
const TLD_INFO = [
SOURCE;
const TLD_INFO_SOURCE_END_TLD_INFO_CONST = <<<SOURCE
];
SOURCE;
const TLD_INFO_SOURCE_END_CLASS = <<<SOURCE
/**
* converts a TLD_INFO element into a TldInfoItem object
*
* @param array \$info element from \\TldEnum\\TldInfo::TLD_INFO
*
* @return \\TldEnum\\TldInfoItem
*/
public static function toInfoItem(array \$info) : TldInfoItem {
\$infoItem = new TldInfoItem;
foreach(\$infoItem as \$prop=>&\$val) {
if (isset(\$info[\$prop])) {
\$val = \$info[\$prop];
}
}
unset(\$prop);
unset(\$val);
return \$infoItem;
}
}
SOURCE;
};

View File

@ -0,0 +1,182 @@
#!/usr/bin/env php
<?php
new class() {
const ME_NAME = 'generate-php-tld-list.php';
const TLDS_CSV_PATH = __DIR__ . '/../../../tlds.csv';
const TLD_ENUM_PATH = __DIR__ . '/../../../formats/php/TldEnum/TldList.php';
private static $_quietMode = false;
public function __construct() {
$opt = getopt ( "q",['quiet']);
if (isset($opt['q']) || isset($opt['quiet'])) {
static::$_quietMode = true;
}
if (!static::$_quietMode) {
echo static::ME_NAME."\n";
echo " (c) 2017 Doug Bird, All Rights Reserved.\n";
echo " see README.md for licensing and other information\n";
echo " https://github.com/katmore/tld-enum#readme\n";
echo "\n";
echo " Generates new PHP format file 'TldList.php' from the 'tlds.csv' file\n";
echo "\n";
}
$fileTldsCsv = static::TLDS_CSV_PATH;
if (!is_file($fileTldsCsv) || !is_readable($fileTldsCsv)) {
static::_echo_error("(FATAL) not a readable path to 'tlds.csv': $fileTldsCsv",1);
}
$tldEnumFile = static::TLD_ENUM_PATH;
$tldEnumDir = pathinfo($tldEnumFile,\PATHINFO_DIRNAME);
if (file_exists($tldEnumFile)) {
if (!is_file($tldEnumFile)) {
static::_echo_error("(FATAL) existing path for 'TldList.php' was not a file as expected: $tldEnumFile",1);
}
if (!is_writable($tldEnumFile)) {
static::_echo_error("(FATAL) existing path for 'TldList.php' is not writable: $tldEnumFile",1);
}
} else {
if (!file_exists($tldEnumDir) || !is_dir($tldEnumDir)) {
static::_echo_error("(FATAL) path for 'TldList.php' directory does not exist as expected: $tldEnumDir",1);
}
if (!is_writable($tldEnumDir)) {
static::_echo_error("(FATAL) path for 'TldList.php' directory is not writeable: $tldEnumDir",1);
}
}
$existingMd5 = null;
if (file_exists($tldEnumFile)) {
$existingMd5 = md5_file($tldEnumFile);
$tldEnumBasename = pathinfo($tldEnumFile,\PATHINFO_FILENAME);
$backupTldEnumFile = $tldEnumDir . \DIRECTORY_SEPARATOR . "$tldEnumBasename-$existingMd5-backup.php";
if (!file_exists($backupTldEnumFile)) {
if (!copy($tldEnumFile,$backupTldEnumFile)) {
static::_echo_error("(FATAL) failed to create backup for 'TldList.php' (source: $tldEnumFile, dest: $backupTldEnumFile)",1);
}
}
}
if (false === ($newTldEnumFile = tempnam ( sys_get_temp_dir() , 'tld-enum-' ))) {
static::_echo_error("(FATAL) unable to initialize new 'TldList.php' file",1);
}
register_shutdown_function(function() use($newTldEnumFile) {
if (is_file($newTldEnumFile) && is_writable($newTldEnumFile)) {
unlink($newTldEnumFile);
}
});
$tldEnum = [];
if (($handle = fopen($fileTldsCsv, "r")) === false) {
static::_echo_error("(FATAL) unable to open 'tlds.csv' in read mode: $fileTldsCsv",1);
} else {
echo "reading 'tlds.csv'...";
$i=0;
while (($row = fgetcsv($handle, 1000, ",")) !== false) {
if (!count($row)) {
static::_echo_error("(FATAL) invalid 'tlds.csv' row #$i: $fileTldsCsv",1);
}
//echo $row[0]."\n";
$tldEnum []= $row[0];
$i++;
}
fclose($handle);
echo "done\n";
}
//echo "new TldList.php: $newTldEnumFile\n";
echo "generating new 'TldList.php' file...";
if (false === file_put_contents($newTldEnumFile,static::TLD_ENUM_SOURCE_START_CLASS)) {
static::_echo_error("(FATAL) failed to write to new 'TldList.php' file",1);
}
if (false === file_put_contents($newTldEnumFile,static::TLD_ENUM_SOURCE_START_TLD_ENUM_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldList.php' file",1);
}
$tldEnumExport = var_export($tldEnum,true);
$tldEnumExport = substr($tldEnumExport,strlen("array ("));
$tldEnumExport = substr($tldEnumExport,0,-1);
$tldEnumLine = [];
$i=0;
foreach(explode("\n",$tldEnumExport) as $line) {
$filteredLine = preg_replace('/[0-9]+ => \'/', "'", $line);
$tldEnumLine []= $filteredLine;
$i++;
}
unset($line);
if (false === file_put_contents($newTldEnumFile, " [".implode("\n",$tldEnumLine)."]",\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldList.php' file",1);
}
if (false === file_put_contents($newTldEnumFile,static::TLD_ENUM_SOURCE_END_TLD_ENUM_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldList.php' file",1);
}
if (false === file_put_contents($newTldEnumFile,static::TLD_ENUM_SOURCE_END_CLASS,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldList.php' file",1);
}
echo "done\n";
if ($existingMd5!==null) {
$newTldEnumMd5 = md5_file($newTldEnumFile);
if ($existingMd5 == $newTldEnumMd5) {
static::_echo_error("(NOTICE) ignoring newly generated 'TldList.php' file that is identical to the existing file (md5: $existingMd5, path: $tldEnumFile)");
return;
}
if (!unlink($tldEnumFile)) {
static::_echo_error("(FATAL) failed to remove stale 'TldList.php': $tldEnumFile",1);
}
}
if (!copy($newTldEnumFile,$tldEnumFile)) {
static::_echo_error("(FATAL) failed to save new 'TldList.php': $tldEnumFile",1);
}
echo "saved new 'TldList.php' file\n";
}
private static function _echo_error(string $str, int $fatal_exit_status=null) : void {
if (substr($str,0,1)!=="\n") {
$str .= "\n";
}
$str = static::ME_NAME . ": ".$str;
if (\PHP_SAPI=='cli') {
fwrite(\STDERR,$str);
} else {
echo $str ;
}
if (is_int($fatal_exit_status)) {
exit($fatal_exit_status);
}
}
const TLD_ENUM_SOURCE_START_CLASS = <<<SOURCE
<?php
namespace TldEnum;
class TldList {
SOURCE;
const TLD_ENUM_SOURCE_START_TLD_ENUM_CONST = <<<SOURCE
const TLD_LIST =
SOURCE;
const TLD_ENUM_SOURCE_END_TLD_ENUM_CONST = <<<SOURCE
;
SOURCE;
const TLD_ENUM_SOURCE_END_CLASS = <<<SOURCE
}
SOURCE;
};

View File

@ -0,0 +1,179 @@
#!/usr/bin/env php
<?php
new class() {
const ME_NAME = 'generate-php-tld-type.php';
const TLDS_CSV_PATH = __DIR__ . '/../../../tlds.csv';
const TLD_TYPE_PATH = __DIR__ . '/../../../formats/php/TldEnum/TldType.php';
private static $_quietMode = false;
public function __construct() {
$opt = getopt ( "q",['quiet']);
if (isset($opt['q']) || isset($opt['quiet'])) {
static::$_quietMode = true;
}
if (!static::$_quietMode) {
echo static::ME_NAME."\n";
echo " (c) 2017 Doug Bird, All Rights Reserved.\n";
echo " see README.md for licensing and other information\n";
echo " https://github.com/katmore/tld-enum#readme\n";
echo "\n";
echo " Generates new PHP format file 'TldType.php' from the 'tlds.csv' file\n";
echo "\n";
}
$fileTldsCsv = static::TLDS_CSV_PATH;
if (!is_file($fileTldsCsv) || !is_readable($fileTldsCsv)) {
static::_echo_error("(FATAL) not a readable path to 'tlds.csv': $fileTldsCsv",1);
}
$tldTypeFile = static::TLD_TYPE_PATH;
$tldTypeDir = pathinfo($tldTypeFile,\PATHINFO_DIRNAME);
if (file_exists($tldTypeFile)) {
if (!is_file($tldTypeFile)) {
static::_echo_error("(FATAL) existing path for 'TldType.php' was not a file as expected: $tldTypeFile",1);
}
if (!is_writable($tldTypeFile)) {
static::_echo_error("(FATAL) existing path for 'TldType.php' is not writable: $tldTypeFile",1);
}
} else {
if (!file_exists($tldTypeDir) || !is_dir($tldTypeDir)) {
static::_echo_error("(FATAL) path for 'TldType.php' directory does not exist as expected: $tldTypeDir",1);
}
if (!is_writable($tldTypeDir)) {
static::_echo_error("(FATAL) path for 'TldType.php' directory is not writeable: $tldTypeDir",1);
}
}
$existingMd5 = null;
if (file_exists($tldTypeFile)) {
$existingMd5 = md5_file($tldTypeFile);
$tldTypeBasename = pathinfo($tldTypeFile,\PATHINFO_FILENAME);
$backupTldTypeFile = $tldTypeDir . \DIRECTORY_SEPARATOR . "$tldTypeBasename-$existingMd5-backup.php";
if (!file_exists($backupTldTypeFile)) {
if (!copy($tldTypeFile,$backupTldTypeFile)) {
static::_echo_error("(FATAL) failed to create backup for 'TldType.php' (source: $tldTypeFile, dest: $backupTldTypeFile)",1);
}
}
}
if (false === ($newTldTypeFile = tempnam ( sys_get_temp_dir() , 'tld-enum-' ))) {
static::_echo_error("(FATAL) unable to initialize new 'TldType.php' file",1);
}
register_shutdown_function(function() use($newTldTypeFile) {
if (is_file($newTldTypeFile) && is_writable($newTldTypeFile)) {
unlink($newTldTypeFile);
}
});
$tldType = [];
if (($handle = fopen($fileTldsCsv, "r")) === false) {
static::_echo_error("(FATAL) unable to open 'tlds.csv' in read mode: $fileTldsCsv",1);
} else {
echo "reading 'tlds.csv'...";
$i=0;
while (($row = fgetcsv($handle, 1000, ",")) !== false) {
if (!count($row)) {
static::_echo_error("(FATAL) invalid 'tlds.csv' row #$i: $fileTldsCsv",1);
}
if (!isset($row[2])) {
static::_echo_error("(FATAL) invalid 'tlds.csv', missing column 3 on row #$i: $fileTldsCsv",1);
}
$domain = $row[0];
$type = $row[2];
$tldType[$domain] = $type;
$i++;
}
fclose($handle);
echo "done\n";
}
//echo "new TldType.php: $newTldTypeFile\n";
echo "generating new 'TldType.php' file...";
if (false === file_put_contents($newTldTypeFile,static::TLD_TYPE_SOURCE_START_CLASS)) {
static::_echo_error("(FATAL) failed to write to new 'TldType.php' file",1);
}
if (false === file_put_contents($newTldTypeFile,static::TLD_TYPE_SOURCE_START_TLD_TYPE_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldType.php' file",1);
}
$tldTypeExport = var_export($tldType, true);
$tldTypeExport = substr($tldTypeExport,strlen("array ("));
$tldTypeExport = substr($tldTypeExport,0,-1);
$tldTypeExport = ' ['.$tldTypeExport.']';
if (false === file_put_contents($newTldTypeFile, $tldTypeExport,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldType.php' file",1);
}
if (false === file_put_contents($newTldTypeFile,static::TLD_TYPE_SOURCE_END_TLD_TYPE_CONST,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldType.php' file",1);
}
if (false === file_put_contents($newTldTypeFile,static::TLD_TYPE_SOURCE_END_CLASS,\FILE_APPEND)) {
static::_echo_error("(FATAL) failed to write to new 'TldType.php' file",1);
}
echo "done\n";
if ($existingMd5!==null) {
$newTldTypeMd5 = md5_file($newTldTypeFile);
if ($existingMd5 == $newTldTypeMd5) {
static::_echo_error("(NOTICE) ignoring newly generated 'TldType.php' file that is identical to the existing file (md5: $existingMd5, path: $tldTypeFile)");
return;
}
if (!unlink($tldTypeFile)) {
static::_echo_error("(FATAL) failed to remove stale 'TldType.php': $tldTypeFile",1);
}
}
if (!copy($newTldTypeFile,$tldTypeFile)) {
static::_echo_error("(FATAL) failed to save new 'TldType.php': $tldTypeFile",1);
}
echo "saved new 'TldType.php' file\n";
}
private static function _echo_error(string $str, int $fatal_exit_status=null) : void {
if (substr($str,0,1)!=="\n") {
$str .= "\n";
}
$str = static::ME_NAME . ": ".$str;
if (\PHP_SAPI=='cli') {
fwrite(\STDERR,$str);
} else {
echo $str ;
}
if (is_int($fatal_exit_status)) {
exit($fatal_exit_status);
}
}
const TLD_TYPE_SOURCE_START_CLASS = <<<SOURCE
<?php
namespace TldEnum;
class TldType {
SOURCE;
const TLD_TYPE_SOURCE_START_TLD_TYPE_CONST = <<<SOURCE
const TLD_TYPE =
SOURCE;
const TLD_TYPE_SOURCE_END_TLD_TYPE_CONST = <<<SOURCE
;
SOURCE;
const TLD_TYPE_SOURCE_END_CLASS = <<<SOURCE
}
SOURCE;
};

View File

@ -0,0 +1,230 @@
#!/usr/bin/env node
const meName = 'generate-tlds-csv.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const request = require('async-request');
const cheerio = require('cheerio');
const countries = require('country-data').countries;
const country = require('countryjs');
const stringify = require('csv-stringify');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const tmp = require('tmp');
tmp.setGracefulCleanup();
const fileTldDescCsv = path.dirname(require.main.filename) + '/../../../assets/tld-desc.csv';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
const urlTldsAlpha = 'http://data.iana.org/TLD/tlds-alpha-by-domain.txt';
const urlDomainsDb = 'https://www.iana.org/domains/root/db';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates the canonical 'tlds.csv' csv file by downloading resources from iana.org");
console.log("");
}
(async() => {
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
process.stdout.write("downloading '" + urlTldsAlpha + "'...");
const responseTldsAlpha = await request(urlTldsAlpha);
if (responseTldsAlpha.statusCode != 200) {
console.log("error");
console.error(meName + ": (FATAL) response status code " + responseTldsAlpha.statusCode + " from URL '" + urlTldsAlpha + "'");
process.exit(1);
return;
}
if (!responseTldsAlpha.body) {
console.log("error");
console.error(meName + ": (FATAL) empty response body " + responseTldsAlpha.statusCode + " from URL '" + urlTldsAlpha + "'");
process.exit(1);
return;
}
const fileTldsAlphaTxt = tmpDir.name + '/tlds-alpha-by-domain.txt';
const fileNewTldsCsv = tmpDir.name + '/tlds.csv';
fs.writeFileSync(fileTldsAlphaTxt, responseTldsAlpha.body, 'utf8');
fs.writeFileSync(fileNewTldsCsv, '', 'utf8');
console.log('success');
process.stdout.write("downloading '" + urlDomainsDb + "'...");
const responseDomainsDb = await request(urlDomainsDb);
if (responseDomainsDb.statusCode != 200) {
console.log("error");
console.error(meName + ": (FATAL) response status code " + responseDomainsDb.statusCode + " from URL '" + urlDomainsDb + "'");
process.exit(1);
return;
}
if (!responseDomainsDb.body) {
console.log("error");
console.error(meName + ": (FATAL) empty response body " + responseDomainsDb.statusCode + " from URL '" + urlDomainsDb + "'");
process.exit(1);
return;
}
const htmlDomainsDb = responseDomainsDb.body;
var $ = cheerio.load(htmlDomainsDb);
console.log('success');
process.stdout.write("building country / TLD hashmap...");
let tld2CountryName = {};
let missingTld = [];
countries.all.forEach((c) => {
let tld = country.tld(c.alpha3, 'ISO3');
if (!tld) {
missingTld.push(c.alpha3);
return;
}
tld2CountryName[tld] = c.name;
});
console.log('done');
if (!program.quiet) {
console.log(meName + ': NOTICE: the following "countries" did not have an assigned top level domain: ' + missingTld.join(', '));
}
process.stdout.write("building description / TLD hashmap...");
let tld2Desc = {};
let parser = parse({ delimiter: ',' });
const csvPosMap = {
domain: 0,
description: 1,
}
parser.on('readable', function() {
let tldData;
while (tldData = parser.read()) {
let tld = {
domain: null,
description: null,
};
let prop;
for (prop in tld) {
if (typeof(tldData[csvPosMap[prop]]) !== 'undefined') {
tld[prop] = tldData[csvPosMap[prop]];
}
}
if (tld.domain && tld.description) {
tld2Desc[tld.domain] = tld.description;
}
}
});
parser.write(fs.readFileSync(fileTldDescCsv));
parser.end(function() {
console.log("done");
const tdPosMap = {
domain: 0,
type: 1,
manager: 2,
};
let tldSet = [];
process.stdout.write("parsing IANA data...");
$('#tld-table').find('tr').each((i, element) => {
let tld = {
domain: null,
type: null,
manager: null,
};
let tldData = [];
// console.log('i ' + i);
// console.log(element);
$(element).find("td").each((iTd, elementTd) => {
// console.log('iTd...');
// console.log(iTd);
tldData.push($(elementTd).text());
});
for (var prop in tld) {
if (typeof(tldData[tdPosMap[prop]]) !== 'undefined') {
tld[prop] = tldData[tdPosMap[prop]];
}
}
if (!tld.domain) {
return;
}
tld.domain = tld.domain.replace(/\s/g, '').replace(/\./g, '');
tldSet.push(tld);
});
console.log('done');
const stringifier = stringify({ delimiter: ',' });
stringifier.on('readable', () => {
let row;
while (row = stringifier.read()) {
fs.appendFileSync(fileNewTldsCsv, row, 'utf8')
}
});
process.stdout.write("serializing new 'tlds.csv'...");
for (var i = 0; i < tldSet.length; i++) {
let tld = tldSet[i];
let csvRow = [tld.domain];
if ((tld.type == 'country-code') && (typeof(tld2CountryName[tld.domain]) !== 'undefined')) {
csvRow.push(tld2CountryName[tld.domain]);
} else {
if (typeof(tld2Desc[tld.domain]) !== 'undefined') {
csvRow.push(tld2Desc[tld.domain]);
} else {
csvRow.push(tld.manager);
}
}
csvRow.push(tld.type);
stringifier.write(csvRow);
}
stringifier.end();
console.log('done');
if (fs.existsSync(fileTldsCsv)) {
const newMd5 = md5File.sync(fileNewTldsCsv);
const csvMd5 = md5File.sync(fileTldsCsv);
if (csvMd5 == newMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'tlds.csv' file that is identical to the existing file (md5: " + csvMd5 + ", path: " + fileTldsCsv + ")");
return;
}
const pathinfoTldsCsv = pathinfo(fileTldsCsv);
const fileBackupTldsCsv = pathinfoTldsCsv.dirname + pathinfoTldsCsv.sep + pathinfoTldsCsv.basename + '-' + csvMd5 + '-backup.csv';
if (!fs.existsSync(fileBackupTldsCsv)) {
fs.copySync(fileTldsCsv, fileBackupTldsCsv);
}
}
process.stdout.write("saving new 'tlds.csv'...");
fs.copySync(fileNewTldsCsv, fileTldsCsv);
console.log('done');
});
})();

View File

@ -0,0 +1,129 @@
#!/usr/bin/env node
const meName = 'generate-js-tld-info.js';
process.on('unhandledRejection', error => {
console.error(meName + ": (FATAL)", error);
process.exit(1);
});
const countries = require('country-data').countries;
const country = require('countryjs');
const parse = require('csv-parse');
const fs = require('fs-extra');
const path = require('path');
const md5File = require('md5-file');
const pathinfo = require('pathinfo');
const program = require('commander');
const stringify = require('csv-stringify');
const tmp = require('tmp');
//tmp.setGracefulCleanup();
const fileTldsTsv = path.dirname(require.main.filename) + '/../../../formats/tsv/tlds.tsv';
const fileTldsCsv = path.dirname(require.main.filename) + '/../../../tlds.csv';
program
.option('-q, --quiet', 'Quiet Mode')
.parse(process.argv);
if (!program.quiet) {
console.log(meName);
console.log(" (c) 2017 Doug Bird, All Rights Reserved.");
console.log(" see README.md for licensing and other information");
console.log(" https://github.com/katmore/tld-enum#readme");
console.log("");
console.log(" Generates new Tab-Separated-Value format file 'tlds.tsv' from the 'tlds.csv' file");
console.log("");
}
(async() => {
const tldInfoStartTldInfo = 'module.exports = ';
const tldInfoEndTldInfo = ';';
const tmpDir = tmp.dirSync({ unsafeCleanup: true });
const fileNewTldsTsv = tmpDir.name + '/tlds.tsv';
let existingMd5 = null;
process.stdout.write("reading 'tlds.csv'...");
let parser = parse({ delimiter: ',' });
let tldInfo = [];
let i = 0;
parser.on('readable', function() {
let row, domain, desc, type;
while (row = parser.read()) {
if (!row.length) {
console.error(meName + ": (FATAL) invalid 'tlds.csv' row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[1] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 2 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
if (typeof row[2] === 'undefined') {
console.error(meName + ": (FATAL) invalid 'tlds.csv', missing column 3 on row #" + i + " in '" + fileTldsCsv+"'");
process.exit(1);
}
domain=row[0];
desc=row[1];
type=row[2];
tldInfo.push({
'domain' : domain,
'description' : desc,
'type' : type,
});
i++;
}
});
parser.write(fs.readFileSync(fileTldsCsv));
parser.end(function() {
console.log("done");
const stringifier = stringify({ delimiter: "\t" });
stringifier.on('readable', () => {
let row;
while (row = stringifier.read()) {
fs.appendFileSync(fileNewTldsTsv, row, 'utf8')
}
});
process.stdout.write("generating new 'tlds.tsv'...");
for (var i = 0; i < tldInfo.length; i++) {
let tld = tldInfo[i];
let csvRow = [tld.domain];
csvRow.push(tld.description);
csvRow.push(tld.type);
stringifier.write(csvRow);
}
stringifier.end();
console.log('done');
if (fs.existsSync(fileTldsTsv)) {
const newMd5 = md5File.sync(fileNewTldsTsv);
const tsvMd5 = md5File.sync(fileTldsTsv);
if (tsvMd5 == newMd5) {
console.error(meName + ": (NOTICE) ignoring newly generated 'tlds.tsv' file that is identical to the existing file (md5: " + tsvMd5 + ", path: " + fileTldsTsv + ")");
return;
}
const pathinfoTldsTsv = pathinfo(fileTldsTsv);
const fileBackupTldsTsv = pathinfoTldsTsv.dirname + pathinfoTldsTsv.sep + pathinfoTldsTsv.basename + '-' + tsvMd5 + '-backup.csv';
if (!fs.existsSync(fileBackupTldsTsv)) {
fs.copySync(fileTldsTsv, fileBackupTldsTsv);
}
}
process.stdout.write("saving new 'tlds.csv'...");
fs.copySync(fileNewTldsTsv, fileTldsTsv);
console.log('done');
});
})();

185
bin/devel/update-formats.sh Executable file
View File

@ -0,0 +1,185 @@
#!/bin/sh
# Updates the tlds.csv file using IANA data and re-generates the format files
#
# @author D. Bird <retran@gmail.com>
#
#
# script localization
#
ME_NAME=$(basename $0)
ME_DIR="/$0"; ME_DIR=${ME_DIR%/*}; ME_DIR=${ME_DIR:-.}; ME_DIR=${ME_DIR#/}/; ME_DIR=$(cd "$ME_DIR"; pwd)
HELPER_DIR=$ME_DIR/helpers
#
# parse options
#
OPTION_STATUS=0
QUIET_MODE=0
HELP_MODE=0
FORCE_PHP=0
SKIP_PHP=0
SKIP_CSV=0
while getopts :?qhua-: arg; do { case $arg in
q) QUIET_MODE=1;;
h|u|a) HELP_MODE=1;;
-) LONG_OPTARG="${OPTARG#*=}"; case $OPTARG in
quiet) QUIET_MODE=1;;
force-php) FORCE_PHP=1;;
skip-php) SKIP_PHP=1;;
skip-csv) SKIP_CSV=1;;
help|usage|about) HELP_MODE=1;;
*) >&2 echo "$ME_NAME: unrecognized long option --$OPTARG"; OPTION_STATUS=2;;
esac ;;
*) >&2 echo "$ME_NAME: unrecognized option -$OPTARG"; OPTION_STATUS=2;;
esac } done
shift $((OPTIND-1)) # remove parsed options and args from $@ list
[ "$OPTION_STATUS" != "0" ] && { >&2 echo "$ME_NAME: (FATAL) one or more invalid options"; exit $OPTION_STATUS; }
[ -z "$@" ] || { >&2 echo "$ME_NAME: (FATAL) one or more unrecognized positional arguments ($@)"; exit 2; }
#
# --skip-php --force-php sanity check
#
if ( [ "$FORCE_PHP" = "1" ] && [ "$SKIP_PHP" = "1" ] ); then
>&2 echo "$ME_NAME: --skip-php cannot be used with --force-php"
exit 2
fi
#
# display welcome message
#
if ( [ "$QUIET_MODE" != "1" ] || [ "$HELP_MODE" = "1" ] ); then
echo "TLD update utility"
echo "(c) 2017-2018 Doug Bird, All Rights Reserved."
echo "https://github.com/katmore/tld-enum#readme"
fi
#
# apply help mode
#
if [ "$HELP_MODE" = "1" ]; then
echo ""
echo "Updates the tlds.csv file using IANA data and re-generates the format files."
echo ""
echo "usage:"
echo " $ME_NAME [-h]|[-q][format file options...]"
echo ""
echo "-h,--help: Print a help message and exit."
echo "-q,--quiet: Print only critical messages."
echo ""
echo "format file options:"
echo " --force-php: Creating the PHP format files is mandatory."
echo " --skip-php: Always skip creating the PHP format files."
echo " --skip-csv: Use existing tlds.csv and do not download new data from IANA."
exit 0
fi
#
# enforce dependencies
#
DEPENDENCY_STATUS=0
node -v > /dev/null 2>&1 || {
>&2 echo "$ME_NAME: failed dependency check for 'node', command is missing or inaccessible"
DEPENDENCY_STATUS=1
}
if [ "$SKIP_PHP" != "1" ]; then
php -v > /dev/null 2>&1 || {
if [ "$FORCE_PHP" = "1" ]; then
>&2 echo "$ME_NAME: failed dependency check for 'php', command is missing or inaccessible"
DEPENDENCY_STATUS=1
else
SKIP_PHP=1
>&2 echo "$ME_NAME: (NOTICE) skipping PHP format generation, 'php' command is missing or inaccessible"
fi
}
fi
if [ "$DEPENDENCY_STATUS" != "0" ]; then
>&2 echo "$ME_NAME: (FATAL) one or more required dependency checks failed"
exit 1
fi
#
# helper execution wrapper function
#
helper() { helper_file=$1; helper_label=$2
if [ "$QUIET_MODE" = "1" ]; then
cmd_output=$("$HELPER_DIR/$helper_file" 2>&1)
cmd_status=$?
[ "$cmd_status" != "0" ] && [ -n "$cmd_output" ] && >&2 printf "$cmd_output\n"
else
printf "generate new $helper_label format file: started\n"
"$HELPER_DIR/$helper_file" -q
cmd_status=$?
[ "$cmd_status" = "0" ] && printf "generate new $helper_label format file: success\n"
fi
if [ "$cmd_status" != "0" ]; then
>&2 echo "$ME_NAME: (FATAL) helper for $helper_label failed ($helper_file exit status $cmd_status)"
exit 1
fi
}
#
# execute CSV helper
#
if [ "$SKIP_CSV" != "1" ]; then
helper generate-tlds-csv.js "CSV 'tlds.csv'"
else
[ "$QUIET_MODE" = "0" ] && printf "$ME_NAME: (NOTICE) skipped downloading IANA data and skipped generating new CSV\n"
fi
#
# execute TSV helper
#
helper generate-tsv-tlds-tsv.js "Tab-Separated-Values 'tlds.tsv'"
#
# execute JavaScript helpers
#
helper generate-js-tld-desc.js "JavaScript 'desc.js'"
helper generate-js-tld-info.js "JavaScript 'info.js'"
helper generate-js-tld-list.js "JavaScript 'list.js'"
helper generate-js-tld-type.js "JavaScript 'type.js'"
#
# execute JSON helpers
#
helper generate-json-tld-desc.js "JSON 'tld-desc.json'"
helper generate-json-tld-info.js "JSON 'tld-info.json'"
helper generate-json-tld-list.js "JSON 'tld-list.json'"
helper generate-json-tld-type.js "JSON 'tld-type.json'"
#
# execute PHP helpers
#
if [ "$SKIP_PHP" != "1" ]; then
helper generate-php-tld-desc.php "PHP 'TldDesc.php'"
helper generate-php-tld-info.php "PHP 'TldInfo.php'"
helper generate-php-tld-list.php "PHP 'TldList.php'"
helper generate-php-tld-type.php "PHP 'TldType.php'"
else
[ "$QUIET_MODE" = "0" ] && printf "$ME_NAME: (NOTICE) skipped generating PHP format files\n"
fi
#
# success
#
if [ "$QUIET_MODE" = "0" ]; then
printf "format file updates were successful\n"
fi

18
composer.json Normal file
View File

@ -0,0 +1,18 @@
{
"name": "katmore/tld-enum",
"description": "Lists of every ICANN TLD in multiple formats",
"homepage": "https://github.com/katmore/tld-enum",
"autoload": {
"psr-4": {
"TldEnum\\": "formats/php/TldEnum/"
}
},
"license": [
"MIT",
"GPL-3.0+"
],
"bin": ["bin/update-formats.sh"],
"require": {
"php": ">=7.2.1"
}
}

21
examples/js-demo.js Normal file
View File

@ -0,0 +1,21 @@
const tldList = require('../formats/js/tld-enum/list');
console.log("There are " + tldList.length + " IANA TLDs");
let tldCheck;
tldCheck = "com";
console.log("Is '" + tldCheck + "' a real TLD?");
if (tldList.indexOf(tldCheck.toLowerCase()) != -1) {
console.log(" yes");
} else {
console.log(" no");
}
tldCheck = "somethingWeird";
console.log("Is '" + tldCheck + "' a real TLD?");
if (tldList.indexOf(tldCheck.toLowerCase()) != -1) {
console.log(" yes");
} else {
console.log(" no");
}

27
examples/js-desc-demo.js Normal file
View File

@ -0,0 +1,27 @@
const tldDesc = require('../formats/js/tld-enum/desc');
console.log("There are " + Object.keys(tldDesc).length + " IANA TLDs");
console.log("");
let tldCheck;
tldCheck = "com";
console.log("Is '" + tldCheck + "' a real TLD?");
if (typeof(tldDesc[tldCheck.toLowerCase()])!=='undefined') {
console.log("yes");
console.log("description: "+tldDesc[tldCheck.toLowerCase()]);
} else {
console.log("no");
}
console.log("");
tldCheck = "somethingWeird";
console.log("Is '" + tldCheck + "' a real TLD?");
if (typeof(tldDesc[tldCheck.toLowerCase()])!=='undefined') {
console.log("yes");
console.log("description: "+tldDesc[tldCheck.toLowerCase()]);
} else {
console.log("no");
}

37
examples/js-info-demo.js Normal file
View File

@ -0,0 +1,37 @@
const tldInfo = require('../formats/js/tld-enum').info;
console.log("There are " + Object.keys(tldInfo).length + " IANA TLDs");
console.log("");
let tldCheck, foundTld;
tldCheck = "com";
console.log("Is '" + tldCheck + "' a real TLD?");
foundTld = tldInfo.find(function(e) {
return e.domain==tldCheck.toLowerCase();
});
if (typeof(foundTld)!=='undefined') {
console.log("yes");
console.log(JSON.stringify(foundTld, null, 2));
} else {
console.log("no");
}
console.log("");
tldCheck = "somethingWeird";
console.log("Is '" + tldCheck + "' a real TLD?");
foundTld = tldInfo.find(function(e) {
return e.domain==tldCheck.toLowerCase();
});
if (typeof(foundTld)!=='undefined') {
console.log("yes");
console.log(JSON.stringify(foundTld, null, 2));
} else {
console.log("no");
}

27
examples/js-type-demo.js Normal file
View File

@ -0,0 +1,27 @@
const tldType = require('../formats/js/tld-enum/type');
console.log("There are " + Object.keys(tldType).length + " IANA TLDs");
console.log("");
let tldCheck;
tldCheck = "com";
console.log("Is '" + tldCheck + "' a real TLD?");
if (typeof(tldType[tldCheck.toLowerCase()])!=='undefined') {
console.log("yes");
console.log("type: "+tldType[tldCheck.toLowerCase()]);
} else {
console.log("no");
}
console.log("");
tldCheck = "somethingWeird";
console.log("Is '" + tldCheck + "' a real TLD?");
if (typeof(tldType[tldCheck.toLowerCase()])!=='undefined') {
console.log("yes");
console.log("type: "+tldType[tldCheck.toLowerCase()]);
} else {
console.log("no");
}

View File

@ -0,0 +1,32 @@
<?php
use TldEnum\TldDesc;
require __DIR__ . '/../vendor/autoload.php';
echo "There are " . count(TldDesc::TLD_DESC) . " IANA TLDs\n";
echo "\n";
$tldCheck = "com";
echo "Is '$tldCheck' a real TLD?\n";
if (isset(TldDesc::TLD_DESC[strtolower($tldCheck)])) {
echo "yes\n";
echo "description: ".TldDesc::TLD_DESC[strtolower($tldCheck)]."\n";
} else {
echo "no\n";
}
echo "\n";
$tldCheck = "somethingWeird";
echo "Is '$tldCheck' a real TLD?\n";
if (isset(TldDesc::TLD_DESC[strtolower($tldCheck)])) {
echo "yes\n";
echo "description: ".TldDesc::TLD_DESC[strtolower($tldCheck)]."\n";
} else {
echo "no\n";
}
echo "\n";

View File

@ -0,0 +1,54 @@
<?php
use TldEnum\TldInfo;
require __DIR__ . '/../vendor/autoload.php';
echo "There are " . count(TldInfo::TLD_INFO) . " IANA TLDs\n";
echo "\n";
$tldCheck = "com";
echo "Is '$tldCheck' a real TLD?\n";
$foundTld = false;
foreach(TldInfo::TLD_INFO as $tldInfoElem) {
$tldInfoItem = TldInfo::toInfoItem($tldInfoElem);
if ($tldInfoItem->domain === strtolower($tldCheck)) {
echo "yes\n";
print_r($tldInfoItem);
$foundTld = true;
break 1;
}
}
unset($tldInfoElem);
if (!$foundTld) {
echo "no\n";
}
echo "\n";
$tldCheck = "somethingWeird";
echo "Is '$tldCheck' a real TLD?\n";
$foundTld = false;
foreach(TldInfo::TLD_INFO as $tldInfoElem) {
$tldInfoItem = TldInfo::toInfoItem($tldInfoElem);
if ($tldInfoItem->domain === strtolower($tldCheck)) {
echo "yes\n";
print_r($tldInfoItem);
$foundTld = true;
break 1;
}
}
unset($tldInfoElem);
if (!$foundTld) {
echo "no\n";
}

View File

@ -0,0 +1,32 @@
<?php
use TldEnum\TldType;
require __DIR__ . '/../vendor/autoload.php';
echo "There are " . count(TldType::TLD_TYPE) . " IANA TLDs\n";
echo "\n";
$tldCheck = "com";
echo "Is '$tldCheck' a real TLD?\n";
if (isset(TldType::TLD_TYPE[strtolower($tldCheck)])) {
echo "yes\n";
echo "type: ".TldType::TLD_TYPE[strtolower($tldCheck)]."\n";
} else {
echo "no\n";
}
echo "\n";
$tldCheck = "somethingWeird";
echo "Is '$tldCheck' a real TLD?\n";
if (isset(TldType::TLD_TYPE[strtolower($tldCheck)])) {
echo "yes\n";
echo "type: ".TldType::TLD_TYPE[strtolower($tldCheck)]."\n";
} else {
echo "no\n";
}
echo "\n";

22
examples/php-demo.php Normal file
View File

@ -0,0 +1,22 @@
<?php
use TldEnum\TldList;
require __DIR__ . '/../vendor/autoload.php';
echo "There are " . count(TldList::TLD_LIST) . " IANA TLDs\n";
$tldCheck = "com";
echo "Is '$tldCheck' a real TLD?\n";
if (in_array(strtolower($tldCheck), TldList::TLD_LIST)) {
echo " yes\n";
} else {
echo " no\n";
}
$tldCheck = "somethingWeird";
echo "Is '$tldCheck' a real TLD?\n";
if (in_array(strtolower($tldCheck), TldList::TLD_LIST)) {
echo " yes\n";
} else {
echo " no\n";
}

0
formats/.gitkeep Normal file
View File

1579
formats/js/tld-enum/desc.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,6 @@
module.exports = {
'desc' : require('./desc'),
'info' : require('./info'),
'list' : require('./list'),
'type' : require('./type'),
}

7887
formats/js/tld-enum/info.js Normal file

File diff suppressed because it is too large Load Diff

1579
formats/js/tld-enum/list.js Normal file

File diff suppressed because it is too large Load Diff

1579
formats/js/tld-enum/type.js Normal file

File diff suppressed because it is too large Load Diff

1579
formats/json/tld-desc.json Normal file

File diff suppressed because it is too large Load Diff

7887
formats/json/tld-info.json Normal file

File diff suppressed because it is too large Load Diff

1579
formats/json/tld-list.json Normal file

File diff suppressed because it is too large Load Diff

1579
formats/json/tld-type.json Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
<?php
namespace TldEnum;
/**
* @deprecated
*/
class TldEnum {
const TLD_ENUM = TldList::TLD_LIST;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
<?php
namespace TldEnum;
class TldInfoItem {
public $domain;
public $description;
public $type;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1577
formats/tsv/tlds.tsv Normal file

File diff suppressed because it is too large Load Diff

1402
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

32
package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "tld-enum",
"version": "2.0.7",
"description": "Lists of every ICANN TLD in multiple formats",
"main": "formats/js/tld-enum",
"repository": {
"type": "git",
"url": "git+https://github.com/katmore/tld-enum.git"
},
"author": "Doug Bird",
"license": "MIT",
"bugs": {
"url": "https://github.com/katmore/tld-enum/issues"
},
"homepage": "https://github.com/katmore/tld-enum#readme",
"devDependencies": {
"async-request": "^1.2.0",
"cheerio": "^1.0.0-rc.2",
"commander": "^2.15.1",
"country-data": "0.0.31",
"countryjs": "^1.8.0",
"csv-parse": "^2.5.0",
"csv-stringify": "^2.1.0",
"es6-promisify": "^5.0.0",
"fs": "0.0.1-security",
"fs-extra": "^5.0.0",
"md5-file": "^3.2.3",
"pathinfo": "^0.1.0",
"request": "^2.87.0",
"tmp": "0.0.33"
}
}

579
tldinfo.sh Executable file
View File

@ -0,0 +1,579 @@
#!/bin/sh
#
# Provides information on IANA top-level domains
#
# For usage, execute with the "--help" option
#
# @author D. Bird <retran@gmail.com>
#
#
# script localization
#
ME_NAME=$(basename $0)
ME_DIR="/$0"; ME_DIR=${ME_DIR%/*}; ME_DIR=${ME_DIR:-.}; ME_DIR=${ME_DIR#/}/; ME_DIR=$(cd "$ME_DIR"; pwd)
ME_SHORTNAME='tldinfo'
#
# number of seconds before warning about TLD database needing an update
# 2592000 seconds = 30 days
#
CHECKED_TIME_TTL=2592000
#
# data root dir
#
SYS_DATA_ROOT=/usr/share/$ME_SHORTNAME
USER_DATA_ROOT=~/.$ME_SHORTNAME
SYS_INSTALL_PATH=/usr/bin/$ME_SHORTNAME
#
# parse options
#
OPTION_STATUS=0
HELP_MODE=0
FORCE_PHP=0
SKIP_PHP=0
SKIP_CSV=0
UPDATE_MODE=0
SHOW_DESC=0
SHOW_TYPE=0
STARTS_WITH=0
INSTALL_MODE=0
while getopts :?qhuaV-: arg; do { case $arg in
h|u|a|V) HELP_MODE=1;;
-) LONG_OPTARG="${OPTARG#*=}"; case $OPTARG in
help|usage|about|version) HELP_MODE=1;;
update) UPDATE_MODE=1;;
show-description) SHOW_DESC=1;;
show-type) SHOW_TYPE=1;;
starts-with) STARTS_WITH=1;;
install) INSTALL_MODE=1;;
*) >&2 echo "$ME_NAME: unrecognized long option --$OPTARG"; OPTION_STATUS=2;;
esac ;;
*) >&2 echo "$ME_NAME: unrecognized option -$OPTARG"; OPTION_STATUS=2;;
esac } done
shift $((OPTIND-1)) # remove parsed options and args from $@ list
[ "$OPTION_STATUS" != "0" ] && { >&2 echo "$ME_NAME: (FATAL) one or more invalid options"; exit $OPTION_STATUS; }
[ "$UPDATE_MODE" != 1 ] && [ -n "$1" ] && { SEARCH=$1; shift; }
[ -z "$@" ] || { >&2 echo "$ME_NAME: (FATAL) one or more unrecognized positional arguments ($@)"; exit 2; }
[ "$STARTS_WITH" = 1 ] && [ -z "$SEARCH" ] && { >&2 echo "$ME_NAME: (FATAL) must specify <SEARCH> argument when using --starts-with option"; exit 2; }
#
# apply help mode
#
if [ "$HELP_MODE" = "1" ]; then
echo "tldinfo"
echo "(c) 2017-2018 Doug Bird, All Rights Reserved."
echo "https://github.com/katmore/tld-enum#readme"
echo ""
echo "Prints IANA top-level domains."
echo ""
echo "usage:"
echo " $ME_NAME [-h][--update]|[display options...][[--starts-with] <SEARCH>]"
echo ""
echo "-h,--help: Print a help message and exit."
echo "--update: Update TLD database as needed and exit."
echo "--install: Install a global 'tldinfo' binary and exit."
echo ""
echo "display options:"
echo "--show-description: Always print domain description."
echo "--show-type: Always print domain type."
echo ""
echo "<SEARCH>:"
echo " Optionally, only print matching domain(s)."
echo " --starts-with: Match domain(s) starting with <SEARCH>."
echo ""
echo "Exit Codes:"
echo " 0 : Success"
echo " 1 : General Error"
echo " 3 : Internal Error"
echo " 20 : No match found for <SEARCH>"
exit 0
fi
#
# dependency checks
#
USE_CURL=0; USE_WGET=0; FOUND_HTTP_CLIENT=0
curl -V > /dev/null 2>&1 && {
USE_CURL=1; FOUND_HTTP_CLIENT=1
} || {
wget -V > /dev/null 2>&1 && {
USE_WGET=1; FOUND_HTTP_CLIENT=1
} }
#
# Prints the url an http request ultimately redirects to.
# Usage:
# print_http_redirect <url>
# Arguments:
# <url>
# The request url
# (Required)
#
print_http_redirect() { url=$1
if [ "$FOUND_HTTP_CLIENT" != 1 ]; then
>&2 echo "$ME_NAME: (failed dependency check) http client binary is not available ('curl' or 'wget')"
exit 1
fi
[ -n "$url" ] || {
>&2 echo "$ME_NAME: (internal error) missing 'url' argument to 'print_http_redirect'"
exit 3
}
if [ "$USE_CURL" = 1 ]; then
hout=$(curl -Ls -o /dev/null -w %{url_effective} $url) || {
>&2 echo "$ME_NAME: (fatal error) 'curl (...print_http_redirect)' failed with exit status $?"
exit 1
}
[ -n "$hout" ] || {
>&2 echo "$ME_NAME: (fatal error) empty URL result from 'curl (...print_http_redirect)'"
exit 1
}
fi
if [ "$USE_WGET" = 1 ]; then
hout=$(wget $url --server-response -O /dev/null 2>&1 | awk '(NR==1){SRC=$3;} /^ Location: /{DEST=$2} END{ print SRC, DEST}' | awk '{print $2}') || {
>&2 echo "$ME_NAME: (fatal error) 'wget (...print_http_redirect)' failed with exit status $?"
exit 1
}
[ -n "$hout" ] || {
>&2 echo "$ME_NAME: (fatal error) empty URL result from 'wget (...print_http_redirect)'"
exit 1
}
fi
echo $hout
}
#
# Saves the response body of an http request to a file.
# Usage:
# http_download <url> <path>
# Arguments:
# <url>
# The request url
# (Required)
# <path>
# Path to save the response body to
# (Required)
#
http_download() { url=$1; path=$2
if [ "$FOUND_HTTP_CLIENT" != 1 ]; then
>&2 echo "$ME_NAME: (failed dependency check) http client binary is not available ('curl' or 'wget')"
exit 1
fi
[ -n "$url" ] || {
>&2 echo "$ME_NAME: (internal error) missing 'url' argument to 'http_download'"
exit 3
}
[ -n "$path" ] || {
>&2 echo "$ME_NAME: (internal error) missing 'path' argument to 'http_download'"
exit 3
}
if [ "$USE_CURL" = 1 ]; then
curl -sS $url > $path || {
>&2 echo "$ME_NAME: (fatal error) 'curl (...http_download)' failed with exit status $?"
exit 1
}
fi
if [ "$USE_WGET" = 1 ]; then
wget -O $path $url || {
>&2 echo "$ME_NAME: (fatal error) 'wget (...http_download)' failed with exit status $?"
exit 1
}
fi
return 0
}
#
# cleanup temp files
#
LATEST_TLDS_TEMP=
cleanup_temp_files() {
if ( [ -n "$LATEST_TLDS_TEMP" ] && [ -f "$LATEST_TLDS_TEMP" ] ); then
rm $LATEST_TLDS_TEMP
fi
}
trap cleanup_temp_files EXIT
#
# Prepares data file
# Usage:
# init_data_file <file-basename>
# Arguments:
# <file-basename>
# Basename of data file; for example. "release"
# (Required)
#
init_data_file() { file_basename=$1;
[ -n "$file_basename" ] || {
>&2 echo "$ME_NAME: (internal error) missing 'file_basename' argument to 'init_data_file'"
exit 3
}
if ( [ -d "$USER_DATA_ROOT" ] && [ "$INSTALL_MODE" != 1 ] ); then
path=$USER_DATA_ROOT/$file_basename
perm=660
else
path=$SYS_DATA_ROOT/$file_basename
perm=444
fi
if [ -f "$path" ]; then
touch $path 2>/dev/null || {
chmod $perm $path || {
>&2 echo "$ME_NAME: (fatal error) failed to initialize data file permission on '$path', do you need sudo?"
exit 1
}
touch $path || {
>&2 echo "$ME_NAME: (fatal error) failed to initialize data file '$path', do you need sudo?"
exit 1
}
return 0
}
chmod $perm $path || {
>&2 echo "$ME_NAME: (fatal error) failed to initialize data file permission on '$path', do you need sudo?"
exit 1
}
else
touch $path || {
>&2 echo "$ME_NAME: (fatal error) failed to initialize data file '$path', do you need sudo?"
exit 1
}
chmod $perm $path || {
>&2 echo "$ME_NAME: (fatal error) failed to initialize data file permission on '$path', do you need sudo?"
exit 1
}
fi
}
#
# Prepares the data root directory
# Usage:
# init_data_root
# Arguments:
# (none)
#
init_data_root() {
if ( [ -d "$USER_DATA_ROOT" ] && [ "$INSTALL_MODE" != 1 ] ); then
root_path=$USER_DATA_ROOT
perm=770
else
root_path=$SYS_DATA_ROOT
perm=775
fi
if [ -d "$root_path" ]; then
if [ ! -w "$root_path" ]; then
>&2 echo "$ME_NAME: (fatal error) missing write permission on data root '$root_path', do you need sudo?"
exit 1
fi
else
data_root_parent=$(dirname $root_path)
if [ ! -w "$(dirname $data_root_parent)" ]; then
>&2 echo "$ME_NAME: (fatal error) missing write permission on data root parent directory '$data_root_parent', do you need sudo?"
exit 1
fi
fi
mkdir -p $root_path || {
>&2 echo "$ME_NAME: (fatal error) failed to create data root '$root_path', do you need sudo?"
exit 1
}
chmod $perm $root_path || {
>&2 echo "$ME_NAME: (fatal error) failed set permissions on data root '$root_path', do you need sudo?"
exit 1
}
init_data_file "checked-time"
init_data_file "release"
}
#
# Prints the contents of a data file.
# Usage:
# print_data_file_contents <file-basename>
# Arguments:
# <file-basename>
# Basename of data file; for example. "release"
# (Required)
#
print_data_file_contents() { file_basename=$1
[ -n "$file_basename" ] || {
>&2 echo "$ME_NAME: (internal error) missing 'file_basename' argument to 'print_data_file_contents'"
exit 3
}
if ( [ -d "$USER_DATA_ROOT" ] && [ "$INSTALL_MODE" != 1 ] ); then
path=$USER_DATA_ROOT/$file_basename
else
path=$SYS_DATA_ROOT/$file_basename
fi
if [ -f "$path" ]; then
cat $path || {
>&2 echo "$ME_NAME: (fatal error) failed to read contents of data file '$path'; do you need sudo?"
exit 1
}
fi
}
#
# Print the path to a data file.
# Usage:
# print_data_file_path <file-basename> <contents>
# Arguments:
# <file-basename>
# Basename of data file; for example. "release"
# (Required)
#
print_data_file_path() { file_basename=$1
[ -n "$file_basename" ] || {
>&2 echo "$ME_NAME: (internal error) missing 'file_basename' argument to 'write_data_file'"
exit 3
}
if ( [ -d "$USER_DATA_ROOT" ] && [ "$INSTALL_MODE" != 1 ] ); then
path=$USER_DATA_ROOT/$file_basename
else
path=$SYS_DATA_ROOT/$file_basename
fi
echo $path
}
#
# wheather to download TLDS database from CDN
#
INITIAL_TLDS_DOWNLOAD=0
#
# install mode
#
if [ "$INSTALL_MODE" = 1 ]; then
ME_PATH=$ME_DIR/$ME_NAME
if [ ! -f "$ME_PATH" ]; then
>&2 echo "$ME_NAME: (fatal error) unable to determine installation source file"
exit 1
fi
if [ ! -w $(dirname $SYS_INSTALL_PATH) ]; then
>&2 echo "$ME_NAME: (fatal error) missing write permission to install path parent dir, do you need sudo?"
exit 1
fi
cp -f $ME_PATH $SYS_INSTALL_PATH || {
>&2 echo "$ME_NAME: (fatal error) failed to copy script to install path"
exit 1
}
init_data_root
INITIAL_TLDS_DOWNLOAD=1
fi
#
# prepare tld database
#
TLDS_PATH=$(print_data_file_path tlds.tsv)
PROJECT_TLDS_PATH=$ME_DIR/formats/tsv/tlds.tsv
if ( [ "$INSTALL_MODE" = 0 ] && [ ! -f "$TLDS_PATH" ] ); then
if ( [ ! -d "$SYS_DATA_ROOT" ] && [ ! -d "$USER_DATA_ROOT" ] ); then
mkdir -p $USER_DATA_ROOT || {
>&2 echo "$ME_NAME: (fatal error) failed to prepare user data dir"
exit 1
}
fi
init_data_root
TLDS_PATH=$(print_data_file_path tlds.tsv)
if [ -f "$PROJECT_TLDS_PATH" ]; then
cp "$PROJECT_TLDS_PATH" "$TLDS_PATH" || {
>&2 echo "$ME_NAME: (fatal error) failed to copy 'tlds.tsv' to user data dir '$TLDS_PATH'"
exit 1
}
date +%s > $(print_data_file_path checked-time)
else
INITIAL_TLDS_DOWNLOAD=1
fi
fi
#
# determine wheather to check for update
#
CHECK_UPDATE=0
LAST_CHECKED_TIME=$(print_data_file_contents checked-time)
if [ -n "$LAST_CHECKED_TIME" ]; then
echo $LAST_CHECKED_TIME | grep -q "^[0-9]*$" && {
TIME_SINCE_LAST_CHECK=$(($(date +%s)-$LAST_CHECKED_TIME))
if [ "$TIME_SINCE_LAST_CHECK" -gt "$CHECKED_TIME_TTL" ]; then
CHECK_UPDATE=1
fi
}
fi
#
# check for updates and optionally apply update mode
#
if ( [ "$INITIAL_TLDS_DOWNLOAD" = 1 ] || [ "$UPDATE_MODE" = 1 ] || [ "$CHECK_UPDATE" = 1 ] ); then
CURRENT_RELEASE=$(print_data_file_contents release)
#
# tld-enum repo
#
GITHUB_REPO=katmore/tld-enum
#
# Github and Rawgit base URIs
#
RAWGIT_URI=https://cdn.rawgit.com
GITHUB_URI=https://github.com
#
# latest tld-enum release
#
LATEST_URL="$GITHUB_URI/$GITHUB_REPO/releases/latest"
#
# permanent Rawgit CDN URL to latest 'tlds.tsv'
#
LATEST_RELEASE=$(basename $(print_http_redirect $LATEST_URL))
#https://cdn.rawgit.com/katmore/tld-enum/cf601629/formats/tsv/tlds.tsv
LATEST_TLDS_TSV_URL="$RAWGIT_URI/$GITHUB_REPO/$LATEST_RELEASE/formats/tsv/tlds.tsv"
if ( [ "$INITIAL_TLDS_DOWNLOAD" = 1 ] || [ "$UPDATE_MODE" = 1 ] ); then
#
# if new release, download and update
#
if ( [ "$INITIAL_TLDS_DOWNLOAD" = 1 ] || [ "$CURRENT_RELEASE" != "$LATEST_RELEASE" ] ); then
if ( [ -d "$USER_DATA_ROOT" ] && [ "$INSTALL_MODE" != 1 ] ); then
perm=660
else
perm=444
fi
#
# prepare data root dir
#
init_data_root
#
# download 'tlds.tsv' from Rawgit to temp file
#
LATEST_TLDS_TEMP=$(mktemp)
http_download "$LATEST_TLDS_TSV_URL" "$LATEST_TLDS_TEMP"
#
# copy to path
#
mv $LATEST_TLDS_TEMP $TLDS_PATH
echo "$LATEST_RELEASE" > $(print_data_file_path release)
date +%s > $(print_data_file_path checked-time)
chmod $perm $(print_data_file_path release)
chmod $perm $(print_data_file_path checked-time)
chmod $perm $TLDS_PATH
echo "updated tlds.tsv to $LATEST_RELEASE"
else
echo "tlds.tsv is already up-to-date ($CURRENT_RELEASE)"
fi
if [ "$UPDATE_MODE" = 1 ]; then
exit 0
fi
else
if [ "$CURRENT_RELEASE" != "$LATEST_RELEASE" ]; then
>&2 echo "$ME_NAME: (current version '$CURRENT_RELEASE') a new release of 'tlds.tsv' is available (see '$ME_NAME --update'): $LATEST_RELEASE"
fi
fi
fi
#
# exit if install mode
#
if [ "$INSTALL_MODE" = 1 ]; then
echo "install '$(basename $SYS_INSTALL_PATH)' success"
exit 0
fi
#
# show description and type if domain <SEARCH> singleton
#
if ( [ -n "$SEARCH" ] && [ "$STARTS_WITH" = 0 ] ); then
SHOW_DESC=1; SHOW_TYPE=1
fi
if [ "$STARTS_WITH" = 1 ]; then
MATCH_COUNT=0
fi
#
# configre IFS with {tab} delimiter
#
IFS_OLD=$IFS
IFS=$(printf "\t")
#
# read tlds.tsv database
#
while read domain desc type; do
#
# apply <SEARCH> arg
#
if [ -n "$SEARCH" ]; then
if [ "$STARTS_WITH" = 0 ]; then
#
# match <SEARCH> singleton
#
if [ "$domain" != "$SEARCH" ]; then
continue
fi
else
#
# match --starts-with <SEARCH>
#
case $domain in
$SEARCH*) MATCH_COUNT=$((MATCH_COUNT+1));;
*) continue;;
esac
fi
fi
#
# concatenate TLD info for display
#
line=
if ( [ -z "$SEARCH" ] || [ "$STARTS_WITH" = 1 ] ); then
line=$domain
fi
[ "$SHOW_DESC" = 1 ] && {
[ -n "$line" ] && line="$line "
line="$line$desc"
}
[ "$SHOW_TYPE" = 1 ] && {
[ -n "$line" ] && line="$line "
line="$line$type"
}
printf "$line\n"
#
# exit on matched <SEARCH> singleton
#
if ( [ -n "$SEARCH" ] && [ "$STARTS_WITH" = 0 ] ); then
exit 0
fi
done < $TLDS_PATH
#
# set IFS to default delimiter
#
IFS=$IFS_OLD
#
# display summary for results of --starts-with <SEARCH>
#
if ( [ -n "$SEARCH" ] && ( [ "$STARTS_WITH" = 0 ] || [ "$MATCH_COUNT" = 0 ] ) ); then
[ "$STARTS_WITH" = 0 ] && >&2 echo "domain '$SEARCH' not found"
[ "$MATCH_COUNT" = 0 ] && >&2 echo "no domains starting with '$SEARCH' found"
exit 20
fi
if [ "$STARTS_WITH" = 1 ]; then
>&2 echo ""
if [ "$MATCH_COUNT" = "1" ]; then
>&2 echo "found 1 matching domain"
else
>&2 echo "found $MATCH_COUNT matching domains"
fi
fi
exit 0

1861
tlds.csv

File diff suppressed because it is too large Load Diff