diff --git a/.gitignore b/.gitignore
index 3826c85..aa7b2ab 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,10 @@
.eunit
deps
+tester
*.o
*.beam
*.plt
+*.swp
erl_crash.dump
ebin/*.beam
rel/example_project
diff --git a/README.md b/README.md
index dcd052b..bb339c7 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,64 @@
-# zx
-Zomp user client
+ZX: The Zomp client.
+
+Project information can be found at https://zxq9com/zx/ and https://github.com/zxq9/zx/
+
+
+ZX is delivered as a zip file containing:
+- `zomp.tar.gz`: An archive of a current working zx/zomp installation
+- `install.escript`: The main installation script
+- `install_unix` and `install_windows.cmd`: System-specific installation starters
+- `README.*` files such as this one
+- `LICENSE`
+- `notify.vbs`: A hacky VBS script to communicate with the Windows GUI during setup
+
+
+Installation
+
+To install ZX the `install.escript` program needs to run. In order to run it requires
+an Erlang environment to be envoked via the Escript interpreter. The system-specific
+installation starter scripts exist to locate the Erlang installation on the local
+system.
+
+The installer will unpack the ZX client and the relevant parts of Zomp (the package
+system underlying everything) to a directory in your home directory called "zomp".
+Once everything is unpacked it will add a link called `zx` to your command environment
+so that you can invoke zx the normal way.
+
+For further information about installation, consult the relevant README file in this
+directory.
+
+
+Features
+
+ZX has a number of features, most of them useful to developers and testers, but the
+most important feature is for users of programs. To run any program from a configured
+Zomp realm you run the command:
+ `zx run [program_name]`
+
+If the version number of the program is omitted (the typical case) then the latest
+version will always be installed and run. If a version number is provided then that
+specific version will be installed and run.
+
+ZX updates itself in the same manner it updates other installed programs. Occasionally
+you may receive a message indicating that you should re-run ZX because a newer version
+has been installed.
+
+At the moment ZX only works from the command line, though desktop links to launchers
+for GUI programs can be easily created.
+
+To create a desktop launcher for a program the launcher must invoke zx the same way
+you do from the command line:
+ `zx run [program_name]`
+
+In the event you need to write an installer for a system you have released through a
+Zomp repository all the installer needs to do is provide an icon set and create a
+launcher for the program that invokes zx the same way you would from the command line.
+
+The default Zomp realm is called "otpr". It is installed automatically and contains
+only FOSS software.
+
+
+ZX supports fetching and resolution of multiple realms at the same time, similar to
+how Linux distribution package managers usually permit configuration of multiple
+repository sources. To create and host your own, possibly private or proprietary, Zomp
+realm consult the Zomp documentation directly.
diff --git a/README.unix b/README.unix
new file mode 100644
index 0000000..6dfac7e
--- /dev/null
+++ b/README.unix
@@ -0,0 +1,29 @@
+Unix installation information for ZX
+
+
+This file contains information about how to install and run ZX on a Unix-type system.
+Consult README.md for general information about ZX as a program and as a project.
+
+Current versions of ZX and this file can be found at https://zxq9.com/zx/
+
+
+The unix startup script, "install_unix", is a BASH script and must be set as executable
+to be used. To set the script as executable:
+
+
+From the command line:
+
+To set the file permission correctly you will need to run the following command:
+ chmod +x install_unix
+Then to execute the installer you will need to run the following command:
+ ./install_unix
+
+
+From a GUI:
+
+If you are using a GUI you will need to do something like right-click the install_unix
+file, then select "properties" (or "permissions" or something similar), and change the
+file "mode" or "permissions" to include "execution" by the owner of the file (the user
+account you are currently using should be the owner of the file). Once the file is set
+as executable, run the file (probably by clicking on it).
+
diff --git a/README.windows b/README.windows
new file mode 100644
index 0000000..4e0ad05
--- /dev/null
+++ b/README.windows
@@ -0,0 +1,2 @@
+This file contains information about how to install and run ZX on a Windows system.
+Consult README.md for general information about ZX as a program and as a project.
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..8041787
--- /dev/null
+++ b/TODO
@@ -0,0 +1,75 @@
+- Make the create project command fail if the realm is invalid or the project bame already exists.
+
+- Add a module name conflict checker to ZX
+
+- Check whether the "repo name doesn't have to be the same as package, package doesn't have to be the same as main interface module" statement is true.
+
+- Make the "create user" bundle command check whether a user already exists at that realm.
+
+- Define the user bundle file contents: .zuf
+
+- Make it possible for a site administrator to declare specific versions for programs executed by clients.
+ Site adminisration via an organizational mirror should not be ricket science.
+
+- zomp nodes must report the realms they provide to upstream nodes to which they connect.
+ On redirect a list of hosts of the form [{zx:host(), [zx:realm()]}] must be provided to the downstream client.
+ This is the only way that downstream clients can determine which redirect hosts are useful to it.
+
+- Write a logging process.
+ Pick a log rotation scheme.
+ Eventually make it so that it can shed log loads in the event they get out of hand.
+
+- Create zx_daemon primes.
+ See below
+
+- Create persistent Windows alias for "zx" using the doskey command and adding it to the localuser's registry.
+ The installation escript will need to be updated to update the windows registry for HKEY_CURRENT_USER\Software\Microsoft\Command Processor
+ AutoRun will need to be set for %USERPROFILE%\zomp_alias.cmd
+ zomp_alias.cmd will need to do something like:
+ `doskey zx="werl.exe -pa %zx_dir%/ebin -run zx start $*"`
+ https://stackoverflow.com/questions/20530996/aliases-in-windows-command-prompt
+ Whatever happens, local users must be able to do `zx $@` and get the expected results.
+ Somewhat more tricky is how to make the creation of shortcuts less taxing on the lay user... ?
+
+
+New Feature: ZX Universal lock
+ Cross-instance communication
+ We don't want multiple zx_daemons doing funny things to the filesystem at the same time.
+ We DO want to be able to run multiple ZX programs to be able to run at the same time.
+ The solution is to guarantee that there is only ever one zx_daemon running at a given time.
+ IPC is messy to get straight across various host systems, but network sockets to localhost work in a normal way.
+ The first zx_daemon to start up will check for a lock file in the $ZOMP_HOME directory.
+ If there is no lock file present it will write a lock file with a timestamp, begin listening on a local port, and then update the lock file with the listening port number.
+ If it finds a lock file in $ZOMP_HOME it will attempt to connect to the running zx_daemon on the port indicated in the lock file. If only a timestamp exists with no port number then it will wait two seconds from the time indicated in the timestamp in the lock file before re-reading it -- if the second read still contains no port number it will remove the lock file and assume the primary role for the system itself.
+ If a connection cannot be established then it will assume the instance that had written the lock file failed to delete it for Bad Reasons, remove the lock file, open a port, and write its own lock file, taking over as the lead zx_daemon.
+
+ Any new zx_daemons that come up in the system will establish a connection to the zx_daemon that wrote the lock file, and proxy all requests through that primary zx_daemon.
+ When a zx_daemon that is acting as primary for the system retires it will complete all ongoing actions first, then begin queueing requests without acting on them, designate the oldest peer as the new leader, get confirmation that the new leader has a port open, update the original lock file with the new port number, redirect all connections to the new zx_daemon, and then retire.
+
+
+init(Args) ->
+ Stuff = do_stuff(),
+ Tries = 3,
+ Path = lock_file(),
+ case check_for_leader(Tries, Path) of
+ no_leader ->
+ {found, Socket} ->
+ end.
+
+
+check_for_leader(0, _) ->
+ no_leader;
+check_for_leader(Tries, Path) ->
+ case file:open(Path, [write, exclusive]) of
+ {ok, FD} -> become_leader(FD);
+ {error, eexist} -> contact_leader()
+ end.
+
+
+ case file:consult(Path) of
+ {ok, Data} ->
+
+ {error, enoexist} ->
+ check_file(Path);
+ end
+ end,
\ No newline at end of file
diff --git a/install.escript b/install.escript
new file mode 100755
index 0000000..6793603
--- /dev/null
+++ b/install.escript
@@ -0,0 +1,118 @@
+#! /usr/bin/env escript
+
+%% ZX install script
+
+-mode(compile).
+
+-spec main(Argv :: [string()]) -> no_return().
+
+main(_) ->
+ OS = os:type(),
+ ZompDir = zomp_dir(OS),
+ case filelib:is_dir(ZompDir) of
+ true ->
+ Message = "Installation directory (~ts) already exists. Aborting.~n",
+ ok = io:format(Message, [ZompDir]),
+ halt(0);
+ false ->
+ unpack(OS, ZompDir)
+ end.
+
+
+-spec unpack(OS, ZompDir) -> no_return()
+ when OS :: {Family :: unix | win32,
+ Name :: atom()},
+ ZompDir :: file:filename().
+
+unpack(OS, ZompDir) ->
+ BaseDir = filename:dirname(ZompDir),
+ ok = erl_tar:extract("zomp.tar.gz", [compressed, {cwd, BaseDir}]),
+ add_launcher(OS, ZompDir).
+
+
+-spec add_launcher(OS, ZompDir) -> no_return()
+ when OS :: {Family :: unix | win32,
+ Name :: atom()},
+ ZompDir :: file:filename().
+
+add_launcher({unix, linux}, ZompDir) ->
+ add_unix_link(ZompDir),
+ ok = io:format("Should attempt a FreeDesktop icon addition here.~n"),
+ halt(0);
+add_launcher({unix, _}, ZompDir) ->
+ add_unix_link(ZompDir),
+ halt(0);
+add_launcher({win32, nt}, _ZompDir) ->
+ ok = io:format("This is going to be a bit of a rodeo...~n"),
+ halt(0).
+
+
+-spec add_unix_link(ZompDir) -> ok
+ when ZompDir :: file:filename().
+
+add_unix_link(ZompDir) ->
+ Home = filename:dirname(ZompDir),
+ Link = filename:join(Home, "bin/zx"),
+ HomeBin = filename:dirname(Link),
+ Target = filename:join(ZompDir, "zx.sh"),
+ ok = filelib:ensure_dir(Link),
+ LinkCommand = "env LANG=en ln -s " ++ Target ++ " " ++ Link,
+ ModeCommand = "env LANG=en chmod +x " ++ Target,
+ ok = os_cmd(LinkCommand),
+ ok = os_cmd(ModeCommand),
+ Path = os:getenv("PATH"),
+ Parts = string:lexemes(Path, ":"),
+ Message =
+ case lists:member(HomeBin, Parts) of
+ true ->
+ "A link to ~ts has been created at ~ts.~n"
+ "~ts seems to be in $PATH already.~n"
+ "You should be able to run any zomp/zx program by typing `zx` "
+ "from anywhere in your system.~n"
+ "Creating launchers to the link that start specific programs may be "
+ "conveinent.~n"
+ "A desktop launcher would need to run the command:~n"
+ " zx run [some_program]~n"
+ "Or alternately (if ~~/bin/ is not in your launcher's $PATH):~n"
+ " ~ts run [some_program]~n";
+ false ->
+ "A link to ~ts has been created at ~ts. "
+ "~ts seems to be NOT in your $PATH. "
+ "You will need to add that to $PATH if you want to be able to run "
+ "zx by simply typing `zx` from anywhere in your system."
+ "Creating launchers to the link that start specific programs may be "
+ "conveinent.~n"
+ "A desktop launcher would need to run the command:~n"
+ " ~ts run [some_program]~n"
+ end,
+ io:format(Message, [Target, Link, HomeBin, Target]).
+
+
+-spec os_cmd(Command :: string()) -> ok.
+
+os_cmd(Command) ->
+ case os:cmd(Command) of
+ "" ->
+ ok;
+ Output ->
+ ok = io:format("Output of: ~tp~n", [Command]),
+ io:format("~ts~n", [Output])
+ end.
+
+
+-spec zomp_dir(OS) -> file:filename()
+ when OS :: {Family :: unix | win32,
+ Name :: atom()}.
+%% @private
+%% Check the host OS and return the absolute path to the zomp filesystem root.
+
+zomp_dir({unix, _}) ->
+ Home = os:getenv("HOME"),
+ filename:join(Home, "zomp");
+zomp_dir({win32, _}) ->
+ Path = os:getenv("LOCALAPPDATA"),
+ filename:join(Path, "zomp");
+zomp_dir(Unknown) ->
+ Message = "zx_install: ERROR Unknown host system type: ~tp",
+ ok = io:format(Message, [Unknown]),
+ halt(1).
diff --git a/install_unix b/install_unix
new file mode 100755
index 0000000..eb2a16c
--- /dev/null
+++ b/install_unix
@@ -0,0 +1,9 @@
+#! /bin/sh
+
+if escript_path=$(command -v escript)
+ then
+ echo "Using escript found at $escript_path"
+ escript install.escript
+ else
+ echo "Could not locate an Erlang installation."
+fi
diff --git a/install_windows.cmd b/install_windows.cmd
new file mode 100644
index 0000000..90b00d2
--- /dev/null
+++ b/install_windows.cmd
@@ -0,0 +1,16 @@
+@echo off
+setlocal
+
+set versions=9.2
+
+for %%v in (%versions%) do (
+ if exist "%ProgramFiles%\erl%%v\bin\escript.exe" (
+ "%ProgramFiles%\erl%%v\bin\escript.exe" install.escript
+ notify "Done!"
+ exit /b
+ )
+)
+
+echo Could not find the Erlang escript.exe executable
+notify "Could not locate a expected Erlang runtime. Consult the README.windows file in this directory for more information."
+exit /b
\ No newline at end of file
diff --git a/notify.vbs b/notify.vbs
new file mode 100644
index 0000000..99e38b5
--- /dev/null
+++ b/notify.vbs
@@ -0,0 +1,2 @@
+messageText = WScript.Arguments(0)
+MsgBox messageText
\ No newline at end of file
diff --git a/packup b/packup
new file mode 100755
index 0000000..bbe2964
--- /dev/null
+++ b/packup
@@ -0,0 +1,24 @@
+#! /usr/bin/env escript
+
+
+main([Version]) ->
+ Tar = "zomp.tar.gz",
+ ok = erl_tar:create(Tar, ["zomp"], [compressed]),
+ Zip = "zx-" ++ Version ++ ".zip",
+ ZipFiles =
+ ["install.escript",
+ "install_unix",
+ "install_windows.cmd",
+ "notify.vbs",
+ "README.md",
+ "README.unix",
+ "README.windows",
+ "LICENSE",
+ Tar],
+ {ok, Zip} = zip:create(Zip, ZipFiles),
+ ok = file:delete(Tar),
+ ok = io:format("Wrote ~ts.~n", [Zip]),
+ halt(0);
+main(_) ->
+ ok = io:format("Provide a single version or extension string as an argument.~n"),
+ halt(1).
diff --git a/zomp/etc/otpr/realm.conf b/zomp/etc/otpr/realm.conf
new file mode 100644
index 0000000..fbff7c3
--- /dev/null
+++ b/zomp/etc/otpr/realm.conf
@@ -0,0 +1,4 @@
+{realm, "otpr"}.
+{prime, {"otpr.psychobitch.party",11311}}.
+{sysop, "zxq9"}.
+{key, "zxq9-root"}.
diff --git a/zomp/etc/sys.conf b/zomp/etc/sys.conf
new file mode 100644
index 0000000..075c2dd
--- /dev/null
+++ b/zomp/etc/sys.conf
@@ -0,0 +1,5 @@
+{timeout,5}.
+{retries,3}.
+{maxconn,5}.
+{managed,[]}.
+{mirrors,[]}.
diff --git a/zomp/etc/version.txt b/zomp/etc/version.txt
new file mode 100644
index 0000000..6e8bf73
--- /dev/null
+++ b/zomp/etc/version.txt
@@ -0,0 +1 @@
+0.1.0
diff --git a/zomp/key/otpr/zxq9-root.pub.der b/zomp/key/otpr/zxq9-root.pub.der
new file mode 100644
index 0000000..636a48f
Binary files /dev/null and b/zomp/key/otpr/zxq9-root.pub.der differ
diff --git a/zomp/lib/otpr/zx/0.1.0/Emakefile b/zomp/lib/otpr/zx/0.1.0/Emakefile
new file mode 100644
index 0000000..68c7b67
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/Emakefile
@@ -0,0 +1 @@
+{"src/*", [debug_info, {i, "include/"}, {outdir, "ebin/"}]}.
diff --git a/zomp/lib/otpr/zx/0.1.0/LICENSE b/zomp/lib/otpr/zx/0.1.0/LICENSE
new file mode 100644
index 0000000..9cecc1d
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+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:
+
+ {project} Copyright (C) {year} {fullname}
+ 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
+.
+
+ 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
+.
diff --git a/zomp/lib/otpr/zx/0.1.0/ebin/zx.app b/zomp/lib/otpr/zx/0.1.0/ebin/zx.app
new file mode 100644
index 0000000..23be553
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/ebin/zx.app
@@ -0,0 +1,12 @@
+{application, zx,
+ [{description, "Zomp client program"},
+ {vsn, "0.1.0"},
+ {applications, [stdlib, kernel]},
+ {modules, [zx,
+ zx_sup,
+ zx_daemon,
+ zx_conn_sup,
+ zx_conn,
+ zx_lib,
+ zx_net]},
+ {mod, {zx, []}}]}.
diff --git a/zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl b/zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl
new file mode 100644
index 0000000..763af58
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl
@@ -0,0 +1,34 @@
+-export([log/2, log/3]).
+
+
+-spec log(Level, Format) -> ok
+ when Level :: info
+ | warning
+ | error,
+ Format :: string().
+%% @private
+%% @equiv log(Level, Format, [])
+
+log(Level, Format) ->
+ log(Level, Format, []).
+
+
+-spec log(Level, Format, Args) -> ok
+ when Level :: info
+ | warning
+ | error,
+ Format :: string(),
+ Args :: [term()].
+%% @private
+%% A logging abstraction to hide whatever logging back end is actually in use.
+%% Format must adhere to Erlang format string rules, and the arity of Args must match
+%% the provided format.
+
+log(Level, Format, Args) ->
+ Tag =
+ case Level of
+ info -> "[INFO]";
+ warning -> "[WARNING]";
+ error -> "[ERROR]"
+ end,
+ io:format("~s ~p: " ++ Format ++ "~n", [Tag, self() | Args]).
diff --git a/zomp/lib/otpr/zx/0.1.0/make_zx b/zomp/lib/otpr/zx/0.1.0/make_zx
new file mode 100755
index 0000000..1ca8077
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/make_zx
@@ -0,0 +1,39 @@
+#! /usr/bin/env escript
+
+-mode(compile).
+
+main(Args) ->
+ true = code:add_patha("ebin"),
+ up_to_date = make:all(),
+ ok = lists:foreach(fun dispatch/1, Args),
+ halt(0).
+
+
+dispatch("edoc") ->
+ ok = edoc();
+dispatch("dialyze") ->
+ ok = dialyze();
+dispatch("test") ->
+ ok = test();
+dispatch(Unknown) ->
+ ok = io:format("make_zx: Unknown directive: ~tp~n", [Unknown]),
+ halt(1).
+
+
+edoc() ->
+ ok = io:format("EDOC: Writing docs...~n"),
+ edoc:application(zx, ".", []).
+
+
+dialyze() ->
+ case dialyzer:run([{from, src_code}, {files_rec, ["./src"]}]) of
+ [] ->
+ io:format("Dialyzer found no errors and returned no warnings! Yay!~n");
+ Warnings ->
+ Messages = [dialyzer:format_warning(W) || W <- Warnings],
+ lists:foreach(fun io:format/1, Messages)
+ end.
+
+
+test() ->
+ io:format("TEST: If I only had a brain.~n").
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx.erl b/zomp/lib/otpr/zx/0.1.0/src/zx.erl
new file mode 100644
index 0000000..1d9fd9c
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx.erl
@@ -0,0 +1,659 @@
+%%% @doc
+%%% ZX
+%%%
+%%% A general dependency and packaging tool that works together with the zomp
+%%% package manager. Given a project directory with a standard layout, zx can:
+%%% - Initialize your project for packaging and semver tracking under zomp.
+%%% - Add dependencies (recursively) defined in any zomp repository realm.
+%%% - Update dependencies (recursively) defined in any zomp repository realm.
+%%% - Remove dependencies.
+%%% - Update, upgrade or run any application from source that zomp tracks.
+%%% - Locally install packages from files and locally stored public keys.
+%%% - Build and run a local project from source using zomp dependencies.
+%%% @end
+
+-module(zx).
+-behavior(application).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+
+-export([run/0, run/1]).
+-export([subscribe/1, unsubscribe/0]).
+-export([start/2, stop/1, stop/0]).
+-export([usage_exit/1]).
+
+-export_type([serial/0, package_id/0, package/0, realm/0, name/0, version/0,
+ identifier/0,
+ host/0,
+ key_id/0, key_name/0, key_data/0,
+ user_id/0, user_name/0, contact_info/0, user_data/0,
+ lower0_9/0, label/0,
+ package_meta/0]).
+
+-include("zx_logger.hrl").
+
+
+
+%%% Type Definitions
+
+-type serial() :: integer().
+-type package_id() :: {realm(), name(), version()}.
+-type package() :: {realm(), name()}.
+-type realm() :: lower0_9().
+-type name() :: lower0_9().
+-type version() :: {Major :: non_neg_integer() | z,
+ Minor :: non_neg_integer() | z,
+ Patch :: non_neg_integer() | z}.
+-type host() :: {string() | inet:ip_address(), inet:port_number()}.
+-type key_id() :: {realm(), key_name()}.
+-type key_name() :: lower0_9().
+-type key_data() :: {ID :: key_id(),
+ Public :: binary() | <<>>,
+ Private :: binary() | <<>>}.
+-type user_id() :: {realm(), user_name()}.
+-type user_name() :: label().
+-type contact_info() :: {Type :: string(), Data :: string()}.
+-type user_data() :: {ID :: user_id(),
+ RealName :: string(),
+ Contact :: contact_info(),
+ KeyData :: [key_data()]}.
+-type lower0_9() :: [$a..$z | $0..$9 | $_].
+-type label() :: [$a..$z | $0..$9 | $_ | $- | $.].
+-type package_meta() :: #{package_id := package_id(),
+ deps := [package_id()],
+ type := app | lib}.
+
+
+
+%%% Command Dispatch
+
+-spec run() -> no_return().
+
+run() ->
+ run([]).
+
+
+-spec run(Args) -> no_return()
+ when Args :: [string()].
+%% Dispatch work functions based on the nature of the input arguments.
+
+run(["help"]) ->
+ usage_exit(0);
+run(["run", PackageString | Args]) ->
+ ok = start(),
+ run(PackageString, Args);
+run(["runlocal" | ArgV]) ->
+ ok = start(),
+ run_local(ArgV);
+run(["init", "app", PackageString]) ->
+ ok = compatibility_check([unix]),
+ zx_local:initialize(app, PackageString);
+run(["init", "lib", PackageString]) ->
+ ok = compatibility_check([unix]),
+ zx_local:initialize(lib, PackageString);
+run(["install", PackageFile]) ->
+ zx_local:assimilate(PackageFile);
+run(["set", "dep", PackageString]) ->
+ zx_local:set_dep(PackageString);
+run(["set", "version", VersionString]) ->
+ ok = compatibility_check([unix]),
+ zx_local:set_version(VersionString);
+run(["verup", Level]) ->
+ ok = compatibility_check([unix]),
+ zx_local:verup(Level);
+run(["list", "realms"]) ->
+ zx_loca:list_realms();
+run(["list", "packages", Realm]) ->
+ ok = start(),
+ zx_local:list_packages(Realm);
+run(["list", "versions", PackageName]) ->
+ ok = start(),
+ zx_local:list_versions(PackageName);
+run(["add", "realm", RealmFile]) ->
+ zx_local:add_realm(RealmFile);
+run(["drop", "dep", PackageString]) ->
+ PackageID = zx_lib:package_id(PackageString),
+ zx_local:drop_dep(PackageID);
+run(["drop", "key", Realm, KeyName]) ->
+ zx_key:drop({Realm, KeyName});
+run(["drop", "realm", Realm]) ->
+ zx_local:drop_realm(Realm);
+run(["package"]) ->
+ {ok, TargetDir} = file:get_cwd(),
+ zx_local:package(TargetDir);
+run(["package", TargetDir]) ->
+ case filelib:is_dir(TargetDir) of
+ true ->
+ zx_local:package(TargetDir);
+ false ->
+ ok = log(error, "Target directory ~tp does not exist!", [TargetDir]),
+ halt(22)
+ end;
+run(["dialyze"]) ->
+ zx_local:dialyze();
+run(["create", "user", Realm, Name]) ->
+ zx_local:create_user(Realm, Name);
+run(["create", "keypair"]) ->
+ zx_key:grow_a_pair();
+run(["create", "plt"]) ->
+ zx_local:create_plt();
+run(["create", "realm"]) ->
+ zx_local:create_realm();
+run(["create", "realmfile", Realm]) ->
+ zx_local:create_realmfile(Realm);
+run(["list", "pending", PackageName]) ->
+ zx_auth:list_pending(PackageName);
+run(["list", "resigns", Realm]) ->
+ zx_auth:list_resigns(Realm);
+run(["submit", PackageFile]) ->
+ zx_auth:submit(PackageFile);
+run(["review", PackageString]) ->
+ zx_auth:review(PackageString);
+run(["approve", PackageString]) ->
+ PackageID = zx_lib:package_id(PackageString),
+ zx_auth:approve(PackageID);
+run(["reject", PackageString]) ->
+ PackageID = zx_lib:package_id(PackageString),
+ zx_auth:reject(PackageID);
+run(["accept", PackageString]) ->
+ zx_auth:accept(PackageString);
+run(["add", "packager", Package, UserName]) ->
+ zx_auth:add_packager(Package, UserName);
+run(["add", "maintainer", Package, UserName]) ->
+ zx_auth:add_maintainer(Package, UserName);
+run(["add", "sysop", Package, UserName]) ->
+ zx_auth:add_sysop(Package, UserName);
+run(["add", "package", PackageName]) ->
+ zx_auth:add_package(PackageName);
+run(_) ->
+ usage_exit(22).
+
+
+-spec compatibility_check(Platforms) -> ok | no_return()
+ when Platforms :: unix | win32.
+%% @private
+%% Some commands only work on specific platforms because they leverage some specific
+%% aspect on that platform, but not common to all. ATM this is mostly developer
+%% commands that leverage things universal to *nix/posix shells but not Windows.
+%% If equivalent procedures are written in Erlang then these restrictions can be
+%% avoided -- but it is unclear whether there are any Erlang developers even using
+%% Windows, so for now this is the bad version of the solution.
+
+compatibility_check(Platforms) ->
+ {Family, Name} = os:type(),
+ case lists:member(Family, Platforms) of
+ true ->
+ ok;
+ false ->
+ Message = "Unfortunately this command is not available on ~tp ~tp",
+ ok = log(error, Message, [Family, Name]),
+ halt(0)
+ end.
+
+
+
+%%% Application Start/Stop
+
+-spec start() -> ok | {error, Reason :: term()}.
+%% @doc
+%% An alias for `application:ensure_started(zx)', meaning it is safe to call this
+%% function more than once, or within a system where you are unsure whether zx is
+%% already running (perhaps due to complex dependencies that require zx already).
+%% In the typical case this function does not ever need to be called, because the
+%% zx_daemon is always started in the background whenever an application is started
+%% using the command `zx run [app_id]'.
+%% @equiv application:ensure_started(zx).
+
+start() ->
+ application:ensure_started(zx).
+
+
+-spec stop() -> ok | {error, Reason :: term()}.
+%% @doc
+%% A safe wrapper for `application:stop(zx)'. Similar to `ensure_started/1,2', returns
+%% `ok' in the case that zx is already stopped.
+
+stop() ->
+ case application:stop(zx) of
+ ok -> ok;
+ {error, {not_started, zx}} -> ok;
+ Error -> Error
+ end.
+
+
+%%% Application Callbacks
+
+-spec start(StartType, StartArgs) -> Result
+ when StartType :: normal,
+ StartArgs :: [],
+ Result :: {ok, pid()}.
+%% @private
+%% Application callback. Not to be called directly.
+
+start(normal, []) ->
+ ok = application:ensure_started(inets),
+ zx_daemon:start_link().
+
+
+-spec stop(term()) -> ok.
+%% @private
+%% Application callback. Not to be called directly.
+
+stop(_) ->
+ ok.
+
+
+
+%%% Daemon Controls
+
+-spec subscribe(package()) -> ok | {error, Reason :: term()}.
+%% @doc
+%% Initiates the zx_daemon and instructs it to subscribe to a package.
+%%
+%% Any events in the Zomp network that apply to the subscribed package will be
+%% forwarded to the process that originally called subscribe/1. How the original
+%% caller reacts to these notifications is up to the author -- not reply or "ack"
+%% is expected.
+%%
+%% Package subscriptions can be used as the basis for user notification of updates,
+%% automatic upgrade restarts, package catalog tracking, etc.
+
+subscribe(Package) ->
+ case application:start(?MODULE, normal) of
+ ok -> zx_daemon:subscribe(Package);
+ Error -> Error
+ end.
+
+
+-spec unsubscribe() -> ok | {error, Reason :: term()}.
+%% @doc
+%% Unsubscribes from package updates.
+
+unsubscribe() ->
+ zx_daemon:unsubscribe().
+
+
+
+%%% Execution of application
+
+-spec run(Identifier, RunArgs) -> no_return()
+ when Identifier :: string(),
+ RunArgs :: [string()].
+%% @private
+%% Given a program Identifier and a list of Args, attempt to locate the program and its
+%% dependencies and run the program. This implies determining whether the program and
+%% its dependencies are installed, available, need to be downloaded, or are inaccessible
+%% given the current system condition (they could also be bogus, of course). The
+%% Identifier must be a valid package string of the form `realm-appname[-version]'
+%% where the `realm()' and `name()' must follow Zomp package naming conventions and the
+%% version should be represented as a semver in string form (where ommitted elements of
+%% the version always default to whatever is most current).
+%%
+%% Once the target program is running, this process, (which will run with the registered
+%% name `zx') will sit in an `exec_wait' state, waiting for either a direct message from
+%% a child program or for calls made via zx_lib to assist in environment discovery.
+%%
+%% If there is a problem anywhere in the locating, discovery, building, and loading
+%% procedure the runtime will halt with an error message.
+
+run(Identifier, RunArgs) ->
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ ok = start(),
+ FuzzyID =
+ case zx_lib:package_id(Identifier) of
+ {ok, Fuzzy} ->
+ Fuzzy;
+ {error, invalid_package_string} ->
+ error_exit("Bad package string: ~ts", [Identifier], ?LINE)
+ end,
+ {ok, PackageID} = ensure_installed(FuzzyID),
+ ok = build(PackageID),
+ Dir = zx_lib:package_dir(PackageID),
+ {ok, Meta} = zx_lib:read_project_meta(Dir),
+ execute(PackageID, Meta, Dir, RunArgs).
+
+
+
+%%% Execution of local project
+
+-spec run_local(RunArgs) -> no_return()
+ when RunArgs :: [term()].
+%% @private
+%% Execute a local project from source from the current directory, satisfying dependency
+%% requirements via the locally installed zomp lib cache. The project must be
+%% initialized as a zomp project (it must have a valid `zomp.meta' file).
+%%
+%% The most common use case for this function is during development. Using zomp support
+%% via the local lib cache allows project authors to worry only about their own code
+%% and use zx commands to add or drop dependencies made available via zomp.
+
+run_local(RunArgs) ->
+ {ok, Meta} = zx_lib:read_project_meta(),
+ PackageID = maps:get(package_id, Meta),
+ ok = zx_lib:build(),
+ {ok, Dir} = file:get_cwd(),
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ ok = start(),
+ execute(PackageID, Meta, Dir, RunArgs).
+
+
+-spec execute(PackageID, Meta, Dir, RunArgs) -> no_return()
+ when PackageID :: package_id(),
+ Meta :: package_meta(),
+ Dir :: file:filename(),
+ RunArgs :: [string()].
+%% @private
+%% Execution prep common to all packages.
+
+execute(PackageID, Meta, Dir, RunArgs) ->
+ PackageString = zx_lib:package_string(PackageID),
+ ok = log(info, "Preparing ~ts...", [PackageString]),
+ Type = maps:get(type, Meta),
+ Deps = maps:get(deps, Meta),
+ case zx_daemon:fetch(Deps) of
+ {{ok, _}, {error, []}} ->
+ ok = lists:foreach(fun install/1, Deps),
+ ok = lists:foreach(fun build/1, Deps),
+ execute(Type, PackageID, Dir, Meta, RunArgs);
+ {{ok, _}, {error, Errors}} ->
+ error_exit("Failed package fetches: ~tp", [Errors], ?LINE)
+ end.
+
+
+-spec execute(Type, PackageID, Meta, Dir, RunArgs) -> no_return()
+ when Type :: app | lib,
+ PackageID :: package_id(),
+ Meta :: package_meta(),
+ Dir :: file:filename(),
+ RunArgs :: [string()].
+%% @private
+%% Gets all the target application's ducks in a row and launches them, then enters
+%% the exec_wait/1 loop to wait for any queries from the application.
+
+execute(app, PackageID, Meta, Dir, RunArgs) ->
+ PackageString = zx_lib:package_string(PackageID),
+ ok = log(info, "Starting ~ts.", [PackageString]),
+ Name = element(2, PackageID),
+ AppMod = list_to_atom(Name),
+ ok = zx_daemon:pass_meta(Meta, Dir),
+ ok = ensure_all_started(AppMod),
+ ok = pass_argv(AppMod, RunArgs),
+ log(info, "Launcher complete.");
+execute(lib, PackageID, _, _, _) ->
+ Message = "Lib ~ts is available on the system, but is not a standalone app.",
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = log(info, Message, [PackageString]),
+ halt(0).
+
+
+-spec ensure_all_started(AppMod) -> ok
+ when AppMod :: module().
+%% @private
+%% Wrap a call to application:ensure_all_started/1 to selectively provide output
+%% in the case any dependencies are actually started by the call. Might remove this
+%% depending on whether SASL winds up becoming a standard part of the system and
+%% whether it becomes common for dependencies to all signal their own start states
+%% somehow.
+
+ensure_all_started(AppMod) ->
+ case application:ensure_all_started(AppMod) of
+ {ok, []} -> ok;
+ {ok, Apps} -> log(info, "Started ~tp", [Apps])
+ end.
+
+
+-spec pass_argv(AppMod, Args) -> ok
+ when AppMod :: module(),
+ Args :: [string()].
+%% @private
+%% Check whether the AppMod:accept_argv/1 is implemented. If so, pass in the
+%% command line arguments provided.
+
+pass_argv(AppMod, Args) ->
+ case lists:member({accept_argv, 1}, AppMod:module_info(exports)) of
+ true -> AppMod:accept_argv(Args);
+ false -> ok
+end.
+
+
+
+
+-spec ensure_installed(PackageID) -> Result | no_return()
+ when PackageID :: package_id(),
+ Result :: {ok, ActualID :: package_id()}.
+%% @private
+%% Given a PackageID, check whether it is installed on the system, and if not, ensure
+%% that the package is either in the cache or can be downloaded. If all attempts at
+%% locating or acquiring the package fail, then exit with an error.
+
+ensure_installed(PackageID = {Realm, Name, Version}) ->
+ case resolve_installed_version(PackageID) of
+ exact -> {ok, PackageID};
+ {ok, Installed} -> {ok, {Realm, Name, Installed}};
+ not_found -> fetch_one({Realm, Name, Version})
+ end.
+
+
+-spec fetch_one(PackageID) -> {ok, ActualID} | no_return()
+ when PackageID :: package_id(),
+ ActualID :: package_id().
+%% @private
+%% A helper function to deal with the special case of downloading and installing a
+%% single primary application package with a possibly incomplete version designator.
+%% All other fetches are for arbitrarily long lists of package IDs with complete
+%% version numbers (dependency fetches).
+
+fetch_one(PackageID) ->
+ case zx_daemon:fetch([PackageID]) of
+ {{ok, [ActualID]}, {error, []}} ->
+ ok = install(ActualID),
+ {ok, ActualID};
+ {{ok, []}, {error, [{PackageID, Reason}]}} ->
+ error_exit("Package fetch failed with: ~tp", [Reason], ?LINE)
+ end.
+
+
+-spec resolve_installed_version(PackageID) -> Result
+ when PackageID :: package_id(),
+ Result :: not_found
+ | exact
+ | {ok, Installed :: version()}.
+%% @private
+%% Resolve the provided PackageID to the latest matching installed package directory
+%% version if one exists, returning a value that indicates whether an exact match was
+%% found (in the case of a full version input), a version matching a partial version
+%% input was found, or no match was found at all.
+
+resolve_installed_version({Realm, Name, Version}) ->
+ PackageDir = filename:join(["lib", Realm, Name]),
+ case filelib:is_dir(PackageDir) of
+ true -> resolve_installed_version(PackageDir, Version);
+ false -> not_found
+ end.
+
+
+resolve_installed_version(PackageDir, Version) ->
+ DirStrings = filelib:wildcard("*", PackageDir),
+ Versions = lists:fold(fun tuplize/2, [], DirStrings),
+ zx_lib:find_latest_compatible(Version, Versions).
+
+
+tuplize(String, Acc) ->
+ case zx_lib:string_to_version(String) of
+ {ok, Version} -> [Version | Acc];
+ _ -> Acc
+ end.
+
+
+
+%%% Package utilities
+
+
+-spec install(package_id()) -> ok.
+%% @private
+%% Install a package from the cache into the local system.
+%% Before calling this function it must be known that:
+%% - The zsp file is in the cache
+%% - The zsp file is valid
+%% - This function will only be called on startup by the launch process
+%% - The package is not already installed
+%% - If this function crashes it will completely halt the system
+
+install(PackageID) ->
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = log(info, "Installing ~ts", [PackageString]),
+ ZrpFile = filename:join("zsp", zx_lib:namify_zsp(PackageID)),
+ Files = zx_lib:extract_zsp_or_die(ZrpFile),
+ TgzFile = zx_lib:namify_tgz(PackageID),
+ {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files),
+ {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files),
+ Meta = binary_to_term(MetaBin),
+ {KeyID, Signature} = maps:get(sig, Meta),
+ {ok, PubKey} = zx_key:load(public, KeyID),
+ ok = ensure_package_dirs(PackageID),
+ PackageDir = filename:join("lib", PackageString),
+ ok = zx_lib:force_dir(PackageDir),
+ ok = zx_key:verify(TgzData, Signature, PubKey),
+ ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageDir}]),
+ log(info, "~ts installed", [PackageString]).
+
+
+-spec build(package_id()) -> ok.
+%% @private
+%% Given an AppID, build the project from source and add it to the current lib path.
+
+build(PackageID) ->
+ {ok, CWD} = file:get_cwd(),
+ ok = file:set_cwd(zx_lib:package_dir(PackageID)),
+ ok = zx_lib:build(),
+ file:set_cwd(CWD).
+
+
+
+%%% Directory & File Management
+
+
+-spec ensure_package_dirs(package_id()) -> ok.
+%% @private
+%% Procedure to guarantee that directory locations necessary for the indicated app to
+%% run have been created or halt execution.
+
+ensure_package_dirs(PackageID = {Realm, Name, _}) ->
+ Package = {Realm, Name},
+ PackageHome = zx_lib:package_dir(PackageID),
+ PackageData = zx_lib:package_dir("var", Package),
+ PackageConf = zx_lib:package_dir("etc", Package),
+ Dirs = [PackageHome, PackageData, PackageConf],
+ ok = lists:foreach(fun zx_lib:force_dir/1, Dirs),
+ log(info, "Created dirs:~n\t~ts~n\t~ts~n\t~ts", Dirs).
+
+
+
+%%% Usage
+
+
+-spec usage_exit(Code) -> no_return()
+ when Code :: integer().
+%% @private
+%% A convenience function that will display the zx usage message before halting
+%% with the provided exit code.
+
+usage_exit(Code) ->
+ ok = usage(),
+ halt(Code).
+
+
+-spec usage() -> ok.
+%% @private
+%% Display the zx command line usage message.
+
+usage() ->
+ T =
+"ZX usage: zx [command] [object] [args]~n"
+"~n"
+"User Actions:~n"
+" zx help~n"
+" zx run PackageID [Args]~n"
+" zx runlocal [Args]~n"
+" zx list realms~n"
+" zx list packages Realm~n"
+" zx list versions PackageID~n"
+" zx latest PackageID~n"
+" zx add realm RealmFile~n"
+" zx drop realm Realm~n"
+" zx install PackageID~n"
+" zx logpath [Package [1-10]]~n"
+" zx status~n"
+" zx set timeout Value~n"
+" zx set mirror Realm Host:Port~n"
+"~n"
+"Developer/Packager/Maintainer Actions:~n"
+" zx create project [app | lib] PackageID~n"
+" zx init Type PackageID~n"
+" zx list deps [PackageID]~n"
+" zx set dep PackageID~n"
+" zx drop dep PackageID~n"
+" zx verup Level~n"
+" zx set version Version~n"
+" zx update .app~n"
+" zx create plt~n"
+" zx dialyze~n"
+" zx package Path~n"
+" zx submit ZspFile~n"
+" zx list pending PackageName~n"
+" zx list resigns Realm~n"
+" zx list packagers PackageName~n"
+" zx list maintainers PackageName~n"
+" zx list sysops Realm~n"
+" zx review PackageID~n"
+" zx approve PackageID~n"
+" zx reject PackageID~n"
+" zx add key Realm KeyName~n"
+" zx get key Realm KeyName~n"
+" zx rem key Realm KeyName~n"
+" zx create user Realm~n"
+" zx create userfiles Realm UserName~n"
+" zx create keypair Realm~n"
+" zx export user UserID~n"
+" zx import user ZdufFile~n"
+"~n"
+"Sysop Actions:~n"
+" zx add user ZpufFile~n"
+" zx add package PackageName~n"
+" zx add packager PackageName UserID~n"
+" zx add maintainer PackageName UserID~n"
+" zx add sysop UserID~n"
+" zx accept PackageID~n"
+" zx create realm~n"
+" zx create realmfile Realm~n"
+" zx create sysop~n"
+"~n"
+"Where~n"
+" PackageID :: A string of the form Realm-Name[-Version]~n"
+" Args :: Arguments to pass to the application~n"
+" Type :: The project type: a standalone \"app\" or a \"lib\"~n"
+" Version :: Version string X, X.Y, or X.Y.Z: \"1\", \"1.2\", \"1.2.3\"~n"
+" RealmFile :: Path to a valid .zrf realm file~n"
+" Realm :: The name of a realm as a string [:a-z:]~n"
+" KeyName :: The prefix of a keypair to drop~n"
+" Level :: The version level, one of \"major\", \"minor\", or \"patch\"~n"
+" Path :: Path to a valid project directory or .zsp file~n",
+ io:format(T).
+
+
+
+%%% Error exits
+
+-spec error_exit(Format, Args, Line) -> no_return()
+ when Format :: string(),
+ Args :: [term()],
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Format, Args, Line) ->
+ File = filename:basename(?FILE),
+ ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]),
+ halt(1).
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl
new file mode 100644
index 0000000..767de5c
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl
@@ -0,0 +1,478 @@
+%%% @doc
+%%% ZX Auth
+%%%
+%%% This module is where all the AUTH type command code lives. AUTH commands are special
+%%% because they do not involve the zx_daemon at all, though they do perform network
+%%% operations.
+%%%
+%%% All AUTH procedures terminate the runtime once complete.
+%%% @end
+
+-module(zx_auth).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([list_pending/1, list_resigns/1,
+ submit/1, review/1, approve/1, reject/1, accept/1,
+ add_packager/2, add_maintainer/2, add_sysop/1,
+ add_package/1]).
+
+-include("zx_logger.hrl").
+
+
+
+%%% Functions
+
+
+-spec list_pending(PackageName :: string()) -> no_return().
+%% @private
+%% List the versions of a package that are pending review. The package name is input by
+%% the user as a string of the form "otpr-zomp" and the output is a list of full
+%% package IDs, printed one per line to stdout (like "otpr-zomp-3.2.2").
+
+list_pending(PackageName) ->
+ Package = {Realm, Name} =
+ case zx_lib:package_id(PackageName) of
+ {ok, {R, N, {z, z, z}}} ->
+ {R, N};
+ {error, invalid_package_string} ->
+ error_exit("~tp is not a valid package name.", [PackageName], ?LINE)
+ end,
+ case zx_daemon:list_pending(Package) of
+ {ok, []} ->
+ Message = "Package ~ts has no versions pending.",
+ ok = log(info, Message, [PackageName]),
+ halt(0);
+ {ok, Versions} ->
+ Print =
+ fun(Version) ->
+ {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}),
+ io:format("~ts~n", [PackageString])
+ end,
+ ok = lists:foreach(Print, Versions),
+ halt(0);
+ {error, bad_realm} ->
+ error_exit("Bad realm name.", ?LINE);
+ {error, bad_package} ->
+ error_exit("Bad package name.", ?LINE);
+ {error, network} ->
+ Message = "Network issues are preventing connection to the realm.",
+ error_exit(Message, ?LINE)
+ end.
+
+
+-spec list_resigns(zx:realm()) -> no_return().
+%% @private
+%% List the package ids of all packages waiting in the resign queue for the given realm,
+%% printed to stdout one per line.
+
+list_resigns(Realm) ->
+ case zx_daemon:list_resigns(Realm) of
+ {ok, []} ->
+ Message = "No packages pending signature in ~tp.",
+ ok = log(info, Message, [Realm]),
+ halt(0);
+ {ok, PackageIDs} ->
+ Print =
+ fun(PackageID) ->
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ io:format("~ts~n", [PackageString])
+ end,
+ ok = lists:foreach(Print, PackageIDs),
+ halt(0);
+ {error, bad_realm} ->
+ error_exit("Bad realm name.", ?LINE);
+ {error, no_realm} ->
+ error_exit("Realm \"~ts\" is not configured.", ?LINE);
+ {error, network} ->
+ Message = "Network issues are preventing connection to the realm.",
+ error_exit(Message, ?LINE)
+ end.
+
+
+-spec submit(PackageFile) -> no_return()
+ when PackageFile :: file:filename().
+%% @private
+%% Submit a package to the appropriate "prime" server for the given realm.
+
+submit(PackageFile) ->
+ Files = zx_lib:extract_zsp_or_die(PackageFile),
+ {ok, PackageData} = file:read_file(PackageFile),
+ {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files),
+ Meta = binary_to_term(MetaBin),
+ {Realm, Package, Version} = maps:get(package_id, Meta),
+ {ok, Socket} = connect_auth(Realm),
+ ok = send(Socket, {submit, {Realm, Package, Version}}),
+ ok = recv_or_die(Socket),
+ ok = gen_tcp:send(Socket, PackageData),
+ ok = log(info, "Done sending contents of ~tp", [PackageFile]),
+ Outcome = recv_or_die(Socket),
+ log(info, "Response: ~tp", [Outcome]),
+ ok = disconnect(Socket),
+ halt(0).
+
+
+review(PackageString) ->
+ PackageID = {Realm, _, _} = zx_lib:package_id(PackageString),
+ Socket = connect_auth_or_die(Realm),
+ ok = send(Socket, {review, PackageID}),
+ {ok, ZrpBin} = recv_or_die(Socket),
+ ok = send(Socket, ok),
+ ok = disconnect(Socket),
+ {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]),
+ {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files),
+ Meta = binary_to_term(MetaBin, [safe]),
+ PackageID = maps:get(package_id, Meta),
+ {KeyID, Signature} = maps:get(sig, Meta),
+ {ok, PubKey} = zx_key:load(public, KeyID),
+ TgzFile = PackageString ++ ".tgz",
+ {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files),
+ ok = zx_key:verify(TgzData, Signature, PubKey),
+ ok =
+ case file:make_dir(PackageString) of
+ ok ->
+ log(info, "Will unpack to directory ./~ts", [PackageString]);
+ {error, Error} ->
+ Message = "Creating dir ./~ts failed with ~ts. Aborting.",
+ ok = log(error, Message, [PackageString, Error]),
+ halt(1)
+ end,
+ ok = erl_tar:extract({binary, TgzData}, [compressed, {cwd, PackageString}]),
+ ok = log(info, "Unpacked and awaiting inspection."),
+ halt(0).
+
+
+approve(PackageID = {Realm, _, _}) ->
+ Socket = connect_auth_or_die(Realm),
+ ok = send(Socket, {approve, PackageID}),
+ ok = recv_or_die(Socket),
+ ok = log(info, "ok"),
+ halt(0).
+
+
+reject(PackageID = {Realm, _, _}) ->
+ Socket = connect_auth_or_die(Realm),
+ ok = send(Socket, {reject, PackageID}),
+ ok = recv_or_die(Socket),
+ ok = log(info, "ok"),
+ halt(0).
+
+
+accept(PackageString) ->
+ PackageID = {Realm, _, _} = zx_lib:package_id(PackageString),
+ RealmConf = zx_lib:load_realm_conf(Realm),
+ {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf),
+ KeySelection = [{K, {R, K}} || {R, K} <- [element(1, K) || K <- PackageKeys]],
+ PackageKeyID = zx_tty:select(KeySelection),
+ {ok, PackageKey} = zx_key:load(private, PackageKeyID),
+ Socket = connect_auth_or_die(Realm),
+ ok = send(Socket, {accept, PackageID}),
+ {ok, ZrpBin} = recv_or_die(Socket),
+ {ok, Files} = erl_tar:extract({binary, ZrpBin}, [memory]),
+ {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files),
+ Meta = binary_to_term(MetaBin, [safe]),
+ PackageID = maps:get(package_id, Meta),
+ {KeyID, Signature} = maps:get(sig, Meta),
+ {ok, PubKey} = zx_key:load(public, KeyID),
+ TgzFile = PackageString ++ ".tgz",
+ {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files),
+ ok = zx_key:verify(TgzData, Signature, PubKey),
+ ReSignature = public_key:sign(TgzData, sha512, PackageKey),
+ FinalMeta = maps:put(sig, {PackageKeyID, ReSignature}, Meta),
+ NewMetaBin = term_to_binary(FinalMeta),
+ NewFiles = lists:keystore("zomp.meta", 1, Files, {"zomp.meta", NewMetaBin}),
+ ResignedZrp = PackageString ++ ".zsp.resign",
+ ok = erl_tar:create(ResignedZrp, NewFiles),
+ {ok, ResignedBin} = file:read_file(ResignedZrp),
+ ok = gen_tcp:send(Socket, ResignedBin),
+ ok = recv_or_die(Socket),
+ ok = file:delete(ResignedZrp),
+ ok = recv_or_die(Socket),
+ ok = disconnect(Socket),
+ ok = log(info, "Resigned ~ts", [PackageString]),
+ halt(0).
+
+
+add_packager(Package, UserFile) ->
+ ok = log(info, "Would add ~ts to packagers for ~160tp now.", [UserFile, Package]),
+ halt(0).
+
+
+add_maintainer(Package, UserFile) ->
+ ok = log(info, "Would add ~ts to maintainer for ~160tp now.", [UserFile, Package]),
+ halt(0).
+
+
+add_sysop(UserFile) ->
+ ok = log(info, "Would add ~ts to sysop list.", [UserFile]),
+ halt(0).
+
+
+-spec add_package(PackageName) -> no_return()
+ when PackageName :: zx:package().
+%% @private
+%% A sysop command that adds a package to a realm operated by the caller.
+
+add_package(PackageName) ->
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ case zx_lib:package_id(PackageName) of
+ {ok, {Realm, Name, {z, z, z}}} ->
+ add_package(Realm, Name);
+ _ ->
+ error_exit("~tp is not a valid package name.", [PackageName], ?LINE)
+ end.
+
+
+-spec add_package(Realm, Name) -> no_return()
+ when Realm :: zx:realm(),
+ Name :: zx:name().
+
+add_package(Realm, Name) ->
+ Socket = connect_auth_or_die(Realm),
+ ok = send(Socket, {add_package, {Realm, Name}}),
+ ok = recv_or_die(Socket),
+ ok = log(info, "\"~ts-~ts\" added successfully.", [Realm, Name]),
+ halt(0).
+
+
+
+%%% Authenticated communication with prime
+
+-spec send(Socket, Message) -> ok
+ when Socket :: gen_tcp:socket(),
+ Message :: term().
+%% @private
+%% Wrapper for the procedure necessary to send an internal message over the wire.
+
+send(Socket, Message) ->
+ Bin = term_to_binary(Message),
+ gen_tcp:send(Socket, Bin).
+
+
+-spec recv_or_die(Socket) -> Result | no_return()
+ when Socket :: gen_tcp:socket(),
+ Result :: ok | {ok, term()}.
+
+recv_or_die(Socket) ->
+ receive
+ {tcp, Socket, Bin} ->
+ case binary_to_term(Bin) of
+ ok ->
+ ok;
+ {ok, Response} ->
+ {ok, Response};
+ {error, Reason} ->
+ error_exit("Action failed with: ~tp", [Reason], ?LINE);
+ Unexpected ->
+ error_exit("Unexpected message: ~tp", [Unexpected], ?LINE)
+ end;
+ {tcp_closed, Socket} ->
+ error_exit("Lost connection to node unexpectedly.", ?LINE)
+ after 5000 ->
+ error_exit("Connection timed out.", ?LINE)
+ end.
+
+
+-spec connect_auth_or_die(zx:realm()) -> gen_tcp:socket() | no_return().
+
+connect_auth_or_die(Realm) ->
+ case connect_auth(Realm) of
+ {ok, Socket} ->
+ Socket;
+ Error ->
+ M1 = "Connection failed to realm prime with ~160tp.",
+ ok = log(warning, M1, [Error]),
+ halt(1)
+ end.
+
+
+-spec connect_auth(Realm) -> Result
+ when Realm :: zx:realm(),
+ Result :: {ok, gen_tcp:socket()}
+ | {error, Reason :: term()}.
+%% @private
+%% Connect to one of the servers in the realm constellation.
+
+connect_auth(Realm) ->
+ RealmConf = zx_lib:load_realm_conf(Realm),
+ {User, KeyID, Key} = prep_auth(Realm, RealmConf),
+ {prime, {Host, Port}} = lists:keyfind(prime, 1, RealmConf),
+ Options = [{packet, 4}, {mode, binary}, {active, true}],
+ case gen_tcp:connect(Host, Port, Options, 5000) of
+ {ok, Socket} ->
+ ok = log(info, "Connected to ~tp prime.", [Realm]),
+ connect_auth(Socket, Realm, User, KeyID, Key);
+ Error = {error, E} ->
+ ok = log(warning, "Connection problem: ~tp", [E]),
+ {error, Error}
+ end.
+
+
+-spec connect_auth(Socket, Realm, User, KeyID, Key) -> Result
+ when Socket :: gen_tcp:socket(),
+ Realm :: zx:realm(),
+ User :: zx:user_id(),
+ KeyID :: zx:key_id(),
+ Key :: term(),
+ Result :: {ok, gen_tcp:socket()}
+ | {error, timeout}.
+%% @private
+%% Send a protocol ID string to notify the server what we're up to, disconnect
+%% if it does not return an "OK" response within 5 seconds.
+
+connect_auth(Socket, Realm, User, KeyID, Key) ->
+ ok = gen_tcp:send(Socket, <<"OTPR AUTH 1">>),
+ receive
+ {tcp, Socket, Bin} ->
+ ok = binary_to_term(Bin, [safe]),
+ confirm_auth(Socket, Realm, User, KeyID, Key);
+ {tcp_closed, Socket} ->
+ ok = log(warning, "Socket closed unexpectedly."),
+ halt(1)
+ after 5000 ->
+ ok = log(warning, "Host realm ~160tp prime timed out.", [Realm]),
+ {error, auth_timeout}
+ end.
+
+
+confirm_auth(Socket, Realm, User, KeyID, Key) ->
+ ok = send(Socket, {User, KeyID}),
+ receive
+ {tcp, Socket, Bin} ->
+ case binary_to_term(Bin, [safe]) of
+ {sign, Blob} ->
+ Sig = public_key:sign(Blob, sha512, Key),
+ ok = send(Socket, {signed, Sig}),
+ confirm_auth(Socket);
+ {error, not_prime} ->
+ M1 = "Connected node is not prime for realm ~160tp",
+ ok = log(warning, M1, [Realm]),
+ ok = disconnect(Socket),
+ {error, not_prime};
+ {error, bad_user} ->
+ M2 = "Bad user record ~160tp",
+ ok = log(warning, M2, [User]),
+ ok = disconnect(Socket),
+ {error, bad_user};
+ {error, unauthorized_key} ->
+ M3 = "Unauthorized user key ~160tp",
+ ok = log(warning, M3, [KeyID]),
+ ok = disconnect(Socket),
+ {error, unauthorized_key};
+ {error, Reason} ->
+ Message = "Could not begin auth exchange. Failed with ~160tp",
+ ok = log(warning, Message, [Reason]),
+ ok = disconnect(Socket),
+ {error, Reason}
+ end;
+ {tcp_closed, Socket} ->
+ ok = log(warning, "Socket closed unexpectedly."),
+ halt(1)
+ after 5000 ->
+ ok = log(warning, "Host realm ~tp prime timed out.", [Realm]),
+ {error, auth_timeout}
+ end.
+
+
+confirm_auth(Socket) ->
+ receive
+ {tcp, Socket, Bin} ->
+ case binary_to_term(Bin, [safe]) of
+ ok -> {ok, Socket};
+ Other -> {error, Other}
+ end;
+ {tcp_closed, Socket} ->
+ ok = log(warning, "Socket closed unexpectedly."),
+ halt(1)
+ after 5000 ->
+ {error, timeout}
+ end.
+
+
+-spec prep_auth(Realm, RealmConf) -> {User, KeyID, Key} | no_return()
+ when Realm :: zx:realm(),
+ RealmConf :: [term()],
+ User :: zx:user_id(),
+ KeyID :: zx:key_id(),
+ Key :: term().
+%% @private
+%% Loads the appropriate User, KeyID and reads in a registered key for use in
+%% connect_auth/4.
+
+prep_auth(Realm, RealmConf) ->
+ UsersFile = filename:join(zx_lib:zomp_dir(), "zomp.users"),
+ Users =
+ case file:consult(UsersFile) of
+ {ok, U} ->
+ U;
+ {error, enoent} ->
+ ok = log(warning, "You do not have any users configured."),
+ halt(1)
+ end,
+ {User, KeyIDs} =
+ case lists:keyfind(Realm, 1, Users) of
+ {Realm, UserName, []} ->
+ W = "User ~tp does not have any keys registered for realm ~tp.",
+ ok = log(warning, W, [UserName, Realm]),
+ ok = log(info, "Contact the following sysop(s) to register a key:"),
+ {sysops, Sysops} = lists:keyfind(sysops, 1, RealmConf),
+ PrintContact =
+ fun({_, _, Email, Name, _, _}) ->
+ log(info, "Sysop: ~ts Email: ~ts", [Name, Email])
+ end,
+ ok = lists:foreach(PrintContact, Sysops),
+ halt(1);
+ {Realm, UserName, KeyNames} ->
+ KIDs = [{Realm, KeyName} || KeyName <- KeyNames],
+ {{Realm, UserName}, KIDs};
+ false ->
+ Message = "You are not a user of the given realm: ~160tp.",
+ ok = log(warning, Message, [Realm]),
+ halt(1)
+ end,
+ KeyID = hd(KeyIDs),
+ true = zx_key:ensure_keypair(KeyID),
+ {ok, Key} = zx_key:load(private, KeyID),
+ {User, KeyID, Key}.
+
+
+-spec disconnect(gen_tcp:socket()) -> ok.
+%% @private
+%% Gracefully shut down a socket, logging (but sidestepping) the case when the socket
+%% has already been closed by the other side.
+
+disconnect(Socket) ->
+ case gen_tcp:shutdown(Socket, read_write) of
+ ok ->
+ log(info, "Disconnected from ~tp", [Socket]);
+ {error, Error} ->
+ Message = "Shutdown connection ~p failed with: ~p",
+ log(warning, Message, [Socket, Error])
+ end.
+
+
+
+%%% Error exits
+
+-spec error_exit(Error, Line) -> no_return()
+ when Error :: term(),
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Error, Line) ->
+ error_exit(Error, [], Line).
+
+
+-spec error_exit(Format, Args, Line) -> no_return()
+ when Format :: string(),
+ Args :: [term()],
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Format, Args, Line) ->
+ File = filename:basename(?FILE),
+ ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]),
+ halt(1).
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl
new file mode 100644
index 0000000..146fec8
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl
@@ -0,0 +1,333 @@
+%%% @doc
+%%% zx_conf_sys: An interface to etc/sys.conf
+%%%
+%%% It may seem overkill to write an interface module for a config file that only tracks
+%%% five things, but scattering this all around the project is just a bit too l33t for
+%%% an infrastructure project like ZX.
+%%%
+%%% Each exported function that is named after an attribute has two versions, one of
+%%% arity-1 and one of arity-2. The arity-1 version is a "getter", and the arity-2
+%%% version is a "setter". Other functions deal with the data in a way that returns
+%%% an answer and updates the state accordingly.
+%%%
+%%% Bad configuration data causes a reset to defaults so that the system can function.
+%%% @end
+
+-module(zx_conf_sys).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([load/0, save/1,
+ timeout/1, timeout/2,
+ retries/1, retries/2, retry/1, retries_left/1,
+ maxconn/1, maxconn/2,
+ managed/1, managed/2, add_managed/2, rem_managed/2,
+ mirrors/1, mirrors/2, add_mirror/2, rem_mirror/2,
+ reset/0]).
+
+-export_type([data/0]).
+
+-include("zx_logger.hrl").
+
+
+
+%%% Type Definitions
+
+-record(d,
+ {timeout = 5 :: pos_integer(),
+ retries = {3, 3} :: non_neg_integer(),
+ maxconn = 5 :: pos_integer(),
+ managed = sets:new() :: sets:set(zx:realm()),
+ mirrors = [] :: [zx:host()]}).
+
+-opaque data() :: #d{}.
+
+
+
+%%% Interface functions
+
+-spec load() -> data().
+%% @doc
+%% Read from etc/sys.conf and return a populated data() record if it exists, or
+%% populate default values and write a new one if it does not. If a damaged sys.conf
+%% is discovered it will be repaired. This function is side-effecty so should only
+%% be called by zx_daemon and utility code.
+
+load() ->
+ Path = path(),
+ case file:consult(Path) of
+ {ok, List} ->
+ populate_data(List);
+ {error, Reason} ->
+ ok = log(error, "Load ~tp failed with: ~tp", [Path, Reason]),
+ Data = #d{},
+ ok = save(Data),
+ Data
+ end.
+
+
+populate_data(List) ->
+ Timeout =
+ case proplists:get_value(timeout, List, 5) of
+ TO when is_integer(TO) and TO > 0 -> TO;
+ _ -> 5
+ end,
+ Retries =
+ case proplists:get_value(retries, List, 3) of
+ RT when is_integer(RT) and RT > 0 -> {RT, RT};
+ _ -> 3
+ end,
+ MaxConn =
+ case proplists:get_value(maxconn, List, 5) of
+ MC when is_integer(MC) and MC > 0 -> MC;
+ _ -> 5
+ end,
+ Managed =
+ case proplists:get_value(managed, List, []) of
+ MN when is_list(MN) -> sets:from_list(MN);
+ _ -> sets:new()
+ end,
+ Mirrors =
+ case proplists:get_value(mirrors, List, []) of
+ MR when is_list(MR) -> MR;
+ _ -> []
+ end,
+ #d{timeout = Timeout,
+ retries = Retries,
+ maxconn = MaxConn,
+ managed = Managed,
+ mirrors = Mirrors}.
+
+
+-spec save(data()) -> ok.
+%% @doc
+%% Save the current etc/sys.conf to disk.
+
+save(#d{timeout = Timeout,
+ retries = {_, Retries},
+ maxconn = MaxConn,
+ managed = Managed,
+ mirrors = Mirrors}) ->
+ Terms =
+ [{timeout, Timeout},
+ {retries, Retries},
+ {maxconn, MaxConn},
+ {managed, sets:to_list(Managed)},
+ {mirrors, Mirrors}],
+ ok = zx_lib:write_terms(path(), Terms),
+ log(info, "Wrote etc/sys.conf").
+
+
+-spec timeout(data()) -> pos_integer().
+%% @doc
+%% Return the timeout value.
+
+timeout(#d{timeout = Timeout}) ->
+ Timeout.
+
+
+-spec timeout(Data, Value) -> NewData
+ when Data :: data(),
+ Value :: pos_integer(),
+ NewData :: data().
+%% @doc
+%% Set the timeout attribute to a new value.
+
+timeout(Data, Value)
+ when is_integer(Value) and Value > 0 ->
+ Data#d{timeout = Value}.
+
+
+-spec retries(data()) -> non_neg_integer().
+%% @doc
+%% Return the retries value.
+
+retries(#d{retries = {_, Retries}}) ->
+ Retries.
+
+
+-spec retries(Data, Value) -> NewData
+ when Data :: data(),
+ Value :: non_neg_integer(),
+ NewData :: data().
+%% @doc
+%% Set the retries attribute to a new value.
+
+retries(Data = #d{retries = {Remaining, _}}, Value)
+ when is_integer(Value) and Value >= 0 ->
+ Data#d{retries = {Remaining, Value}}.
+
+
+-spec retry(Data) -> Result
+ when Data :: data(),
+ Result :: {ok, NewData}
+ | no_retries,
+ NewData :: data().
+%% @doc
+%% Tell the caller whether there are any more retries remaining or return `ok' and
+%% update the state.
+
+retry(#d{retries = {0, _}}) ->
+ no_retries;
+retry(Data = #d{retries = {Remaining, Setting}}) ->
+ NewRemaining = Remaining - 1,
+ NewData = Data#d{retries = {NewRemaining, Setting}},
+ {ok, NewData}.
+
+
+-spec retries_left(data()) -> non_neg_integer().
+%% @doc
+%% Return the number of retries remaining.
+
+retries_left(#d{retries = {Remaining, _}}) ->
+ Remaining.
+
+
+-spec maxconn(data()) -> pos_integer().
+%% @doc
+%% Return the value of maxconn.
+
+maxconn(#d{maxconn = MaxConn}) ->
+ MaxConn.
+
+
+-spec maxconn(Data, Value) -> NewData
+ when Data :: data(),
+ Value :: pos_integer(),
+ NewData :: data().
+%% @doc
+%% Set the value of maxconn.
+
+maxconn(Data, Value)
+ when is_integer(Value) and Value > 0 ->
+ Data#d{maxconn = Value}.
+
+
+-spec managed(data()) -> list(zx:realm()).
+%% @doc
+%% Return the list of realms managed by the current node.
+
+managed(#d{managed = Managed}) ->
+ sets:to_list(Managed).
+
+
+-spec managed(Data, List) -> NewData
+ when Data :: data(),
+ List :: [zx:realm()],
+ NewData :: data().
+%% @doc
+%% Reset the set of managed realms entirely.
+%% The realms must be configured on the current realm at a minimum.
+
+managed(Data, List) ->
+ Desired = sets:from_list(List),
+ Configured = sets:from_list(zx_lib:list_realms()),
+ NewManaged = sets:intersection(Desired, Configured),
+ Data#d{managed = NewManaged}.
+
+
+-spec add_managed(Data, Realm) -> Result
+ when Data :: data(),
+ Realm :: zx:realm(),
+ Result :: {ok, NewData}
+ | {error, unconfigured},
+ NewData :: data().
+%% @doc
+%% Add a new realm to the list of managed realms. The new realm must be configured on
+%% the current node. This node will then behave as the prime node for the realm (whether
+%% it is or not).
+
+add_managed(Data = #d{managed = Managed}, Realm) ->
+ case lists:member(Realm, zx_lib:list_realms()) of
+ true ->
+ NewData = Data#d{managed = sets:add_element(Realm, Managed)},
+ ok = log(info, "Now managing realm: ~tp", [Realm]),
+ {ok, NewData};
+ false ->
+ ok = log(warning, "Cannot manage unconfigured realm: ~tp", [Realm]),
+ {error, unconfigured}
+ end.
+
+
+-spec rem_managed(Data, Realm) -> Result
+ when Data :: data(),
+ Realm :: zx:realm(),
+ Result :: {ok, NewData}
+ | {error, unmanaged},
+ NewData :: data().
+%% @doc
+%% Stop managing a realm.
+
+rem_managed(Data = #d{managed = Managed}, Realm) ->
+ case sets:is_element(Realm, Managed) of
+ true ->
+ NewData = Data#d{managed = sets:del_element(Realm, Managed)},
+ ok = log(info, "No longer managing realm: ~tp", [Realm]),
+ {ok, NewData};
+ false ->
+ ok = log(warning, "Cannot stop managing unmanaged realm: ~tp", [Realm]),
+ {error, unmanaged}
+ end.
+
+
+-spec mirrors(data()) -> [zx:host()].
+%% @doc
+%% Return the list of private mirrors.
+
+mirrors(#d{mirrors = Mirrors}) ->
+ Mirrors.
+
+
+-spec mirrors(Data, Hosts) -> NewData
+ when Data :: data(),
+ Hosts :: [zx:host()],
+ NewData :: data().
+%% @private
+%% Reset the mirror configuration.
+
+mirrors(Data, Hosts) ->
+ Data#d{mirrors = Hosts}.
+
+
+-spec add_mirror(Data, Host) -> NewData
+ when Data :: data(),
+ Host :: zx:host(),
+ NewData :: data().
+%% @doc
+%% Add a mirror to the permanent configuration.
+
+add_mirror(Data = #d{mirrors = Mirrors}, Host) ->
+ case lists:member(Host, Mirrors) of
+ false -> Data#d{mirrors = [Host | Mirrors]};
+ true -> Data
+ end.
+
+
+-spec rem_mirror(Data, Host) -> NewData
+ when Data :: data(),
+ Host :: zx:host(),
+ NewData :: data().
+%% @private
+%% Remove a host from the list of permanent mirrors.
+
+rem_mirror(Data = #d{mirrors = Mirrors}, Host) ->
+ Data#d{mirrors = lists:delete(Host, Mirrors)}.
+
+
+-spec reset() -> data().
+%% @private
+%% Reset sys.conf.
+
+reset() ->
+ Data = #d{},
+ save(Data),
+ Data.
+
+
+-spec path() -> file:filename().
+%% @private
+%% Return the path to $ZOMP_DIR/etc/sys.conf.
+
+path() ->
+ filename:join(zx_lib:path(etc), "sys.conf").
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl
new file mode 100644
index 0000000..30f5ef6
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl
@@ -0,0 +1,543 @@
+%% @doc
+%%% ZX Connector
+%%%
+%%% This module represents a connection to a Zomp server.
+%%% Multiple connections can exist at a given time, but each one of these processes
+%%% only represents a single connection at a time.
+%%% @end
+
+-module(zx_conn).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+% FIXME
+-compile(export_all).
+
+-export([subscribe/2, unsubscribe/2, fetch/3, query/3]).
+-export([start/1, stop/1]).
+-export([start_link/1, init/2]).
+
+-include("zx_logger.hrl").
+
+
+%%% Types
+
+%-type incoming() :: ping
+% | {sub, Channel :: term(), Message :: term()}
+% | term().
+
+
+%%% Interface
+
+-spec subscribe(Conn, Package) -> ok
+ when Conn :: pid(),
+ Package :: zx:package().
+
+subscribe(Conn, Realm) ->
+ Conn ! {subscribe, Realm},
+ ok.
+
+
+-spec unsubscribe(Conn, Package) -> ok
+ when Conn :: pid(),
+ Package :: zx:package().
+
+unsubscribe(Conn, Package) ->
+ Conn ! {unsubscribe, Package},
+ ok.
+
+
+-spec fetch(Conn, ID, Object) -> ok
+ when Conn :: pid(),
+ ID :: zx_daemon:id(),
+ Object :: zx_daemon:object().
+
+fetch(Conn, ID, Object) ->
+ Conn ! {fetch, ID, Object},
+ ok.
+
+
+-spec query(Conn, ID, Action) -> ok
+ when Conn :: pid(),
+ ID :: zx_daemon:id(),
+ Action :: zx_daemon:action().
+
+query(Conn, ID, Action) ->
+ Conn ! {query, ID, Action},
+ ok.
+
+
+%%% Startup
+
+-spec start(Target) -> Result
+ when Target :: zx:host(),
+ Result :: {ok, pid()}
+ | {error, Reason :: term()}.
+%% @doc
+%% Starts a connection to a given target Zomp node. This call itself should never fail,
+%% but this process may fail to connect or crash immediately after spawning. Should
+%% only be called by zx_daemon.
+
+start(Target) ->
+ zx_conn_sup:start_conn(Target).
+
+
+-spec stop(Conn :: pid()) -> ok.
+%% @doc
+%% Signals the connection to disconnect and retire immediately.
+
+stop(Conn) ->
+ Conn ! stop,
+ ok.
+
+
+-spec start_link(Target) -> Result
+ when Target :: zx:host(),
+ Result :: {ok, pid()}
+ | {error, Reason},
+ Reason :: term().
+%% @private
+%% The supervisor's way of spawning a new connector.
+
+start_link(Target) ->
+ proc_lib:start_link(?MODULE, init, [self(), Target]).
+
+
+-spec init(Parent, Target) -> no_return()
+ when Parent :: pid(),
+ Target :: zx:host().
+%% @private
+%% gen_server callback. For more information refer to the OTP documentation.
+
+init(Parent, Target) ->
+ ok = log(info, "Connecting to ~tp", [Target]),
+ Debug = sys:debug_options([]),
+ ok = proc_lib:init_ack(Parent, {ok, self()}),
+ connect(Parent, Debug, Target).
+
+
+
+%%% Connection Procedure
+
+-spec connect(Parent, Debug, Target) -> no_return()
+ when Parent :: pid(),
+ Debug :: [sys:dbg_opt()],
+ Target :: zx:host().
+
+connect(Parent, Debug, {Host, Port}) ->
+ Options = [{packet, 4}, {mode, binary}, {nodelay, true}, {active, true}],
+ case gen_tcp:connect(Host, Port, Options, 5000) of
+ {ok, Socket} ->
+ confirm_service(Parent, Debug, Socket);
+ {error, Error} ->
+ ok = log(warning, "Connection problem with ~tp: ~tp", [Host, Error]),
+ ok = zx_daemon:report(failed),
+ terminate()
+ end.
+
+
+-spec confirm_service(Parent, Debug, Socket) -> no_return()
+ when Parent :: pid(),
+ Debug :: [sys:dbg_opt()],
+ Socket :: gen_tcp:socket().
+%% @private
+%% Confirm the zomp node can handle "OTPR USER 1" and is accepting connections or try
+%% another node.
+
+confirm_service(Parent, Debug, Socket) ->
+ ok = gen_tcp:send(Socket, <<"OTPR USER 1">>),
+ receive
+ {tcp, Socket, Bin} ->
+ case binary_to_term(Bin, [safe]) of
+ ok ->
+ query_realms(Parent, Debug, Socket);
+ {redirect, Hosts} ->
+ ok = zx_daemon:report({redirect, Hosts}),
+ ok = zx_net:disconnect(Socket),
+ terminate()
+ end;
+ {tcp_closed, Socket} ->
+ handle_unexpected_close()
+ after 5000 ->
+ handle_timeout(Socket)
+ end.
+
+
+-spec query_realms(Parent, Debug, Socket) -> no_return()
+ when Parent :: pid(),
+ Debug :: [sys:dbg_opt()],
+ Socket :: gen_tcp:socket().
+%% @private
+%% Confirm that the connected host has a valid serial for the realm zx is trying to
+%% reach, and if not retry on another node.
+
+query_realms(Parent, Debug, Socket) ->
+ ok = zx_net:send(Socket, list),
+ receive
+ {tcp, Socket, Bin} ->
+ {ok, Realms} = binary_to_term(Bin, [safe]),
+ ok = zx_daemon:report({connected, Realms}),
+ loop(Parent, Debug, Socket);
+ {tcp_closed, Socket} ->
+ handle_unexpected_close()
+ after 5000 ->
+ handle_timeout(Socket)
+ end.
+
+
+
+%%% Service Loop
+
+-spec loop(Parent, Debug, Socket) -> no_return()
+ when Parent :: pid(),
+ Debug :: [sys:dbg_opt()],
+ Socket :: gen_tcp:socket().
+%% @private
+%% Service loop. Messages incoming from the connected Zomp node, the zx_daemon, and
+%% OTP system messages all come here. This is the only catch-all receive loop, so
+%% messages that occur in a specific state must not be accidentally received here out
+%% of order or else whatever sequenced communication was happening will be corrupted.
+
+loop(Parent, Debug, Socket) ->
+ receive
+ {tcp, Socket, Bin} ->
+ ok = handle_message(Socket, Bin),
+ ok = inet:setopts(Socket, [{active, once}]),
+ loop(Parent, Debug, Socket);
+ {subscribe, Package} ->
+ ok = zx_net:send(Socket, {subscribe, Package}),
+ loop(Parent, Debug, Socket);
+ {unsubscribe, Package} ->
+ ok = zx_net:send(Socket, {unsubscribe, Package}),
+ loop(Parent, Debug, Socket);
+ {fetch, ID, Object} ->
+ {ok, Outcome} = handle_fetch(Socket, Object),
+ ok = zx_daemon:result(ID, Outcome),
+ loop(Parent, Debug, Socket);
+ {query, ID, Action} ->
+ {ok, Outcome} = handle_query(Socket, Action),
+ ok = zx_daemon:result(ID, Outcome),
+ loop(Parent, Debug, Socket);
+ stop ->
+ ok = zx_net:disconnect(Socket),
+ terminate();
+ Unexpected ->
+ ok = log(warning, "Unexpected message: ~tp", [Unexpected]),
+ loop(Parent, Debug, Socket)
+ end.
+
+
+
+%%% Idle Incoming Upstream Messages
+
+-spec handle_message(Socket, Bin) -> ok | no_return()
+ when Socket :: gen_tcp:socket(),
+ Bin :: binary().
+%% @private
+%% Single point to convert a binary message to a safe internal message. Actual handling
+%% of the converted message occurs in dispatch/2.
+
+handle_message(Socket, Bin) ->
+ Message = binary_to_term(Bin, [safe]),
+ ok = log(info, "Received network message: ~tp", [Message]),
+ case binary_to_term(Bin, [safe]) of
+ ping ->
+ zx_net:send(Socket, pong);
+ {sub, Channel, Message} ->
+ log("Sub: ~tp - ~tp", [Channel, Message]);
+ {update, Message} ->
+ log("Update: ~tp", [Message]);
+ {redirect, Nodes} ->
+ log("Redirected to ~tp", [Nodes]);
+ Invalid ->
+ {ok, {Addr, Port}} = zomp:peername(Socket),
+ Host = inet:ntoa(Addr),
+ Warning = "Invalid message from ~s:~p: ~tp",
+ ok = log(warning, Warning, [Host, Port, Invalid]),
+ ok = zx_net:disconnect(Socket),
+ terminate()
+ end.
+
+
+
+%%% Incoming Request Actions
+
+-spec handle_request(Socket, Action) -> Result
+ when Socket :: gen_tcp:socket(),
+ Action :: term(),
+ Result :: {ok, Outcome :: term()}.
+
+handle_request(Socket, Action) ->
+ ok = zx_net:send(Socket, Action),
+ Response =
+ case element(1, Action) of
+ list ->
+ do_list(Action, Socket);
+ latest ->
+ do_latest(Action, Socket);
+ fetch ->
+ do_fetch(Action, Socket);
+ key ->
+ do_key(Action, Socket);
+ pending ->
+ do_pending(Action, Socket);
+ packagers ->
+ do_packagers(Action, Socket);
+ maintainers ->
+ do_maintainers(Action, Socket);
+ sysops ->
+ do_sysops(Action, Socket)
+ end,
+ handle_response(Socket, Response).
+
+
+handle_fetch(_, _) -> {error, nyi}.
+
+handle_query(_, _) -> {error, nyi}.
+
+do_list(_, _) -> {error, nyi}.
+
+do_latest(_, _) -> {error, nyi}.
+
+do_fetch(_, _) -> {error, nyi}.
+
+do_key(_, _) -> {error, nyi}.
+
+do_pending(_, _) -> {error, nyi}.
+
+do_packagers(_, _) -> {error, nyi}.
+
+do_maintainers(_, _) -> {error, nyi}.
+
+do_sysops(_, _) -> {error, nyi}.
+
+
+
+handle_response(Socket, Command) ->
+ receive
+ {tcp, Socket, Bin} ->
+ Outcome = binary_to_term(Bin, [safe]),
+ interpret_response(Socket, Outcome, Command);
+ {tcp_closed, Socket} ->
+ handle_unexpected_close()
+ after 5000 ->
+ handle_timeout(Socket)
+ end.
+
+
+interpret_response(Socket, ping, Command) ->
+ ok = zx_net:send(Socket, pong),
+ handle_response(Socket, Command);
+interpret_response(Socket, {sub, Channel, Message}, Command) ->
+ ok = zx_daemon:notify(Channel, Message),
+ handle_response(Socket, Command).
+%interpret_response(Socket, {update, Message}, Command) ->
+%interpret_response(Socket, Response, list) ->
+%interpret_response(Socket, Response, latest) ->
+%interpret_response(Socket, Response, fetch) ->
+%interpret_response(Socket, Response, key) ->
+%interpret_response(Socket, Response, pending) ->
+%interpret_response(Socket, Response, packagers) ->
+%interpret_response(Socket, Response, maintainers) ->
+%interpret_response(Socket, Response, sysops) ->
+%
+%
+%
+% case element(1, Action) of
+% end,
+
+
+-spec fetch(Socket, PackageID) -> Result
+ when Socket :: gen_tcp:socket(),
+ PackageID :: zx:package_id(),
+ Result :: ok.
+%% @private
+%% Download a package to the local cache.
+
+fetch(Socket, PackageID) ->
+ {ok, LatestID} = request_zsp(Socket, PackageID),
+ ok = receive_zsp(Socket, LatestID),
+ Latest = zx_lib:package_string(LatestID),
+ log(info, "Fetched ~ts", [Latest]).
+
+
+-spec request_zsp(Socket, PackageID) -> Result
+ when Socket :: gen_tcp:socket(),
+ PackageID :: zx:package_id(),
+ Result :: {ok, Latest :: zx:package_id()}
+ | {error, Reason :: timeout | term()}.
+
+request_zsp(Socket, PackageID) ->
+ ok = zx_net:send(Socket, {fetch, PackageID}),
+ receive
+ {tcp, Socket, Bin} ->
+ case binary_to_term(Bin) of
+ {sending, LatestID} ->
+ {ok, LatestID};
+ Error = {error, Reason} ->
+ PackageString = zx_lib:package_string(PackageID),
+ Message = "Error receiving package ~ts: ~tp",
+ ok = log(info, Message, [PackageString, Reason]),
+ Error
+ end;
+ {tcp_closed, Socket} ->
+ handle_unexpected_close()
+ after 60000 ->
+ {error, timeout}
+ end.
+
+
+-spec receive_zsp(Socket, PackageID) -> Result
+ when Socket :: gen_tcp:socket(),
+ PackageID :: zx:package_id(),
+ Result :: ok | {error, timeout}.
+
+receive_zsp(Socket, PackageID) ->
+ receive
+ {tcp, Socket, Bin} ->
+ ZrpPath = filename:join("zsp", zx_lib:namify_zsp(PackageID)),
+ ok = file:write_file(ZrpPath, Bin),
+ ok = zx_net:send(Socket, ok),
+ log(info, "Wrote ~ts", [ZrpPath]);
+ {tcp_closed, Socket} ->
+ handle_unexpected_close()
+ after 60000 ->
+ ok = log(error, "Timeout in socket receive for ~tp", [PackageID]),
+ {error, timeout}
+ end.
+
+
+
+%%% Terminal handlers
+
+-spec handle_unexpected_close() -> no_return().
+
+handle_unexpected_close() ->
+ ok = zx_daemon:report(disconnected),
+ terminate().
+
+
+-spec handle_timeout(gen_tcp:socket()) -> no_return().
+
+handle_timeout(Socket) ->
+ ok = zx_daemon:report(timeout),
+ ok = zx_net:disconnect(Socket),
+ terminate().
+
+
+-spec terminate() -> no_return().
+%% @private
+%% Convenience wrapper around the suicide call.
+%% In the case that a more formal retirement procedure is required, consider notifying
+%% the supervisor with `supervisor:terminate_child(zomp_client_sup, PID)' and writing
+%% a proper system_terminate/2.
+
+terminate() ->
+ exit(normal).
+
+
+
+%-spec do_query_latest(Object, State) -> {Result, NewState}
+% when Object :: zx:package() | zx:package_id(),
+% State :: state(),
+% Result :: {ok, zx:version()}
+% | {error, Reason},
+% Reason :: bad_realm
+% | bad_package
+% | bad_version,
+% NewState :: state().
+%% @private
+%% Queries a zomp realm for the latest version of a package or package
+%% version (complete or incomplete version number).
+%
+%do_query_latest(Socket, {Realm, Name}) ->
+% ok = zx_net:send(Socket, {latest, Realm, Name}),
+% receive
+% {tcp, Socket, Bin} -> binary_to_term(Bin)
+% after 5000 -> {error, timeout}
+% end;
+%do_query_latest(Socket, {Realm, Name, Version}) ->
+% ok = zx_net:send(Socket, {latest, Realm, Name, Version}),
+% receive
+% {tcp, Socket, Bin} -> binary_to_term(Bin)
+% after 5000 -> {error, timeout}
+% end.
+
+
+%-spec do_fetch(PackageIDs, State) -> NewState
+% when PackageIDs :: [zx:package_id()],
+% State :: state(),
+% NewState :: state(),
+% Result :: ok
+% | {error, Reason},
+% Reason :: bad_realm
+% | bad_package
+% | bad_version
+% | network.
+%% @private
+%%
+%
+%do_fetch(PackageIDs, State) ->
+% FIXME: Need to create a job queue divided by realm and dispatched to connectors,
+% and cleared from the master pending queue kept here by the daemon as the
+% workers succeed. Basic task queue management stuff... which never existed
+% in ZX before... grrr...
+% case scrub(PackageIDs) of
+% [] ->
+% ok;
+% Needed ->
+% Partitioned = partition_by_realm(Needed),
+% EnsureDeps =
+% fun({Realm, Packages}) ->
+% ok = zx_conn:queue_package(Pid, Realm, Packages),
+% log(info, "Disconnecting from realm: ~ts", [Realm])
+% end,
+% lists:foreach(EnsureDeps, Partitioned)
+% end.
+%
+%
+%partition_by_realm(PackageIDs) ->
+% PartitionMap = lists:foldl(fun partition_by_realm/2, #{}, PackageIDs),
+% maps:to_list(PartitionMap).
+%
+%
+%partition_by_realm({R, P, V}, M) ->
+% maps:update_with(R, fun(Ps) -> [{P, V} | Ps] end, [{P, V}], M).
+%
+%
+%ensure_deps(_, _, []) ->
+% ok;
+%ensure_deps(Socket, Realm, [{Name, Version} | Rest]) ->
+% ok = ensure_dep(Socket, {Realm, Name, Version}),
+% ensure_deps(Socket, Realm, Rest).
+%
+%
+%-spec ensure_dep(gen_tcp:socket(), package_id()) -> ok | no_return().
+%% @private
+%% Given an PackageID as an argument, check whether its package file exists in the
+%% system cache, and if not download it. Should return `ok' whenever the file is
+%% sourced, but exit with an error if it cannot locate or acquire the package.
+%
+%ensure_dep(Socket, PackageID) ->
+% ZrpFile = filename:join("zsp", namify_zsp(PackageID)),
+% ok =
+% case filelib:is_regular(ZrpFile) of
+% true -> ok;
+% false -> fetch(Socket, PackageID)
+% end,
+% ok = install(PackageID),
+% build(PackageID).
+%
+%
+%-spec scrub(Deps) -> Scrubbed
+% when Deps :: [package_id()],
+% Scrubbed :: [package_id()].
+%% @private
+%% Take a list of dependencies and return a list of dependencies that are not yet
+%% installed on the system.
+%
+%scrub([]) ->
+% [];
+%scrub(Deps) ->
+% lists:filter(fun(PackageID) -> not zx_lib:installed(PackageID) end, Deps).
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl
new file mode 100644
index 0000000..31e3572
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl
@@ -0,0 +1,73 @@
+%%% @doc
+%%% The ZX Connection Supervisor
+%%%
+%%% This supervisor maintains the lifecycle of all zomp_client worker processes.
+%%% @end
+
+-module(zx_conn_sup).
+-behavior(supervisor).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([start_conn/2]).
+-export([start_link/0]).
+-export([init/1]).
+
+
+
+%%% Interface Functions
+
+-spec start_conn(Host, Serial) -> Result
+ when Host :: zx:host(),
+ Serial :: zx:serial(),
+ Result :: {ok, pid()}
+ | {error, Reason},
+ Reason :: term().
+%% @doc
+%% Start an upstream connection handler.
+%% (Should only be called from zx_conn).
+
+start_conn(Host, Serial) ->
+ supervisor:start_child(?MODULE, [Host, Serial]).
+
+
+
+%%% Startup
+
+-spec start_link() -> Result
+ when Result :: {ok, pid()}
+ | {error, Reason},
+ Reason :: {already_started, pid()}
+ | {shutdown, term()}
+ | term().
+%% @private
+%% Called by zx_sup.
+%%
+%% Spawns a single, registered supervisor process.
+%%
+%% Error conditions, supervision strategies, and other important issues are
+%% explained in the supervisor module docs:
+%% http://erlang.org/doc/man/supervisor.html
+
+start_link() ->
+ supervisor:start_link({local, ?MODULE}, ?MODULE, none).
+
+
+-spec init(none) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
+%% @private
+%% Do not call this function directly -- it is exported only because it is a
+%% necessary part of the OTP supervisor behavior.
+
+init(none) ->
+ RestartStrategy = {simple_one_for_one, 1, 60},
+
+ Client = {zx_conn,
+ {zx_conn, start_link, []},
+ temporary,
+ brutal_kill,
+ worker,
+ [zx_conn]},
+
+ Children = [Client],
+ {ok, {RestartStrategy, Children}}.
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl
new file mode 100644
index 0000000..a7dada8
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl
@@ -0,0 +1,2036 @@
+%%% @doc
+%%% ZX Daemon
+%%%
+%%% Resident task daemon and runtime interface to Zomp.
+%%%
+%%% The daemon resides in the background once started and awaits query requests and
+%%% subscriptions from other processes. The daemon is only capable of handling
+%%% unprivileged ("leaf") actions.
+%%%
+%%%
+%%% Discrete state and local abstract data types
+%%%
+%%% The daemon must keep track of requestors, subscribers, peers, and zx_conn processes
+%%% by using monitors. Because these various types of clients are found in different
+%%% structures the monitors are maintained in a data type called monitor_index(),
+%%% shortened to "mx" throughout the module. This structure is treated as an opaque
+%%% data type and is handled by a set of functions defined toward the end of the module
+%%% as mx_*/N.
+%%%
+%%% Node connections (zx_conn processes) must also be tracked for status and realm
+%%% availability. This is done using a type called conn_index(), shortened to "cx"
+%%% throughout the module. conn_index() is treated as an abstract, opaque datatype
+%%% throughout the module and is handled via a set of cx_*/N functions (after the
+%%% mx_*/N section).
+%%%
+%%% Do NOT directly access data within these structures, use (or write) an accessor
+%%% function that does what you want. Accessor functions MUST be pure with the
+%%% exception of mx_add_monitor/3 and mx_del_monitor/3 that create and destroy
+%%% monitors.
+%%%
+%%%
+%%% Connection handling
+%%%
+%%% The daemon is structured as a service manager in a service -> worker structure.
+%%% http://zxq9.com/archives/1311
+%%% This allows it to abstract the servicing of tasks at a high level, making it
+%%% unnecessary for other processes to talk directly to any zx_conn processes or care
+%%% whether the current runtime is the host's zx proxy or a peer instance.
+%%%
+%%% It is in charge of the high-level task of servicing requested actions and returning
+%%% responses to callers as well as mapping successful connections to configured realms
+%%% and repairing failed connections to nodes that reduce availability of configured
+%%% realms.
+%%%
+%%% When the zx_daemon is started it checks local configuration and cache files to
+%%% determine what realms must be available and what cached Zomp nodes it is aware of.
+%%% It populates the CX (conn_index(), mentioned above) with realm config and host
+%%% cache data, and then initiates a connection attempt to each configured prime node
+%%% and up to maxconn connection attempts to cached nodes for each realm as well.
+%%% (See init_connections/0).
+%%%
+%%% Once connection attempts have been initiated the daemon waits in receive for
+%%% either a connection report (success or failure) or an action request from
+%%% elsewhere in the system.
+%%%
+%%% Connection status is relayed with report/1 and indicates to the daemon whether
+%%% a connection has failed, been disconneocted, redirected, or succeeded. See the
+%%% zx_conn internals for details. If a connection is successful then the zx_conn
+%%% will relay the connected node's realm availability status to the daemon, and
+%%% the daemon will match the node's provided realms with the configured realm list.
+%%% Any realms that are not yet provided by another connection will be assigned to
+%%% the reporting successful zx_conn. If no unserviced realms are provided by the
+%%% node the zx_conn will be shut down but the host info will be cached for future
+%%% use. Any realms that have an older serial than the serial currently known to
+%%% zx will be disregarded (which may result in termination of the connection if it
+%%% means there are no useful realms available on a given node).
+%%%
+%%% A failure can occur at any time. In the event a connected and assigned zx_conn
+%%% has failed the target host will be dropped from the hosts cache, the zx_conn will
+%%% terminate and a new one will be spawned in its place if there is a gap in
+%%% configured realm coverage.
+%%%
+%%% Nodes may be too busy (their client slots full) to accept a new connection. In
+%%% this case the node should give the zx_conn a redirect instruction during protocol
+%%% negotiation. The zx_conn will report the redirect and host list to the daemon,
+%%% and the daemon will add the hosts to the host cache and the redirecting host will
+%%% be placed at the rear of the host cache unless it is the prime node for the target
+%%% realm.
+%%%
+%%%
+%%% Request queues
+%%%
+%%% Requests, reports and subscription updates are all either forwarded to affected
+%%% processes or entered into a work queue. All such work requests are received as
+%%% asynchronous messages and cause the work queue to first be updated, and then,
+%%% as a separate step, the work queue is re-evaluated in its entirety. Any work that
+%%% cannot be completed (due to a realm not being available, for example) is recycled
+%%% to the queue. A connection report also triggers a queue re-evaluation, so there
+%%% should not be cases where the work queue stalls on active requests.
+%%%
+%%% Requestors sending either download or realm query requests are given a reference
+%%% (an integer, not an Erlang reference, as the message may cross node boundaries)
+%%% to match on for receipt of their result messages or to be used to cancel the
+%%% requested work (timeouts are handled by the caller, not by the daemon).
+%%%
+%%% A bit of state handling is required (queueing requests and storing the current
+%%% action state), but this permits the system above the daemon to interact with it in
+%%% a blocking way, establishing its own receive timeouts or implementing either an
+%%% asynchronous or synchronous interface library atop zx_daemon interface function,
+%%% but leaving zx_daemon and zx_conn alone to work asynchronously with one another.
+%%%
+%%%
+%%% Race Avoidance
+%%%
+%%% Each runtime can only have one zx_daemon alive at a time, and each system can
+%%% only have one zx_daemon directly performing actions at a time. This is to prevent
+%%% problems where multiple zx instances are running at the same time using the same
+%%% home directory and might clash with one another (overwriting each other's data,
+%%% corrupting package or key files, etc.). OTP makes running a single registered
+%%% process simple within a single runtime, but there is no standard cross-platform
+%%% method for ensuring a given process is the only one of its type in a given scope
+%%% within a host system.
+%%%
+%%% When zx starts the daemon will attempt an exclusive write to a lock file called
+%%% $ZOMP_DIR/john.locke using file:open(LockFile, [exclusive]), writing a system
+%%% timestamp. If the write succeeds then the daemon knows it is the master for the
+%%% system and will begin initiating connections as described above as well as open a
+%%% local socket to listen for other zx instances which will need to proxy their own
+%%% actions through the master. Once the socket is open, the lock file is updated with
+%%% the local port number. If the write fails then the file is read and if a port
+%%% number is indicated then the daemon connects to the master zx_daemon and proxies
+%%% its requests through it. If no port number exists then the daemon waits 5 seconds,
+%%% checks again, and if there is still no port number then it checks whether the
+%%% timestamp is more than 5 seconds old or in the future. If the timestamp is more
+%%% than 5 seconds old or in the future then the file is deleted and the process
+%%% of master identification starts again.
+%%%
+%%% If a master daemon's runtime is shutting down it will designate its oldest peer
+%%% daemon connection as the new master. At that point the new master will open a port
+%%% and rewrite the lock file. Once written the old master will drop all its node
+%%% connections and dequeue all current requests, then pass a local redirect message
+%%% to the subordinate daemons telling them the new port to which they should connect.
+%%%
+%%% Even if there is considrable churn within a system from, for example, scripted
+%%% initiation of several small utilities that have never been executed before, the
+%%% longest-living daemon should always become the master. This is not the most
+%%% efficient procedure, but it is the easiest to understand and debug across various
+%%% platforms.
+%%% @end
+
+-module(zx_daemon).
+-behavior(gen_server).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([pass_meta/3,
+ subscribe/1, unsubscribe/1,
+ list/0, list/1, list/2, list/3, latest/1,
+ fetch_zsp/1, fetch_key/1,
+ pending/1, packagers/1, maintainers/1, sysops/1]).
+-export([report/1, result/2, notify/2]).
+-export([start_link/0, stop/0]).
+-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
+ code_change/3, terminate/2]).
+
+
+-export_type([id/0, result/0,
+ realm_list/0, package_list/0, version_list/0, latest_result/0,
+ fetch_result/0, key_result/0,
+ pending_result/0, pack_result/0, maint_result/0, sysop_result/0,
+ sub_message/0]).
+
+
+-include("zx_logger.hrl").
+
+
+
+%%% Type Definitions
+
+-record(s,
+ {meta = none :: none | zx:package_meta(),
+ home = none :: none | file:filename(),
+ argv = none :: none | [string()],
+ sys_conf = zx_conf_sys:load() :: zx_conf_sys:data(),
+ id = 0 :: id(),
+ actions = [] :: [request()],
+ requests = maps:new() :: requests(),
+ dropped = maps:new() :: requests(),
+ mx = mx_new() :: monitor_index(),
+ cx = cx_load() :: conn_index()}).
+
+
+-record(cx,
+ {realms = #{} :: #{zx:realm() := realm_meta()},
+ attempts = [] :: [{pid(), zx:host(), [zx:realm()]}],
+ conns = [] :: [connection()]}).
+
+
+-record(rmeta,
+ {revision = 0 :: non_neg_integer(),
+ serial = 0 :: non_neg_integer(),
+ prime = {"zomp.tsuriai.jp", 11311} :: zx:host(),
+ private = [] :: [zx:host()],
+ mirrors = queue:new() :: queue:queue(zx:host()),
+ realm_keys = [] :: [zx:key_meta()],
+ package_keys = [] :: [zx:key_meta()],
+ sysops = [] :: [zx:sysop_meta()],
+ assigned = none :: none | pid(),
+ available = [] :: [pid()]}).
+
+
+-record(conn,
+ {pid :: pid(),
+ host :: zx:host(),
+ realms :: [zx:realm()],
+ requests :: [id()],
+ subs :: [{pid(), zx:package()}]}).
+
+
+%% State Types
+-type state() :: #s{}.
+-opaque id() :: non_neg_integer().
+-type request() :: {subscribe, pid(), zx:package()}
+ | {unsubscribe, pid(), zx:package()}
+ | {request, pid(), id(), action()}.
+-type requests() :: #{id() := {pid(), action()}}.
+-type monitor_index() :: #{pid() := {reference(), category()}}.
+-type conn_index() :: #cx{}.
+-type realm_meta() :: #rmeta{}.
+-type connection() :: #conn{}.
+-type category() :: {Reqs :: [id()], Subs :: [zx:package()]}
+ | attempt
+ | conn.
+
+%% Conn Communication
+-type conn_report() :: {connected, Realms :: [{zx:realm(), zx:serial()}]}
+ | {redirect, Hosts :: [zx:host()]}
+ | failed
+ | disconnected
+ | timeout.
+
+%% Subscriber / Requestor Communication
+% Incoming Request messages
+% This form allows a bit of cheating with blind calls to `element(2, Request)'.
+-type action() :: list
+ | {list, zx:realm()}
+ | {list, zx:realm(), zx:name()}
+ | {list, zx:realm(), zx:name(), zx:version()}
+ | {latest, zx:realm(), zx:name(), zx:version()}
+ | {fetch, zx:realm(), zx:name(), zx:version()}
+ | {fetchkey, zx:realm(), zx:key_name()}
+ | {pending, zx:realm(), zx:name()}
+ | {resigns, zx:realm()}
+ | {packagers, zx:realm(), zx:name()}
+ | {maintainers, zx:realm(), zx:name()}
+ | {sysops, zx:realm()}.
+
+% Outgoing Result Messages
+%
+% Results are sent wrapped a triple: {result, Ref, Result}
+% where the result itself is a triple: {Type, Identifier, Content}
+%
+% Subscription messages are a separate type below.
+
+-type result() :: {z_result,
+ RequestID :: id(),
+ Message :: realm_list()
+ | package_list()
+ | version_list()
+ | latest_result()
+ | fetch_result()
+ | key_result()
+ | pending_result()
+ | pack_result()
+ | maint_result()
+ | sysop_result()}.
+
+-type realm_list() :: [zx:realm()].
+-type package_list() :: {ok, [zx:name()]}
+ | {error, bad_realm
+ | timeout}.
+-type version_list() :: {ok, [zx:version()]}
+ | {error, bad_realm
+ | bad_package
+ | timeout}.
+-type latest_result() :: {ok, zx:version()}
+ | {error, bad_realm
+ | bad_package
+ | bad_version
+ | timeout}.
+-type fetch_result() :: {hops, non_neg_integer()}
+ | done
+ | {error, bad_realm
+ | bad_package
+ | bad_version
+ | timeout}.
+-type key_result() :: done
+ | {error, bad_realm
+ | bad_key
+ | timeout}.
+-type pending_result() :: {ok, [zx:version()]}
+ | {error, bad_realm
+ | bad_package
+ | timeout}.
+-type pack_result() :: {ok, [zx:user()]}
+ | {error, bad_realm
+ | bad_package
+ | timeout}.
+-type maint_result() :: {ok, [zx:user()]}
+ | {error, bad_realm
+ | bad_package
+ | timeout}.
+-type sysop_result() :: {ok, [zx:user()]}
+ | {error, bad_host
+ | timeout}.
+
+
+% Subscription Results
+-type sub_message() :: {z_sub,
+ zx:package(),
+ Message :: {update, zx:package_id()}
+ | {error, bad_realm | bad_package}}.
+
+
+%%% Requestor Interface
+
+-spec pass_meta(Meta, Dir, ArgV) -> ok
+ when Meta :: zx:package_meta(),
+ Dir :: file:filename(),
+ ArgV :: [string()].
+%% @private
+%% Load the daemon with the primary running application's meta data and location within
+%% the filesystem. This step allows running development code from any location in
+%% the filesystem against installed dependencies without requiring any magical
+%% references.
+
+pass_meta(Meta, Dir, ArgV) ->
+ gen_server:cast(?MODULE, {pass_meta, Meta, Dir, ArgV}).
+
+
+-spec subscribe(Package) -> ok
+ when Package :: zx:package().
+%% @doc
+%% Subscribe to update notifications for a for a package.
+%% The caller will receive update notifications of type `sub_message()' as Erlang
+%% messages whenever an update occurs.
+%% Crashes the caller if the Realm or Name of the Package argument are illegal
+%% `zx:lower0_9()' strings.
+
+subscribe(Package = {Realm, Name}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ gen_server:cast(?MODULE, {subscribe, self(), Package}).
+
+
+-spec unsubscribe(Package) -> ok
+ when Package :: zx:package().
+%% @doc
+%% Instructs the daemon to unsubscribe if subscribed. Has no effect if not subscribed.
+%% Crashes the caller if the Realm or Name of the Package argument are illegal
+%% `lower0_9' strings.
+
+unsubscribe(Package = {Realm, Name}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ gen_server:cast(?MODULE, {unsubscribe, self(), Package}).
+
+
+-spec list() -> realm_list().
+%% @doc
+%% Request a list of currently configured realms. Because this call is entirely local
+%% it is the only one that does not involve a round-trip
+
+list() ->
+ gen_server:call(?MODULE, {request, list}).
+
+
+-spec list(Realm) -> {ok, RequestID}
+ when Realm :: zx:realm(),
+ RequestID :: term().
+%% @doc
+%% Requests a list of packages provided by the given realm.
+%% Returns a request ID which will be returned in a message with the result from an
+%% upstream zomp node. Crashes the caller if Realm is an illegal string.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `package_list()'.
+
+list(Realm) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ request({list, Realm}).
+
+
+-spec list(Realm, Name) -> {ok, RequestID}
+ when Realm :: zx:realm(),
+ Name :: zx:name(),
+ RequestID :: term().
+%% @doc
+%% Requests a list of package versions.
+%% Returns a request ID which will be returned in a message with the result from an
+%% upstream zomp node. Crashes the if Realm or Name are illegal strings.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `version_list()'.
+
+list(Realm, Name) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ request({list, Realm, Name}).
+
+
+-spec list(Realm, Name, Version) -> {ok, RequestID}
+ when Realm :: zx:realm(),
+ Name :: zx:name(),
+ Version :: zx:version(),
+ RequestID :: term().
+%% @doc
+%% Request a list of package versions constrained by a partial version.
+%% Returns a request ID which will be returned in a message with the result from an
+%% upstream zomp node. Can be used to check for a specific version by testing for a
+%% response of `{error, bad_version}' when a full version number is provided.
+%% Crashes the caller on an illegal realm name, package name, or version tuple.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `list_result()'.
+
+list(Realm, Name, Version) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ true = zx_lib:valid_version(Version),
+ request({list, Realm, Name, Version}).
+
+
+-spec latest(Identifier) -> {ok, RequestID}
+ when Identifier :: zx:package() | zx:package_id(),
+ RequestID :: integer().
+%% @doc
+%% Request the lastest version of a package within the provided version constraint.
+%% If no version is provided then the latest version overall will be returned.
+%% Returns a request ID which will be returned in a message with the result from an
+%% upstream zomp node. Crashes the caller on an illegal realm name, package name or
+%% version tuple.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `latest_result()'.
+
+latest({Realm, Name}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ request({latest, Realm, Name, {z, z, z}});
+latest({Realm, Name, Version}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ true = zx_lib:valid_version(Version),
+ request({latest, Realm, Name, Version}).
+
+
+-spec fetch_zsp(PackageID) -> {ok, RequestID}
+ when PackageID :: zx:package_id(),
+ RequestID :: integer().
+%% @doc
+%% Ensure a package is available locally, or queue it for download otherwise.
+%% Returns a request ID which will be returned in a message with the result from an
+%% upstream zomp node. Crashes the caller on an illegal realm name, package name or
+%% version tuple.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `fetch_result()'.
+
+fetch_zsp(PackageID = {Realm, Name, Version}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ true = zx_lib:valid_version(Version),
+ request({fetch, zsp, PackageID}).
+
+
+-spec fetch_key(KeyID) -> {ok, RequestID}
+ when KeyID :: zx:key_id(),
+ RequestID :: id().
+%% @doc
+%% Request a public key be fetched from its relevant realm.
+%% Crashes the caller if either component of the KeyID is illegal.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `key_result()'.
+
+fetch_key(KeyID = {Realm, KeyName}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(KeyName),
+ request({fetch, key, KeyID}).
+
+
+-spec pending(Package) -> {ok, RequestID}
+ when Package :: zx:package(),
+ RequestID :: id().
+%% @doc
+%% Request the list of versions of a given package that have been submitted but not
+%% signed and included in their relevant realm.
+%% Crashes the caller if either component of the Package is illegal.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `pending_result()'.
+
+pending({Realm, Name}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ request({pending, Realm, Name}).
+
+
+-spec packagers(Package) -> {ok, RequestID}
+ when Package :: zx:package(),
+ RequestID :: id().
+%% @doc
+%% Request a list of packagers assigned to work on a given package.
+%% Crashes the caller if either component of the Package is illegal.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `pack_result()'.
+
+packagers({Realm, Name}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ request({packagers, Realm, Name}).
+
+
+-spec maintainers(Package) -> {ok, RequestID}
+ when Package :: zx:package(),
+ RequestID :: id().
+%% @doc
+%% Request a list of maintainers assigned to work on a given package.
+%% Crashes the caller if either component of the Package is illegal.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `maint_result()'.
+
+maintainers({Realm, Name}) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ true = zx_lib:valid_lower0_9(Name),
+ request({maintainers, Realm, Name}).
+
+
+-spec sysops(Realm) -> {ok, RequestID}
+ when Realm :: zx:realm(),
+ RequestID :: id().
+%% @doc
+%% Request a list of sysops in charge of maintaining a given realm. What this
+%% effectively does is request the sysops of the prime host of the given realm.
+%% Crashes the caller if the Realm string is illegal.
+%%
+%% Response messages are of the type `result()' where the third element is of the
+%% type `sysops_result()'.
+
+sysops(Realm) ->
+ true = zx_lib:valid_lower0_9(Realm),
+ request({sysops, Realm}).
+
+
+%% Request Caster
+-spec request(action()) -> {ok, RequestID}
+ when RequestID :: integer().
+%% @private
+%% Private function to wrap the necessary bits up.
+
+request(Action) ->
+ gen_server:call(?MODULE, {request, self(), Action}).
+
+
+
+%%% Upstream Zomp connection interface
+
+-spec report(Message) -> ok
+ when Message :: {connected, Realms :: [{zx:realm(), zx:serial()}]}
+ | {redirect, Hosts :: [{zx:host(), [zx:realm()]}]}
+ | failed
+ | disconnected.
+%% @private
+%% Should only be called by a zx_conn. This function is how a zx_conn reports its
+%% current connection status and job results.
+
+report(Message) ->
+ gen_server:cast(?MODULE, {report, self(), Message}).
+
+
+-spec result(id(), result()) -> ok.
+%% @private
+%% Return a tagged result back to the daemon to be forwarded to the original requestor.
+
+result(Reference, Result) ->
+ gen_server:cast(?MODULE, {result, Reference, Result}).
+
+
+-spec notify(Package, Message) -> ok
+ when Package :: zx:package(),
+ Message :: term().
+%% @private
+%% Function called by a connection when a subscribed update arrives.
+
+notify(Package, Message) ->
+ gen_server:cast(?MODULE, {notify, self(), Package, Message}).
+
+
+
+%%% Startup
+
+-spec start_link() -> {ok, pid()} | {error, term()}.
+%% @private
+%% Startup function -- intended to be called by supervisor.
+
+start_link() ->
+ gen_server:start_link({local, ?MODULE}, ?MODULE, none, []).
+
+
+-spec init(none) -> {ok, state()}.
+%% @private
+%% TODO: Implement lockfile checking and master lock acquisition.
+
+init(none) ->
+ Blank = blank_state(),
+ {ok, MX, CX} = init_connections(),
+ State = Blank#s{mx = MX, cx = CX},
+ {ok, State}.
+
+
+-spec blank_state() -> state().
+%% @private
+%% Used to generate a correct, but exactly empty state.
+%% Useful mostly for testing and validation, though also actually used in the program.
+
+blank_state() ->
+ #s{}.
+
+
+-spec init_connections() -> {ok, MX, CX}
+ when MX :: monitor_index(),
+ CX :: conn_index().
+%% @private
+%% Starting from a stateless condition, recruit and resolve all realm relevant data,
+%% populate host caches, and initiate connections to required realms. On completion
+%% return a populated MX and CX to the caller. Should only ever be called by init/1.
+%% Returns an `ok' tuple to disambiguate it from pure functions *and* to leave an
+%% obvious place to populate error returns in the future if desired.
+
+init_connections() ->
+ CX = cx_load(),
+ MX = mx_new(),
+ Realms = cx_realms(CX),
+ init_connections(Realms, MX, CX).
+
+
+-spec init_connections(Realms, MX, CX) -> {ok, NewMX, NewCX}
+ when Realms :: [zx:realm()],
+ MX :: monitor_index(),
+ CX :: conn_index(),
+ NewMX :: monitor_index(),
+ NewCX :: conn_index().
+
+init_connections([Realm | Realms], MX, CX) ->
+ {ok, Hosts, NextCX} = cx_next_hosts(3, Realm, CX),
+ MaybeAttempt =
+ fun(Host, {M, C}) ->
+ case cx_maybe_add_attempt(Host, Realm, C) of
+ not_connected ->
+ {ok, Pid} = zx_conn:start(Host),
+ NewM = mx_add_monitor(Pid, attempt, M),
+ NewC = cx_add_attempt(Pid, Host, Realm, C),
+ {NewM, NewC};
+ {ok, NewC} ->
+ {M, NewC}
+ end
+ end,
+ {NewMX, NewCX} = lists:foldl(MaybeAttempt, {MX, NextCX}, Hosts),
+ init_connections(Realms, NewMX, NewCX);
+init_connections([], MX, CX) ->
+ {ok, MX, CX}.
+
+
+
+%%% Shutdown
+
+-spec stop() -> ok.
+%% @doc
+%% A polite way to shut down the daemon without doing a bunch of vile things.
+
+stop() ->
+ gen_server:cast(?MODULE, stop).
+
+
+
+%%% gen_server
+
+%% @private
+%% gen_server callback for OTP calls
+
+handle_call({request, list}, _, State = #s{cx = CX}) ->
+ Realms = cx_realms(CX),
+ {reply, {ok, Realms}, State};
+handle_call({request, Requestor, Action}, From, State = #s{id = ID}) ->
+ NewID = ID + 1,
+ _ = gen_server:reply(From, {ok, NewID}),
+ NextState = do_request(Requestor, Action, State#s{id = NewID}),
+ NewState = eval_queue(NextState),
+ {noreply, NewState};
+handle_call(Unexpected, From, State) ->
+ ok = log(warning, "Unexpected call ~tp: ~tp", [From, Unexpected]),
+ {noreply, State}.
+
+
+%% @private
+%% gen_server callback for OTP casts
+
+handle_cast({pass_meta, Meta, Dir, ArgV}, State) ->
+ NewState = do_pass_meta(Meta, Dir, ArgV, State),
+ {noreply, NewState};
+handle_cast({subscribe, Pid, Package}, State) ->
+ NextState = do_subscribe(Pid, Package, State),
+ NewState = eval_queue(NextState),
+ {noreply, NewState};
+handle_cast({unsubscribe, Pid, Package}, State) ->
+ NextState = do_unsubscribe(Pid, Package, State),
+ NewState = eval_queue(NextState),
+ {noreply, NewState};
+handle_cast({report, Conn, Message}, State) ->
+ NextState = do_report(Conn, Message, State),
+ NewState = eval_queue(NextState),
+ {noreply, NewState};
+handle_cast({result, Ref, Result}, State) ->
+ NextState = do_result(Ref, Result, State),
+ NewState = eval_queue(NextState),
+ {noreply, NewState};
+handle_cast({notify, Conn, Package, Update}, State) ->
+ ok = do_notify(Conn, Package, Update, State),
+ NewState = eval_queue(State),
+ {noreply, NewState};
+handle_cast(stop, State) ->
+ {stop, normal, State};
+handle_cast(Unexpected, State) ->
+ ok = log(warning, "Unexpected cast: ~tp", [Unexpected]),
+ {noreply, State}.
+
+
+%% @private
+%% gen_sever callback for general Erlang message handling
+
+handle_info({'DOWN', Ref, process, Pid, Reason}, State) ->
+ NewState = clear_monitor(Pid, Ref, Reason, State),
+ {noreply, NewState};
+handle_info(Unexpected, State) ->
+ ok = log(warning, "Unexpected info: ~tp", [Unexpected]),
+ {noreply, State}.
+
+
+%% @private
+%% gen_server callback to handle state transformations necessary for hot
+%% code updates. This template performs no transformation.
+
+code_change(_, State, _) ->
+ {ok, State}.
+
+
+%% @private
+%% gen_server callback to handle shutdown/cleanup tasks on receipt of a clean
+%% termination request.
+%% TODO: Implement new master selection, dequeuing and request queue passing.
+
+terminate(normal, #s{cx = CX}) ->
+ ok = log(info, "zx_daemon shutting down..."),
+ case cx_store_cache(CX) of
+ ok ->
+ log(info, "Cache written.");
+ {error, Reason} ->
+ Message = "Cache write failed with ~tp",
+ log(error, Message, [Reason])
+ end.
+
+
+
+%%% Doer Functions
+
+-spec do_pass_meta(Meta, Home, ArgV, State) -> NewState
+ when Meta :: zx:package_meta(),
+ Home :: file:filename(),
+ ArgV :: [string()],
+ State :: state(),
+ NewState :: state().
+
+do_pass_meta(Meta, Home, ArgV, State) ->
+ PackageID = maps:get(package_id, Meta),
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = log(info, "Received meta for ~tp.", [PackageString]),
+ State#s{meta = Meta, home = Home, argv = ArgV}.
+
+
+-spec do_subscribe(Pid, Package, State) -> NextState
+ when Pid :: pid(),
+ Package :: zx:package(),
+ State :: state(),
+ NextState :: state().
+%% @private
+%% Enqueue a subscription request.
+
+do_subscribe(Pid, Package, State = #s{actions = Actions}) ->
+ NewActions = [{subscribe, Pid, Package} | Actions],
+ State#s{actions = NewActions}.
+
+
+-spec do_unsubscribe(Pid, Package, State) -> NextState
+ when Pid :: pid(),
+ Package :: zx:package(),
+ State :: state(),
+ NextState :: state().
+%% @private
+%% Clear or dequeue a subscription request.
+
+do_unsubscribe(Pid, Package, State = #s{actions = Actions}) ->
+ NewActions = [{unsubscribe, Pid, Package} | Actions],
+ State#s{actions = NewActions}.
+
+
+-spec do_request(Requestor, Action, State) -> NextState
+ when Requestor :: pid(),
+ Action :: action(),
+ State :: state(),
+ NextState :: state().
+%% @private
+%% Enqueue requests and update relevant index.
+
+do_request(Requestor, Action, State = #s{id = ID, actions = Actions}) ->
+ NewActions = [{request, Requestor, ID, Action} | Actions],
+ State#s{actions = NewActions}.
+
+
+-spec do_report(Conn, Message, State) -> NewState
+ when Conn :: pid(),
+ Message :: conn_report(),
+ State :: state(),
+ NewState :: state().
+%% @private
+%% Receive a report from a connection process, update the connection index and
+%% possibly retry connections.
+
+do_report(Conn, {connected, Realms}, State = #s{mx = MX, cx = CX}) ->
+ NextMX = mx_upgrade_conn(Conn, MX),
+ {NewMX, NewCX} =
+ case cx_connected(Realms, Conn, CX) of
+ {assigned, NextCX} ->
+ {NextMX, NextCX};
+ {unassigned, NextCX} ->
+ ScrubbedMX = mx_del_monitor(Conn, conn, NextMX),
+ ok = zx_conn:stop(Conn),
+ {ScrubbedMX, NextCX}
+ end,
+ State#s{mx = NewMX, cx = NewCX};
+do_report(Conn, {redirect, Hosts}, State = #s{mx = MX, cx = CX}) ->
+ NextMX = mx_del_monitor(Conn, attempt, MX),
+ {Unassigned, NextCX} = cx_redirect(Conn, Hosts, CX),
+ {NewMX, NewCX} = ensure_connections(Unassigned, NextMX, NextCX),
+ State#s{mx = NewMX, cx = NewCX};
+do_report(Conn, failed, State = #s{mx = MX}) ->
+ NewMX = mx_del_monitor(Conn, attempt, MX),
+ failed(Conn, State#s{mx = NewMX});
+do_report(Conn, disconnected, State = #s{mx = MX}) ->
+ NewMX = mx_del_monitor(Conn, conn, MX),
+ disconnected(Conn, State#s{mx = NewMX});
+do_report(Conn, timeout, State = #s{mx = MX}) ->
+ ok = log(warning, "Connection ~tp timed out.", [Conn]),
+ NewMX = mx_del_monitor(Conn, conn, MX),
+ disconnected(Conn, State#s{mx = NewMX}).
+
+
+-spec failed(Conn, State) -> NewState
+ when Conn :: pid(),
+ State :: state(),
+ NewState :: state().
+
+failed(Conn, State = #s{mx = MX, cx = CX}) ->
+ {Realms, NextCX} = cx_failed(Conn, CX),
+ {NewMX, NewCX} = ensure_connections(Realms, MX, NextCX),
+ State#s{mx = NewMX, cx = NewCX}.
+
+
+-spec disconnected(Conn, State) -> NewState
+ when Conn :: pid(),
+ State :: state(),
+ NewState :: state().
+
+disconnected(Conn,
+ State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) ->
+ {Pending, LostSubs, Unassigned, ScrubbedCX} = cx_disconnected(Conn, CX),
+ ReSubs = [{S, {subscribe, P}} || {S, P} <- LostSubs],
+ {Dequeued, NewRequests} = maps:fold(dequeue(Pending), {#{}, #{}}, Requests),
+ ReReqs = maps:to_list(Dequeued),
+ NewActions = ReReqs ++ ReSubs ++ Actions,
+ {NewMX, NewCX} = ensure_connections(Unassigned, MX, ScrubbedCX),
+ State#s{actions = NewActions,
+ requests = NewRequests,
+ mx = NewMX,
+ cx = NewCX}.
+
+
+-spec dequeue(Pending) -> fun((K, V, {D, R}) -> {NewD, NewR})
+ when Pending :: [id()],
+ K :: id(),
+ V :: request(),
+ D :: #{id() := request()},
+ R :: #{id() := request()},
+ NewD :: #{id() := request()},
+ NewR :: #{id() := request()}.
+%% @private
+%% Return a function that partitions the current Request map into two maps, one that
+%% matches the closed `Pending' list of references and ones that don't.
+
+dequeue(Pending) ->
+ fun(K, V, {D, R}) ->
+ case lists:member(K, Pending) of
+ true -> {maps:put(K, V, D), R};
+ false -> {D, maps:put(K, V, R)}
+ end
+ end.
+
+
+-spec ensure_connections(Realms, MX, CX) -> {NewMX, NewCX}
+ when Realms :: [zx:realm()],
+ MX :: monitor_index(),
+ CX :: conn_index(),
+ NewMX :: monitor_index(),
+ NewCX :: conn_index().
+%% @private
+%% Check the list of unprovided realms with all available connections that can provide
+%% it, and allocate accordingly. If any realms cannot be provided by existing
+%% connections, new connections are initiated for all unprovided realms.
+
+ensure_connections(Realms, MX, CX) ->
+ {NextCX, Unavailable} = reassign_conns(Realms, CX, []),
+ {ok, NewMX, NewCX} = init_connections(Unavailable, MX, NextCX),
+ {NewMX, NewCX}.
+
+
+-spec reassign_conns(Realms, CX, Unavailable) -> {NewCX, NewUnavailable}
+ when Realms :: [zx:realm()],
+ CX :: conn_index(),
+ Unavailable :: [zx:realm()],
+ NewCX :: conn_index(),
+ NewUnavailable :: [zx:realm()].
+%% @private
+%% Finds connections that provide a requested realm and assigns that connection to
+%% take over realm provision. Returns the updated CX and a list of all the realms
+%% that could not be provided by any available connection.
+
+reassign_conns([Realm | Realms], CX = #cx{realms = RMetas}, Unassigned) ->
+ {NewUnassigned, NewCX} =
+ case maps:get(Realm, RMetas) of
+ #rmeta{available = []} ->
+ {[Realm | Unassigned], CX};
+ Meta = #rmeta{available = [Conn | Conns]} ->
+ NewMeta = Meta#rmeta{assigned = Conn, available = Conns},
+ NewRMetas = maps:put(Realm, NewMeta, RMetas),
+ NextCX = CX#cx{realms = NewRMetas},
+ {Unassigned, NextCX}
+ end,
+ reassign_conns(Realms, NewCX, NewUnassigned);
+reassign_conns([], CX, Unassigned) ->
+ {CX, Unassigned}.
+
+
+-spec do_result(ID, Result, State) -> NewState
+ when ID :: id(),
+ Result :: result(),
+ State :: state(),
+ NewState :: state().
+%% @private
+%% Receive the result of a sent request and route it back to the original requestor.
+
+do_result(ID, Result, State = #s{requests = Requests, dropped = Dropped, mx = MX}) ->
+ {NewDropped, NewRequests, NewMX} =
+ case maps:take(ID, Requests) of
+ {Request, NextRequests} ->
+ Requestor = element(1, Request),
+ Requestor ! {z_result, ID, Result},
+ NextMX = mx_del_monitor(Requestor, {requestor, ID}, MX),
+ {Dropped, NextRequests, NextMX};
+ error ->
+ NextDropped = handle_orphan_result(ID, Result, Dropped),
+ {NextDropped, Requests, MX}
+ end,
+ State#s{requests = NewRequests, dropped = NewDropped, mx = NewMX}.
+
+
+-spec handle_orphan_result(ID, Result, Dropped) -> NewDropped
+ when ID :: id(),
+ Result :: result(),
+ Dropped :: requests(),
+ NewDropped :: requests().
+%% @private
+%% Log request results if they have been orphaned by their original requestor.
+%% Log a warning if the result is totally unknown.
+
+handle_orphan_result(ID, Result, Dropped) ->
+ case maps:take(ID, Dropped) of
+ {Request, NewDropped} ->
+ Message = "Received orphan result for ~tp, ~tp: ~tp",
+ ok = log(info, Message, [ID, Request, Result]),
+ NewDropped;
+ error ->
+ Message = "Received untracked request result ~tp: ~tp",
+ ok = log(warning, Message, [ID, Result]),
+ Dropped
+ end.
+
+
+-spec do_notify(Conn, Channel, Message, State) -> ok
+ when Conn :: pid(),
+ Channel :: term(),
+ Message :: term(),
+ State :: state().
+%% @private
+%% Broadcast a subscription message to all subscribers of a channel.
+%% At the moment the only possible sub channels are packages, but this will almost
+%% certainly change in the future to include general realm update messages (new keys,
+%% packages, user announcements, etc.) and whatever else becomes relevant as the
+%% system evolves. The types here are deliberately a bit abstract to prevent future
+%% type tracing with Dialyzer, since we know the functions calling this routine and
+%% are already tightly typed.
+
+do_notify(Conn, Channel, Message, #s{cx = CX}) ->
+ Subscribers = cx_get_subscribers(Conn, Channel, CX),
+ Notify = fun(P) -> P ! {z_sub, Channel, Message} end,
+ lists:foreach(Notify, Subscribers).
+
+
+-spec eval_queue(State) -> NewState
+ when State :: state(),
+ NewState :: state().
+%% @private
+%% This is one of the two engines that drives everything, the other being do_report/3.
+%% This function must iterate as far as it can into the request queue, adding response
+%% entries to the pending response structure as it goes.
+
+eval_queue(State = #s{actions = Actions}) ->
+ InOrder = lists:reverse(Actions),
+ eval_queue(InOrder, State#s{actions = []}).
+
+
+-spec eval_queue(Actions, State) -> NewState
+ when Actions :: [action()],
+ State :: state(),
+ NewState :: state().
+%% @private
+%% This is essentially a big, gnarly fold over the action list with State as the
+%% accumulator. It repacks the State#s.actions list with whatever requests were not
+%% able to be handled and updates State in whatever way necessary according to the
+%% handled requests.
+
+eval_queue([], State) ->
+ State;
+eval_queue([Action = {request, Pid, ID, Message} | Rest],
+ State = #s{actions = Actions, requests = Requests, mx = MX, cx = CX}) ->
+ {NewActions, NewRequests, NewMX, NewCX} =
+ case dispatch_request(Message, ID, CX) of
+ {dispatched, NextCX} ->
+ NextRequests = maps:put(ID, {Pid, Message}, Requests),
+ NextMX = mx_add_monitor(Pid, requestor, MX),
+ {Actions, NextRequests, NextMX, NextCX};
+ {result, Response} ->
+ Pid ! Response,
+ {Actions, Requests, MX, CX};
+ wait ->
+ NextActions = [Action | Actions],
+ NextMX = mx_add_monitor(Pid, requestor, MX),
+ {NextActions, Requests, NextMX, CX}
+ end,
+ NewState =
+ State#s{actions = NewActions,
+ requests = NewRequests,
+ mx = NewMX,
+ cx = NewCX},
+ eval_queue(Rest, NewState);
+eval_queue([Action = {subscribe, Pid, Package} | Rest],
+ State = #s{actions = Actions, mx = MX, cx = CX}) ->
+ {NewActions, NewMX, NewCX} =
+ case cx_add_sub(Pid, Package, CX) of
+ {need_sub, Conn, NextCX} ->
+ ok = zx_conn:subscribe(Conn, Package),
+ NextMX = mx_add_monitor(Pid, subscriber, MX),
+ {Actions, NextMX, NextCX};
+ {have_sub, NextCX} ->
+ NextMX = mx_add_monitor(Pid, subscriber, MX),
+ {Actions, NextMX, NextCX};
+ unassigned ->
+ NextMX = mx_add_monitor(Pid, subscriber, MX),
+ {[Action | Actions], NextMX, CX};
+ unconfigured ->
+ Pid ! {z_sub, Package, {error, bad_realm}},
+ {Actions, MX, CX}
+ end,
+ eval_queue(Rest, State#s{actions = NewActions, mx = NewMX, cx = NewCX});
+eval_queue([{unsubscribe, Pid, Package} | Rest],
+ State = #s{mx = MX, cx = CX}) ->
+ {ok, NewMX} = mx_del_monitor(Pid, {subscription, Package}, MX),
+ NewCX =
+ case cx_del_sub(Pid, Package, CX) of
+ {{drop_sub, ConnPid}, NextCX} ->
+ ok = zx_conn:unsubscribe(ConnPid, Package),
+ NextCX;
+ {keep_sub, NextCX} ->
+ NextCX;
+ unassigned ->
+ CX;
+ unconfigured ->
+ Message = "Received 'unsubscribe' request for unconfigured realm: ~tp",
+ ok = log(warning, Message, [Package]),
+ CX
+ end,
+ eval_queue(Rest, State#s{mx = NewMX, cx = NewCX}).
+
+
+-spec dispatch_request(Action, ID, CX) -> Result
+ when Action :: action(),
+ ID :: id(),
+ CX :: conn_index(),
+ Result :: {dispatched, NewCX}
+ | {result, Response}
+ | wait,
+ NewCX :: conn_index(),
+ Response :: result().
+%% @private
+%% Routes a request to the correct realm connector, if it is available. If it is not
+%% available but configured it will return `wait' indicating that the caller should
+%% repack the request and attempt to re-evaluate it later. If the realm is not
+%% configured at all, the process is short-circuited by forming an error response
+%% directly.
+
+dispatch_request(Action, ID, CX) ->
+ Realm = element(2, Action),
+ case cx_pre_send(Realm, ID, CX) of
+ {ok, Conn, NewCX} ->
+ ok = zx_conn:request(Conn, ID, Action),
+ {dispatched, NewCX};
+ unassigned ->
+ wait;
+ unconfigured ->
+ Error = {error, bad_realm},
+ {result, ID, Error}
+ end.
+
+
+-spec clear_monitor(Pid, Ref, Reason, State) -> NewState
+ when Pid :: pid(),
+ Ref :: reference(),
+ Reason :: term(),
+ State :: state(),
+ NewState :: state().
+%% @private
+%% Deal with a crashed requestor, subscriber or connector.
+
+clear_monitor(Pid,
+ Ref,
+ Reason,
+ State = #s{actions = Actions,
+ requests = Requests,
+ dropped = Dropped,
+ mx = MX,
+ cx = CX}) ->
+ case mx_crashed_monitor(Pid, MX) of
+ {attempt, NewMX} ->
+ failed(Pid, State#s{mx = NewMX});
+ {conn, NewMX} ->
+ disconnected(Pid, State#s{mx = NewMX});
+ {{Reqs, Subs}, NewMX} ->
+ NewActions = drop_actions(Pid, Actions),
+ {NewDropped, NewRequests} = drop_requests(Pid, Dropped, Requests),
+ NewCX = cx_clear_client(Pid, Reqs, Subs, CX),
+ State#s{actions = NewActions,
+ requests = NewRequests,
+ dropped = NewDropped,
+ mx = NewMX,
+ cx = NewCX};
+ unknown ->
+ Unexpected = {'DOWN', Ref, process, Pid, Reason},
+ ok = log(warning, "Unexpected info: ~tp", [Unexpected]),
+ State
+ end.
+
+
+-spec drop_actions(Requestor, Actions) -> NewActions
+ when Requestor :: pid(),
+ Actions :: [request()],
+ NewActions :: [request()].
+
+drop_actions(Pid, Actions) ->
+ Clear =
+ fun
+ ({request, P, _}) -> P /= Pid;
+ ({subscribe, P, _}) -> P /= Pid;
+ ({unsubscribe, _, _}) -> false
+ end,
+ lists:filter(Clear, Actions).
+
+
+-spec drop_requests(ReqIDs, Dropped, Requests) -> {NewDropped, NewRequests}
+ when ReqIDs :: [id()],
+ Dropped :: requests(),
+ Requests :: requests(),
+ NewDropped :: requests(),
+ NewRequests :: requests().
+
+drop_requests(ReqIDs, Dropped, Requests) ->
+ Partition =
+ fun(K, {Drop, Keep}) ->
+ {V, NewKeep} = maps:take(K, Keep),
+ NewDrop = maps:put(K, V, Drop),
+ {NewDrop, NewKeep}
+ end,
+ lists:fold(Partition, {Dropped, Requests}, ReqIDs).
+
+
+
+%%% Monitor Index ADT Interface Functions
+
+-spec mx_new() -> monitor_index().
+%% @private
+%% Returns a new, empty monitor index.
+
+mx_new() ->
+ maps:new().
+
+
+-spec mx_add_monitor(Pid, Category, MX) -> NewMX
+ when Pid :: pid(),
+ Category :: subscriber
+ | requestor
+ | attempt,
+ MX :: monitor_index(),
+ NewMX :: monitor_index().
+%% @private
+%% Begin monitoring the given Pid, keeping track of its category.
+
+mx_add_monitor(Pid, subscriber, MX) ->
+ case maps:take(Pid, MX) of
+ {{Ref, {Subs, Reqs}}, NextMX} ->
+ maps:put(Pid, {Ref, {Subs + 1, Reqs}}, NextMX);
+ error ->
+ Ref = monitor(process, Pid),
+ maps:put(Pid, {Ref, {1, 0}}, MX)
+ end;
+mx_add_monitor(Pid, requestor, MX) ->
+ case maps:take(Pid, MX) of
+ {{Ref, {Subs, Reqs}}, NextMX} ->
+ maps:put(Pid, {Ref, {Subs, Reqs + 1}}, NextMX);
+ error ->
+ Ref = monitor(process, Pid),
+ maps:put(Pid, {Ref, {0, 1}}, MX)
+ end;
+mx_add_monitor(Pid, attempt, MX) ->
+ false = maps:is_key(Pid, MX),
+ Ref = monitor(process, Pid),
+ maps:put(Pid, {Ref, attempt}, MX).
+
+
+-spec mx_upgrade_conn(Pid, MX) -> NewMX
+ when Pid :: pid(),
+ MX :: monitor_index(),
+ NewMX :: monitor_index().
+%% @private
+%% Upgrade an `attempt' monitor to a `conn' monitor.
+
+mx_upgrade_conn(Pid, MX) ->
+ {{Ref, attempt}, NextMX} = maps:take(Pid, MX),
+ maps:put(Pid, {Ref, conn}, NextMX).
+
+
+-spec mx_del_monitor(Conn, Category, MX) -> NewMX
+ when Conn :: pid(),
+ Category :: attempt
+ | conn
+ | {requestor, id()}
+ | {subscriber, Sub :: tuple()},
+ MX :: monitor_index(),
+ NewMX :: monitor_index().
+%% @private
+%% Drop a monitor category, removing the entire monitor in the case only one category
+%% exists. Returns a tuple including the remaining request references in the case of
+%% a conn type.
+
+mx_del_monitor(Pid, attempt, MX) ->
+ {{Ref, attempt}, NewMX} = maps:take(Pid, MX),
+ true = demonitor(Ref, [flush]),
+ NewMX;
+mx_del_monitor(Pid, conn, MX) ->
+ {{Ref, conn}, NewMX} = maps:take(Pid, MX),
+ true = demonitor(Ref, [flush]),
+ NewMX;
+mx_del_monitor(Pid, {requestor, ID}, MX) ->
+ case maps:take(Pid, MX) of
+ {{Ref, {[ID], []}}, NextMX} ->
+ true = demonitor(Ref, [flush]),
+ NextMX;
+ {{Ref, {Reqs, Subs}}, NextMX} when Reqs > 0 ->
+ NewReqs = lists:delete(ID, Reqs),
+ maps:put(Pid, {Ref, {NewReqs, Subs}}, NextMX)
+ end;
+mx_del_monitor(Pid, {subscriber, Sub}, MX) ->
+ case maps:take(Pid, MX) of
+ {{Ref, {[], [Sub]}}, NextMX} ->
+ true = demonitor(Ref, [flush]),
+ NextMX;
+ {{Ref, {Reqs, Subs}}, NextMX} when Subs > 0 ->
+ NewSubs = lists:delete(Sub, Subs),
+ maps:put(Pid, {Ref, {Reqs, NewSubs}}, NextMX)
+ end.
+
+
+-spec mx_crashed_monitor(Pid, MX) -> Result
+ when Pid :: pid(),
+ MX :: monitor_index(),
+ Result :: {Type, NewMX}
+ | error,
+ Type :: attempt
+ | conn
+ | {Reqs :: [id()], Subs :: [tuple()]},
+ NewMX :: monitor_index().
+
+mx_crashed_monitor(Pid, MX) ->
+ case maps:take(Pid, MX) of
+ {{Ref, Type}, NewMX} ->
+ true = demonitor(Ref, [flush]),
+ {Type, NewMX};
+ error ->
+ unknown
+ end.
+
+
+
+%%% Connection Index ADT Interface Functions
+%%%
+%%% Functions to manipulate the conn_index() data type are in this section. This
+%%% data should be treated as abstract by functions outside of this section, as it is
+%%% a deep structure and future requirements are likely to wind up causing it to
+%%% change a little. For the same reason, these functions are all pure, independently
+%%% testable, and have no side effects.
+%%%
+%%% Return values often carry some status information with them.
+
+-spec cx_load() -> conn_index().
+%% @private
+%% Used to load a connection index populated with necessary realm configuration data
+%% and cached mirror data, if such things can be found in the system, otherwise return
+%% a blank connection index structure.
+
+cx_load() ->
+ case cx_populate() of
+ {ok, Realms} ->
+ #cx{realms = maps:from_list(Realms)};
+ {error, Reason} ->
+ Message = "Realm data and host cache load failed with : ~tp",
+ ok = log(error, Message, [Reason]),
+ ok = log(warning, "No realms configured."),
+ #cx{}
+ end.
+
+
+-spec cx_populate() -> Result
+ when Result :: {ok, conn_index()}
+ | {error, Reason},
+ Reason :: no_realms
+ | file:posix().
+%% @private
+%% This procedure, relying zx_lib:zomp_dir() allows the system to load zomp data
+%% from any arbitrary home for zomp. This has been included mostly to make testing of
+%% Zomp and ZX easier, but incidentally opens the possibility that an arbitrary Zomp
+%% home could be selected by an installer (especially on consumer systems like Windows
+%% where any number of wild things might be going on in the user's filesystem).
+
+cx_populate() ->
+ Home = zx_lib:zomp_dir(),
+ Pattern = filename:join(Home, "*.realm"),
+ case filelib:wildcard(Pattern) of
+ [] -> {error, no_realms};
+ RealmFiles -> {ok, cx_populate(RealmFiles, [])}
+ end.
+
+
+-spec cx_populate(RealmFiles, Realms) -> NewRealms
+ when RealmFiles :: file:filename(),
+ Realms :: [{zx:realm(), realm_meta()}],
+ NewRealms :: [{zx:realm(), realm_meta()}].
+%% @private
+%% Pack an initially empty conn_index() with realm meta and host cache data.
+%% Should not halt on a corrupted, missing, malformed, etc. realm file but will log
+%% any loading errors.
+
+cx_populate([File | Files], Realms) ->
+ NewRealms =
+ case file:consult(File) of
+ {ok, Meta} ->
+ Realm = cx_load_realm_meta(Meta),
+ [Realm | Realms];
+ {error, Reason} ->
+ Message = "Loading realm file ~tp failed with: ~tp. Skipping...",
+ ok = log(warning, Message, [File, Reason]),
+ Realms
+ end,
+ cx_populate(Files, NewRealms);
+cx_populate([], Realms) ->
+ Realms.
+
+
+-spec cx_load_realm_meta(Meta) -> Result
+ when Meta :: [{Key :: atom(), Value :: term()}],
+ Result :: {zx:realm(), realm_meta()}.
+%% @private
+%% This function MUST adhere to the realmfile definition found at.
+
+cx_load_realm_meta(Meta) ->
+ {realm, Realm} = lists:keyfind(realm, 1, Meta),
+ {revision, Revision} = lists:keyfind(revision, 1, Meta),
+ {prime, Prime} = lists:keyfind(prime, 1, Meta),
+ {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, Meta),
+ {package_keys, PackageKeys} = lists:keyfind(packge_keys, 1, Meta),
+ {sysops, Sysops} = lists:keyfind(sysops, 1, Meta),
+ Basic =
+ #rmeta{revision = Revision,
+ prime = Prime,
+ realm_keys = RealmKeys,
+ package_keys = PackageKeys,
+ sysops = Sysops},
+ Complete = cx_load_cache(Realm, Basic),
+ {Realm, Complete}.
+
+
+-spec cx_load_cache(Realm, Basic) -> Complete
+ when Realm :: zx:realm(),
+ Basic :: realm_meta(),
+ Complete :: realm_meta().
+%% @private
+%% Receive a realm_meta() that lacks any cache data and load the realm's cache file
+%% if it exists, and return it fully populated.
+%% FIXME: If several instances of zomp or zx are running at once it may be possible
+%% to run into file access contention or receive an incomplete read on some
+%% systems. At the moment this is only a remote possibility and for now should
+%% be handled by simply re-running whatever command caused the failure.
+%% Better file contention and parallel-executing system handling should
+%% eventually be implemented, especially if zx becomes common for end-user
+%% GUI programs.
+%% NOTE: This "fixme" will only apply until the zx universal lock is implemented.
+
+cx_load_cache(Realm, Basic) ->
+ CacheFile = cx_cache_file(Realm),
+ case file:consult(CacheFile) of
+ {ok, Cache} ->
+ {serial, Serial} = lists:keyfind(serial, 1, Cache),
+ {private, Private} = lists:keyfind(private, 1, Cache),
+ {mirrors, Mirrors} = lists:keyfind(mirrors, 1, Cache),
+ PQueue = queue:from_list(Private),
+ Enqueue = fun(H, Q) -> queue:in(H, Q) end,
+ MQueue = lists:foldl(Enqueue, Mirrors, PQueue),
+ Basic#rmeta{serial = Serial, private = Private, mirrors = MQueue};
+ {error, enoent} ->
+ Basic
+ end.
+
+
+-spec cx_store_cache(CX) -> Result
+ when CX :: conn_index(),
+ Result :: ok
+ | {error, file:posix()}.
+
+cx_store_cache(#cx{realms = Realms}) ->
+ lists:foreach(fun cx_write_cache/1, maps:to_list(Realms)).
+
+
+-spec cx_write_cache({zx:realm(), realm_meta()}) -> ok.
+%% @private
+%% FIXME: The same concerns as noted in the cx_load_cache/2 FIXME comment apply here.
+%% NOTE: This "fixme" will only apply until the zx universal lock is implemented.
+
+cx_write_cache({Realm,
+ #rmeta{serial = Serial, private = Private, mirrors = Mirrors}}) ->
+ CacheFile = cx_cache_file(Realm),
+ MList = queue:to_list(Mirrors),
+ ActualMirrors = lists:subtract(MList, Private),
+ CacheMeta = [{serial, Serial}, {mirrors, ActualMirrors}],
+ ok = zx_lib:write_terms(CacheFile, CacheMeta),
+ log(info, "Wrote cache for realm ~ts", [Realm]).
+
+
+-spec cx_cache_file(zx:realm()) -> file:filename().
+
+cx_cache_file(Realm) ->
+ filename:join(zx_lib:zomp_dir(), Realm ++ ".cache").
+
+
+-spec cx_realms(conn_index()) -> [zx:realms()].
+
+cx_realms(#cx{realms = Realms}) ->
+ maps:keys(Realms).
+
+
+-spec cx_next_host(Realm, CX) -> Result
+ when Realm :: zx:realm(),
+ CX :: conn_index(),
+ Result :: {ok, Next, NewCX}
+ | {prime, Prime, NewCX}
+ | {error, Reason, NewCX},
+ Next :: zx:host(),
+ Prime :: zx:host(),
+ NewCX :: conn_index(),
+ Reason :: bad_realm
+ | connected.
+%% @private
+%% Given a realm, retun the next cached host location to which to connect. Returns
+%% error if the realm is already assigned, if it is available but should have been
+%% assigned, or if the realm is not configured.
+%% If all cached mirrors are exhausted it will return the realm's prime host and
+%% reload the mirrors queue with private mirrors.
+
+cx_next_host(Realm, CX = #cx{realms = Realms}) ->
+ case maps:find(Realm, Realms) of
+ {ok, Meta = #rmeta{assigned = none, available = [Pid | Pids]}} ->
+ ok = log(warning, "Call to cx_next_host/2 when connection available."),
+ NewMeta = Meta#rmeta{assigned = Pid, available = Pids},
+ NewRealms = maps:put(Realm, NewMeta, Realms),
+ NewCX = CX#cx{realms = NewRealms},
+ {error, connected, NewCX};
+ {ok, Meta = #rmeta{assigned = none, available = []}} ->
+ {Outcome, Host, NewMeta} = cx_next_host(Meta),
+ NewRealms = maps:put(Realm, NewMeta, Realms),
+ NewCX = CX#cx{realms = NewRealms},
+ {Outcome, Host, NewCX};
+ {ok, #rmeta{assigned = Conn}} when is_pid(Conn) ->
+ ok = log(warning, "Call to cx_next_host/2 when connection assigned."),
+ {error, connected, CX};
+ error ->
+ {error, bad_realm, CX}
+ end.
+
+
+-spec cx_next_host(Meta) -> Result
+ when Meta :: realm_meta(),
+ Result :: {ok, Next, NewMeta}
+ | {prime, Prime, NewMeta},
+ Next :: zx:host(),
+ Prime :: zx:host(),
+ NewMeta :: realm_meta().
+
+cx_next_host(Meta = #rmeta{prime = Prime, private = Private, mirrors = Mirrors}) ->
+ case queue:out(Mirrors) of
+ {{value, Next}, NewMirrors} ->
+ {ok, Next, Meta#rmeta{mirrors = NewMirrors}};
+ {empty, Mirrors} ->
+ Enqueue = fun(H, Q) -> queue:in(H, Q) end,
+ NewMirrors = lists:foldl(Enqueue, Private, Mirrors),
+ {prime, Prime, Meta#rmeta{mirrors = NewMirrors}}
+ end.
+
+
+-spec cx_next_hosts(N, Realm, CX) -> Result
+ when N :: non_neg_integer(),
+ Realm :: zx:realm(),
+ CX :: conn_index(),
+ Result :: {ok, Hosts, NewCX}
+ | {error, Reason},
+ Hosts :: [zx:host()],
+ NewCX :: conn_index(),
+ Reason :: {connected, Conn :: pid()}
+ | bad_realm.
+%% @private
+%% This function allows recruiting an arbitrary number of hosts from the host cache
+%% of a given realm, taking private mirrors first, then public mirrors, and ending
+%% with the prime node for the realm if no others exist.
+
+cx_next_hosts(N, Realm, CX) ->
+ cx_next_hosts(N, Realm, [], CX).
+
+
+cx_next_hosts(N, Realm, Hosts, CX) when N > 0 ->
+ case cx_next_host(Realm, CX) of
+ {ok, Host, NewCX} -> cx_next_hosts(N - 1, Realm, [Host | Hosts], NewCX);
+ {prime, Host, NewCX} -> {ok, [Host | Hosts], NewCX};
+ Error -> Error
+ end;
+cx_next_hosts(0, _, Hosts, CX) ->
+ {ok, Hosts, CX}.
+
+
+-spec cx_maybe_add_attempt(Host, Realm, CX) -> Result
+ when Host :: zx:host(),
+ Realm :: zx:realm(),
+ CX :: conn_index(),
+ Result :: not_connected
+ | {ok, NewCX},
+ NewCX :: conn_index().
+
+cx_maybe_add_attempt(Host, Realm, CX = #cx{attempts = Attempts}) ->
+ case lists:keytake(Host, 2, Attempts) of
+ false ->
+ not_connected;
+ {value, {Pid, Host, Realms}, NextAttempts} ->
+ NewAttempts = [{Pid, Host, [Realm | Realms]} | NextAttempts],
+ NewCX = CX#cx{attempts = NewAttempts},
+ {ok, NewCX}
+ end.
+
+
+-spec cx_add_attempt(Pid, Host, Realm, CX) -> NewCX
+ when Pid :: pid(),
+ Host :: zx:host(),
+ Realm :: zx:realm(),
+ CX :: conn_index(),
+ NewCX :: conn_index().
+
+cx_add_attempt(Pid, Host, Realm, CX = #cx{attempts = Attempts}) ->
+ CX#cx{attempts = [{Pid, Host, [Realm]} | Attempts]}.
+
+
+-spec cx_connected(Available, Pid, CX) -> Result
+ when Available :: [{zx:realm(), zx:serial()}],
+ Pid :: pid(),
+ CX :: conn_index(),
+ Result :: {Assignment, NewCX},
+ Assignment :: assigned | unassigned,
+ NewCX :: conn_index().
+%% @private
+%% An abstract data handler which is called whenever a new connection is successfully
+%% established by a zx_conn. Any unconnected realms with a valid serial will be
+%% assigned to the new connection; if none are needed then the connection is closed.
+%% The successful host is placed back in the hosts queue for each available realm.
+%% The return value is a tuple that indicates whether the new connection was assigned
+%% or not and the updated CX data value.
+
+cx_connected(Available, Pid, CX = #cx{attempts = Attempts}) ->
+ {value, Attempt, NewAttempts} = lists:keytake(Pid, 1, Attempts),
+ Host = element(2, Attempt),
+ Realms = [element(1, R) || R <- Available],
+ NewCX = CX#cx{attempts = NewAttempts},
+ Conn = #conn{pid = Pid, host = Host, realms = Realms},
+ cx_connected(unassigned, Available, Conn, NewCX).
+
+
+-spec cx_connected(A, Available, Conn, CX) -> {NewA, NewCX}
+ when A :: unassigned | assigned,
+ Available :: [{zx:realm(), zx:serial()}],
+ Conn :: connection(),
+ CX :: conn_index(),
+ NewA :: unassigned | assigned,
+ NewCX :: conn_index().
+%% @private
+%% Only accept a new realm as available if the reported serial is equal or newer to the
+%% highest known serial.
+
+cx_connected(A,
+ [{Realm, Serial} | Rest],
+ Conn = #conn{pid = Pid},
+ CX = #cx{realms = Realms}) ->
+ case maps:find(Realm, Realms) of
+ {ok, Meta = #rmeta{serial = S, available = Available}} when S =< Serial ->
+ NewMeta = Meta#rmeta{serial = Serial, available = [Pid | Available]},
+ {NewA, NewCX} = cx_connected(A, Realm, Conn, NewMeta, CX),
+ cx_connected(NewA, Rest, Conn, NewCX);
+ {ok, #rmeta{serial = S}} when S > Serial ->
+ cx_connected(A, Rest, Conn, CX);
+ error ->
+ cx_connected(A, Rest, Conn, CX)
+ end;
+cx_connected(A,
+ [],
+ Conn,
+ CX = #cx{conns = Conns}) ->
+ {A, CX#cx{conns = [Conn | Conns]}}.
+
+
+-spec cx_connected(A, Realm, Conn, Meta, CX) -> {NewA, NewCX}
+ when A :: unassigned | assigned,
+ Realm :: zx:host(),
+ Conn :: connection(),
+ Meta :: realm_meta(),
+ CX :: conn_index(),
+ NewA :: unassigned | assigned,
+ NewCX :: conn_index().
+%% @private
+%% This function matches on two elements:
+%% - Whether or not the realm is already assigned (and if so, set `A' to `assigned'
+%% - Whether the host node is the prime node (and if not, ensure it is a member of
+%% of the mirror queue).
+
+cx_connected(_,
+ Realm,
+ #conn{pid = Pid, host = Prime},
+ Meta = #rmeta{prime = Prime, assigned = none},
+ CX = #cx{realms = Realms}) ->
+ NewMeta = Meta#rmeta{assigned = Pid},
+ NewRealms = maps:put(Realm, NewMeta, Realms),
+ NewCX = CX#cx{realms = NewRealms},
+ {assigned, NewCX};
+cx_connected(_,
+ Realm,
+ #conn{pid = Pid, host = Host},
+ Meta = #rmeta{mirrors = Mirrors, assigned = none},
+ CX = #cx{realms = Realms}) ->
+ NewMirrors = cx_enqueue_unique(Host, Mirrors),
+ NewMeta = Meta#rmeta{mirrors = NewMirrors, assigned = Pid},
+ NewRealms = maps:put(Realm, NewMeta, Realms),
+ NewCX = CX#cx{realms = NewRealms},
+ {assigned, NewCX};
+cx_connected(A,
+ _,
+ #conn{host = Prime},
+ #rmeta{prime = Prime},
+ CX) ->
+ {A, CX};
+cx_connected(A,
+ Realm,
+ #conn{host = Host},
+ Meta = #rmeta{mirrors = Mirrors},
+ CX = #cx{realms = Realms}) ->
+ NewMirrors = cx_enqueue_unique(Host, Mirrors),
+ NewMeta = Meta#rmeta{mirrors = NewMirrors},
+ NewRealms = maps:put(Realm, NewMeta, Realms),
+ NewCX = CX#cx{realms = NewRealms},
+ {A, NewCX}.
+
+
+-spec cx_enqueue_unique(term(), queue:queue()) -> queue:queue().
+%% @private
+%% Simple function to ensure that only unique elements are added to a queue. Obviously
+%% this operation is extremely general and O(n) in complexity due to the use of
+%% queue:member/2.
+
+cx_enqueue_unique(Element, Queue) ->
+ case queue:member(Element, Queue) of
+ true -> Queue;
+ false -> queue:in(Element, Queue)
+ end.
+
+
+-spec cx_failed(Conn, CX) -> {Realms, NewCX}
+ when Conn :: pid(),
+ CX :: conn_index(),
+ Realms :: [zx:realm()],
+ NewCX :: conn_index().
+%% @private
+%% Remove a failed attempt and all its associations.
+
+cx_failed(Conn, CX = #cx{attempts = Attempts}) ->
+ {value, Attempt, NewAttempts} = lists:keytake(Conn, 1, Attempts),
+ Realms = element(3, Attempt),
+ {Realms, CX#cx{attempts = NewAttempts}}.
+
+
+-spec cx_redirect(Conn, Hosts, CX) -> {Unassigned, NewCX}
+ when Conn :: pid(),
+ Hosts :: [{zx:host(), [zx:realm()]}],
+ CX :: conn_index(),
+ Unassigned :: [zx:realm()],
+ NewCX :: conn_index().
+%% @private
+%% Remove a redirected connection attempt from CX, add its redirect hosts to the
+%% mirror queue, and proceed to make further connection atempts to all unassigned
+%% realms. This can cause an inflationary number of new connection attempts, but this
+%% is considered preferrable because the more mirrors fail the longer the user is
+%% waiting and the more urgent the need to discover a working node becomes.
+
+cx_redirect(Conn, Hosts, CX = #cx{attempts = Attempts}) ->
+ NewAttempts = lists:keydelete(Conn, 1, Attempts),
+ NextCX = CX#cx{attempts = NewAttempts},
+ NewCX = cx_redirect(Hosts, NextCX),
+ Unassigned = cx_unassigned(NewCX),
+ {Unassigned, NewCX}.
+
+
+-spec cx_redirect(Hosts, CX) -> NewCX
+ when Hosts :: [{zx:host(), [zx:realm()]}],
+ CX :: conn_index(),
+ NewCX :: conn_index().
+%% @private
+%% Add the host to any realm mirror queues that it provides.
+
+cx_redirect([{Host, Provided} | Rest], CX = #cx{realms = Realms}) ->
+ Apply =
+ fun(R, Rs) ->
+ case maps:find(R, Rs) of
+ {ok, Meta = #rmeta{mirrors = Mirrors}} ->
+ NewMirrors = cx_enqueue_unique(Host, Mirrors),
+ NewMeta = Meta#rmeta{mirrors = NewMirrors},
+ maps:put(R, NewMeta, Rs);
+ error ->
+ Rs
+ end
+ end,
+ NewRealms = lists:foldl(Apply, Realms, Provided),
+ cx_redirect(Rest, CX#cx{realms = NewRealms});
+cx_redirect([], CX) ->
+ CX.
+
+
+-spec cx_unassigned(CX) -> Unassigned
+ when CX :: conn_index(),
+ Unassigned :: [zx:realm()].
+%% @private
+%% Scan CX#cx.realms for unassigned realms and return a list of all unassigned
+%% realm names.
+
+cx_unassigned(#cx{realms = Realms}) ->
+ NotAssigned =
+ fun(Realm, #rmeta{assigned = Conn}, Unassigned) ->
+ case Conn == none of
+ true -> [Realm | Unassigned];
+ false -> Unassigned
+ end
+ end,
+ maps:fold(NotAssigned, [], Realms).
+
+
+-spec cx_disconnected(Conn, CX) -> {Requests, Subs, Unassigned, NewCX}
+ when Conn :: pid(),
+ CX :: conn_index(),
+ Requests :: [id()],
+ Subs :: [zx:package()],
+ Unassigned :: [zx:realm()],
+ NewCX :: conn_index().
+%% @private
+%% An abstract data handler which is called whenever a connection terminates.
+%% This function removes all data related to the disconnected pid and its assigned
+%% realms, and returns the monitor reference of the pid, a list of realms that are now
+%% unassigned, and an updated connection index.
+
+cx_disconnected(Pid, CX = #cx{realms = Realms, conns = Conns}) ->
+ {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns),
+ #conn{host = Host, requests = Requests, subs = Subs} = Conn,
+ NewRealms = cx_scrub_assigned(Pid, Host, Realms),
+ NewCX = CX#cx{realms = NewRealms, conns = NewConns},
+ Unassigned = cx_unassigned(NewCX),
+ {Requests, Subs, Unassigned, NewCX}.
+
+
+-spec cx_scrub_assigned(Pid, Host, Realms) -> NewRealms
+ when Pid :: pid(),
+ Host :: zx:host(),
+ Realms :: [realm_meta()],
+ NewRealms :: [realm_meta()].
+%% @private
+%% This could have been performed as a set of two list operations (a partition and a
+%% map), but to make the procedure perfectly clear it is written out explicitly.
+
+cx_scrub_assigned(Pid, Host, Realms) ->
+ Scrub =
+ fun
+ (_, V = #rmeta{mirrors = M, available = A, assigned = C}) when C == Pid ->
+ V#rmeta{mirrors = cx_enqueue_unique(Host, M),
+ available = lists:delete(Pid, A),
+ assigned = none};
+ (_, V = #rmeta{mirrors = M, available = A}) ->
+ V#rmeta{mirrors = cx_enqueue_unique(Host, M),
+ available = lists:delete(Pid, A)}
+ end,
+ maps:map(Scrub, Realms).
+
+
+-spec cx_resolve(Realm, CX) -> Result
+ when Realm :: zx:realm(),
+ CX :: conn_index(),
+ Result :: {ok, Conn :: pid()}
+ | unassigned
+ | unconfigured.
+%% @private
+%% Check the registry of assigned realms and return the pid of the appropriate
+%% connection, or an `unassigned' indication if the realm is not yet connected.
+
+cx_resolve(Realm, #cx{realms = Realms}) ->
+ case maps:find(Realm, Realms) of
+ {ok, #rmeta{assigned = none}} -> unassigned;
+ {ok, #rmeta{assigned = Conn}} -> {ok, Conn};
+ error -> unconfigured
+ end.
+
+
+-spec cx_pre_send(Realm, ID, CX) -> Result
+ when Realm :: zx:realm(),
+ ID :: id(),
+ CX :: conn_index(),
+ Result :: {ok, pid(), NewCX :: conn_index()}
+ | unassigned
+ | unconfigured.
+%% @private
+%% Prepare a request to be sent by queueing it in the connection active request
+%% reference list and returning the Pid of the connection handling the required realm
+%% if it is available, otherwise return an atom indicating the status of the realm..
+
+cx_pre_send(Realm, ID, CX = #cx{conns = Conns}) ->
+ case cx_resolve(Realm, CX) of
+ {ok, Pid} ->
+ {value, Conn, NextConns} = lists:keytake(Pid, #conn.pid, Conns),
+ #conn{requests = Requests} = Conn,
+ NewRequests = [ID | Requests],
+ NewConn = Conn#conn{requests = NewRequests},
+ NewCX = CX#cx{conns = [NewConn | NextConns]},
+ {ok, Pid, NewCX};
+ NoGo ->
+ NoGo
+ end.
+
+
+-spec cx_add_sub(Subscriber, Channel, CX) -> Result
+ when Subscriber :: pid(),
+ Channel :: tuple(),
+ CX :: conn_index(),
+ Result :: {need_sub, Conn, NewCX}
+ | {have_sub, NewCX}
+ | unassigned
+ | unconfigured,
+ Conn :: pid(),
+ NewCX :: conn_index().
+%% @private
+%% Adds a subscription to the current list of subs, and returns a value indicating
+%% whether the connection needs to be told to subscribe or not based on whether it
+%% is already subscribed to that particular channel.
+
+cx_add_sub(Subscriber, Channel, CX = #cx{conns = Conns}) ->
+ Realm = element(1, Channel),
+ case cx_resolve(Realm, CX) of
+ {ok, Pid} ->
+ {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns),
+ cx_maybe_new_sub(Conn, {Subscriber, Channel}, CX#cx{conns = NewConns});
+ Other ->
+ Other
+ end.
+
+
+-spec cx_maybe_new_sub(Conn, Sub, CX) -> Result
+ when Conn :: connection(),
+ Sub :: {pid(), tuple()},
+ CX :: conn_index(),
+ Result :: {need_sub, ConnPid, NewCX}
+ | {have_sub, NewCX},
+ ConnPid :: pid(),
+ NewCX :: conn_index().
+
+cx_maybe_new_sub(Conn = #conn{pid = ConnPid, subs = Subs},
+ Sub = {_, Channel},
+ CX = #cx{conns = Conns}) ->
+ NewSubs = [Sub | Subs],
+ NewConn = Conn#conn{subs = NewSubs},
+ NewConns = [NewConn | Conns],
+ NewCX = CX#cx{conns = NewConns},
+ case lists:keymember(Channel, 2, Subs) of
+ false -> {need_sub, ConnPid, NewCX};
+ true -> {have_sub, NewCX}
+ end.
+
+
+-spec cx_del_sub(Subscriber, Channel, CX) -> Result
+ when Subscriber :: pid(),
+ Channel :: tuple(),
+ CX :: conn_index(),
+ Result :: {drop_sub, NewCX}
+ | {keep_sub, NewCX}
+ | unassigned
+ | unconfigured,
+ NewCX :: conn_index().
+%% @private
+%% Remove a subscription from the list of subs, and return a value indicating whether
+%% the connection needs to be told to unsubscribe entirely.
+
+cx_del_sub(Subscriber, Channel, CX = #cx{conns = Conns}) ->
+ Realm = element(1, Channel),
+ case cx_resolve(Realm, CX) of
+ {ok, Pid} ->
+ {value, Conn, NewConns} = lists:keytake(Pid, #conn.pid, Conns),
+ cx_maybe_last_sub(Conn, {Subscriber, Channel}, CX#cx{conns = NewConns});
+ Other ->
+ Other
+ end.
+
+
+-spec cx_maybe_last_sub(Conn, Sub, CX) -> {Verdict, NewCX}
+ when Conn :: connection(),
+ Sub :: {pid(), term()},
+ CX :: conn_index(),
+ Verdict :: {drop_sub, Conn :: pid()} | keep_sub,
+ NewCX :: conn_index().
+%% @private
+%% Tells us whether a sub is still valid for any clients. If a sub is unsubbed by all
+%% then it needs to be unsubscribed at the upstream node.
+
+cx_maybe_last_sub(Conn = #conn{pid = ConnPid, subs = Subs},
+ Sub = {_, Channel},
+ CX = #cx{conns = Conns}) ->
+ NewSubs = lists:delete(Sub, Subs),
+ NewConn = Conn#conn{subs = NewSubs},
+ NewConns = [NewConn | Conns],
+ NewCX = CX#cx{conns = NewConns},
+ Verdict =
+ case lists:keymember(Channel, 2, NewSubs) of
+ false -> {drop_sub, ConnPid};
+ true -> keep_sub
+ end,
+ {Verdict, NewCX}.
+
+
+-spec cx_get_subscribers(Conn, Channel, CX) -> Subscribers
+ when Conn :: pid(),
+ Channel :: term(),
+ CX :: conn_index(),
+ Subscribers :: [pid()].
+
+cx_get_subscribers(Conn, Channel, #cx{conns = Conns}) ->
+ #conn{subs = Subs} = lists:keyfind(Conn, #conn.pid, Conns),
+ lists:fold(registered_to(Channel), [], Subs).
+
+
+-spec registered_to(Channel) -> fun(({P, C}, A) -> NewA)
+ when Channel :: term(),
+ P :: pid(),
+ C :: term(),
+ A :: [pid()],
+ NewA :: [pid()].
+%% @private
+%% Matching function that closes over a given channel in a subscriber list.
+%% This function exists mostly to make its parent function read nicely.
+
+registered_to(Channel) ->
+ fun({P, C}, A) ->
+ case C == Channel of
+ true -> [P | A];
+ false -> A
+ end
+ end.
+
+
+-spec cx_clear_client(Pid, DeadReqs, DeadSubs, CX) -> NewCX
+ when Pid :: pid(),
+ DeadReqs :: [id()],
+ DeadSubs :: [term()],
+ CX :: conn_index(),
+ NewCX :: conn_index().
+
+cx_clear_client(Pid, DeadReqs, DeadSubs, CX = #cx{conns = Conns}) ->
+ DropSubs = [{Pid, Sub} || Sub <- DeadSubs],
+ Clear =
+ fun(C = #conn{requests = Requests, subs = Subs}) ->
+ NewSubs = lists:subtract(Subs, DropSubs),
+ NewRequests = lists:subtract(Requests, DeadReqs),
+ C#conn{requests = NewRequests, subs = NewSubs}
+ end,
+ NewConns = lists:map(Clear, Conns),
+ CX#cx{conns = NewConns}.
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl
new file mode 100644
index 0000000..e9e9ed7
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_key.erl
@@ -0,0 +1,306 @@
+%%% @doc
+%%% ZX Key
+%%%
+%%% Abstraction module for dealing with keys.
+%%%
+%%% "Ewwwww! Keys!"
+%%% -- Bertrand Russel
+%%% @end
+
+-module(zx_key).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([ensure_keypair/1, have_public_key/1, have_private_key/1,
+ prompt_keygen/0, grow_a_pair/0, generate_rsa/1,
+ load/2, verify/3]).
+
+-include("zx_logger.hrl").
+
+
+%%% Functions
+
+-spec ensure_keypair(zx:key_id()) -> true | no_return().
+%% @private
+%% Check if both the public and private key based on KeyID exists.
+
+ensure_keypair(KeyID = {Realm, KeyName}) ->
+ case {have_public_key(KeyID), have_private_key(KeyID)} of
+ {true, true} ->
+ true;
+ {false, true} ->
+ Message = "Public key for ~tp/~tp cannot be found",
+ ok = log(error, Message, [Realm, KeyName]),
+ halt(1);
+ {true, false} ->
+ Message = "Private key for ~tp/~tp cannot be found",
+ ok = log(error, Message, [Realm, KeyName]),
+ halt(1);
+ {false, false} ->
+ Message = "Key pair for ~tp/~tp cannot be found",
+ ok = log(error, Message, [Realm, KeyName]),
+ halt(1)
+ end.
+
+
+-spec have_public_key(zx:key_id()) -> boolean().
+%% @private
+%% Determine whether the public key indicated by KeyID is in the keystore.
+
+have_public_key({Realm, KeyName}) ->
+ PublicKeyFile = KeyName ++ ".pub.der",
+ PublicKeyPath = filename:join([zx_lib:zomp_dir(), "key", Realm, PublicKeyFile]),
+ filelib:is_regular(PublicKeyPath).
+
+
+-spec have_private_key(zx:key_id()) -> boolean().
+%% @private
+%% Determine whether the private key indicated by KeyID is in the keystore.
+
+have_private_key({Realm, KeyName}) ->
+ PrivateKeyFile = KeyName ++ ".key.der",
+ PrivateKeyPath = filename:join([zx_lib:zomp_dir(), "key", Realm, PrivateKeyFile]),
+ filelib:is_regular(PrivateKeyPath).
+
+
+
+%%% Key generation
+
+-spec prompt_keygen() -> zx:key_id().
+%% @private
+%% Prompt the user for a valid KeyPrefix to use for naming a new RSA keypair.
+
+prompt_keygen() ->
+ Message =
+ "~n Enter a name for your new keys.~n~n"
+ " Valid names must start with a lower-case letter, and can include~n"
+ " only lower-case letters, numbers, and periods, but no series of~n"
+ " consecutive periods. (That is: [a-z0-9\\.])~n~n"
+ " To designate the key as realm-specific, enter the realm name and~n"
+ " key name separated by a space.~n~n"
+ " Example: some.realm my.key~n",
+ ok = io:format(Message),
+ Input = zx_tty:get_input(),
+ {Realm, KeyName} =
+ case string:lexemes(Input, " ") of
+ [R, K] -> {R, K};
+ [K] -> {"otpr", K}
+ end,
+ case {zx_lib:valid_lower0_9(Realm), zx_lib:valid_label(KeyName)} of
+ {true, true} ->
+ {Realm, KeyName};
+ {false, true} ->
+ ok = io:format("Bad realm name ~tp. Try again.~n", [Realm]),
+ prompt_keygen();
+ {true, false} ->
+ ok = io:format("Bad key name ~tp. Try again.~n", [KeyName]),
+ prompt_keygen();
+ {false, false} ->
+ ok = io:format("NUTS! Both key and realm names are illegal. Try again.~n"),
+ prompt_keygen()
+ end.
+
+
+-spec grow_a_pair() -> no_return().
+%% @private
+%% Execute the key generation procedure for 16k RSA keys once and then terminate.
+
+grow_a_pair() ->
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ KeyID = prompt_keygen(),
+ case generate_rsa(KeyID) of
+ {ok, _, _} -> halt(0);
+ Error -> error_exit("grow_a_pair/0 error: ~tp", [Error], ?LINE)
+ end.
+
+
+-spec generate_rsa(KeyID) -> Result
+ when KeyID :: zx:key_id(),
+ Result :: {ok, KeyFile, PubFile}
+ | {error, keygen_fail},
+ KeyFile :: file:filename(),
+ PubFile :: file:filename().
+%% @private
+%% Generate an RSA keypair and write them in der format to the current directory, using
+%% filenames derived from Prefix.
+%% NOTE: The current version of this command is likely to only work on a unix system.
+
+generate_rsa({Realm, KeyName}) ->
+ KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]),
+ ok = zx_lib:force_dir(KeyDir),
+ PemFile = filename:join(KeyDir, KeyName ++ ".pub.pem"),
+ KeyFile = filename:join(KeyDir, KeyName ++ ".key.der"),
+ PubFile = filename:join(KeyDir, KeyName ++ ".pub.der"),
+ ok = lists:foreach(fun zx_lib:halt_if_exists/1, [PemFile, KeyFile, PubFile]),
+ ok = log(info, "Generating ~p and ~p. Please be patient...", [KeyFile, PubFile]),
+ ok = gen_p_key(KeyFile),
+ ok = der_to_pem(KeyFile, PemFile),
+ {ok, PemBin} = file:read_file(PemFile),
+ [PemData] = public_key:pem_decode(PemBin),
+ Pub = public_key:pem_entry_decode(PemData),
+ PubDer = public_key:der_encode('RSAPublicKey', Pub),
+ ok = file:write_file(PubFile, PubDer),
+ case check_key(KeyFile, PubFile) of
+ true ->
+ ok = file:delete(PemFile),
+ ok = log(info, "~ts and ~ts agree", [KeyFile, PubFile]),
+ ok = log(info, "Wrote private key to: ~ts.", [KeyFile]),
+ ok = log(info, "Wrote public key to: ~ts.", [PubFile]),
+ {ok, KeyFile, PubFile};
+ false ->
+ ok = lists:foreach(fun file:delete/1, [PemFile, KeyFile, PubFile]),
+ ok = log(error, "Something has gone wrong."),
+ {error, keygen_fail}
+ end.
+
+
+-spec gen_p_key(KeyFile) -> ok
+ when KeyFile :: file:filename().
+%% @private
+%% Format an openssl shell command that will generate proper 16k RSA keys.
+
+gen_p_key(KeyFile) ->
+ Command =
+ io_lib:format("~ts genpkey"
+ " -algorithm rsa"
+ " -out ~ts"
+ " -outform DER"
+ " -pkeyopt rsa_keygen_bits:16384",
+ [openssl(), KeyFile]),
+ Out = os:cmd(Command),
+ io:format(Out).
+
+
+-spec der_to_pem(KeyFile, PemFile) -> ok
+ when KeyFile :: file:filename(),
+ PemFile :: file:filename().
+%% @private
+%% Format an openssl shell command that will convert the given keyfile to a pemfile.
+%% The reason for this conversion is to sidestep some formatting weirdness that OpenSSL
+%% injects into its generated DER formatted key output (namely, a few empty headers)
+%% which Erlang's ASN.1 defintion files do not take into account. A conversion to PEM
+%% then a conversion back to DER (via Erlang's ASN.1 module) resolves this in a reliable
+%% way.
+
+der_to_pem(KeyFile, PemFile) ->
+ Command =
+ io_lib:format("~ts rsa"
+ " -inform DER"
+ " -in ~ts"
+ " -outform PEM"
+ " -pubout"
+ " -out ~ts",
+ [openssl(), KeyFile, PemFile]),
+ Out = os:cmd(Command),
+ io:format(Out).
+
+
+-spec check_key(KeyFile, PubFile) -> Result
+ when KeyFile :: file:filename(),
+ PubFile :: file:filename(),
+ Result :: true | false.
+%% @private
+%% Compare two keys for pairedness.
+
+check_key(KeyFile, PubFile) ->
+ {ok, KeyBin} = file:read_file(KeyFile),
+ {ok, PubBin} = file:read_file(PubFile),
+ Key = public_key:der_decode('RSAPrivateKey', KeyBin),
+ Pub = public_key:der_decode('RSAPublicKey', PubBin),
+ TestMessage = <<"Some test data to sign.">>,
+ Signature = public_key:sign(TestMessage, sha512, Key),
+ public_key:verify(TestMessage, sha512, Signature, Pub).
+
+
+-spec openssl() -> Executable | no_return()
+ when Executable :: file:filename().
+%% @private
+%% Attempt to locate the installed openssl executable for use in shell commands.
+%% Halts execution with an error message if the executable cannot be found.
+
+openssl() ->
+ OpenSSL =
+ case os:type() of
+ {unix, _} -> "openssl";
+ {win32, _} -> "openssl.exe"
+ end,
+ ok =
+ case os:find_executable(OpenSSL) of
+ false ->
+ ok = log(error, "OpenSSL could not be found in this system's PATH."),
+ ok = log(error, "Install OpenSSL and then retry."),
+ error_exit("Missing system dependenct: OpenSSL", ?LINE);
+ Path ->
+ log(info, "OpenSSL executable found at: ~ts", [Path])
+ end,
+ OpenSSL.
+
+
+-spec load(Type, KeyID) -> Result
+ when Type :: private | public,
+ KeyID :: zx:key_id(),
+ Result :: {ok, DecodedKey :: term()}
+ | {error, Reason :: term()}.
+%% @private
+%% Hide the details behind reading and loading DER encoded RSA key files.
+
+load(Type, {Realm, KeyName}) ->
+ {DerType, Path} =
+ case Type of
+ private ->
+ KeyDer = KeyName ++ ".key.der",
+ P = filename:join([zx_lib:zomp_dir(), "key", Realm, KeyDer]),
+ {'RSAPrivateKey', P};
+ public ->
+ PubDer = KeyName ++ ".pub.der",
+ P = filename:join([zx_lib:zomp_dir(), "key", Realm, PubDer]),
+ {'RSAPublicKey', P}
+ end,
+ ok = log(info, "Loading key from file ~ts", [Path]),
+ case file:read_file(Path) of
+ {ok, Bin} -> {ok, public_key:der_decode(DerType, Bin)};
+ Error -> Error
+ end.
+
+
+-spec verify(Data, Signature, PubKey) -> ok | no_return()
+ when Data :: binary(),
+ Signature :: binary(),
+ PubKey :: public_key:rsa_public_key().
+%% @private
+%% Verify the RSA Signature of some Data against the given PubKey or halt execution.
+%% This function always assumes sha512 is the algorithm being used.
+%% Should only ever be called by the initial launch process.
+
+verify(Data, Signature, PubKey) ->
+ case public_key:verify(Data, sha512, Signature, PubKey) of
+ true -> ok;
+ false -> error_exit("Bad package signature!", ?LINE)
+ end.
+
+
+
+%%% Error exits
+
+-spec error_exit(Error, Line) -> no_return()
+ when Error :: term(),
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Error, Line) ->
+ error_exit(Error, [], Line).
+
+
+-spec error_exit(Format, Args, Line) -> no_return()
+ when Format :: string(),
+ Args :: [term()],
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Format, Args, Line) ->
+ File = filename:basename(?FILE),
+ ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]),
+ halt(1).
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl
new file mode 100644
index 0000000..a95a618
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl
@@ -0,0 +1,758 @@
+%%% @doc
+%%% ZX Library
+%%%
+%%% This module contains a set of common-use functions internal to the ZX project.
+%%% These functions are subject to radical change, are not publicly documented and
+%%% should NOT be used by other projects.
+%%%
+%%% The public interface to the externally useful parts of this library are maintained
+%%% in the otpr-zxxl package.
+%%% @end
+
+-module(zx_lib).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([zomp_dir/0, find_zomp_dir/0,
+ path/1, path/2, path/3,
+ force_dir/1,
+ list_realms/0,
+ hosts_cache_file/1, get_prime/1, realm_meta/1,
+ read_project_meta/0, read_project_meta/1, read_package_meta/1,
+ write_project_meta/1, write_project_meta/2,
+ write_terms/2,
+ valid_lower0_9/1, valid_label/1, valid_version/1,
+ string_to_version/1, version_to_string/1,
+ package_id/1, package_string/1,
+ package_dir/1, package_dir/2,
+ namify_zsp/1, namify_tgz/1,
+ find_latest_compatible/2, installed/1,
+ realm_conf/1, load_realm_conf/1,
+ extract_zsp_or_die/1, halt_if_exists/1,
+ build/0,
+ rm_rf/1, rm/1]).
+
+-include("zx_logger.hrl").
+
+
+
+%%% Functions
+
+-spec zomp_dir() -> file:filename().
+%% @doc
+%% Return the path to the Zomp/ZX installation directory.
+
+zomp_dir() ->
+ case os:getenv("ZOMP_DIR") of
+ false ->
+ ZompDir = find_zomp_dir(),
+ true = os:putenv("ZOMP_DIR", ZompDir),
+ ZompDir;
+ ZompDir ->
+ ZompDir
+ end.
+
+
+-spec find_zomp_dir() -> file:filename().
+%% @private
+%% Check the host OS and return the absolute path to the zomp filesystem root.
+
+find_zomp_dir() ->
+ case os:type() of
+ {unix, _} ->
+ Home = os:getenv("HOME"),
+ Dir = ".zomp",
+ filename:join(Home, Dir);
+ {win32, _} ->
+ Home = os:getenv("LOCALAPPDATA"),
+ Dir = "zomp",
+ filename:join(Home, Dir)
+ end.
+
+
+-spec path(Type) -> Result
+ when Type :: etc
+ | var
+ | tmp
+ | log
+ | lib,
+ Result :: file:filename().
+%% @private
+%% Return the top-level path of the given type in the Zomp/ZX system.
+
+path(etc) -> filename:join(zomp_dir(), "etc");
+path(var) -> filename:join(zomp_dir(), "var");
+path(tmp) -> filename:join(zomp_dir(), "tmp");
+path(log) -> filename:join(zomp_dir(), "log");
+path(lib) -> filename:join(zomp_dir(), "lib").
+
+
+-spec path(Type, Realm) -> Result
+ when Type :: etc
+ | var
+ | tmp
+ | log
+ | lib,
+ Realm :: zx:realm(),
+ Result :: file:filename().
+%% @private
+%% Return the realm-level path of the given type in the Zomp/ZX system.
+
+path(Type, Realm) ->
+ filename:join(path(Type), Realm).
+
+
+-spec path(Type, Realm, Name) -> Result
+ when Type :: etc
+ | var
+ | tmp
+ | log
+ | lib,
+ Realm :: zx:realm(),
+ Name :: zx:name(),
+ Result :: file:filename().
+%% @private
+%% Return the package-level path of the given type in the Zomp/ZX system.
+
+path(Type, Realm, Name) ->
+ filename:join([path(Type), Realm, Name]).
+
+
+-spec force_dir(Path) -> Result
+ when Path :: file:filename(),
+ Result :: ok
+ | {error, file:posix()}.
+%% @private
+%% Guarantee a directory path is created if it is possible to create or if it already
+%% exists.
+
+force_dir(Path) ->
+ case filelib:is_dir(Path) of
+ true -> ok;
+ false -> filelib:ensure_dir(filename:join(Path, "foo"))
+ end.
+
+
+-spec hosts_cache_file(zx:realm()) -> file:filename().
+%% @private
+%% Given a Realm name, construct a realm's .hosts filename and return it.
+
+hosts_cache_file(Realm) ->
+ filename:join(zomp_dir(), Realm ++ ".hosts").
+
+
+-spec list_realms() -> [zx:realm()].
+%% @private
+%% Check the filesystem for etc/[Realm Name]/realm.conf files.
+
+list_realms() ->
+ Pattern = filename:join([path(etc), "*", "realm.conf"]),
+ [filename:basename(filename:dirname(C)) || C <- filelib:wildcard(Pattern)].
+
+
+-spec get_prime(Realm) -> Result
+ when Realm :: zx:realm(),
+ Result :: {ok, zx:host()}
+ | {error, file:posix()}.
+%% @private
+%% Check the given Realm's config file for the current prime node and return it.
+
+get_prime(Realm) ->
+ case realm_meta(Realm) of
+ {ok, RealmMeta} ->
+ {prime, Prime} = lists:keyfind(prime, 1, RealmMeta),
+ {ok, Prime};
+ Error ->
+ Error
+ end.
+
+
+-spec realm_meta(Realm) -> Result
+ when Realm :: string(),
+ Result :: {ok, Meta}
+ | {error, Reason},
+ Meta :: [{atom(), term()}],
+ Reason :: file:posix().
+%% @private
+%% Given a realm name, try to locate and read the realm's configuration file if it
+%% exists, exiting with an appropriate error message if there is a problem reading
+%% the file.
+
+realm_meta(Realm) ->
+ RealmFile = filename:join(path(etc, Realm), "realm.conf"),
+ file:consult(RealmFile).
+
+
+-spec read_project_meta() -> Result
+ when Result :: {ok, zx:package_meta()}
+ | {error, file:posix()}.
+%% @private
+%% @equiv read_meta(".")
+
+read_project_meta() ->
+ read_project_meta(".").
+
+
+-spec read_project_meta(Dir) -> Result
+ when Dir :: file:filename(),
+ Result :: {ok, zx:package_meta()}
+ | {error, file:posix()}.
+%% @private
+%% Read the `zomp.meta' file from the indicated directory, if possible.
+
+read_project_meta(Dir) ->
+ Path = filename:join(Dir, "zomp.meta"),
+ case file:consult(Path) of
+ {ok, Meta} ->
+ {ok, maps:from_list(Meta)};
+ Error ->
+ ok = log(error, "Failed to open \"zomp.meta\" with ~tp", [Error]),
+ ok = log(error, "Wrong directory?"),
+ Error
+ end.
+
+
+-spec read_package_meta(PackageID) -> Result
+ when PackageID :: zx:package_id(),
+ Result :: {ok, zx:package_meta()}
+ | {error, file:posix()}.
+
+read_package_meta({Realm, Name, Version}) ->
+ {ok, VersionString} = version_to_string(Version),
+ Path = filename:join([zomp_dir(), "lib", Realm, Name, VersionString]),
+ read_project_meta(Path).
+
+
+-spec write_project_meta(Meta) -> Result
+ when Meta :: zx:package_meta(),
+ Result :: ok
+ | {error, Reason},
+ Reason :: badarg
+ | terminated
+ | system_limit
+ | file:posix().
+%% @private
+%% @equiv write_meta(".")
+
+write_project_meta(Meta) ->
+ write_project_meta(".", Meta).
+
+
+-spec write_project_meta(Dir, Meta) -> ok
+ when Dir :: file:filename(),
+ Meta :: zx:package_meta().
+%% @private
+%% Write the contents of the provided meta structure (a map these days) as a list of
+%% Erlang K/V terms.
+
+write_project_meta(Dir, Meta) ->
+ Path = filename:join(Dir, "zomp.meta"),
+ write_terms(Path, maps:to_list(Meta)).
+
+
+-spec write_terms(Filename, Terms) -> Result
+ when Filename :: file:filename(),
+ Terms :: [term()],
+ Result :: ok
+ | {error, Reason},
+ Reason :: badarg
+ | terminated
+ | system_limit
+ | file:posix().
+%% @private
+%% Provides functionality roughly inverse to file:consult/1.
+
+write_terms(Filename, List) ->
+ Format = fun(Term) -> io_lib:format("~tp.~n", [Term]) end,
+ Text = lists:map(Format, List),
+ file:write_file(Filename, Text).
+
+
+-spec valid_lower0_9(string()) -> boolean().
+%% @private
+%% Check whether a provided string is a valid lower0_9.
+
+valid_lower0_9([Char | Rest])
+ when $a =< Char, Char =< $z ->
+ valid_lower0_9(Rest, Char);
+valid_lower0_9(_) ->
+ false.
+
+
+-spec valid_lower0_9(String, Last) -> boolean()
+ when String :: string(),
+ Last :: char().
+
+valid_lower0_9([$_ | _], $_) ->
+ false;
+valid_lower0_9([Char | Rest], _)
+ when $a =< Char, Char =< $z;
+ $0 =< Char, Char =< $9;
+ Char == $_ ->
+ valid_lower0_9(Rest, Char);
+valid_lower0_9([], _) ->
+ true;
+valid_lower0_9(_, _) ->
+ false.
+
+
+-spec valid_label(string()) -> boolean().
+%% @private
+%% Check whether a provided string is a valid label.
+
+valid_label([Char | Rest])
+ when $a =< Char, Char =< $z ->
+ valid_label(Rest, Char);
+valid_label(_) ->
+ false.
+
+
+-spec valid_label(String, Last) -> boolean()
+ when String :: string(),
+ Last :: char().
+
+valid_label([$. | _], $.) ->
+ false;
+valid_label([$_ | _], $_) ->
+ false;
+valid_label([$- | _], $-) ->
+ false;
+valid_label([Char | Rest], _)
+ when $a =< Char, Char =< $z;
+ $0 =< Char, Char =< $9;
+ Char == $_; Char == $-;
+ Char == $. ->
+ valid_label(Rest, Char);
+valid_label([], _) ->
+ true;
+valid_label(_, _) ->
+ false.
+
+
+-spec valid_version(zx:version()) -> boolean().
+
+valid_version({z, z, z}) ->
+ true;
+valid_version({X, z, z})
+ when is_integer(X), X >= 0 ->
+ true;
+valid_version({X, Y, z})
+ when is_integer(X), X >= 0,
+ is_integer(Y), Y >= 0 ->
+ true;
+valid_version({X, Y, Z})
+ when is_integer(X), X >= 0,
+ is_integer(Y), Y >= 0,
+ is_integer(Z), Z >= 0 ->
+ true;
+valid_version(_) ->
+ false.
+
+
+-spec string_to_version(VersionString) -> Result
+ when VersionString :: string(),
+ Result :: {ok, zx:version()}
+ | {error, invalid_version_string}.
+%% @private
+%% @equiv string_to_version(string(), "", {z, z, z})
+
+string_to_version(String) ->
+ string_to_version(String, "", {z, z, z}).
+
+
+-spec string_to_version(String, Acc, Version) -> Result
+ when String :: string(),
+ Acc :: list(),
+ Version :: zx:version(),
+ Result :: {ok, zx:version()}
+ | {error, invalid_version_string}.
+%% @private
+%% Accepts a full or partial version string of the form `X.Y.Z', `X.Y' or `X' and
+%% returns a zomp-type version tuple or crashes on bad data.
+
+string_to_version([Char | Rest], Acc, Version) when $0 =< Char andalso Char =< $9 ->
+ string_to_version(Rest, [Char | Acc], Version);
+string_to_version("", "", Version) ->
+ {ok, Version};
+string_to_version(_, "", _) ->
+ {error, invalid_version_string};
+string_to_version([$. | Rest], Acc, {z, z, z}) ->
+ X = list_to_integer(lists:reverse(Acc)),
+ string_to_version(Rest, "", {X, z, z});
+string_to_version([$. | Rest], Acc, {X, z, z}) ->
+ Y = list_to_integer(lists:reverse(Acc)),
+ string_to_version(Rest, "", {X, Y, z});
+string_to_version([], Acc, {z, z, z}) ->
+ X = list_to_integer(lists:reverse(Acc)),
+ {ok, {X, z, z}};
+string_to_version([], Acc, {X, z, z}) ->
+ Y = list_to_integer(lists:reverse(Acc)),
+ {ok, {X, Y, z}};
+string_to_version([], Acc, {X, Y, z}) ->
+ Z = list_to_integer(lists:reverse(Acc)),
+ {ok, {X, Y, Z}};
+string_to_version(_, _, _) ->
+ {error, invalid_version_string}.
+
+
+-spec version_to_string(zx:version()) -> {ok, string()} | {error, invalid_version}.
+%% @private
+%% Inverse of string_to_version/3.
+
+version_to_string({z, z, z}) ->
+ {ok, ""};
+version_to_string({X, z, z}) when is_integer(X) ->
+ {ok, integer_to_list(X)};
+version_to_string({X, Y, z}) when is_integer(X), is_integer(Y) ->
+ DeepList = lists:join($., [integer_to_list(Element) || Element <- [X, Y]]),
+ FlatString = lists:flatten(DeepList),
+ {ok, FlatString};
+version_to_string({X, Y, Z}) when is_integer(X), is_integer(Y), is_integer(Z) ->
+ DeepList = lists:join($., [integer_to_list(Element) || Element <- [X, Y, Z]]),
+ FlatString = lists:flatten(DeepList),
+ {ok, FlatString};
+version_to_string(_) ->
+ {error, invalid_version}.
+
+
+-spec package_id(string()) -> {ok, zx:package_id()} | {error, invalid_package_string}.
+%% @private
+%% Converts a proper package_string to a package_id().
+%% This function takes into account missing version elements.
+%% Examples:
+%% `{ok, {"foo", "bar", {1, 2, 3}}} = package_id("foo-bar-1.2.3")'
+%% `{ok, {"foo", "bar", {1, 2, z}}} = package_id("foo-bar-1.2")'
+%% `{ok, {"foo", "bar", {1, z, z}}} = package_id("foo-bar-1")'
+%% `{ok, {"foo", "bar", {z, z, z}}} = package_id("foo-bar")'
+%% `{error, invalid_package_string} = package_id("Bad-Input")'
+
+package_id(String) ->
+ case dash_split(String) of
+ {ok, [Realm, Name, VersionString]} ->
+ package_id(Realm, Name, VersionString);
+ {ok, [A, B]} ->
+ case valid_lower0_9(B) of
+ true -> package_id(A, B, "");
+ false -> package_id("otpr", A, B)
+ end;
+ {ok, [Name]} ->
+ package_id("otpr", Name, "");
+ error ->
+ {error, invalid_package_string}
+ end.
+
+
+-spec dash_split(string()) -> {ok, [string()]} | error.
+%% @private
+%% An explicit, strict token split that ensures invalid names with leading, trailing or
+%% double dashes don't slip through (a problem discovered with using string:tokens/2
+%% and string:lexemes/2.
+
+dash_split(String) ->
+ dash_split(String, "", []).
+
+
+dash_split([$- | Rest], Acc, Elements) ->
+ Element = lists:reverse(Acc),
+ dash_split(Rest, "", [Element | Elements]);
+dash_split([Char | Rest], Acc, Elements) ->
+ dash_split(Rest, [Char | Acc], Elements);
+dash_split("", Acc, Elements) ->
+ Element = lists:reverse(Acc),
+ {ok, lists:reverse([Element | Elements])};
+dash_split(_, _, _) ->
+ error.
+
+
+-spec package_id(Realm, Name, VersionString) -> Result
+ when Realm :: zx:realm(),
+ Name :: zx:name(),
+ VersionString :: string(),
+ Result :: {ok, zx:package_id()}
+ | {error, invalid_package_string}.
+
+package_id(Realm, Name, VersionString) ->
+ ValidRealm = valid_lower0_9(Realm),
+ ValidName = valid_lower0_9(Name),
+ MaybeVersion = string_to_version(VersionString),
+ case {ValidRealm, ValidName, MaybeVersion} of
+ {true, true, {ok, Version}} -> {ok, {Realm, Name, Version}};
+ _ -> {error, invalid_package_string}
+ end.
+
+
+-spec package_string(zx:package_id()) -> {ok, string()} | {error, invalid_package_id}.
+%% @private
+%% Map an PackageID to a correct string representation.
+%% This function takes into account missing version elements.
+%% Examples:
+%% `{ok, "foo-bar-1.2.3"} = package_string({"foo", "bar", {1, 2, 3}})'
+%% `{ok, "foo-bar-1.2"} = package_string({"foo", "bar", {1, 2, z}})'
+%% `{ok, "foo-bar-1"} = package_string({"foo", "bar", {1, z, z}})'
+%% `{ok, "foo-bar"} = package_string({"foo", "bar", {z, z, z}})'
+%% `{error, invalid_package_id = package_string({"Bad", "Input"})'
+
+package_string({Realm, Name, {z, z, z}}) ->
+ ValidRealm = valid_lower0_9(Realm),
+ ValidName = valid_lower0_9(Name),
+ case ValidRealm and ValidName of
+ true ->
+ PackageString = lists:flatten(lists:join($-, [Realm, Name])),
+ {ok, PackageString};
+ false ->
+ {error, invalid_package_id}
+ end;
+package_string({Realm, Name, Version}) ->
+ ValidRealm = valid_lower0_9(Realm),
+ ValidName = valid_lower0_9(Name),
+ MaybeVersionString = version_to_string(Version),
+ case {ValidRealm, ValidName, MaybeVersionString} of
+ {true, true, {ok, VerString}} ->
+ PackageString = lists:flatten(lists:join($-, [Realm, Name, VerString])),
+ {ok, PackageString};
+ _ ->
+ {error, invalid_package_id}
+ end;
+package_string({Realm, Name}) ->
+ package_string({Realm, Name, {z, z, z}});
+package_string(_) ->
+ {error, invalid_package_id}.
+
+
+-spec package_dir(zx:package_id()) -> file:filename().
+%% @private
+%% Returns the path to a package installation. Crashes if PackageID is not a valid
+%% identitifer or if the version is incomplete (it is not possible to create a path
+%% to a partial version number).
+
+package_dir({Realm, Name, Version = {X, Y, Z}})
+ when is_integer(X), is_integer(Y), is_integer(Z) ->
+ {ok, PackageDir} = package_string({Realm, Name}),
+ {ok, VersionDir} = version_to_string(Version),
+ filename:join([zomp_dir(), "lib", PackageDir, VersionDir]).
+
+
+-spec package_dir(Prefix, Package) -> PackageDataDir
+ when Prefix :: string(),
+ Package :: zx:package(),
+ PackageDataDir :: file:filename().
+%% @private
+%% Create an absolute path to an application directory prefixed by the inclued argument.
+
+package_dir(Prefix, {Realm, Name}) ->
+ PackageString = package_string({Realm, Name, {z, z, z}}),
+ filename:join([zomp_dir(), Prefix, PackageString]).
+
+
+-spec namify_zsp(PackageID) -> ZrpFileName
+ when PackageID :: zx:package_id(),
+ ZrpFileName :: file:filename().
+%% @private
+%% Map an PackageID to its correct .zsp package file name.
+
+namify_zsp(PackageID) -> namify(PackageID, "zsp").
+
+
+-spec namify_tgz(PackageID) -> TgzFileName
+ when PackageID :: zx:package_id(),
+ TgzFileName :: file:filename().
+%% @private
+%% Map an PackageID to its correct gzipped tarball source bundle filename.
+
+namify_tgz(PackageID) -> namify(PackageID, "tgz").
+
+
+-spec namify(PackageID, Suffix) -> FileName
+ when PackageID :: zx:package_id(),
+ Suffix :: string(),
+ FileName :: file:filename().
+%% @private
+%% Converts an PackageID to a canonical string, then appends the provided
+%% filename Suffix.
+
+namify(PackageID, Suffix) ->
+ {ok, PackageString} = package_string(PackageID),
+ PackageString ++ "." ++ Suffix.
+
+
+-spec find_latest_compatible(Version, Versions) -> Result
+ when Version :: zx:version(),
+ Versions :: [zx:version()],
+ Result :: exact
+ | {ok, zx:version()}
+ | not_found.
+%% @private
+%% Find the latest compatible version from a list of versions. Returns the atom
+%% `exact' in the case a full version is specified and it exists, the tuple
+%% `{ok, Version}' in the case a compatible version was found against a partial
+%% version tuple, and the atom `not_found' in the case no compatible version exists
+%% in the list. Will fail with `not_found' if the input `Version' is not a valid
+%% `zx:version()' tuple.
+
+find_latest_compatible(Version, Versions) ->
+ Descending = lists:reverse(lists:sort(Versions)),
+ latest_compatible(Version, Descending).
+
+
+latest_compatible({z, z, z}, Versions) ->
+ {ok, hd(Versions)};
+latest_compatible({X, z, z}, Versions) ->
+ case lists:keyfind(X, 1, Versions) of
+ false -> not_found;
+ Version -> {ok, Version}
+ end;
+latest_compatible({X, Y, z}, Versions) ->
+ NotMatch = fun({Q, W, _}) -> not (Q == X andalso W == Y) end,
+ case lists:dropwhile(NotMatch, Versions) of
+ [] -> not_found;
+ Vs -> {ok, hd(Vs)}
+ end;
+latest_compatible(Version, Versions) ->
+ case lists:member(Version, Versions) of
+ true -> exact;
+ false -> not_found
+ end.
+
+
+-spec installed(zx:package_id()) -> boolean().
+%% @private
+%% True to its name, tells whether a package's install directory is found.
+
+installed(PackageID) ->
+ filelib:is_dir(package_dir(PackageID)).
+
+
+
+
+-spec realm_conf(Realm) -> RealmFileName
+ when Realm :: string(),
+ RealmFileName :: file:filename().
+%% @private
+%% Take a realm name, and return the name of the realm filename that would result.
+
+realm_conf(Realm) ->
+ Realm ++ ".realm".
+
+
+-spec load_realm_conf(Realm) -> Result
+ when Realm :: zx:realm(),
+ Result :: {ok, RealmConf}
+ | {error, Reason},
+ RealmConf :: list(),
+ Reason :: badarg
+ | terminated
+ | system_limit
+ | file:posix()
+ | {Line :: integer(), Mod :: module(), Cause :: term()}.
+%% @private
+%% Load the config for the given realm or halt with an error.
+
+load_realm_conf(Realm) ->
+ Path = filename:join(path(etc, Realm), "realm.conf"),
+ case file:consult(Path) of
+ {ok, C} ->
+ C;
+ {error, enoent} ->
+ ok = log(warning, "Realm ~tp is not configured.", [Realm]),
+ halt(1)
+ end.
+
+
+-spec extract_zsp_or_die(FileName) -> Files | no_return()
+ when FileName :: file:filename(),
+ Files :: [{file:filename(), binary()}].
+%% @private
+%% Extract a zsp archive, if possible. If not possible, halt execution with as accurate
+%% an error message as can be managed.
+
+extract_zsp_or_die(FileName) ->
+ case erl_tar:extract(FileName, [memory]) of
+ {ok, Files} ->
+ Files;
+ {error, {FileName, enoent}} ->
+ Message = "Can't find file ~ts.",
+ error_exit(Message, [FileName], ?LINE);
+ {error, invalid_tar_checksum} ->
+ Message = "~ts is not a valid zsp archive.",
+ error_exit(Message, [FileName], ?LINE);
+ {error, Reason} ->
+ Message = "Extracting package file failed with: ~160tp.",
+ error_exit(Message, [Reason], ?LINE)
+ end.
+
+
+-spec halt_if_exists(file:filename()) -> ok | no_return().
+%% @private
+%% A helper function to guard against overwriting an existing file. Halts execution if
+%% the file is found to exist.
+
+halt_if_exists(Path) ->
+ case filelib:is_file(Path) of
+ true -> error_exit("~ts already exists! Halting.", [Path], ?LINE);
+ false -> ok
+ end.
+
+
+-spec build() -> ok.
+%% @private
+%% Run any local `zxmake' script needed by the project for non-Erlang code (if present),
+%% then add the local `ebin/' directory to the runtime search path, and finally build
+%% the Erlang part of the project with make:all/0 according to the local `Emakefile'.
+
+build() ->
+ ZxMake = "zxmake",
+ ok =
+ case filelib:is_regular(ZxMake) of
+ true ->
+ Out = os:cmd(ZxMake),
+ log(info, Out);
+ false ->
+ ok
+ end,
+ true = code:add_patha(filename:absname("ebin")),
+ up_to_date = make:all(),
+ ok.
+
+
+-spec rm_rf(file:filename()) -> ok | {error, file:posix()}.
+%% @private
+%% Recursively remove files and directories. Equivalent to `rm -rf'.
+
+rm_rf(Path) ->
+ case filelib:is_dir(Path) of
+ true ->
+ Pattern = filename:join(Path, "**"),
+ Contents = lists:reverse(lists:sort(filelib:wildcard(Pattern))),
+ ok = lists:foreach(fun rm/1, Contents),
+ file:del_dir(Path);
+ false ->
+ file:delete(Path)
+ end.
+
+
+-spec rm(file:filename()) -> ok | {error, file:posix()}.
+%% @private
+%% An omnibus delete helper.
+
+rm(Path) ->
+ case filelib:is_dir(Path) of
+ true -> file:del_dir(Path);
+ false -> file:delete(Path)
+ end.
+
+
+
+%%% Error exits
+
+-spec error_exit(Format, Args, Line) -> no_return()
+ when Format :: string(),
+ Args :: [term()],
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Format, Args, Line) ->
+ File = filename:basename(?FILE),
+ ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]),
+ halt(1).
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_local.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_local.erl
new file mode 100644
index 0000000..e73c872
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_local.erl
@@ -0,0 +1,1177 @@
+%%% @doc
+%%% ZX Local
+%%%
+%%% This module defines procedures that affect the local host and terminate on
+%%% completion.
+%%% @end
+
+-module(zx_local).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([initialize/2, assimilate/1, set_dep/1, set_version/1,
+ list_realms/0, list_packages/1, list_versions/1, add_realm/1,
+ drop_dep/1, drop_key/1, drop_realm/1, verup/1, package/1,
+ create_plt/0, dialyze/0,
+ create_user/2, create_realm/0, create_realmfile/1]).
+
+-include("zx_logger.hrl").
+
+
+
+%%% Functions
+
+-spec initialize(Type, PackageString) -> no_return()
+ when Type :: app | lib,
+ PackageString :: string().
+%% @private
+%% Initialize an application in the local directory based on the PackageID provided.
+%% This function does not care about the name of the current directory and leaves
+%% providing a complete, proper and accurate PackageID.
+%% This function will check the current `lib/' directory for zomp-style dependencies.
+%% If this is not the intended function or if there are non-compliant directory names
+%% in `lib/' then the project will need to be rearranged to become zomp compliant or
+%% the `deps' section of the resulting meta file will need to be manually updated.
+
+initialize(Type, RawPackageString) ->
+ ok =
+ case filelib:is_file("zomp.meta") of
+ false -> ok;
+ true -> error_exit("This project is already Zompified.", ?LINE)
+ end,
+ PackageID =
+ case zx_lib:package_id(RawPackageString) of
+ {ok, {R, N, {z, z, z}}} ->
+ {R, N, {0, 1, 0}};
+ {ok, {R, N, {X, z, z}}} ->
+ {R, N, {X, 0, 0}};
+ {ok, {R, N, {X, Y, z}}} ->
+ {R, N, {X, Y, 0}};
+ {ok, ID} ->
+ ID;
+ {error, invalid_package_string} ->
+ error_exit("Invalid package string: ~tp", [RawPackageString], ?LINE)
+ end,
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = check_package_conflict(PackageID, PackageString),
+ ok = log(info, "Initializing ~s...", [PackageString]),
+ Prefix = solicit_prefix(),
+ ok = update_source_vsn(element(3, PackageID)),
+ ok = update_app_file(PackageID),
+ MetaList =
+ [{package_id, PackageID},
+ {deps, []},
+ {type, Type},
+ {prefix, Prefix}],
+ Meta = maps:from_list(MetaList),
+ ok = zx_lib:write_project_meta(Meta),
+ ok = log(info, "Project ~tp initialized.", [PackageString]),
+ Message =
+ "~nNOTICE:~n"
+ " This project is currently listed as having no dependencies.~n"
+ " If this is not true then run `zx set dep DepID` for each current dependency.~n"
+ " (run `zx help` for more information on usage)~n",
+ ok = io:format(Message),
+ halt(0).
+
+
+-spec check_package_conflict(zx:package_id(), string()) -> ok.
+%% @private
+%% Check the realm's upstream for the existence of a package that already has the same
+%% name, or the name of any modules in src/ and report them to the user. Give the user
+%% a chance to change their package's name or ignore the conflict, and report all module
+%% naming conflicts.
+
+check_package_conflict(_PackageID, _PackageString) ->
+ log(info, "TODO: This is where the intended realm is checked for conflicts "
+ "and the user is given a chance to rename or ignore the conflict. "
+ "This check will have to wait for the network protocol fix.").
+
+
+-spec solicit_prefix() -> ok.
+%% @private
+%% Most Erlang projects outside of the core distribution evolve a prefix of some sort
+%% to namespace their work from other projects (or deliberately mimic another project's
+%% prefix in the case that a new project is meant to augment, but not alter, an already
+%% existing one).
+%% A prefix is decided upon or disregarded here and stored in the meta file. The user
+%% is given the option to update module names now (to include modifying call sites
+%% in project code automatically -- while providing ample warnings about breaking
+%% external code).
+%% Just like with check_package_conflict/2, this procedure gives the user a chance to
+%% ignore all warnings and just go.
+
+solicit_prefix() ->
+ ok = log(info, "Will solicit a prefix here. Just returning \"zz\" right now. Hah!"),
+ "zz".
+
+
+-spec update_source_vsn(zx:version()) -> ok.
+%% @private
+%% Use grep to tell us which files have a `-vsn' attribute and which don't.
+%% Use sed to insert a line after `-module' in the files that don't have it,
+%% and update the files that do.
+%% This procedure is still halfway into "works for me" territory. It will take a bit
+%% of survey data to know which platforms can't work with some form of something
+%% in here by default (bash may need to be called explicitly, for example, or the
+%% old backtick executor terms used, etc).
+
+update_source_vsn(Version) ->
+ {ok, VersionString} = zx_lib:version_to_string(Version),
+ AddF = "sed -i 's/^-module(.*)\\.$/&\\n-vsn(\"~s\")./' $(grep -L '^-vsn(' src/*)",
+ SubF = "sed -i 's/-vsn(.*$/-vsn(\"~s\")./' $(grep -l '^-vsn(' src/*)",
+ Add = lists:flatten(io_lib:format(AddF, [VersionString])),
+ Sub = lists:flatten(io_lib:format(SubF, [VersionString])),
+ ok = exec_shell(Add),
+ ok = exec_shell(Sub),
+ log(info, "Source version attributes set").
+
+
+-spec update_app_file(zx:package_id()) -> ok.
+%% @private
+%% Update the app file or create it if it is missing.
+%% TODO: If the app file is missing, interpret the src/*app.src file correctly.
+%% Should really pull a few pages out of the rebar/erland.mk books on this,
+%% as they've done all the hard pioneering work already.
+%% TODO: Interactively determine whether the main module is the name, or the prefix
+%% is the name, or the name is the prefix, or the name is the description, etc.
+%% before writing anything out.
+
+update_app_file({_, Name, Version}) ->
+ {ok, VersionString} = zx_lib:version_to_string(Version),
+ AppName = list_to_atom(Name),
+ AppFile = filename:join("ebin", Name ++ ".app"),
+ {application, AppName, RawAppData} =
+ case filelib:is_regular(AppFile) of
+ true ->
+ {ok, [D]} = file:consult(AppFile),
+ D;
+ false ->
+ {application,
+ AppName,
+ [{registered, []},
+ {included_applications, []},
+ {applications, [stdlib, kernel]}]}
+ end,
+ Grep = "grep -oP '^-module\\(\\K[^)]+' src/* | cut -d: -f2",
+ Modules = [list_to_atom(M) || M <- string:lexemes(os:cmd(Grep), "\n")],
+ Properties =
+ [{vsn, VersionString},
+ {modules, Modules},
+ {mod, {AppName, []}}],
+ Store = fun(T, L) -> lists:keystore(element(1, T), 1, L, T) end,
+ AppData = lists:foldl(Store, RawAppData, Properties),
+ AppProfile = {application, AppName, AppData},
+ ok = log(info, "Writing app file: ~ts~n~tp", [AppFile, AppProfile]),
+ zx_lib:write_terms(AppFile, [AppProfile]).
+
+
+-spec exec_shell(CMD) -> ok | no_return()
+ when CMD :: string().
+%% @private
+%% Print the output of an os:cmd/1 event only if there is any.
+
+exec_shell(CMD) ->
+ case os:cmd(CMD) of
+ "" ->
+ ok;
+ Out ->
+ Trimmed = string:trim(Out, trailing, "\r\n"),
+ log(info, "os:cmd(~tp) ->~n~ts", [CMD, Trimmed])
+ end.
+
+
+-spec assimilate(PackageFile) -> PackageID
+ when PackageFile :: file:filename(),
+ PackageID :: zx:package_id().
+%% @private
+%% Receives a path to a file containing package data, examines it, and copies it to a
+%% canonical location under a canonical name, returning the PackageID of the package
+%% contents.
+
+assimilate(PackageFile) ->
+ Files = zx_lib:extract_zsp_or_die(PackageFile),
+ {ok, CWD} = file:get_cwd(),
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ {"zomp.meta", MetaBin} = lists:keyfind("zomp.meta", 1, Files),
+ Meta = binary_to_term(MetaBin),
+ PackageID = maps:get(package_id, Meta),
+ TgzFile = zx_lib:namify_tgz(PackageID),
+ {TgzFile, TgzData} = lists:keyfind(TgzFile, 1, Files),
+ {KeyID, Signature} = maps:get(sig, Meta),
+ {ok, PubKey} = zx_key:load(public, KeyID),
+ ok =
+ case public_key:verify(TgzData, sha512, Signature, PubKey) of
+ true ->
+ ZrpPath = filename:join("zsp", zx_lib:namify_zsp(PackageID)),
+ file:copy(PackageFile, ZrpPath);
+ false ->
+ error_exit("Bad package signature: ~ts", [PackageFile], ?LINE)
+ end,
+ ok = file:set_cwd(CWD),
+ Message = "~ts is now locally available.",
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = log(info, Message, [PackageString]),
+ halt(0).
+
+
+-spec set_dep(Identifier :: string()) -> no_return().
+%% @private
+%% Set a specific dependency in the current project. If the project currently has a
+%% dependency on the same package then the version of that dependency is updated to
+%% reflect that in the PackageString argument. The AppString is permitted to be
+%% incomplete. Incomplete elements of the VersionString (if included) will default to
+%% the latest version available at the indicated level.
+
+set_dep(Identifier) ->
+ {ok, {Realm, Name, FuzzyVersion}} = zx_lib:package_id(Identifier),
+ Version =
+ case FuzzyVersion of
+ {X, Y, Z} when is_integer(X), is_integer(Y), is_integer(Z) ->
+ {X, Y, Z};
+ _ ->
+ error_exit("Incomplete version tuple: ~tp", [FuzzyVersion])
+ end,
+ set_dep({Realm, Name}, Version).
+
+
+set_dep({Realm, Name}, Version) ->
+ PackageID = {Realm, Name, Version},
+ {ok, Meta} = zx_lib:read_project_meta(),
+ Deps = maps:get(deps, Meta),
+ case lists:member(PackageID, Deps) of
+ true ->
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = log(info, "~ts is already a dependency", [PackageString]),
+ halt(0);
+ false ->
+ set_dep(PackageID, Deps, Meta)
+ end.
+
+
+-spec set_dep(PackageID, Deps, Meta) -> no_return()
+ when PackageID :: zx:package_id(),
+ Deps :: [zx:package_id()],
+ Meta :: [term()].
+%% @private
+%% Given the PackageID, list of Deps and the current contents of the project Meta, add
+%% or update Deps to include (or update) Deps to reflect a dependency on PackageID, if
+%% such a dependency is not already present. Then write the project meta back to its
+%% file and exit.
+
+set_dep(PackageID = {Realm, Name, NewVersion}, Deps, Meta) ->
+ ExistingPackageIDs = fun({R, N, _}) -> {R, N} == {Realm, Name} end,
+ NewDeps =
+ case lists:partition(ExistingPackageIDs, Deps) of
+ {[{Realm, Name, OldVersion}], Rest} ->
+ Message = "Updating dep ~ts to ~ts",
+ {ok, OldPS} = zx_lib:package_string({Realm, Name, OldVersion}),
+ {ok, NewPS} = zx_lib:package_string({Realm, Name, NewVersion}),
+ ok = log(info, Message, [OldPS, NewPS]),
+ [PackageID | Rest];
+ {[], Deps} ->
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ok = log(info, "Adding dep ~ts", [PackageString]),
+ [PackageID | Deps]
+ end,
+ NewMeta = maps:put(deps, NewDeps, Meta),
+ ok = zx_lib:write_project_meta(NewMeta),
+ halt(0).
+
+
+-spec set_version(VersionString) -> no_return()
+ when VersionString :: string().
+%% @private
+%% Convert a version string to a new version, sanitizing it in the process and returning
+%% a reasonable error message on bad input.
+
+set_version(VersionString) ->
+ NewVersion =
+ case zx_lib:string_to_version(VersionString) of
+ {ok, {_, _, z}} ->
+ Message = "'set version' arguments must be complete, ex: 1.2.3",
+ error_exit(Message, ?LINE);
+ {ok, Version} ->
+ Version;
+ {error, invalid_version_string} ->
+ Message = "Invalid version string: ~tp",
+ error_exit(Message, [VersionString], ?LINE)
+ end,
+ {ok, Meta} = zx_lib:read_project_meta(),
+ {Realm, Name, OldVersion} = maps:get(package_id, Meta),
+ update_version(Realm, Name, OldVersion, NewVersion, Meta).
+
+
+-spec update_version(Realm, Name, OldVersion, NewVersion, OldMeta) -> no_return()
+ when Realm :: zx:realm(),
+ Name :: zx:name(),
+ OldVersion :: zx:version(),
+ NewVersion :: zx:version(),
+ OldMeta :: zx:package_meta().
+%% @private
+%% Update a project's `zomp.meta' file by either incrementing the indicated component,
+%% or setting the version number to the one specified in VersionString.
+%% This part of the procedure updates the meta and does the final write, if the write
+%% turns out to be possible. If successful it will indicate to the user what was
+%% changed.
+
+update_version(Realm, Name, OldVersion, NewVersion, OldMeta) ->
+ PackageID = {Realm, Name, NewVersion},
+ NewMeta = maps:put(package_id, PackageID, OldMeta),
+ ok = zx_lib:write_project_meta(NewMeta),
+ {ok, OldVS} = zx_lib:version_to_string(OldVersion),
+ {ok, NewVS} = zx_lib:version_to_string(NewVersion),
+ ok = log(info, "Version changed from ~s to ~s.", [OldVS, NewVS]),
+ halt(0).
+
+
+-spec list_realms() -> no_return().
+%% @private
+%% List all currently configured realms. The definition of a "configured realm" is a
+%% realm for which a .realm file exists in $ZOMP_HOME. The realms will be printed to
+%% stdout and the program will exit.
+
+list_realms() ->
+ ok = lists:foreach(fun(R) -> io:format("~ts~n", [R]) end, zx_lib:list_realms()),
+ halt(0).
+
+
+-spec list_packages(zx:realm()) -> no_return().
+%% @private
+%% Contact the indicated realm and query it for a list of registered packages and print
+%% them to stdout.
+
+list_packages(Realm) ->
+ ok = zx:start(),
+ case zx_daemon:list_packages(Realm) of
+ {ok, []} ->
+ ok = log(info, "Realm ~tp has no packages available.", [Realm]),
+ halt(0);
+ {ok, Packages} ->
+ Print = fun({R, N}) -> io:format("~ts-~ts~n", [R, N]) end,
+ ok = lists:foreach(Print, Packages),
+ halt(0);
+ {error, bad_realm} ->
+ error_exit("Bad realm name.", ?LINE);
+ {error, no_realm} ->
+ error_exit("Realm \"~ts\" is not configured.", ?LINE);
+ {error, network} ->
+ Message = "Network issues are preventing connection to the realm.",
+ error_exit(Message, ?LINE)
+ end.
+
+
+-spec list_versions(PackageName :: string()) -> no_return().
+%% @private
+%% List the available versions of the package indicated. The user enters a string-form
+%% package name (such as "otpr-zomp") and the return values will be full package strings
+%% of the form "otpr-zomp-1.2.3", one per line printed to stdout.
+
+list_versions(PackageName) ->
+ Package = {Realm, Name} =
+ case zx_lib:package_id(PackageName) of
+ {ok, {R, N, {z, z, z}}} ->
+ {R, N};
+ {error, invalid_package_string} ->
+ error_exit("~tp is not a valid package name.", [PackageName], ?LINE)
+ end,
+ ok = zx:start(),
+ case zx_daemon:list_versions(Package) of
+ {ok, []} ->
+ Message = "Package ~ts has no versions available.",
+ ok = log(info, Message, [PackageName]),
+ halt(0);
+ {ok, Versions} ->
+ Print =
+ fun(Version) ->
+ {ok, PackageString} = zx_lib:package_string({Realm, Name, Version}),
+ io:format("~ts~n", [PackageString])
+ end,
+ ok = lists:foreach(Print, Versions),
+ halt(0);
+ {error, bad_realm} ->
+ error_exit("Bad realm name.", ?LINE);
+ {error, bad_package} ->
+ error_exit("Bad package name.", ?LINE);
+ {error, network} ->
+ Message = "Network issues are preventing connection to the realm.",
+ error_exit(Message, ?LINE)
+ end.
+
+
+-spec add_realm(Path) -> no_return()
+ when Path :: file:filename().
+%% @private
+%% Add a .realm file to $ZOMP_HOME from a location in the filesystem.
+%% Print the SHA512 of the .realm file for the user so they can verify that the file
+%% is authentic. This implies, of course, that .realm maintainers are going to
+%% post SHA512 sums somewhere visible.
+
+add_realm(Path) ->
+ case file:read_file(Path) of
+ {ok, Data} ->
+ Digest = crypto:hash(sha512, Data),
+ Text = integer_to_list(binary:decode_unsigned(Digest, big), 16),
+ ok = log(info, "SHA512 of ~ts: ~ts", [Path, Text]),
+ add_realm(Path, Data);
+ {error, enoent} ->
+ ok = log(warning, "FAILED: ~ts does not exist.", [Path]),
+ halt(1);
+ {error, eisdir} ->
+ ok = log(warning, "FAILED: ~ts is a directory, not a realm file.", [Path]),
+ halt(1)
+ end.
+
+
+-spec add_realm(Path, Data) -> no_return()
+ when Path :: file:filename(),
+ Data :: binary().
+
+add_realm(Path, Data) ->
+ case erl_tar:extract({binary, Data}, [compressed, {cwd, zx_lib:zomp_dir()}]) of
+ ok ->
+ {Realm, _} = string:take(filename:basename(Path), ".", true),
+ ok = log(info, "Realm ~ts is now visible to this system.", [Realm]),
+ halt(0);
+ {error, invalid_tar_checksum} ->
+ error_exit("~ts is not a valid realm file.", [Path], ?LINE);
+ {error, eof} ->
+ error_exit("~ts is not a valid realm file.", [Path], ?LINE)
+ end.
+
+
+-spec drop_dep(zx:package_id()) -> no_return().
+%% @private
+%% Remove the indicate dependency from the local project's zomp.meta record.
+
+drop_dep(PackageID) ->
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ {ok, Meta} = zx_lib:read_project_meta(),
+ Deps = maps:get(deps, Meta),
+ case lists:member(PackageID, Deps) of
+ true ->
+ NewDeps = lists:delete(PackageID, Deps),
+ NewMeta = maps:put(deps, NewDeps, Meta),
+ ok = zx_lib:write_project_meta(NewMeta),
+ Message = "~ts removed from dependencies.",
+ ok = log(info, Message, [PackageString]),
+ halt(0);
+ false ->
+ ok = log(info, "~ts not found in dependencies.", [PackageString]),
+ halt(0)
+ end.
+
+
+-spec drop_key(zx:key_id()) -> no_return().
+%% @private
+%% Given a KeyID, remove the related public and private keys from the keystore, if they
+%% exist. If not, exit with a message that no keys were found, but do not return an
+%% error exit value (this instruction is idempotent if used in shell scripts).
+
+drop_key({Realm, KeyName}) ->
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ KeyGlob = KeyName ++ ".{key,pub},der",
+ Pattern = filename:join([zx_lib:zomp_dir(), "key", Realm, KeyGlob]),
+ case filelib:wildcard(Pattern) of
+ [] ->
+ ok = log(warning, "Key ~ts/~ts not found", [Realm, KeyName]),
+ halt(0);
+ Files ->
+ ok = lists:foreach(fun file:delete/1, Files),
+ ok = log(info, "Keyset ~ts/~ts removed", [Realm, KeyName]),
+ halt(0)
+ end.
+
+
+-spec drop_realm(zx:realm()) -> no_return().
+
+drop_realm(Realm) ->
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ RealmConf = zx_lib:realm_conf(Realm),
+ case filelib:is_regular(RealmConf) of
+ true ->
+ Message =
+ "~n"
+ " WARNING: Are you SURE you want to remove realm ~ts?~n"
+ " (Only \"Y\" will confirm this action.)~n",
+ ok = io:format(Message, [Realm]),
+ case zx_tty:get_input() of
+ "Y" ->
+ ok = file:delete(RealmConf),
+ ok = drop_prime(Realm),
+ ok = clear_keys(Realm),
+ ok = log(info, "All traces of realm ~ts have been removed."),
+ halt(0);
+ _ ->
+ ok = log(info, "Aborting."),
+ halt(0)
+ end;
+ false ->
+ ok = log(warning, "Realm conf ~ts not found.", [RealmConf]),
+ clear_keys(Realm)
+ end.
+
+
+-spec drop_prime(zx:realm()) -> ok.
+
+drop_prime(Realm) ->
+ Path = "zomp.conf",
+ case file:consult(Path) of
+ {ok, Conf} ->
+ {managed, Primes} = lists:keyfind(managed, 1, Conf),
+ NewPrimes = lists:delete(Realm, Primes),
+ NewConf = lists:keystore(managed, 1, Primes, {managed, NewPrimes}),
+ ok = zx_lib:write_terms(Path, NewConf),
+ log(info, "Ensuring ~ts is not a prime in ~ts", [Realm, Path]);
+ {error, enoent} ->
+ ok
+ end.
+
+
+-spec clear_keys(zx:realm()) -> ok.
+
+clear_keys(Realm) ->
+ KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]),
+ case filelib:is_dir(KeyDir) of
+ true -> zx_lib:rm_rf(KeyDir);
+ false -> log(warning, "Keydir ~ts not found", [KeyDir])
+ end.
+
+
+-spec verup(Level) -> no_return()
+ when Level :: string().
+%% @private
+%% Convert input string arguments to acceptable atoms for use in update_version/1.
+
+verup("major") -> version_up(major);
+verup("minor") -> version_up(minor);
+verup("patch") -> version_up(patch);
+verup(_) -> zx:usage_exit(22).
+
+
+-spec version_up(Level) -> no_return()
+ when Level :: major
+ | minor
+ | patch.
+%% @private
+%% Update a project's `zomp.meta' file by either incrementing the indicated component,
+%% or setting the version number to the one specified in VersionString.
+%% This part of the procedure guards for the case when the zomp.meta file cannot be
+%% read for some reason.
+
+version_up(Arg) ->
+ Meta =
+ case zx_lib:read_project_meta() of
+ {ok, M} -> M;
+ Error -> error_exit("verup failed with: ~tp", [Error], ?LINE)
+ end,
+ PackageID = maps:get(package_id, Meta),
+ version_up(Arg, PackageID, Meta).
+
+
+-spec version_up(Level, PackageID, Meta) -> no_return()
+ when Level :: major
+ | minor
+ | patch
+ | zx:version(),
+ PackageID :: zx:package_id(),
+ Meta :: [{atom(), term()}].
+%% @private
+%% Update a project's `zomp.meta' file by either incrementing the indicated component,
+%% or setting the version number to the one specified in VersionString.
+%% This part of the procedure does the actual update calculation, to include calling to
+%% convert the VersionString (if it is passed) to a `version()' type and check its
+%% validity (or halt if it is a bad string).
+
+version_up(major, {Realm, Name, OldVersion = {Major, _, _}}, OldMeta) ->
+ NewVersion = {Major + 1, 0, 0},
+ update_version(Realm, Name, OldVersion, NewVersion, OldMeta);
+version_up(minor, {Realm, Name, OldVersion = {Major, Minor, _}}, OldMeta) ->
+ NewVersion = {Major, Minor + 1, 0},
+ update_version(Realm, Name, OldVersion, NewVersion, OldMeta);
+version_up(patch, {Realm, Name, OldVersion = {Major, Minor, Patch}}, OldMeta) ->
+ NewVersion = {Major, Minor, Patch + 1},
+ update_version(Realm, Name, OldVersion, NewVersion, OldMeta).
+
+
+-spec package(TargetDir) -> no_return()
+ when TargetDir :: file:filename().
+%% @private
+%% Turn a target project directory into a package, prompting the user for appropriate
+%% key selection or generation actions along the way.
+
+package(TargetDir) ->
+ ok = log(info, "Packaging ~ts", [TargetDir]),
+ {ok, Meta} = zx_lib:read_project_meta(TargetDir),
+ {Realm, _, _} = maps:get(package_id, Meta),
+ KeyDir = filename:join([zx_lib:zomp_dir(), "key", Realm]),
+ ok = zx_lib:force_dir(KeyDir),
+ Pattern = KeyDir ++ "/*.key.der",
+ case [filename:basename(F, ".key.der") || F <- filelib:wildcard(Pattern)] of
+ [] ->
+ ok = log(info, "Need to generate key"),
+ KeyID = zx_key:prompt_keygen(),
+ {ok, _, _} = zx_key:generate_rsa(KeyID),
+ package(KeyID, TargetDir);
+ [KeyName] ->
+ KeyID = {Realm, KeyName},
+ ok = log(info, "Using key: ~ts/~ts", [Realm, KeyName]),
+ package(KeyID, TargetDir);
+ KeyNames ->
+ KeyName = zx_tty:select_string(KeyNames),
+ package({Realm, KeyName}, TargetDir)
+ end.
+
+
+-spec package(KeyID, TargetDir) -> no_return()
+ when KeyID :: zx:key_id(),
+ TargetDir :: file:filename().
+%% @private
+%% Accept a KeyPrefix for signing and a TargetDir containing a project to package and
+%% build a zsp package file ready to be submitted to a repository.
+
+package(KeyID, TargetDir) ->
+ {ok, Meta} = zx_lib:read_project_meta(TargetDir),
+ PackageID = maps:get(package_id, Meta),
+ true = element(1, PackageID) == element(1, KeyID),
+ {ok, PackageString} = zx_lib:package_string(PackageID),
+ ZrpFile = PackageString ++ ".zsp",
+ TgzFile = PackageString ++ ".tgz",
+ ok = zx_lib:halt_if_exists(ZrpFile),
+ ok = remove_binaries(TargetDir),
+ {ok, Everything} = file:list_dir(TargetDir),
+ DotFiles = filelib:wildcard(".*", TargetDir),
+ Ignores = ["lib" | DotFiles],
+ Targets = lists:subtract(Everything, Ignores),
+ {ok, CWD} = file:get_cwd(),
+ ok = file:set_cwd(TargetDir),
+ ok = zx_lib:build(),
+ Modules =
+ [filename:basename(M, ".beam") || M <- filelib:wildcard("*.beam", "ebin")],
+ ok = remove_binaries("."),
+ ok = erl_tar:create(filename:join(CWD, TgzFile), Targets, [compressed]),
+ ok = file:set_cwd(CWD),
+ {ok, Key} = zx_key:load(private, KeyID),
+ {ok, TgzBin} = file:read_file(TgzFile),
+ Sig = public_key:sign(TgzBin, sha512, Key),
+ Add = fun({K, V}, M) -> maps:put(K, V, M) end,
+ FinalMeta = lists:foldl(Add, Meta, [{modules, Modules}, {sig, {KeyID, Sig}}]),
+ ok = file:write_file("zomp.meta", term_to_binary(FinalMeta)),
+ ok = erl_tar:create(ZrpFile, ["zomp.meta", TgzFile]),
+ ok = file:delete(TgzFile),
+ ok = file:delete("zomp.meta"),
+ ok = log(info, "Wrote archive ~ts", [ZrpFile]),
+ halt(0).
+
+
+-spec remove_binaries(TargetDir) -> ok
+ when TargetDir :: file:filename().
+%% @private
+%% Procedure to delete all .beam and .ez files from a given directory starting at
+%% TargetDir. Called as part of the pre-packaging sanitization procedure.
+
+remove_binaries(TargetDir) ->
+ Beams = filelib:wildcard("**/*.{beam,ez}", TargetDir),
+ case [filename:join(TargetDir, Beam) || Beam <- Beams] of
+ [] ->
+ ok;
+ ToDelete ->
+ ok = log(info, "Removing: ~tp", [ToDelete]),
+ lists:foreach(fun file:delete/1, ToDelete)
+ end.
+
+
+-spec create_plt() -> no_return().
+%% @private
+%% Generate a fresh PLT file that includes most basic core applications needed to
+%% make a resonable estimate of a type system, write the name of the PLT to stdout,
+%% and exit.
+
+create_plt() ->
+ ok = build_plt(),
+ halt(0).
+
+
+-spec build_plt() -> ok.
+%% @private
+%% Build a general plt file for Dialyzer based on the core Erland distro.
+%% TODO: Make a per-package + dependencies version of this.
+
+build_plt() ->
+ PLT = default_plt(),
+ Template =
+ "dialyzer --build_plt"
+ " --output_plt ~ts"
+ " --apps asn1 reltool wx common_test crypto erts eunit inets"
+ " kernel mnesia public_key sasl ssh ssl stdlib",
+ Command = io_lib:format(Template, [PLT]),
+ Message =
+ "Generating PLT file and writing to: ~tp~n"
+ " There will be a list of \"unknown functions\" in the final output.~n"
+ " Don't panic. This is normal. Turtles all the way down, after all...",
+ ok = log(info, Message, [PLT]),
+ ok = log(info, "This may take a while. Patience is a virtue."),
+ Out = os:cmd(Command),
+ log(info, Out).
+
+
+-spec default_plt() -> file:filename().
+
+default_plt() ->
+ filename:join(zx_lib:zomp_dir(), "basic.plt").
+
+
+-spec dialyze() -> no_return().
+%% @private
+%% Preps a copy of this script for typechecking with Dialyzer.
+%% TODO: Create a package_id() based version of this to handle dialyzation of complex
+%% projects.
+
+dialyze() ->
+ PLT = default_plt(),
+ ok =
+ case filelib:is_regular(PLT) of
+ true -> log(info, "Using PLT: ~tp", [PLT]);
+ false -> build_plt()
+ end,
+ TmpDir = filename:join(zx_lib:zomp_dir(), "tmp"),
+ Me = escript:script_name(),
+ EvilTwin = filename:join(TmpDir, filename:basename(Me ++ ".erl")),
+ ok = log(info, "Temporarily reconstructing ~tp as ~tp", [Me, EvilTwin]),
+ Sed = io_lib:format("sed 's/^#!.*$//' ~s > ~s", [Me, EvilTwin]),
+ "" = os:cmd(Sed),
+ ok = case dialyzer:run([{init_plt, PLT}, {from, src_code}, {files, [EvilTwin]}]) of
+ [] ->
+ io:format("Dialyzer found no errors and returned no warnings! Yay!~n");
+ Warnings ->
+ Mine = [dialyzer:format_warning({Tag, {Me, Line}, Msg})
+ || {Tag, {_, Line}, Msg} <- Warnings],
+ lists:foreach(fun io:format/1, Mine)
+ end,
+ ok = file:delete(EvilTwin),
+ halt(0).
+
+
+-spec create_user(zx:realm(), zx:user_name()) -> no_return().
+%% @private
+%% Validate the realm and username provided, prompt the user to either select a keypair
+%% to use or generate a new one, and bundle a .zuser file for conveyance of the user
+%% data and his relevant keys (for import into an existing zomp server via `add'
+%% command like "add packager", "add maintainer" and "add sysop".
+
+create_user(Realm, Username) ->
+ Message = "Would be generating a user file for {~160tp, ~160to}.",
+ ok = log(info, Message, [Realm, Username]),
+ halt(0).
+
+
+-spec create_realm() -> no_return().
+%% @private
+%% Prompt the user to input the information necessary to create a new zomp realm,
+%% package the data appropriately for the server and deliver the final keys and
+%% realm file to the user.
+
+create_realm() ->
+ Instructions =
+ "~n"
+ " Enter a name for your new realm.~n"
+ " Names can contain only lower-case letters, numbers and the underscore.~n"
+ " Names must begin with a lower-case letter.~n",
+ ok = io:format(Instructions),
+ Realm = zx_tty:get_input(),
+ case zx_lib:valid_lower0_9(Realm) of
+ true ->
+ RealmFile = filename:join(zx_lib:zomp_dir(), Realm ++ ".realm"),
+ case filelib:is_regular(RealmFile) of
+ false ->
+ create_realm(Realm);
+ true ->
+ ok = io:format("That realm already exists. Be more original.~n"),
+ create_realm()
+ end;
+ false ->
+ ok = io:format("Bad realm name \"~ts\". Try again.~n", [Realm]),
+ create_realm()
+ end.
+
+
+-spec create_realm(Realm) -> no_return()
+ when Realm :: zx:realm().
+
+create_realm(Realm) ->
+ ExAddress = prompt_external_address(),
+ create_realm(Realm, ExAddress).
+
+
+-spec prompt_external_address() -> Result
+ when Result :: inet:hostname() | inet:ip_address().
+
+prompt_external_address() ->
+ Message = external_address_prompt(),
+ ok = io:format(Message),
+ case zx_tty:get_input() of
+ "" ->
+ ok = io:format("You need to enter an address.~n"),
+ prompt_external_address();
+ String ->
+ parse_address(String)
+ end.
+
+
+-spec external_address_prompt() -> string().
+
+external_address_prompt() ->
+ "~n"
+ " Enter a static, valid hostname or IPv4 or IPv6 address at which this host "
+ "can be reached from the public internet (or internal network if it will never "
+ "need to be reached from the internet).~n"
+ " DO NOT INCLUDE A PORT NUMBER IN THIS STEP~n".
+
+
+-spec parse_address(string()) -> inet:hostname() | inet:ip_address().
+
+parse_address(String) ->
+ case inet:parse_address(String) of
+ {ok, Address} -> Address;
+ {error, einval} -> String
+ end.
+
+
+-spec create_realm(Realm, ExAddress) -> no_return()
+ when Realm :: zx:realm(),
+ ExAddress :: inet:hostname() | inet:ip_address().
+
+create_realm(Realm, ExAddress) ->
+ Message =
+ "~n"
+ " Enter the public (external) port number at which this service should be "
+ "available. (This might be different from the local port number if you are "
+ "forwarding ports or have a complex network layout.)~n",
+ ok = io:format(Message),
+ ExPort = prompt_port_number(11311),
+ create_realm(Realm, ExAddress, ExPort).
+
+
+-spec create_realm(Realm, ExAddress, ExPort) -> no_return()
+ when Realm :: zx:realm(),
+ ExAddress :: inet:hostname() | inet:ip_address(),
+ ExPort :: inet:port_number().
+
+create_realm(Realm, ExAddress, ExPort) ->
+ Message =
+ "~n"
+ " Enter the local (internal/LAN) port number at which this service should be "
+ "available. (This might be different from the public port visible from the "
+ "internet if you are port forwarding or have a complex network layout.)~n",
+ ok = io:format(Message),
+ InPort = prompt_port_number(11311),
+ create_realm(Realm, ExAddress, ExPort, InPort).
+
+
+-spec prompt_port_number(Current) -> Result
+ when Current :: inet:port_number(),
+ Result :: inet:port_number().
+
+prompt_port_number(Current) ->
+ Instructions =
+ " A valid port is any number from 1 to 65535."
+ " [Press enter to accept the current setting: ~tw]~n",
+ ok = io:format(Instructions, [Current]),
+ case zx_tty:get_input() of
+ "" ->
+ Current;
+ S ->
+ try
+ case list_to_integer(S) of
+ Port when 16#ffff >= Port, Port > 0 ->
+ Port;
+ Illegal ->
+ Whoops = "Whoops! ~tw is out of bounds (1~65535). Try again.~n",
+ ok = io:format(Whoops, [Illegal]),
+ prompt_port_number(Current)
+ end
+ catch error:badarg ->
+ ok = io:format("~tp is not a port number. Try again...", [S]),
+ prompt_port_number(Current)
+ end
+ end.
+
+
+-spec create_realm(Realm, ExAddress, ExPort, InPort) -> no_return()
+ when Realm :: zx:realm(),
+ ExAddress :: inet:hostname() | inet:ip_address(),
+ ExPort :: inet:port_number(),
+ InPort :: inet:port_number().
+
+create_realm(Realm, ExAddress, ExPort, InPort) ->
+ Instructions =
+ "~n"
+ " Enter a username for the realm sysop.~n"
+ " Names can contain only lower-case letters, numbers and the underscore.~n"
+ " Names must begin with a lower-case letter.~n",
+ ok = io:format(Instructions),
+ UserName = zx_tty:get_input(),
+ case zx_lib:valid_lower0_9(UserName) of
+ true ->
+ create_realm(Realm, ExAddress, ExPort, InPort, UserName);
+ false ->
+ ok = io:format("Bad username ~tp. Try again.~n", [UserName]),
+ create_realm(Realm, ExAddress, ExPort, InPort)
+ end.
+
+
+-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName) -> no_return()
+ when Realm :: zx:realm(),
+ ExAddress :: inet:hostname() | inet:ip_address(),
+ ExPort :: inet:port_number(),
+ InPort :: inet:port_number(),
+ UserName :: string().
+
+create_realm(Realm, ExAddress, ExPort, InPort, UserName) ->
+ Instructions =
+ "~n"
+ " Enter an email address for the realm sysop.~n"
+ " Valid email address rules apply though the checking done here is quite "
+ "minimal. Check the address you enter carefully. The only people who will "
+ "suffer from an invalid address are your users.~n",
+ ok = io:format(Instructions),
+ Email = zx_tty:get_input(),
+ [User, Host] = string:lexemes(Email, "@"),
+ case {zx_lib:valid_lower0_9(User), zx_lib:valid_label(Host)} of
+ {true, true} ->
+ create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email);
+ {false, true} ->
+ Message = "The user part of the email address seems invalid. Try again.~n",
+ ok = io:format(Message),
+ create_realm(Realm, ExAddress, ExPort, InPort, UserName);
+ {true, false} ->
+ Message = "The host part of the email address seems invalid. Try again.~n",
+ ok = io:format(Message),
+ create_realm(Realm, ExAddress, ExPort, InPort, UserName);
+ {false, false} ->
+ Message = "This email address seems like its totally bonkers. Try again.~n",
+ ok = io:format(Message),
+ create_realm(Realm, ExAddress, ExPort, InPort, UserName)
+ end.
+
+
+-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) ->
+ no_return()
+ when Realm :: zx:realm(),
+ ExAddress :: inet:hostname() | inet:ip_address(),
+ ExPort :: inet:port_number(),
+ InPort :: inet:port_number(),
+ UserName :: string(),
+ Email :: string().
+
+create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email) ->
+ Instructions =
+ "~n"
+ " Enter the real name (or whatever name people recognize) for the sysop.~n"
+ " There are no rules for this one. Any valid UTF-8 printables are legal.~n",
+ ok = io:format(Instructions),
+ RealName = zx_tty:get_input(),
+ create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName).
+
+
+-spec create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) -> no_return()
+ when Realm :: zx:realm(),
+ ExAddress :: inet:hostname() | inet:ip_address(),
+ ExPort :: inet:port_number(),
+ InPort :: inet:port_number(),
+ UserName :: string(),
+ Email :: string(),
+ RealName :: string().
+
+create_realm(Realm, ExAddress, ExPort, InPort, UserName, Email, RealName) ->
+ ok = io:format("~nGenerating keys. This might take a while, so settle in...~n"),
+ {ok, RealmKey, RealmPub} = zx_key:generate_rsa({Realm, Realm ++ ".1.realm"}),
+ {ok, PackageKey, PackagePub} = zx_key:generate_rsa({Realm, Realm ++ ".1.package"}),
+ {ok, SysopKey, SysopPub} = zx_key:generate_rsa({Realm, UserName ++ ".1"}),
+ ok = log(info, "Generated 16k RSA pair ~ts ~ts", [RealmKey, RealmPub]),
+ ok = log(info, "Generated 16k RSA pair ~ts ~ts", [PackageKey, PackagePub]),
+ ok = log(info, "Generated 16k RSA pair ~ts ~ts", [SysopKey, SysopPub]),
+
+ Timestamp = calendar:now_to_universal_time(erlang:timestamp()),
+
+ {ok, RealmPubData} = file:read_file(RealmPub),
+ RealmPubRecord =
+ {{Realm, filename:basename(RealmPub, ".pub.der")},
+ realm,
+ {realm, Realm},
+ crypto:hash(sha512, RealmPubData),
+ Timestamp},
+ {ok, PackagePubData} = file:read_file(PackagePub),
+ PackagePubRecord =
+ {{Realm, filename:basename(PackagePub, ".pub.der")},
+ package,
+ {realm, Realm},
+ crypto:hash(sha512, PackagePubData),
+ Timestamp},
+ UserRecord =
+ {{Realm, UserName},
+ [filename:basename(SysopPub, ".pub.der")],
+ Email,
+ RealName},
+ RealmSettings =
+ [{realm, Realm},
+ {revision, 0},
+ {prime, {ExAddress, ExPort}},
+ {private, []},
+ {mirrors, []},
+ {sysops, [UserRecord]},
+ {realm_keys, [RealmPubRecord]},
+ {package_keys, [PackagePubRecord]}],
+ ZompSettings =
+ [{managed, [Realm]},
+ {external_address, ExAddress},
+ {external_port, ExPort},
+ {internal_port, InPort}],
+
+ {ok, CWD} = file:get_cwd(),
+ {ok, TempDir} = mktemp_dir("zomp"),
+ ok = file:set_cwd(TempDir),
+ KeyDir = filename:join("key", Realm),
+ ok = filelib:ensure_dir(KeyDir),
+ ok = file:make_dir(KeyDir),
+ KeyCopy =
+ fun(K) ->
+ {ok, _} = file:copy(K, filename:join(KeyDir, filename:basename(K))),
+ ok
+ end,
+
+ PublicZRF = filename:join(CWD, Realm ++ ".zrf"),
+ RealmFN = Realm ++ ".realm",
+ ok = zx_lib:write_terms(RealmFN, RealmSettings),
+ ok = KeyCopy(PackagePub),
+ ok = KeyCopy(RealmPub),
+ ok = erl_tar:create(PublicZRF, [RealmFN, "key"], [compressed]),
+
+ PrimeZRF = filename:join(CWD, Realm ++ ".zpf"),
+ ok = KeyCopy(SysopPub),
+ ok = zx_lib:write_terms("zomp.conf", ZompSettings),
+ ok = erl_tar:create(PrimeZRF, [RealmFN, "zomp.conf", "key"], [compressed]),
+
+ KeyBundle = filename:join(CWD, Realm ++ ".zkf"),
+ ok = lists:foreach(KeyCopy, [PackageKey, RealmKey, SysopKey]),
+ ok = erl_tar:create(KeyBundle, [KeyDir], [compressed]),
+
+ ok = file:set_cwd(CWD),
+ ok = zx_lib:rm_rf(TempDir),
+
+ Message =
+ "===========================================================================~n"
+ "DONE!~n"
+ "~n"
+ "The realm ~ts has been created and is accessible from the current system.~n"
+ "Three configuration bundles have been created in the current directory:~n"
+ "~n"
+ " 1. ~ts ~n"
+ "This is the PRIVATE realm file you will need to install on the realm's prime~n"
+ "node. It includes the your (the sysop's) public key.~n"
+ "~n"
+ " 2. ~ts ~n"
+ "This file is the PUBLIC realm file other zomp nodes and zx users will need~n"
+ "to access the realm. It does not include your (the sysop's) public key.~n"
+ "~n"
+ " 3. ~ts ~n"
+ "This is the bundle of ALL KEYS that are defined in this realm at the moment.~n"
+ "~n"
+ "Now you need to make copies of these three files and back them up.~n"
+ "~n"
+ "On the PRIME NODE you need to run `zx add realm ~ts` and follow the prompts~n"
+ "to cause it to begin serving that realm as prime. (Node restart required.)~n"
+ "~n"
+ "On all zx CLIENTS that want to access your new realm and on all subordinate~n"
+ "MIRROR NODES the command `zx add realm ~ts` will need to be run.~n"
+ "The method of public realm file distribution (~ts) is up to you.~n"
+ "~n"
+ "~n"
+ "Public & Private key installation (if you need to recover them or perform~n"
+ "sysop functions from another computer) is `zx add keybundle ~ts`.~n"
+ "===========================================================================~n",
+ Substitutions =
+ [Realm,
+ PrimeZRF, PublicZRF, KeyBundle,
+ PrimeZRF,
+ PublicZRF, PublicZRF,
+ KeyBundle],
+ ok = io:format(Message, Substitutions),
+ halt(0).
+
+
+-spec mktemp_dir(Prefix) -> Result
+ when Prefix :: string(),
+ Result :: {ok, TempDir :: file:filename()}
+ | {error, Reason :: file:posix()}.
+
+mktemp_dir(Prefix) ->
+ Rand = integer_to_list(binary:decode_unsigned(crypto:strong_rand_bytes(8)), 36),
+ TempPath = filename:basedir(user_cache, Prefix),
+ TempDir = filename:join(TempPath, Rand),
+ Result1 = filelib:ensure_dir(TempDir),
+ Result2 = file:make_dir(TempDir),
+ case {Result1, Result2} of
+ {ok, ok} -> {ok, TempDir};
+ {ok, Error} -> Error;
+ {Error, _} -> Error
+ end.
+
+
+-spec create_realmfile(zx:realm()) -> no_return().
+
+create_realmfile(Realm) ->
+ RealmConf = zx_lib:load_realm_conf(Realm),
+ ok = log(info, "Realm found, creating realm file..."),
+ {revision, Revision} = lists:keyfind(revision, 1, RealmConf),
+ {realm_keys, RealmKeys} = lists:keyfind(realm_keys, 1, RealmConf),
+ {package_keys, PackageKeys} = lists:keyfind(package_keys, 1, RealmConf),
+ RealmKeyIDs = [element(1, K) || K <- RealmKeys],
+ PackageKeyIDs = [element(1, K) || K <- PackageKeys],
+ create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs).
+
+
+-spec create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) -> ok
+ when Realm :: zx:realm(),
+ Revision :: non_neg_integer(),
+ RealmKeyIDs :: [zx:key_id()],
+ PackageKeyIDs :: [zx:key_id()].
+
+create_realmfile(Realm, Revision, RealmKeyIDs, PackageKeyIDs) ->
+ {ok, CWD} = file:get_cwd(),
+ ok = file:set_cwd(zx_lib:zomp_dir()),
+ KeyPath = fun({R, K}) -> filename:join(["key", R, K ++ ".pub.der"]) end,
+ RealmKeyPaths = lists:map(KeyPath, RealmKeyIDs),
+ PackageKeyPaths = lists:map(KeyPath, PackageKeyIDs),
+ Targets = [zx_lib:realm_conf(Realm) | RealmKeyPaths ++ PackageKeyPaths],
+ OutFile = filename:join(CWD, Realm ++ "." ++ integer_to_list(Revision) ++ ".zrf"),
+ ok = erl_tar:create(OutFile, Targets, [compressed]),
+ ok = log(info, "Realm conf file written to ~ts", [OutFile]),
+ halt(0).
+
+
+
+%%% Error exits
+
+-spec error_exit(Error, Line) -> no_return()
+ when Error :: term(),
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Error, Line) ->
+ error_exit(Error, [], Line).
+
+
+-spec error_exit(Format, Args, Line) -> no_return()
+ when Format :: string(),
+ Args :: [term()],
+ Line :: non_neg_integer().
+%% @private
+%% Format an error message in a way that makes it easy to locate.
+
+error_exit(Format, Args, Line) ->
+ File = filename:basename(?FILE),
+ ok = log(error, "~ts:~tp: " ++ Format, [File, Line | Args]),
+ halt(1).
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_net.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_net.erl
new file mode 100644
index 0000000..ee67951
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_net.erl
@@ -0,0 +1,68 @@
+%%% @doc
+%%% ZX Network Functions
+%%%
+%%% A few common network functions concentrated in one place.
+%%% @end
+
+-module(zx_net).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([send/2, disconnect/1]).
+
+-include("zx_logger.hrl").
+
+
+-spec send(Socket, Message) -> Result
+ when Socket :: gen_tcp:socket(),
+ Message :: term(),
+ Result :: ok
+ | {error, Reason},
+ Reason :: closed | inet:posix().
+%% @doc
+%% Packages an Erlang term and sends it to the indicated socket.
+
+send(Socket, Message) ->
+ BinMessage = term_to_binary(Message),
+ gen_tcp:send(Socket, BinMessage).
+
+
+-spec disconnect(Socket) -> ok
+ when Socket :: gen_tcp:socket().
+%% @doc
+%% Disconnects from a socket, handling the case where the socket is already
+%% disconnected on the other side.
+
+disconnect(Socket) ->
+ case zomp:peername(Socket) of
+ {ok, {Addr, Port}} ->
+ Host = inet:ntoa(Addr),
+ disconnect(Socket, Host, Port);
+ {error, Reason} ->
+ log(warning, "Disconnect failed with: ~p", [Reason])
+ end.
+
+
+-spec disconnect(Socket, Host, Port) -> ok
+ when Socket :: gen_tcp:socket(),
+ Host :: string(),
+ Port :: inet:port_number().
+
+disconnect(Socket, Host, Port) ->
+ case gen_tcp:shutdown(Socket, read_write) of
+ ok ->
+ log(info, "~ts:~w disconnected", [Host, Port]);
+ {error, enotconn} ->
+ log(info, "~ts:~w disconnected", [Host, Port]),
+ receive
+ {tcp_closed, Socket} -> ok
+ after 0 -> ok
+ end;
+ {error, E} ->
+ log(warning, "~ts:~w disconnect failed with: ~p", [Host, Port, E]),
+ receive
+ {tcp_closed, Socket} -> ok
+ after 0 -> ok
+ end
+ end.
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl
new file mode 100644
index 0000000..5f07fba
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl
@@ -0,0 +1,60 @@
+%%% @doc
+%%% ZX Daemon Supervisor
+%%%
+%%% This supervisor maintains the lifecycle of the zxd worker process.
+%%% @end
+
+-module(zx_sup).
+-behavior(supervisor).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([start_link/0, init/1]).
+
+
+
+%%% Startup
+
+-spec start_link() -> Result
+ when Result :: {ok, pid()}
+ | {error, Reason},
+ Reason :: {already_started, pid()}
+ | {shutdown, term()}
+ | term().
+%% @private
+%% Called by zx:subscribe/1.
+%% Starts this single, registered supervisor.
+%%
+%% Error conditions, supervision strategies, and other important issues are
+%% explained in the supervisor module docs:
+%% http://erlang.org/doc/man/supervisor.html
+
+start_link() ->
+ supervisor:start_link({local, ?MODULE}, ?MODULE, none).
+
+
+-spec init(none) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
+%% @private
+%% Do not call this function directly -- it is exported only because it is a
+%% necessary part of the OTP supervisor behavior.
+
+init(none) ->
+ RestartStrategy = {rest_for_one, 1, 60},
+
+ Daemon = {zx_daemon,
+ {zx_daemon, start_link, []},
+ permanent,
+ 10000,
+ worker,
+ [zx_daemon]},
+
+ ConnSup = {zx_conn_sup,
+ {zx_conn_sup, start_link, []},
+ permanent,
+ brutal_kill,
+ supervisor,
+ [zx_conn_sup]},
+
+ Children = [Daemon, ConnSup],
+ {ok, {RestartStrategy, Children}}.
diff --git a/zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl b/zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl
new file mode 100644
index 0000000..46e91e7
--- /dev/null
+++ b/zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl
@@ -0,0 +1,101 @@
+%%% @doc
+%%% ZX TTY
+%%%
+%%% This module lets other parts of ZX interact (very clumsily) with the user via a text
+%%% interface. Hopefully this will never be called on Windows.
+%%% @end
+
+-module(zx_tty).
+-author("Craig Everett ").
+-copyright("Craig Everett ").
+-license("GPL-3.0").
+
+-export([get_input/0, select/1, select_string/1]).
+
+
+%%% Type Definitions
+
+-type option() :: {string(), term()}.
+
+
+%%% User menu interface (terminal)
+
+-spec get_input() -> string().
+%% @private
+%% Provide a standard input prompt and newline sanitized return value.
+
+get_input() ->
+ string:trim(io:get_line("(^C to quit): ")).
+
+
+-spec select(Options) -> Selected
+ when Options :: [option()],
+ Selected :: term().
+%% @private
+%% Take a list of Options to present the user, then return the indicated option to the
+%% caller once the user selects something.
+
+select(Options) ->
+ Max = show(Options),
+ case pick(string:to_integer(io:get_line("(or ^C to quit)~n ? ")), Max) of
+ error ->
+ ok = hurr(),
+ select(Options);
+ I ->
+ {_, Value} = lists:nth(I, Options),
+ Value
+ end.
+
+
+-spec select_string(Strings) -> Selected
+ when Strings :: [string()],
+ Selected :: string().
+%% @private
+%% @equiv select([{S, S} || S <- Strings])
+
+select_string(Strings) ->
+ select([{S, S} || S <- Strings]).
+
+
+-spec show(Options) -> Index
+ when Options :: [option()],
+ Index :: pos_integer().
+%% @private
+%% @equiv show(Options, 0).
+
+show(Options) ->
+ show(Options, 0).
+
+
+-spec show(Options, Index) -> Count
+ when Options :: [option()],
+ Index :: non_neg_integer(),
+ Count :: pos_integer().
+%% @private
+%% Display the list of options needed to the user, and return the option total count.
+
+show([], I) ->
+ I;
+show([{Label, _} | Rest], I) ->
+ Z = I + 1,
+ ok = io:format(" ~2w - ~ts~n", [Z, Label]),
+ show(Rest, Z).
+
+
+-spec pick({Selection, term()}, Max) -> Result
+ when Selection :: error | integer(),
+ Max :: pos_integer(),
+ Result :: pos_integer() | error.
+%% @private
+%% Interpret a user's selection returning either a valid selection index or `error'.
+
+pick({error, _}, _) -> error;
+pick({I, _}, Max) when 0 < I, I =< Max -> I;
+pick(_, _) -> error.
+
+
+-spec hurr() -> ok.
+%% @private
+%% Present an appropriate response when the user derps on selection.
+
+hurr() -> io:format("That isn't an option.~n").
diff --git a/zomp/zx b/zomp/zx
new file mode 100755
index 0000000..c2ebddd
--- /dev/null
+++ b/zomp/zx
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+ZOMP_DIR="$HOME/.zomp"
+VERSION=$(cat "$ZOMP_DIR/etc/version.txt")
+ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION"
+
+pushd "$ZX_DIR" > /dev/null
+./make_zx
+popd > /dev/null
+erl -pa "$ZX_DIR/ebin" -run zx run $@
diff --git a/zomp/zx.cmd b/zomp/zx.cmd
new file mode 100644
index 0000000..12e5aec
--- /dev/null
+++ b/zomp/zx.cmd
@@ -0,0 +1,9 @@
+REM Prepare the environment for ZX and launch it
+
+set ZOMP_DIR="%LOCALAPPDATA%\zomp"
+set VERSION=<"%ZOMP_DIR%\etc\version.txt"
+set ZX_DIR="%ZOMP_DIR%\lib\otpr\zx\%VERSION%"
+pushd "%ZX_DIR%"
+escript.exe make_zx
+popd
+erl.exe -pa "%ZX_DIR%/ebin" -run zx run "%*"
diff --git a/zx_dev b/zx_dev
new file mode 100755
index 0000000..a370431
--- /dev/null
+++ b/zx_dev
@@ -0,0 +1,15 @@
+#!/bin/bash
+
+pushd $(dirname $BASH_SOURCE) > /dev/null
+ZX_DEV_ROOT=$PWD
+popd > /dev/null
+export ZOMP_DIR="$ZX_DEV_ROOT/tester"
+rm -rf "$ZOMP_DIR"
+cp -r "$ZX_DEV_ROOT/zomp" "$ZOMP_DIR"
+VERSION=$(cat "$ZOMP_DIR/etc/version.txt")
+export ZX_DIR="$ZOMP_DIR/lib/otpr/zx/$VERSION"
+
+pushd "$ZX_DIR" > /dev/null
+./make_zx
+popd > /dev/null
+erl -pa "$ZX_DIR/ebin" -run zx run $@