Merge pull request #1 from zxq9/dev
Where is fancy bred, in the heart or in the head?
This commit is contained in:
commit
0fed8ef89d
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,8 +1,10 @@
|
||||
.eunit
|
||||
deps
|
||||
tester
|
||||
*.o
|
||||
*.beam
|
||||
*.plt
|
||||
*.swp
|
||||
erl_crash.dump
|
||||
ebin/*.beam
|
||||
rel/example_project
|
||||
|
||||
66
README.md
66
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.
|
||||
|
||||
29
README.unix
Normal file
29
README.unix
Normal file
@ -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).
|
||||
|
||||
2
README.windows
Normal file
2
README.windows
Normal file
@ -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.
|
||||
75
TODO
Normal file
75
TODO
Normal file
@ -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,
|
||||
118
install.escript
Executable file
118
install.escript
Executable file
@ -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).
|
||||
9
install_unix
Executable file
9
install_unix
Executable file
@ -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
|
||||
16
install_windows.cmd
Normal file
16
install_windows.cmd
Normal file
@ -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
|
||||
2
notify.vbs
Normal file
2
notify.vbs
Normal file
@ -0,0 +1,2 @@
|
||||
messageText = WScript.Arguments(0)
|
||||
MsgBox messageText
|
||||
24
packup
Executable file
24
packup
Executable file
@ -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).
|
||||
4
zomp/etc/otpr/realm.conf
Normal file
4
zomp/etc/otpr/realm.conf
Normal file
@ -0,0 +1,4 @@
|
||||
{realm, "otpr"}.
|
||||
{prime, {"otpr.psychobitch.party",11311}}.
|
||||
{sysop, "zxq9"}.
|
||||
{key, "zxq9-root"}.
|
||||
5
zomp/etc/sys.conf
Normal file
5
zomp/etc/sys.conf
Normal file
@ -0,0 +1,5 @@
|
||||
{timeout,5}.
|
||||
{retries,3}.
|
||||
{maxconn,5}.
|
||||
{managed,[]}.
|
||||
{mirrors,[]}.
|
||||
1
zomp/etc/version.txt
Normal file
1
zomp/etc/version.txt
Normal file
@ -0,0 +1 @@
|
||||
0.1.0
|
||||
BIN
zomp/key/otpr/zxq9-root.pub.der
Normal file
BIN
zomp/key/otpr/zxq9-root.pub.der
Normal file
Binary file not shown.
1
zomp/lib/otpr/zx/0.1.0/Emakefile
Normal file
1
zomp/lib/otpr/zx/0.1.0/Emakefile
Normal file
@ -0,0 +1 @@
|
||||
{"src/*", [debug_info, {i, "include/"}, {outdir, "ebin/"}]}.
|
||||
674
zomp/lib/otpr/zx/0.1.0/LICENSE
Normal file
674
zomp/lib/otpr/zx/0.1.0/LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
{one line to give the program's name and a brief idea of what it does.}
|
||||
Copyright (C) {year} {name of author}
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
{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
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
12
zomp/lib/otpr/zx/0.1.0/ebin/zx.app
Normal file
12
zomp/lib/otpr/zx/0.1.0/ebin/zx.app
Normal file
@ -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, []}}]}.
|
||||
34
zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl
Normal file
34
zomp/lib/otpr/zx/0.1.0/include/zx_logger.hrl
Normal file
@ -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]).
|
||||
39
zomp/lib/otpr/zx/0.1.0/make_zx
Executable file
39
zomp/lib/otpr/zx/0.1.0/make_zx
Executable file
@ -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").
|
||||
659
zomp/lib/otpr/zx/0.1.0/src/zx.erl
Normal file
659
zomp/lib/otpr/zx/0.1.0/src/zx.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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).
|
||||
478
zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl
Normal file
478
zomp/lib/otpr/zx/0.1.0/src/zx_auth.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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).
|
||||
333
zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl
Normal file
333
zomp/lib/otpr/zx/0.1.0/src/zx_conf_sys.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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").
|
||||
543
zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl
Normal file
543
zomp/lib/otpr/zx/0.1.0/src/zx_conn.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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).
|
||||
73
zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl
Normal file
73
zomp/lib/otpr/zx/0.1.0/src/zx_conn_sup.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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}}.
|
||||
2036
zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl
Normal file
2036
zomp/lib/otpr/zx/0.1.0/src/zx_daemon.erl
Normal file
File diff suppressed because it is too large
Load Diff
306
zomp/lib/otpr/zx/0.1.0/src/zx_key.erl
Normal file
306
zomp/lib/otpr/zx/0.1.0/src/zx_key.erl
Normal file
@ -0,0 +1,306 @@
|
||||
%%% @doc
|
||||
%%% ZX Key
|
||||
%%%
|
||||
%%% Abstraction module for dealing with keys.
|
||||
%%%
|
||||
%%% "Ewwwww! Keys!"
|
||||
%%% -- Bertrand Russel
|
||||
%%% @end
|
||||
|
||||
-module(zx_key).
|
||||
-author("Craig Everett <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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).
|
||||
758
zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl
Normal file
758
zomp/lib/otpr/zx/0.1.0/src/zx_lib.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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).
|
||||
1177
zomp/lib/otpr/zx/0.1.0/src/zx_local.erl
Normal file
1177
zomp/lib/otpr/zx/0.1.0/src/zx_local.erl
Normal file
File diff suppressed because it is too large
Load Diff
68
zomp/lib/otpr/zx/0.1.0/src/zx_net.erl
Normal file
68
zomp/lib/otpr/zx/0.1.0/src/zx_net.erl
Normal file
@ -0,0 +1,68 @@
|
||||
%%% @doc
|
||||
%%% ZX Network Functions
|
||||
%%%
|
||||
%%% A few common network functions concentrated in one place.
|
||||
%%% @end
|
||||
|
||||
-module(zx_net).
|
||||
-author("Craig Everett <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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.
|
||||
60
zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl
Normal file
60
zomp/lib/otpr/zx/0.1.0/src/zx_sup.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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}}.
|
||||
101
zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl
Normal file
101
zomp/lib/otpr/zx/0.1.0/src/zx_tty.erl
Normal file
@ -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 <zxq9@zxq9.com>").
|
||||
-copyright("Craig Everett <zxq9@zxq9.com>").
|
||||
-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").
|
||||
10
zomp/zx
Executable file
10
zomp/zx
Executable file
@ -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 $@
|
||||
9
zomp/zx.cmd
Normal file
9
zomp/zx.cmd
Normal file
@ -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 "%*"
|
||||
15
zx_dev
Executable file
15
zx_dev
Executable file
@ -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 $@
|
||||
Loading…
x
Reference in New Issue
Block a user