Inital import

This commit is contained in:
Nicolas JUHEL
2020-01-04 14:42:49 +01:00
parent 5f64069754
commit c388f4f985
80 changed files with 9028 additions and 0 deletions

0
CHANGELOG Normal file
View File

0
CONTRIBUTING.md Normal file
View File

11
README.md Normal file
View File

@@ -0,0 +1,11 @@
GoDoc | Travis | Snyk
:-: | :-: | :-:
[![Documentation Status](https://godoc.org/github.com/nabbar/gopkg-njs-logger?status.png "Documentation Status")](https://godoc.org/github.com/nabbar/gopkg-njs-logger) | [![Build Status](https://travis-ci.com/nabbar/gopkg-njs-logger.svg?branch=master)](https://travis-ci.com/nabbar/gopkg-njs-logger) | [![Known Vulnerabilities](https://snyk.io/test/github/nabbar/gopkg-njs-logger/badge.svg?style=plastic "Known Vulnerabilities")](https://snyk.io/test/github/nabbar/gopkg-njs-logger)
# gopkg-njs-logger
This lib is a more an helper than a lib.
This lib is use to simplify integration and common use of the lib logrus
... in construction

1
njs-.git/HEAD Normal file
View File

@@ -0,0 +1 @@
ref: refs/heads/master

5
njs-.git/config Normal file
View File

@@ -0,0 +1,5 @@
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true

1
njs-.git/description Normal file
View File

@@ -0,0 +1 @@
Unnamed repository; edit this file 'description' to name the repository.

View File

@@ -0,0 +1,15 @@
#!/bin/sh
#
# An example hook script to check the commit log message taken by
# applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit. The hook is
# allowed to edit the commit message file.
#
# To enable this hook, rename this file to "applypatch-msg".
. git-sh-setup
commitmsg="$(git rev-parse --git-path hooks/commit-msg)"
test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"}
:

View File

@@ -0,0 +1,24 @@
#!/bin/sh
#
# An example hook script to check the commit log message.
# Called by "git commit" with one argument, the name of the file
# that has the commit message. The hook should exit with non-zero
# status after issuing an appropriate message if it wants to stop the
# commit. The hook is allowed to edit the commit message file.
#
# To enable this hook, rename this file to "commit-msg".
# Uncomment the below to add a Signed-off-by line to the message.
# Doing this in a hook is a bad idea in general, but the prepare-commit-msg
# hook is more suited to it.
#
# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1"
# This example catches duplicate Signed-off-by lines.
test "" = "$(grep '^Signed-off-by: ' "$1" |
sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || {
echo >&2 Duplicate Signed-off-by lines.
exit 1
}

View File

@@ -0,0 +1,114 @@
#!/usr/bin/perl
use strict;
use warnings;
use IPC::Open2;
# An example hook script to integrate Watchman
# (https://facebook.github.io/watchman/) with git to speed up detecting
# new and modified files.
#
# The hook is passed a version (currently 1) and a time in nanoseconds
# formatted as a string and outputs to stdout all files that have been
# modified since the given time. Paths must be relative to the root of
# the working tree and separated by a single NUL.
#
# To enable this hook, rename this file to "query-watchman" and set
# 'git config core.fsmonitor .git/hooks/query-watchman'
#
my ($version, $time) = @ARGV;
# Check the hook interface version
if ($version == 1) {
# convert nanoseconds to seconds
$time = int $time / 1000000000;
} else {
die "Unsupported query-fsmonitor hook version '$version'.\n" .
"Falling back to scanning...\n";
}
my $git_work_tree;
if ($^O =~ 'msys' || $^O =~ 'cygwin') {
$git_work_tree = Win32::GetCwd();
$git_work_tree =~ tr/\\/\//;
} else {
require Cwd;
$git_work_tree = Cwd::cwd();
}
my $retry = 1;
launch_watchman();
sub launch_watchman {
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'watchman -j --no-pretty')
or die "open2() failed: $!\n" .
"Falling back to scanning...\n";
# In the query expression below we're asking for names of files that
# changed since $time but were not transient (ie created after
# $time but no longer exist).
#
# To accomplish this, we're using the "since" generator to use the
# recency index to select candidate nodes and "fields" to limit the
# output to file names only. Then we're using the "expression" term to
# further constrain the results.
#
# The category of transient files that we want to ignore will have a
# creation clock (cclock) newer than $time_t value and will also not
# currently exist.
my $query = <<" END";
["query", "$git_work_tree", {
"since": $time,
"fields": ["name"],
"expression": ["not", ["allof", ["since", $time, "cclock"], ["not", "exists"]]]
}]
END
print CHLD_IN $query;
close CHLD_IN;
my $response = do {local $/; <CHLD_OUT>};
die "Watchman: command returned no output.\n" .
"Falling back to scanning...\n" if $response eq "";
die "Watchman: command returned invalid output: $response\n" .
"Falling back to scanning...\n" unless $response =~ /^\{/;
my $json_pkg;
eval {
require JSON::XS;
$json_pkg = "JSON::XS";
1;
} or do {
require JSON::PP;
$json_pkg = "JSON::PP";
};
my $o = $json_pkg->new->utf8->decode($response);
if ($retry > 0 and $o->{error} and $o->{error} =~ m/unable to resolve root .* directory (.*) is not watched/) {
print STDERR "Adding '$git_work_tree' to watchman's watch list.\n";
$retry--;
qx/watchman watch "$git_work_tree"/;
die "Failed to make watchman watch '$git_work_tree'.\n" .
"Falling back to scanning...\n" if $? != 0;
# Watchman will always return all files on the first query so
# return the fast "everything is dirty" flag to git and do the
# Watchman query just to get it over with now so we won't pay
# the cost in git to look up each individual file.
print "/\0";
eval { launch_watchman() };
exit 0;
}
die "Watchman: $o->{error}.\n" .
"Falling back to scanning...\n" if $o->{error};
binmode STDOUT, ":utf8";
local $, = "\0";
print @{$o->{files}};
}

View File

@@ -0,0 +1,8 @@
#!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".
exec git update-server-info

View File

@@ -0,0 +1,14 @@
#!/bin/sh
#
# An example hook script to verify what is about to be committed
# by applypatch from an e-mail message.
#
# The hook should exit with non-zero status after issuing an
# appropriate message if it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-applypatch".
. git-sh-setup
precommit="$(git rev-parse --git-path hooks/pre-commit)"
test -x "$precommit" && exec "$precommit" ${1+"$@"}
:

View File

@@ -0,0 +1,49 @@
#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments. The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".
if git rev-parse --verify HEAD >/dev/null 2>&1
then
against=HEAD
else
# Initial commit: diff against an empty tree object
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --bool hooks.allownonascii)
# Redirect output to stderr.
exec 1>&2
# Cross platform projects tend to avoid non-ASCII filenames; prevent
# them from being added to the repository. We exploit the fact that the
# printable range starts at the space character and ends with tilde.
if [ "$allownonascii" != "true" ] &&
# Note that the use of brackets around a tr range is ok here, (it's
# even required, for portability to Solaris 10's /usr/bin/tr), since
# the square bracket bytes happen to fall in the designated range.
test $(git diff --cached --name-only --diff-filter=A -z $against |
LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
then
cat <<\EOF
Error: Attempt to add a non-ASCII file name.
This can cause problems if you want to work with people on other platforms.
To be portable it is advisable to rename the file.
If you know what you are doing you can disable this check using:
git config hooks.allownonascii true
EOF
exit 1
fi
# If there are whitespace errors, print the offending file names and fail.
exec git diff-index --check --cached $against --

53
njs-.git/hooks/pre-push.sample Executable file
View File

@@ -0,0 +1,53 @@
#!/bin/sh
# An example hook script to verify what is about to be pushed. Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
:
else
if [ "$remote_sha" = $z40 ]
then
# New branch, examine all commits
range="$local_sha"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
fi
# Check for WIP commit
commit=`git rev-list -n 1 --grep '^WIP' "$range"`
if [ -n "$commit" ]
then
echo >&2 "Found WIP commit in $local_ref, not pushing"
exit 1
fi
fi
done
exit 0

169
njs-.git/hooks/pre-rebase.sample Executable file
View File

@@ -0,0 +1,169 @@
#!/bin/sh
#
# Copyright (c) 2006, 2008 Junio C Hamano
#
# The "pre-rebase" hook is run just before "git rebase" starts doing
# its job, and can prevent the command from running by exiting with
# non-zero status.
#
# The hook is called with the following parameters:
#
# $1 -- the upstream the series was forked from.
# $2 -- the branch being rebased (or empty when rebasing the current branch).
#
# This sample shows how to prevent topic branches that are already
# merged to 'next' branch from getting rebased, because allowing it
# would result in rebasing already published history.
publish=next
basebranch="$1"
if test "$#" = 2
then
topic="refs/heads/$2"
else
topic=`git symbolic-ref HEAD` ||
exit 0 ;# we do not interrupt rebasing detached HEAD
fi
case "$topic" in
refs/heads/??/*)
;;
*)
exit 0 ;# we do not interrupt others.
;;
esac
# Now we are dealing with a topic branch being rebased
# on top of master. Is it OK to rebase it?
# Does the topic really exist?
git show-ref -q "$topic" || {
echo >&2 "No such branch $topic"
exit 1
}
# Is topic fully merged to master?
not_in_master=`git rev-list --pretty=oneline ^master "$topic"`
if test -z "$not_in_master"
then
echo >&2 "$topic is fully merged to master; better remove it."
exit 1 ;# we could allow it, but there is no point.
fi
# Is topic ever merged to next? If so you should not be rebasing it.
only_next_1=`git rev-list ^master "^$topic" ${publish} | sort`
only_next_2=`git rev-list ^master ${publish} | sort`
if test "$only_next_1" = "$only_next_2"
then
not_in_topic=`git rev-list "^$topic" master`
if test -z "$not_in_topic"
then
echo >&2 "$topic is already up to date with master"
exit 1 ;# we could allow it, but there is no point.
else
exit 0
fi
else
not_in_next=`git rev-list --pretty=oneline ^${publish} "$topic"`
/usr/bin/perl -e '
my $topic = $ARGV[0];
my $msg = "* $topic has commits already merged to public branch:\n";
my (%not_in_next) = map {
/^([0-9a-f]+) /;
($1 => 1);
} split(/\n/, $ARGV[1]);
for my $elem (map {
/^([0-9a-f]+) (.*)$/;
[$1 => $2];
} split(/\n/, $ARGV[2])) {
if (!exists $not_in_next{$elem->[0]}) {
if ($msg) {
print STDERR $msg;
undef $msg;
}
print STDERR " $elem->[1]\n";
}
}
' "$topic" "$not_in_next" "$not_in_master"
exit 1
fi
<<\DOC_END
This sample hook safeguards topic branches that have been
published from being rewound.
The workflow assumed here is:
* Once a topic branch forks from "master", "master" is never
merged into it again (either directly or indirectly).
* Once a topic branch is fully cooked and merged into "master",
it is deleted. If you need to build on top of it to correct
earlier mistakes, a new topic branch is created by forking at
the tip of the "master". This is not strictly necessary, but
it makes it easier to keep your history simple.
* Whenever you need to test or publish your changes to topic
branches, merge them into "next" branch.
The script, being an example, hardcodes the publish branch name
to be "next", but it is trivial to make it configurable via
$GIT_DIR/config mechanism.
With this workflow, you would want to know:
(1) ... if a topic branch has ever been merged to "next". Young
topic branches can have stupid mistakes you would rather
clean up before publishing, and things that have not been
merged into other branches can be easily rebased without
affecting other people. But once it is published, you would
not want to rewind it.
(2) ... if a topic branch has been fully merged to "master".
Then you can delete it. More importantly, you should not
build on top of it -- other people may already want to
change things related to the topic as patches against your
"master", so if you need further changes, it is better to
fork the topic (perhaps with the same name) afresh from the
tip of "master".
Let's look at this example:
o---o---o---o---o---o---o---o---o---o "next"
/ / / /
/ a---a---b A / /
/ / / /
/ / c---c---c---c B /
/ / / \ /
/ / / b---b C \ /
/ / / / \ /
---o---o---o---o---o---o---o---o---o---o---o "master"
A, B and C are topic branches.
* A has one fix since it was merged up to "next".
* B has finished. It has been fully merged up to "master" and "next",
and is ready to be deleted.
* C has not merged to "next" at all.
We would want to allow C to be rebased, refuse A, and encourage
B to be deleted.
To compute (1):
git rev-list ^master ^topic next
git rev-list ^master next
if these match, topic has not merged in next at all.
To compute (2):
git rev-list master..topic
if this is empty, it is fully merged to "master".
DOC_END

View File

@@ -0,0 +1,24 @@
#!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi

View File

@@ -0,0 +1,42 @@
#!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
# case "$COMMIT_SOURCE,$SHA1" in
# ,|template,)
# /usr/bin/perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
# *) ;;
# esac
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi

128
njs-.git/hooks/update.sample Executable file
View File

@@ -0,0 +1,128 @@
#!/bin/sh
#
# An example hook script to block unannotated tags from entering.
# Called by "git receive-pack" with arguments: refname sha1-old sha1-new
#
# To enable this hook, rename this file to "update".
#
# Config
# ------
# hooks.allowunannotated
# This boolean sets whether unannotated tags will be allowed into the
# repository. By default they won't be.
# hooks.allowdeletetag
# This boolean sets whether deleting tags will be allowed in the
# repository. By default they won't be.
# hooks.allowmodifytag
# This boolean sets whether a tag may be modified after creation. By default
# it won't be.
# hooks.allowdeletebranch
# This boolean sets whether deleting branches will be allowed in the
# repository. By default they won't be.
# hooks.denycreatebranch
# This boolean sets whether remotely creating branches will be denied
# in the repository. By default this is allowed.
#
# --- Command line
refname="$1"
oldrev="$2"
newrev="$3"
# --- Safety check
if [ -z "$GIT_DIR" ]; then
echo "Don't run this script from the command line." >&2
echo " (if you want, you could supply GIT_DIR then run" >&2
echo " $0 <ref> <oldrev> <newrev>)" >&2
exit 1
fi
if [ -z "$refname" -o -z "$oldrev" -o -z "$newrev" ]; then
echo "usage: $0 <ref> <oldrev> <newrev>" >&2
exit 1
fi
# --- Config
allowunannotated=$(git config --bool hooks.allowunannotated)
allowdeletebranch=$(git config --bool hooks.allowdeletebranch)
denycreatebranch=$(git config --bool hooks.denycreatebranch)
allowdeletetag=$(git config --bool hooks.allowdeletetag)
allowmodifytag=$(git config --bool hooks.allowmodifytag)
# check for no description
projectdesc=$(sed -e '1q' "$GIT_DIR/description")
case "$projectdesc" in
"Unnamed repository"* | "")
echo "*** Project description file hasn't been set" >&2
exit 1
;;
esac
# --- Check types
# if $newrev is 0000...0000, it's a commit to delete a ref.
zero="0000000000000000000000000000000000000000"
if [ "$newrev" = "$zero" ]; then
newrev_type=delete
else
newrev_type=$(git cat-file -t $newrev)
fi
case "$refname","$newrev_type" in
refs/tags/*,commit)
# un-annotated tag
short_refname=${refname##refs/tags/}
if [ "$allowunannotated" != "true" ]; then
echo "*** The un-annotated tag, $short_refname, is not allowed in this repository" >&2
echo "*** Use 'git tag [ -a | -s ]' for tags you want to propagate." >&2
exit 1
fi
;;
refs/tags/*,delete)
# delete tag
if [ "$allowdeletetag" != "true" ]; then
echo "*** Deleting a tag is not allowed in this repository" >&2
exit 1
fi
;;
refs/tags/*,tag)
# annotated tag
if [ "$allowmodifytag" != "true" ] && git rev-parse $refname > /dev/null 2>&1
then
echo "*** Tag '$refname' already exists." >&2
echo "*** Modifying a tag is not allowed in this repository." >&2
exit 1
fi
;;
refs/heads/*,commit)
# branch
if [ "$oldrev" = "$zero" -a "$denycreatebranch" = "true" ]; then
echo "*** Creating a branch is not allowed in this repository" >&2
exit 1
fi
;;
refs/heads/*,delete)
# delete branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a branch is not allowed in this repository" >&2
exit 1
fi
;;
refs/remotes/*,commit)
# tracking branch
;;
refs/remotes/*,delete)
# delete tracking branch
if [ "$allowdeletebranch" != "true" ]; then
echo "*** Deleting a tracking branch is not allowed in this repository" >&2
exit 1
fi
;;
*)
# Anything else (is there anything else?)
echo "*** Update hook: unknown type of update to ref $refname of type $newrev_type" >&2
exit 1
;;
esac
# --- Finished
exit 0

6
njs-.git/info/exclude Normal file
View File

@@ -0,0 +1,6 @@
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~

21
njs-certif/LICENSE Normal file
View File

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

0
njs-certif/README.md Normal file
View File

318
njs-certif/tlsTools.go Normal file
View File

@@ -0,0 +1,318 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_certif
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"os"
"strings"
njs_logger "github.com/nabbar/golib/njs-logger"
)
var (
rootCA = x509.NewCertPool()
certificates = make([]tls.Certificate, 0)
caCertificates = x509.NewCertPool()
tlsMinVersion uint16 = tls.VersionTLS12
cipherList = []uint16{
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
}
curveList = []tls.CurveID{tls.X25519}
dynSizing = true
ticketSession = true
clientAuth = tls.NoClientCert
)
func AddRootCAContents(rootContent string) bool {
if rootContent != "" {
return rootCA.AppendCertsFromPEM([]byte(rootContent))
}
return false
}
func AddRootCAFile(rootFile string) bool {
if rootFile == "" {
return false
}
if _, e := os.Stat(rootFile); njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.InfoLevel, "checking certificates file '%s'", e, rootFile) {
return false
}
c, e := ioutil.ReadFile(rootFile) // #nosec
if !njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.InfoLevel, "loading certificates file '%s'", e, rootFile) {
return rootCA.AppendCertsFromPEM(c)
}
return false
}
func AddCACertificateContents(caContent string) bool {
if caContent != "" {
return caCertificates.AppendCertsFromPEM([]byte(caContent))
}
return false
}
func AddCACertificateFile(caFile string) bool {
if caFile == "" {
return false
}
if _, e := os.Stat(caFile); njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.InfoLevel, "checking certificates file '%s'", e, caFile) {
return false
}
c, e := ioutil.ReadFile(caFile) // #nosec
if !njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.InfoLevel, "loading certificates file '%s'", e, caFile) {
return caCertificates.AppendCertsFromPEM(c)
}
return false
}
func CheckCertificates() bool {
return len(certificates) > 0
}
func AddCertificateContents(keyContents, certContents string) bool {
keyContents = strings.TrimSpace(keyContents)
certContents = strings.TrimSpace(certContents)
if keyContents != "" && keyContents != "\n" && certContents != "" && certContents != "\n" {
c, err := tls.X509KeyPair([]byte(certContents), []byte(keyContents))
if !njs_logger.ErrorLevel.LogErrorCtx(njs_logger.InfoLevel, "loading certificates contents", err) {
certificates = append(certificates, c)
return true
}
}
return false
}
func AddCertificateFile(keyFile, certFile string) bool {
if keyFile == "" || certFile == "" {
return false
}
if _, e := os.Stat(keyFile); njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.InfoLevel, "loading certificates file '%s'", e, keyFile) {
return false
}
if _, e := os.Stat(certFile); njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.InfoLevel, "loading certificates file '%s'", e, certFile) {
return false
}
if c, e := tls.LoadX509KeyPair(certFile, keyFile); !njs_logger.ErrorLevel.LogErrorCtx(njs_logger.InfoLevel, "loading X509 Pair file", e) {
certificates = append(certificates, c)
return true
}
return false
}
func GetCertificates() []tls.Certificate {
return certificates
}
func AppendCertificates(cert []tls.Certificate) []tls.Certificate {
if !CheckCertificates() {
return cert
}
return append(cert, certificates...)
}
func GetRootCA() *x509.CertPool {
return rootCA
}
func GetClientCA() *x509.CertPool {
return caCertificates
}
func SetStringTlsVersion(tlsVersStr string) {
tlsVersStr = strings.ToLower(tlsVersStr)
tlsVersStr = strings.Replace(tlsVersStr, "TLS", "", -1)
tlsVersStr = strings.TrimSpace(tlsVersStr)
switch tlsVersStr {
case "1", "1.0":
tlsMinVersion = tls.VersionTLS10
case "1.1":
tlsMinVersion = tls.VersionTLS11
default:
tlsMinVersion = tls.VersionTLS12
}
}
func SetTlsVersion(tlsVers uint16) {
switch tlsVers {
case tls.VersionTLS10:
tlsMinVersion = tls.VersionTLS10
case tls.VersionTLS11:
tlsMinVersion = tls.VersionTLS11
default:
tlsMinVersion = tls.VersionTLS12
}
}
func SetClientAuth(auth string) {
switch strings.ToLower(auth) {
case "request":
clientAuth = tls.RequestClientCert
case "require":
clientAuth = tls.RequireAnyClientCert
case "verify":
clientAuth = tls.VerifyClientCertIfGiven
case "strict":
clientAuth = tls.RequireAndVerifyClientCert
default:
clientAuth = tls.NoClientCert
}
}
func GetCipherKey(cipher string) uint16 {
cipher = strings.ToLower(cipher)
RSA := strings.Contains(cipher, "rsa")
DSA := strings.Contains(cipher, "ecdsa")
GSM := strings.Contains(cipher, "gsm")
AES128 := strings.Contains(cipher, "aes128") || strings.Contains(cipher, "aes_128") || strings.Contains(cipher, "aes-128")
AES256 := strings.Contains(cipher, "aes256") || strings.Contains(cipher, "aes_256") || strings.Contains(cipher, "aes-256")
CHACHA := strings.Contains(cipher, "chacha20") || strings.Contains(cipher, "chacha_20") || strings.Contains(cipher, "chacha-20")
POLY := strings.Contains(cipher, "poly1305") || strings.Contains(cipher, "poly_1305") || strings.Contains(cipher, "poly-1305")
if RSA && AES128 && !GSM {
return tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
} else if RSA && AES128 && GSM {
return tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
} else if RSA && AES256 {
return tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
} else if RSA && (CHACHA || POLY) {
return tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
} else if DSA && AES128 && !GSM {
return tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
} else if DSA && AES128 && GSM {
return tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
} else if DSA && AES256 {
return tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
} else if DSA && (CHACHA || POLY) {
return tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
}
return 0
}
func GetCurveID(curveRef string) tls.CurveID {
curveRef = strings.ToLower(curveRef)
if strings.Contains(curveRef, "p256") {
return tls.CurveP256
} else if strings.Contains(curveRef, "p384") {
return tls.CurveP384
} else if strings.Contains(curveRef, "p521") {
return tls.CurveP521
} else if strings.Contains(curveRef, "x25519") {
return tls.X25519
}
return 0
}
func SetCipherList(cipher []uint16) {
cipherList = cipher
}
func SetCurve(curves []tls.CurveID) {
curveList = curves
}
func SetDynamicSizing(enable bool) {
dynSizing = enable
}
func SetSessionTicket(enable bool) {
ticketSession = enable
}
func GetTLSConfig(serverName string) *tls.Config {
cnf := &tls.Config{
RootCAs: rootCA,
ClientCAs: caCertificates,
MinVersion: tlsMinVersion,
InsecureSkipVerify: false,
}
if serverName != "" {
cnf.ServerName = serverName
}
if len(cipherList) > 0 {
cnf.PreferServerCipherSuites = true
cnf.CipherSuites = cipherList
}
if len(curveList) > 0 {
cnf.CurvePreferences = curveList
}
if dynSizing {
cnf.DynamicRecordSizingDisabled = false
} else {
cnf.DynamicRecordSizingDisabled = true
}
if ticketSession {
cnf.SessionTicketsDisabled = false
} else {
cnf.SessionTicketsDisabled = true
}
return cnf
}
func GetTlsConfigCertificates() *tls.Config {
cnf := GetTLSConfig("")
if clientAuth != tls.NoClientCert {
cnf.ClientAuth = clientAuth
}
cnf.Certificates = certificates
cnf.BuildNameToCertificate()
return cnf
}

21
njs-console/LICENSE Normal file
View File

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

0
njs-console/README.md Normal file
View File

116
njs-console/color.go Normal file
View File

@@ -0,0 +1,116 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_console
import (
"fmt"
"github.com/fatih/color"
)
type colorType uint8
const (
ColorPrompt colorType = iota
ColorPrint
ColorFatal
ColorError
ColorWarn
ColorInfo
ColorDebug
)
var (
colorList map[colorType]*color.Color
)
func init() {
colorList = map[colorType]*color.Color{
ColorPrompt: nil,
ColorPrint: nil,
ColorFatal: nil,
ColorError: nil,
ColorWarn: nil,
ColorInfo: nil,
ColorDebug: nil,
}
}
func (c colorType) SetColor(col *color.Color) {
colorList[c] = col
}
func (c colorType) println(text string) {
if colorList[c] != nil {
_, _ = colorList[c].Println(text) // #nosec
} else {
println(text)
}
}
func (c colorType) print(text string) {
if colorList[c] != nil {
_, _ = colorList[c].Print(text) // #nosec
} else {
print(text)
}
}
func (c colorType) printf(format string, args ...interface{}) {
c.println(fmt.Sprintf(format, args...))
}
func (c colorType) printfLn(format string, args ...interface{}) {
c.println(fmt.Sprintf(format, args...))
}
func Print(format string, args ...interface{}) {
ColorPrint.printf(format, args)
}
func PrintLn(format string, args ...interface{}) {
ColorPrint.printfLn(format, args)
}
func Debug(text string) {
ColorDebug.print(text)
}
func Info(text string) {
ColorInfo.print(text)
}
func Warn(text string) {
ColorWarn.print(text)
}
func Error(text string) {
ColorError.print(text)
}
func Fatal(text string) {
ColorFatal.print(text)
}

26
njs-console/console.go Normal file
View File

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

50
njs-console/padding.go Normal file
View File

@@ -0,0 +1,50 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_console
import (
"strings"
"unicode/utf8"
)
func padTimes(str string, n int) (out string) {
for i := 0; i < n; i++ {
out += str
}
return
}
func PadLeft(str string, len int, pad string) string {
return padTimes(pad, len-utf8.RuneCountInString(str)) + str
}
func PadRight(str string, len int, pad string) string {
return str + padTimes(pad, len-utf8.RuneCountInString(str))
}
func PrintTab(tablLevel int, format string, args ...interface{}) {
Print(strings.Repeat(" ", tablLevel)+format, args...)
}

104
njs-console/prompt.go Normal file
View File

@@ -0,0 +1,104 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_console
import (
"bufio"
"fmt"
"net/url"
"os"
"strconv"
"golang.org/x/crypto/ssh/terminal"
)
func printPrompt(text string) {
if text != "" {
ColorPrompt.printf("%s: ", text)
}
}
func PromptString(text string) (string, error) {
var (
scn *bufio.Scanner = bufio.NewScanner(os.Stdin)
res string
err error
)
printPrompt(text)
for scn.Scan() {
res = scn.Text()
err = scn.Err()
break
}
return res, err
}
func PromptInt(text string) (int64, error) {
if str, err := PromptString(text); err != nil {
return 0, err
} else {
return strconv.ParseInt(str, 10, 64)
}
}
func PromptUrl(text string) (*url.URL, error) {
if str, err := PromptString(text); err != nil {
return nil, err
} else {
return url.Parse(str)
}
}
func PromptBool(text string) (bool, error) {
if str, err := PromptString(text); err != nil {
return false, err
} else {
return strconv.ParseBool(str)
}
}
func PromptPassword(text string) (string, error) {
var (
res string
err error
)
printPrompt(text)
res, err = getTerminal().ReadPassword("")
fmt.Printf("\n")
return res, err
}
func getTerminal() *terminal.Terminal {
r := bufio.NewReader(os.Stdin)
w := bufio.NewWriter(os.Stdout)
b := bufio.NewReadWriter(r, w)
return terminal.NewTerminal(b, "")
}

21
njs-crypt/LICENSE Normal file
View File

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

0
njs-crypt/README.md Normal file
View File

113
njs-crypt/crypt.go Normal file
View File

@@ -0,0 +1,113 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_crypt
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
var (
cryptKey = make([]byte, 32)
cryptNonce = make([]byte, 12)
)
func SetKeyHex(key, nonce string) error {
var err error
// Load your secret key from a safe place and reuse it across multiple
// Seal/Open calls. (Obviously don't use this example key for anything
// real.) If you want to convert a passphrase to a key, use a suitable
// package like bcrypt or scrypt.
cryptKey, err = hex.DecodeString(key)
if err != nil {
return fmt.Errorf("converting hexa key error : %v", err)
}
cryptNonce, err = hex.DecodeString(nonce)
if err != nil {
return fmt.Errorf("converting hexa nonce error : %v", err)
}
return nil
}
func SetKeyByte(key [32]byte, nonce [12]byte) {
cryptKey = key[:]
cryptNonce = nonce[:]
}
func GenKeyByte() ([]byte, []byte, error) {
// Never use more than 2^32 random key with a given key because of the risk of a repeat.
if _, err := io.ReadFull(rand.Reader, cryptKey); err != nil {
return make([]byte, 32), make([]byte, 12), fmt.Errorf("key generate error : %v", err)
}
// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
if _, err := io.ReadFull(rand.Reader, cryptNonce); err != nil {
return make([]byte, 32), make([]byte, 12), fmt.Errorf("nonce generate error : %v", err)
}
return cryptKey, cryptNonce, nil
}
func Encrypt(clearValue []byte) (string, error) {
// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
block, err := aes.NewCipher(cryptKey)
if err != nil {
return "", fmt.Errorf("init AES block error : %v", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", fmt.Errorf("AES GSM cipher init : %v", err)
}
return hex.EncodeToString(aesgcm.Seal(nil, cryptNonce, clearValue, nil)), nil
}
func Decrypt(hexaVal string) ([]byte, error) {
// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
ciphertext, err := hex.DecodeString(hexaVal)
if err != nil {
return nil, fmt.Errorf("hexa decode crypted value error : %v", err)
}
block, err := aes.NewCipher(cryptKey)
if err != nil {
return nil, fmt.Errorf("AES block init error : %v", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("AES GSM cipher init error : %v", err)
}
return aesgcm.Open(nil, cryptNonce, ciphertext, nil)
}

21
njs-httpcli/LICENSE Normal file
View File

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

0
njs-httpcli/README.md Normal file
View File

143
njs-httpcli/http.go Normal file
View File

@@ -0,0 +1,143 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_httpcli
import (
"bytes"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
njs_certif "github.com/nabbar/golib/njs-certif"
njs_logger "github.com/nabbar/golib/njs-logger"
)
type httpClient struct {
url *url.URL
cli *http.Client
}
type HTTP interface {
Check() bool
Call(file *bytes.Buffer) (bool, *bytes.Buffer)
}
func NewClient(uri string) HTTP {
var (
pUri *url.URL
err error
host string
)
if uri != "" {
pUri, err = url.Parse(uri)
njs_logger.PanicLevel.LogErrorCtx(njs_logger.NilLevel, fmt.Sprintf("parsing url '%s'", uri), err)
host = pUri.Host
} else {
pUri = nil
host = ""
}
return &httpClient{
url: pUri,
cli: GetClient(host),
}
}
func GetClient(serverName string) *http.Client {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 30 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableCompression: true,
TLSClientConfig: njs_certif.GetTLSConfig(serverName),
},
}
}
func (obj *httpClient) Check() bool {
obj.doRequest(obj.newRequest(http.MethodHead, nil))
return true
}
func (obj *httpClient) Call(body *bytes.Buffer) (bool, *bytes.Buffer) {
return obj.checkResponse(
obj.doRequest(
obj.newRequest(http.MethodPost, body),
),
)
}
func (obj *httpClient) newRequest(method string, body *bytes.Buffer) *http.Request {
var reader *bytes.Reader
if body != nil && body.Len() > 0 {
reader = bytes.NewReader(body.Bytes())
}
req, err := http.NewRequest(method, obj.url.String(), reader)
njs_logger.PanicLevel.LogErrorCtx(njs_logger.NilLevel, fmt.Sprintf("creating '%s' request to '%s'", method, obj.url.Host), err)
return req
}
func (obj *httpClient) doRequest(req *http.Request) *http.Response {
res, err := obj.cli.Do(req)
njs_logger.PanicLevel.LogErrorCtx(njs_logger.NilLevel, fmt.Sprintf("running request '%s:%s'", req.Method, req.URL.Host), err)
return res
}
func (obj *httpClient) checkResponse(res *http.Response) (bool, *bytes.Buffer) {
var buf *bytes.Buffer
if res.Body != nil {
bdy, err := ioutil.ReadAll(res.Body)
if err == nil {
_, err = buf.Write(bdy)
}
njs_logger.DebugLevel.LogError(err)
}
njs_logger.InfoLevel.Logf("Calling '%s:%s' result %s (Body : %d bytes)", res.Request.Method, res.Request.URL.Host, res.Status, buf.Len())
return strings.HasPrefix(res.Status, "2"), buf
}

21
njs-httpserver/LICENSE Normal file
View File

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

0
njs-httpserver/README.md Normal file
View File

233
njs-httpserver/http.go Normal file
View File

@@ -0,0 +1,233 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_httpserver
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"sync"
"syscall"
"time"
njs_certif "github.com/nabbar/golib/njs-certif"
njs_logger "github.com/nabbar/golib/njs-logger"
)
type modelServer struct {
ssl *tls.Config
srv *http.Server
hdl http.Handler
addr *url.URL
host string
port int
}
type HTTPServer interface {
GetBindable() string
GetExpose() string
IsRunning() bool
Listen()
Restart()
Shutdown()
WaitNotify()
}
func NewServer(listen, expose string, handler http.Handler, tlsConfig *tls.Config) HTTPServer {
srv := &modelServer{
hdl: handler,
ssl: tlsConfig,
}
if host, prt, err := net.SplitHostPort(listen); err != nil {
srv.host = listen
srv.port = 0
} else if port, err := strconv.Atoi(prt); err != nil {
srv.host = host
srv.port = 0
} else {
srv.host = host
srv.port = port
}
if expose == "" {
expose = listen
}
if uri, err := url.Parse(expose); err == nil {
srv.addr = uri
} else if uri, err = url.Parse(listen); err == nil {
srv.addr = uri
} else {
srv.addr = &url.URL{
Host: expose,
}
}
if srv.addr.Scheme == "" {
if srv.ssl != nil {
srv.addr.Scheme = "https"
} else {
srv.addr.Scheme = "http"
}
} else if srv.addr.Scheme == "http" {
srv.ssl = nil
}
return srv
}
func ListenWaitNotify(allSrv ...HTTPServer) {
var wg sync.WaitGroup
wg.Add(len(allSrv))
for _, s := range allSrv {
go func(serv HTTPServer) {
defer wg.Done()
serv.Listen()
serv.WaitNotify()
}(s)
}
wg.Wait()
}
func Listen(allSrv ...HTTPServer) {
for _, s := range allSrv {
go func(serv HTTPServer) {
serv.Listen()
}(s)
}
}
func Restart(allSrv ...HTTPServer) {
for _, s := range allSrv {
s.Restart()
}
}
func Shutdown(allSrv ...HTTPServer) {
for _, s := range allSrv {
s.Shutdown()
}
}
func IsRunning(allSrv ...HTTPServer) bool {
for _, s := range allSrv {
if s.IsRunning() {
return true
}
}
return false
}
func (srv modelServer) GetBindable() string {
return fmt.Sprintf("%s:%d", srv.host, srv.port)
}
func (srv modelServer) GetExpose() string {
return srv.addr.String()
}
func (srv *modelServer) Listen() {
if srv.srv != nil {
srv.Shutdown()
}
srv.srv = &http.Server{
Addr: srv.GetBindable(),
ErrorLog: njs_logger.GetLogger("http server"),
Handler: srv.hdl,
TLSConfig: srv.ssl,
}
njs_logger.InfoLevel.Logf("Server starting with bindable: %s", srv.GetBindable())
go func() {
if srv.ssl == nil || !njs_certif.CheckCertificates() {
if err := srv.srv.ListenAndServe(); err != nil {
njs_logger.FatalLevel.Logf("Listen Error: %v", err)
return
}
} else {
if err := srv.srv.ListenAndServeTLS("", ""); err != nil {
njs_logger.FatalLevel.Logf("Listen config Error: %v", err)
return
}
}
}()
}
func (srv *modelServer) WaitNotify() {
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT)
signal.Notify(quit, syscall.SIGTERM)
//signal.Notify(quit, syscall.SIGKILL)
signal.Notify(quit, syscall.SIGQUIT)
<-quit
srv.Shutdown()
}
func (srv *modelServer) Restart() {
if srv.srv != nil {
srv.Shutdown()
}
srv.Listen()
}
func (srv *modelServer) Shutdown() {
njs_logger.InfoLevel.Logf("Shutdown Server ...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if srv.srv == nil {
return
}
if err := srv.srv.Shutdown(ctx); err != nil {
njs_logger.FatalLevel.Logf("Server Shutdown Error: %v", err)
}
srv.srv = nil
}
func (srv *modelServer) IsRunning() bool {
return srv.srv != nil
}

21
njs-ldap/LICENSE Normal file
View File

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

0
njs-ldap/README.md Normal file
View File

384
njs-ldap/ldap.go Normal file
View File

@@ -0,0 +1,384 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_ldap
import (
"crypto/tls"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/nabbar/golib/njs-certif"
"github.com/nabbar/golib/njs-logger"
"gopkg.in/ldap.v2"
)
//HelperLDAP struct use to manage connection to server and request it
type HelperLDAP struct {
Attributes []string
conn *ldap.Conn
config *Config
tlsConfig *tls.Config
tlsMode TLSMode
bindDN string
bindPass string
}
//NewLDAP build a new LDAP helper based on config struct given
func NewLDAP(cnf *Config, attributes []string) *HelperLDAP {
if cnf == nil {
panic("given config is a nil struct")
}
return &HelperLDAP{
Attributes: attributes,
tlsConfig: njs_certif.GetTLSConfig(cnf.Uri),
tlsMode: tlsmode_init,
config: cnf.Clone(),
}
}
//SetCredentials used to defined the BindDN and password for connection
func (lc *HelperLDAP) SetCredentials(user, pass string) {
lc.bindDN = user
lc.bindPass = pass
}
//SetCredentials used to defined the BindDN and password for connection
func (lc *HelperLDAP) ForceTLSMode(tlsMode TLSMode, tlsConfig *tls.Config) {
switch tlsMode {
case TLSMODE_TLS, TLSMODE_STARTTLS, TLSMODE_NONE:
lc.tlsConfig = tlsConfig
}
if tlsConfig != nil {
lc.tlsConfig = tlsConfig
}
}
func (lc *HelperLDAP) tryConnect() (TLSMode, error) {
var (
l *ldap.Conn
err error
)
defer func(l *ldap.Conn) {
if l != nil {
l.Close()
}
}(l)
if lc.config.Portldaps != 0 {
l, err = ldap.DialTLS("tcp", lc.config.ServerAddr(true), lc.tlsConfig)
if err == nil {
njs_logger.DebugLevel.Logf("ldap connected with tls mode '%s'", lc.tlsMode.String())
return TLSMODE_TLS, nil
}
}
if lc.config.PortLdap == 0 {
return 0, fmt.Errorf("ldap server not well defined")
}
l, err = ldap.Dial("tcp", lc.config.ServerAddr(false))
if err != nil {
return 0, err
}
if e := l.StartTLS(lc.tlsConfig); e == nil {
njs_logger.DebugLevel.Logf("ldap connected with tls mode '%s'", lc.tlsMode.String())
return TLSMODE_STARTTLS, nil
}
njs_logger.DebugLevel.Logf("ldap connected with tls mode '%s'", lc.tlsMode.String())
return TLSMODE_NONE, nil
}
func (lc *HelperLDAP) connect() error {
if lc.conn == nil {
var (
l *ldap.Conn
err error
)
if lc.tlsMode == tlsmode_init {
m, e := lc.tryConnect()
if e != nil {
return e
}
lc.tlsMode = m
}
if lc.tlsMode == TLSMODE_TLS {
l, err = ldap.DialTLS("tcp", lc.config.ServerAddr(true), lc.tlsConfig)
if err != nil {
return fmt.Errorf("ldap connection error with tls mode '%s': %v", lc.tlsMode.String(), err)
}
}
if lc.tlsMode == TLSMODE_NONE || lc.tlsMode == TLSMODE_STARTTLS {
l, err = ldap.Dial("tcp", lc.config.ServerAddr(false))
if err != nil {
return fmt.Errorf("ldap connection error with tls mode '%s': %v", lc.tlsMode.String(), err)
}
}
if lc.tlsMode == TLSMODE_STARTTLS {
err = l.StartTLS(lc.tlsConfig)
if err != nil {
return fmt.Errorf("ldap connection error with tls mode '%s': %v", lc.tlsMode.String(), err)
}
}
njs_logger.DebugLevel.Logf("ldap connected with tls mode '%s'", lc.tlsMode.String())
lc.conn = l
}
return nil
}
//Check used to check if connection success (without any bind)
func (lc *HelperLDAP) Check() error {
if err := lc.connect(); err != nil {
return err
}
lc.Close()
return nil
}
//Close used to close connection object
func (lc *HelperLDAP) Close() {
if lc.conn != nil {
lc.conn.Close()
lc.conn = nil
}
}
//AuthUser used to test bind given user uid and password
func (lc *HelperLDAP) AuthUser(username, password string) error {
if err := lc.connect(); err != nil {
return err
}
if username == "" || password == "" {
return errors.New("Cannot bind with partial credentials, bindDN or bind password is empty string")
}
return lc.conn.Bind(username, password)
}
//Connect used to connect and bind to server
func (lc *HelperLDAP) Connect() error {
if err := lc.AuthUser(lc.bindDN, lc.bindPass); err != nil {
return fmt.Errorf("error while trying to bind on LDAP server %s with tls mode '%s': %v", lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), err)
}
njs_logger.DebugLevel.Logf("Bind success on LDAP server %s with tls mode '%s'", lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String())
return nil
}
func (lc *HelperLDAP) runSearch(filter string, attributes []string) (*ldap.SearchResult, error) {
var (
err error
src *ldap.SearchResult
)
if err = lc.Connect(); err != nil {
return nil, err
}
defer lc.Close()
searchRequest := ldap.NewSearchRequest(
lc.config.Basedn,
ldap.ScopeWholeSubtree,
ldap.NeverDerefAliases,
100, 0, false,
filter,
attributes,
nil,
)
if src, err = lc.conn.Search(searchRequest); err != nil {
return nil, fmt.Errorf("error while looking for '%s' on ldap server %s with tls mode '%s': %v", filter, lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), err)
}
njs_logger.DebugLevel.Logf("Search success on server '%s' with tls mode '%s', with filter [%s] and attribute %v", lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), filter, attributes)
return src, nil
}
//UserInfo used to retrieve the information of a given username
func (lc *HelperLDAP) UserInfo(username string) (map[string]string, error) {
var (
err error
src *ldap.SearchResult
userRes map[string]string
)
if username == "" {
usr := lc.ParseEntries(lc.bindDN)
username = usr["uid"][0]
}
userRes = make(map[string]string)
attributes := append(lc.Attributes, "cn")
if src, err = lc.runSearch(fmt.Sprintf(lc.config.FilterUser, username), attributes); err != nil {
return userRes, err
}
if len(src.Entries) != 1 {
if len(src.Entries) > 1 {
err = errors.New("Username not unique")
} else {
err = errors.New("Username not found")
}
return userRes, fmt.Errorf("error while looking for username '%s' on ldap server '%s' with tls mode '%s': %v", username, lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), err)
}
for _, attr := range attributes {
userRes[attr] = src.Entries[0].GetAttributeValue(attr)
}
if _, ok := userRes["DN"]; !ok {
userRes["DN"] = src.Entries[0].DN
}
njs_logger.DebugLevel.Logf("Map info retrieve in ldap server '%s' with tls mode '%s' about user [%s] : %v", lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), username, userRes)
return userRes, nil
}
//UserMemberOf returns the group list of a given user.
func (lc *HelperLDAP) UserMemberOf(username string) ([]string, error) {
var (
err error
src *ldap.SearchResult
grp []string
)
if username == "" {
usr := lc.ParseEntries(lc.bindDN)
username = usr["uid"][0]
}
grp = make([]string, 0)
if src, err = lc.runSearch(fmt.Sprintf(lc.config.FilterUser, username), []string{"memberOf"}); err != nil {
return grp, err
}
for _, entry := range src.Entries {
for _, mmb := range entry.GetAttributeValues("memberOf") {
njs_logger.DebugLevel.Logf("Group find for uid '%s' on server '%s' with tls mode '%s' : %v", username, lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), mmb)
mmo := lc.ParseEntries(mmb)
grp = append(grp, mmo["cn"]...)
}
}
njs_logger.DebugLevel.Logf("Groups find for uid '%s' on server '%s' with tls mode '%s' : %v", username, lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), grp)
return grp, nil
}
//UserIsInGroup used to check if a given username is a group member of a list of reference group name
func (lc *HelperLDAP) UserIsInGroup(username string, groupname []string) (bool, error) {
var (
err error
grpMmbr []string
)
if username == "" {
usr := lc.ParseEntries(lc.bindDN)
username = usr["uid"][0]
}
if grpMmbr, err = lc.UserMemberOf(username); err != nil {
return false, err
}
for _, grpSrch := range groupname {
for _, grpItem := range grpMmbr {
if strings.ToUpper(grpSrch) == strings.ToUpper(grpItem) {
return true, nil
}
}
}
return false, nil
}
//UsersOfGroup used to retrieve the member list of a given group name
func (lc *HelperLDAP) UsersOfGroup(groupname string) ([]string, error) {
var (
err error
src *ldap.SearchResult
grp []string
)
grp = make([]string, 0)
if src, err = lc.runSearch(fmt.Sprintf(lc.config.FilterGroup, groupname), []string{"member"}); err != nil {
return grp, err
}
for _, entry := range src.Entries {
for _, mmb := range entry.GetAttributeValues("member") {
member := lc.ParseEntries(mmb)
grp = append(grp, member["uid"]...)
}
}
njs_logger.DebugLevel.Logf("Member of groups [%s] find on server '%s' with tls mode '%s' : %v", groupname, lc.config.ServerAddr(lc.tlsMode == TLSMODE_TLS), lc.tlsMode.String(), grp)
return grp, nil
}
//ParseEntries used to clean attributes of an object class
func (lc HelperLDAP) ParseEntries(entry string) map[string][]string {
var listEntries = make(map[string][]string)
for _, ent := range strings.Split(entry, ",") {
key := strings.SplitN(ent, "=", 2)
if len(key) != 2 || len(key[0]) < 1 || len(key[1]) < 1 {
continue
}
key[0] = strings.TrimSpace(key[0])
key[1] = strings.TrimSpace(key[1])
if _, ok := listEntries[key[0]]; !ok {
listEntries[key[0]] = []string{}
}
listEntries[key[0]] = append(listEntries[key[0]], key[1])
}
return listEntries
}

View File

@@ -0,0 +1,83 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_ldap_test
import (
"io/ioutil"
"os"
"testing"
"github.com/nabbar/golib/njs-logger"
"gopkg.in/yaml.v2"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/nabbar/golib/njs-ldap"
"github.com/nabbar/golib/njs-ldap/ldaptestserver"
)
var (
ldap *njs_ldap.HelperLDAP
conf *njs_ldap.Config
)
func init() {
dir, err := os.Getwd()
if err != nil {
panic(err)
}
filepath := dir + "/test.yml"
if _, err := os.Stat(filepath); err != nil {
panic(err)
}
conf = njs_ldap.NewConfig()
if cnt, err := ioutil.ReadFile(filepath); err != nil {
panic(err)
} else if err := yaml.Unmarshal(cnt, &conf); err != nil {
panic(err)
}
}
func TestHelpers(t *testing.T) {
njs_logger.InfoLevel.Log("Starting LDAP Test Server...")
ldaptestserver.RunTestLDAPServer()
defer func() {
if ldap != nil {
ldap.Close()
}
ldaptestserver.StopTestLDAPServer()
njs_logger.InfoLevel.Log("LDAP Test Server is stopped...")
}()
RegisterFailHandler(Fail)
RunSpecs(t, "Test Suite of Helpers LDAP")
}

134
njs-ldap/ldap_test.go Normal file
View File

@@ -0,0 +1,134 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_ldap_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/nabbar/golib/njs-ldap"
"github.com/nabbar/golib/njs-ldap/ldaptestserver"
"github.com/nabbar/golib/njs-logger"
)
var (
username = ""
grpAdmin = "Test - Group2"
grpManager = "Test - Group3"
userBindEr = "uid=false,dc=example,dc=com"
userBindDn = "uid=" + ldaptestserver.GetTestAccountDN(ldaptestserver.TEST_ACCOUNT_TYPE_USER, ldaptestserver.TEST_ACCOUNT_ID_MAIN) + ",dc=example,dc=com"
userBindPw = "abc123def"
)
func init() {
njs_logger.SetLevel(njs_logger.InfoLevel)
}
var _ = Describe("Helpers Test: ", func() {
Context("Test LDAP", func() {
Context("having a false user connection", func() {
BeforeEach(func() {
ldap = njs_ldap.NewLDAP(conf, njs_ldap.GetDefaultAttributes())
ldap.SetCredentials(userBindEr, userBindPw)
})
It("have a connected instance of helper ldap", func() {
Expect(ldap).ToNot(BeNil())
Expect(ldap.Connect()).To(HaveOccurred())
})
})
Context("having a good user connection", func() {
BeforeEach(func() {
ldap = njs_ldap.NewLDAP(conf, njs_ldap.GetDefaultAttributes())
ldap.SetCredentials(userBindDn, userBindPw)
})
It("have a connected instance of helper ldap", func() {
Expect(ldap).ToNot(BeNil())
Expect(ldap.Connect()).ToNot(HaveOccurred())
})
It("return an error on retrieve User Info of a false username", func() {
usr, err := ldap.UserInfo("notExists")
Expect(err).To(HaveOccurred())
Expect(usr).To(Equal(make(map[string]string)))
})
})
Context("given a real username", func() {
BeforeEach(func() {
username = "Test2"
ldap = njs_ldap.NewLDAP(conf, njs_ldap.GetDefaultAttributes())
ldap.SetCredentials(userBindDn, userBindPw)
})
It("have a connected instance of helper ldap", func() {
Expect(ldap).ToNot(BeNil())
Expect(ldap.Connect()).ToNot(HaveOccurred())
})
It("return the retrieved User Info", func() {
usr, err := ldap.UserInfo("Test2")
Expect(err).ToNot(HaveOccurred())
Expect(usr).ToNot(Equal(make(map[string]string)))
Expect(usr["uid"]).To(Equal("Test2"))
})
It("Return true and no error when check Is in Admin group", func() {
chk, err := ldap.UserIsInGroup(username, []string{grpAdmin})
Expect(err).ToNot(HaveOccurred())
Expect(chk).To(BeTrue())
})
It("Return false and no error when check Is in Manager group", func() {
chk, err := ldap.UserIsInGroup(username, []string{grpManager})
Expect(err).ToNot(HaveOccurred())
Expect(chk).To(BeFalse())
})
It("Return no error and the list when retrieve members of a group", func() {
lst, err := ldap.UsersOfGroup("Test - Group1")
Expect(err).ToNot(HaveOccurred())
Expect(len(lst)).To(Equal(3))
})
Context("given a empty password", func() {
It("return an error on authentificate with LDAP", func() {
Expect(ldap.AuthUser("uid="+username, "")).To(HaveOccurred())
})
})
Context("given a wrong password", func() {
It("return no error but a false result when authentificate with LDAP", func() {
Expect(ldap.AuthUser("uid="+username, "wrongPassword")).To(HaveOccurred())
})
})
Context("given a good password", func() {
It("return no error but a false result when authentificate with LDAP", func() {
Expect(ldap.AuthUser("uid="+username, "abc123def")).ToNot(HaveOccurred())
})
})
})
})
})

465
njs-ldap/ldaptestserver.go Normal file
View File

@@ -0,0 +1,465 @@
package njs_ldap
import (
"crypto/tls"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/onsi/ginkgo"
"github.com/sirupsen/logrus"
"github.com/vjeantet/ldapserver"
)
const (
TEST_ACCOUNT_TYPE_USER = iota
TEST_ACCOUNT_TYPE_GROUP
)
const (
TEST_ACCOUNT_ID_MAIN = iota
TEST_ACCOUNT_ID_1
TEST_ACCOUNT_ID_2
TEST_ACCOUNT_ID_3
)
const (
TEST_ACCOUNT_VALID_PASSWORD = "abc123def"
)
var (
ch chan os.Signal
testLDAPserver *ldapserver.Server
)
func GetTestAccountDN(typeAccount int, idAccound int) string {
switch typeAccount {
case TEST_ACCOUNT_TYPE_GROUP:
switch idAccound {
case TEST_ACCOUNT_ID_1:
return "Test - Group1"
case TEST_ACCOUNT_ID_2:
return "Test - Group2"
case TEST_ACCOUNT_ID_3:
return "Test - Group3"
}
case TEST_ACCOUNT_TYPE_USER:
switch idAccound {
case TEST_ACCOUNT_ID_1:
return "Test1"
case TEST_ACCOUNT_ID_2:
return "Test2"
case TEST_ACCOUNT_ID_3:
return "Test3"
case TEST_ACCOUNT_ID_MAIN:
return "bindMainReadOnly"
}
}
return ""
}
func RunTestLDAPServer() {
//Create a new LDAP Server
testLDAPserver = ldapserver.NewServer()
//Create routes bindings
routes := ldapserver.NewRouteMux()
routes.NotFound(handleNotFound)
routes.Abandon(handleAbandon)
routes.Bind(handleBind)
routes.Compare(handleCompare)
routes.Add(handleAdd)
routes.Delete(handleDelete)
routes.Modify(handleModify)
routes.Extended(handleStartTLS).RequestName(ldapserver.NoticeOfStartTLS)
routes.Extended(handleWhoAmI).RequestName(ldapserver.NoticeOfWhoAmI)
routes.Extended(handleExtended)
routes.Search(handleSearch)
//Attach routes to server
testLDAPserver.Handle(routes)
ch = make(chan os.Signal)
// listen on 10389 and serve
go func() {
defer ginkgo.GinkgoRecover()
if err := testLDAPserver.ListenAndServe("127.0.0.1:10389"); err != nil {
logrus.Fatal("Error on LDAP Test Server : %v", err)
}
}()
time.Sleep(5 * time.Second)
}
func StopTestLDAPServer() {
// When CTRL+C, SIGINT and SIGTERM signal occurs
// Then stop server gracefully
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
// <-ch
time.Sleep(5 * time.Second)
close(ch)
testLDAPserver.Stop()
}
func handleNotFound(w ldapserver.ResponseWriter, r *ldapserver.Message) {
switch r.GetProtocolOp() {
case ldapserver.ApplicationBindRequest:
res := ldapserver.NewBindResponse(ldapserver.LDAPResultSuccess)
res.DiagnosticMessage = "Default binding behavior set to return Success"
w.Write(res)
default:
res := ldapserver.NewResponse(ldapserver.LDAPResultUnwillingToPerform)
res.DiagnosticMessage = "Operation not implemented by server"
w.Write(res)
}
}
func handleAbandon(w ldapserver.ResponseWriter, m *ldapserver.Message) {
var req = m.GetAbandonRequest()
// retreive the request to abandon, and send a abort signal to it
if requestToAbandon, ok := m.Client.GetMessageByID(int(req)); ok {
requestToAbandon.Abandon()
//logrus.Infof("Abandon signal sent to request processor [messageID=%d]", int(req))
}
}
func handleBind(w ldapserver.ResponseWriter, m *ldapserver.Message) {
res := ldapserver.NewBindResponse(ldapserver.LDAPResultSuccess)
r := m.GetBindRequest()
//logrus.Debugf("Calling Bind Request for : User=%s, Pass=%#v", string(r.GetLogin()), string(r.GetPassword()))
if string(r.GetPassword()) == TEST_ACCOUNT_VALID_PASSWORD {
switch string(r.GetLogin()) {
case fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_MAIN)),
fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_1)),
fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_2)),
fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_3)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_MAIN)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_1)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_2)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_3)):
w.Write(res)
return
}
}
//logrus.Debugf("Bind failed User=%s, Pass=%s", string(r.GetLogin()), string(r.GetPassword()))
res.ResultCode = ldapserver.LDAPResultInvalidCredentials
res.DiagnosticMessage = "invalid credentials"
w.Write(res)
}
// The resultCode is set to compareTrue, compareFalse, or an appropriate
// error. compareTrue indicates that the assertion value in the ava
// Comparerequest field matches a value of the attribute or subtype according to the
// attribute's EQUALITY matching rule. compareFalse indicates that the
// assertion value in the ava field and the values of the attribute or
// subtype did not match. Other result codes indicate either that the
// result of the comparison was Undefined, or that
// some error occurred.
func handleCompare(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetCompareRequest()
logrus.Debugf("Comparing entry: %s", r.GetEntry())
//attributes values
logrus.Debugf(" attribute name to compare : \"%s\"", r.GetAttributeValueAssertion().GetName())
logrus.Debugf(" attribute value expected : \"%s\"", r.GetAttributeValueAssertion().GetValue())
*/
res := ldapserver.NewCompareResponse(ldapserver.LDAPResultCompareTrue)
w.Write(res)
}
func handleAdd(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetAddRequest()
logrus.Debugf("Adding entry: %s", r.GetEntryDN())
//attributes values
for _, attribute := range r.GetAttributes() {
for _, attributeValue := range attribute.GetValues() {
logrus.Debugf("- %s:%s", attribute.GetDescription(), attributeValue)
}
}
*/
res := ldapserver.NewAddResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleModify(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetModifyRequest()
logrus.Debugf("Modify entry: %s", r.GetObject())
for _, change := range r.GetChanges() {
modification := change.GetModification()
var operationString string
switch change.GetOperation() {
case ldapserver.ModifyRequestChangeOperationAdd:
operationString = "Add"
case ldapserver.ModifyRequestChangeOperationDelete:
operationString = "Delete"
case ldapserver.ModifyRequestChangeOperationReplace:
operationString = "Replace"
}
logrus.Debugf("%s attribute '%s'", operationString, modification.GetDescription())
for _, attributeValue := range modification.GetValues() {
logrus.Debugf("- value: %s", attributeValue)
}
}
*/
res := ldapserver.NewModifyResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleDelete(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetDeleteRequest()
logrus.Debugf("Deleting entry: %s", r)
*/
res := ldapserver.NewDeleteResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleExtended(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetExtendedRequest()
logrus.Debugf("Extended request received, name=%s", r.GetResponseName())
logrus.Debugf("Extended request received, value=%x", r.GetResponseValue())
*/
res := ldapserver.NewExtendedResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleWhoAmI(w ldapserver.ResponseWriter, m *ldapserver.Message) {
res := ldapserver.NewExtendedResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleSearchDSE(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetSearchRequest()
attr := make([]string, 0)
for _, v := range r.GetAttributes() {
attr = append(attr, string(v))
}
/*
logrus.Debugf("Request BaseDn=%s", r.GetBaseObject())
logrus.Debugf("Request Filter=%s", r.GetFilter())
logrus.Debugf("Request Attributes=%s", strings.Join(attr, ","))
logrus.Debugf("Request TimeLimit=%d", r.GetTimeLimit())
*/
e := ldapserver.NewSearchResultEntry()
e.AddAttribute("vendorName", "Test Vendor")
e.AddAttribute("vendorVersion", "0.0.1")
e.AddAttribute("objectClass", "top", "extensibleObject")
e.AddAttribute("supportedLDAPVersion", "3")
e.AddAttribute("namingContexts", "o=Test Company, c=US")
w.Write(e)
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleSearchMyCompany(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetSearchRequest()
//logrus.Debugf("handleSearchMyCompany - Request BaseDn=%s", r.GetBaseObject())
e := ldapserver.NewSearchResultEntry()
e.SetDn(string(r.GetBaseObject()))
e.AddAttribute("objectClass", "top", "organizationalUnit")
w.Write(e)
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleSearch(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetSearchRequest()
if string(r.GetBaseObject()) == "" && r.GetScope() == ldapserver.SearchRequestScopeBaseObject && r.GetFilter() == "(objectclass=*)" {
handleSearchDSE(w, m)
return
}
if string(r.GetBaseObject()) == "o=My Company, c=US" && r.GetScope() == ldapserver.SearchRequestScopeBaseObject {
handleSearchMyCompany(w, m)
return
}
attr := make([]string, 0)
for _, v := range r.GetAttributes() {
attr = append(attr, string(v))
}
/*
logrus.Debugf("Request BaseDn=%s", string(r.GetBaseObject()))
logrus.Debugf("Request Filter=%s", r.GetFilter())
logrus.Debugf("Request Attributes=%s", strings.Join(attr, ","))
logrus.Debugf("Request TimeLimit=%d", r.GetTimeLimit())
*/
// Handle Stop Signal (server stop / client disconnected / Abandoned request....)
select {
case <-m.Done:
//logrus.Info("Leaving handleSearch...")
return
default:
}
if r.GetFilter() == "(uid=Test1)" {
//logrus.Debugf("Prepare Result Test1 for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test1," + string(r.GetBaseObject()))
e.AddAttribute("mail", "test.ldap@example.com", "testldap@example.com")
e.AddAttribute("uid", "Test1")
e.AddAttribute("cn", "Test1")
e.AddAttribute("ou", "People")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("memberOf", "cn=Test - Group1,dc=example,dc=com", "cn=Test - Group2,dc=example,dc=com", "cn=Test - Group3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(uid=Test2)" {
//logrus.Debugf("Prepare Result Test2 for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test2," + string(r.GetBaseObject()))
e.AddAttribute("mail", "test.2.ldap@example.com")
e.AddAttribute("uid", "Test2")
e.AddAttribute("cn", "Test2")
e.AddAttribute("ou", "People")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("memberOf", "cn=Test - Group1,dc=example,dc=com", "cn=Test - Group2,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(uid=Test3)" {
//logrus.Debugf("Prepare Result Test3 for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test3," + string(r.GetBaseObject()))
e.AddAttribute("mail", "test.3.ldap@example.com")
e.AddAttribute("uid", "Test3")
e.AddAttribute("cn", "Test3")
e.AddAttribute("ou", "People")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("memberOf", "cn=Test - Group1,dc=example,dc=com", "cn=Test - Group3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(&(objectClass=groupOfNames)(cn=Test - Group1))" {
//logrus.Debugf("Prepare Result [Test - Group1] for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test - Group1," + string(r.GetBaseObject()))
e.AddAttribute("cn", "Test - Group1")
e.AddAttribute("ou", "Group")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("member", "uid=Test1,dc=example,dc=com", "uid=Test2,dc=example,dc=com", "uid=Test3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(&(objectClass=groupOfNames)(cn=Test - Group2))" {
//logrus.Debugf("Prepare Result [Test - Group2] for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test - Group2," + string(r.GetBaseObject()))
e.AddAttribute("cn", "Test - Group2")
e.AddAttribute("ou", "Group")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("member", "uid=Test1,dc=example,dc=com", "uid=Test3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(&(objectClass=groupOfNames)(cn=Test - Group3))" {
//logrus.Debugf("Prepare Result [Test - Group3] for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test - Group3," + string(r.GetBaseObject()))
e.AddAttribute("cn", "Test - Group3")
e.AddAttribute("ou", "Group")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("member", "uid=Test1,dc=example,dc=com", "uid=Test2,dc=example,dc=com")
w.Write(e)
}
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
//logrus.Debugf("Res Found : %v", res)
w.Write(res)
}
// localhostCert is a PEM-encoded TLS cert with SAN DNS names
// "127.0.0.1" and "[::1]", expiring at the last second of 2049 (the end
// of ASN.1 time).
var localhostCert = []byte(`-----BEGIN CERTIFICATE-----
MIIBOTCB5qADAgECAgEAMAsGCSqGSIb3DQEBBTAAMB4XDTcwMDEwMTAwMDAwMFoX
DTQ5MTIzMTIzNTk1OVowADBaMAsGCSqGSIb3DQEBAQNLADBIAkEAsuA5mAFMj6Q7
qoBzcvKzIq4kzuT5epSp2AkcQfyBHm7K13Ws7u+0b5Vb9gqTf5cAiIKcrtrXVqkL
8i1UQF6AzwIDAQABo08wTTAOBgNVHQ8BAf8EBAMCACQwDQYDVR0OBAYEBAECAwQw
DwYDVR0jBAgwBoAEAQIDBDAbBgNVHREEFDASggkxMjcuMC4wLjGCBVs6OjFdMAsG
CSqGSIb3DQEBBQNBAJH30zjLWRztrWpOCgJL8RQWLaKzhK79pVhAx6q/3NrF16C7
+l1BRZstTwIGdoGId8BRpErK1TXkniFb95ZMynM=
-----END CERTIFICATE-----
`)
// localhostKey is the private key for localhostCert.
var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIBPQIBAAJBALLgOZgBTI+kO6qAc3LysyKuJM7k+XqUqdgJHEH8gR5uytd1rO7v
tG+VW/YKk3+XAIiCnK7a11apC/ItVEBegM8CAwEAAQJBAI5sxq7naeR9ahyqRkJi
SIv2iMxLuPEHaezf5CYOPWjSjBPyVhyRevkhtqEjF/WkgL7C2nWpYHsUcBDBQVF0
3KECIQDtEGB2ulnkZAahl3WuJziXGLB+p8Wgx7wzSM6bHu1c6QIhAMEp++CaS+SJ
/TrU0zwY/fW4SvQeb49BPZUF3oqR8Xz3AiEA1rAJHBzBgdOQKdE3ksMUPcnvNJSN
poCcELmz2clVXtkCIQCLytuLV38XHToTipR4yMl6O+6arzAjZ56uq7m7ZRV0TwIh
AM65XAOw8Dsg9Kq78aYXiOEDc5DL0sbFUu/SlmRcCg93
-----END RSA PRIVATE KEY-----
`)
// getTLSconfig returns a tls configuration used
// to build a TLSlistener for TLS or StartTLS
func getTLSconfig() (*tls.Config, error) {
cert, err := tls.X509KeyPair(localhostCert, localhostKey)
if err != nil {
return &tls.Config{}, err
}
return &tls.Config{
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
ServerName: "127.0.0.1",
}, nil
}
func handleStartTLS(w ldapserver.ResponseWriter, m *ldapserver.Message) {
tlsconfig, e := getTLSconfig()
if e != nil {
logrus.Errorf("error while retrieve TLS config: %v", e)
}
tlsConn := tls.Server(m.Client.GetConn(), tlsconfig)
res := ldapserver.NewExtendedResponse(ldapserver.LDAPResultSuccess)
res.ResponseName = ldapserver.NoticeOfStartTLS
w.Write(res)
if err := tlsConn.Handshake(); err != nil {
logrus.Errorf("StartTLS Handshake error %v", err)
res.DiagnosticMessage = fmt.Sprintf("StartTLS Handshake error : \"%s\"", err.Error())
res.ResultCode = ldapserver.LDAPResultOperationsError
w.Write(res)
return
}
m.Client.SetConn(tlsConn)
logrus.Info("StartTLS OK")
}

View File

@@ -0,0 +1,465 @@
package ldaptestserver
import (
"crypto/tls"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"github.com/onsi/ginkgo"
"github.com/sirupsen/logrus"
"github.com/vjeantet/ldapserver"
)
const (
TEST_ACCOUNT_TYPE_USER = iota
TEST_ACCOUNT_TYPE_GROUP
)
const (
TEST_ACCOUNT_ID_MAIN = iota
TEST_ACCOUNT_ID_1
TEST_ACCOUNT_ID_2
TEST_ACCOUNT_ID_3
)
const (
TEST_ACCOUNT_VALID_PASSWORD = "abc123def"
)
var (
ch chan os.Signal
testLDAPserver *ldapserver.Server
)
func GetTestAccountDN(typeAccount int, idAccound int) string {
switch typeAccount {
case TEST_ACCOUNT_TYPE_GROUP:
switch idAccound {
case TEST_ACCOUNT_ID_1:
return "Test - Group1"
case TEST_ACCOUNT_ID_2:
return "Test - Group2"
case TEST_ACCOUNT_ID_3:
return "Test - Group3"
}
case TEST_ACCOUNT_TYPE_USER:
switch idAccound {
case TEST_ACCOUNT_ID_1:
return "Test1"
case TEST_ACCOUNT_ID_2:
return "Test2"
case TEST_ACCOUNT_ID_3:
return "Test3"
case TEST_ACCOUNT_ID_MAIN:
return "bindMainReadOnly"
}
}
return ""
}
func RunTestLDAPServer() {
//Create a new LDAP Server
testLDAPserver = ldapserver.NewServer()
//Create routes bindings
routes := ldapserver.NewRouteMux()
routes.NotFound(handleNotFound)
routes.Abandon(handleAbandon)
routes.Bind(handleBind)
routes.Compare(handleCompare)
routes.Add(handleAdd)
routes.Delete(handleDelete)
routes.Modify(handleModify)
routes.Extended(handleStartTLS).RequestName(ldapserver.NoticeOfStartTLS)
routes.Extended(handleWhoAmI).RequestName(ldapserver.NoticeOfWhoAmI)
routes.Extended(handleExtended)
routes.Search(handleSearch)
//Attach routes to server
testLDAPserver.Handle(routes)
ch = make(chan os.Signal)
// listen on 10389 and serve
go func() {
defer ginkgo.GinkgoRecover()
if err := testLDAPserver.ListenAndServe("127.0.0.1:10389"); err != nil {
logrus.Fatal("Error on LDAP Test Server : %v", err)
}
}()
time.Sleep(5 * time.Second)
}
func StopTestLDAPServer() {
// When CTRL+C, SIGINT and SIGTERM signal occurs
// Then stop server gracefully
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
// <-ch
time.Sleep(5 * time.Second)
close(ch)
testLDAPserver.Stop()
}
func handleNotFound(w ldapserver.ResponseWriter, r *ldapserver.Message) {
switch r.GetProtocolOp() {
case ldapserver.ApplicationBindRequest:
res := ldapserver.NewBindResponse(ldapserver.LDAPResultSuccess)
res.DiagnosticMessage = "Default binding behavior set to return Success"
w.Write(res)
default:
res := ldapserver.NewResponse(ldapserver.LDAPResultUnwillingToPerform)
res.DiagnosticMessage = "Operation not implemented by server"
w.Write(res)
}
}
func handleAbandon(w ldapserver.ResponseWriter, m *ldapserver.Message) {
var req = m.GetAbandonRequest()
// retreive the request to abandon, and send a abort signal to it
if requestToAbandon, ok := m.Client.GetMessageByID(int(req)); ok {
requestToAbandon.Abandon()
//logrus.Infof("Abandon signal sent to request processor [messageID=%d]", int(req))
}
}
func handleBind(w ldapserver.ResponseWriter, m *ldapserver.Message) {
res := ldapserver.NewBindResponse(ldapserver.LDAPResultSuccess)
r := m.GetBindRequest()
//logrus.Debugf("Calling Bind Request for : User=%s, Pass=%#v", string(r.GetLogin()), string(r.GetPassword()))
if string(r.GetPassword()) == TEST_ACCOUNT_VALID_PASSWORD {
switch string(r.GetLogin()) {
case fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_MAIN)),
fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_1)),
fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_2)),
fmt.Sprintf("uid=%s", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_3)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_MAIN)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_1)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_2)),
fmt.Sprintf("uid=%s,dc=example,dc=com", GetTestAccountDN(TEST_ACCOUNT_TYPE_USER, TEST_ACCOUNT_ID_3)):
w.Write(res)
return
}
}
//logrus.Debugf("Bind failed User=%s, Pass=%s", string(r.GetLogin()), string(r.GetPassword()))
res.ResultCode = ldapserver.LDAPResultInvalidCredentials
res.DiagnosticMessage = "invalid credentials"
w.Write(res)
}
// The resultCode is set to compareTrue, compareFalse, or an appropriate
// error. compareTrue indicates that the assertion value in the ava
// Comparerequest field matches a value of the attribute or subtype according to the
// attribute's EQUALITY matching rule. compareFalse indicates that the
// assertion value in the ava field and the values of the attribute or
// subtype did not match. Other result codes indicate either that the
// result of the comparison was Undefined, or that
// some error occurred.
func handleCompare(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetCompareRequest()
logrus.Debugf("Comparing entry: %s", r.GetEntry())
//attributes values
logrus.Debugf(" attribute name to compare : \"%s\"", r.GetAttributeValueAssertion().GetName())
logrus.Debugf(" attribute value expected : \"%s\"", r.GetAttributeValueAssertion().GetValue())
*/
res := ldapserver.NewCompareResponse(ldapserver.LDAPResultCompareTrue)
w.Write(res)
}
func handleAdd(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetAddRequest()
logrus.Debugf("Adding entry: %s", r.GetEntryDN())
//attributes values
for _, attribute := range r.GetAttributes() {
for _, attributeValue := range attribute.GetValues() {
logrus.Debugf("- %s:%s", attribute.GetDescription(), attributeValue)
}
}
*/
res := ldapserver.NewAddResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleModify(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetModifyRequest()
logrus.Debugf("Modify entry: %s", r.GetObject())
for _, change := range r.GetChanges() {
modification := change.GetModification()
var operationString string
switch change.GetOperation() {
case ldapserver.ModifyRequestChangeOperationAdd:
operationString = "Add"
case ldapserver.ModifyRequestChangeOperationDelete:
operationString = "Delete"
case ldapserver.ModifyRequestChangeOperationReplace:
operationString = "Replace"
}
logrus.Debugf("%s attribute '%s'", operationString, modification.GetDescription())
for _, attributeValue := range modification.GetValues() {
logrus.Debugf("- value: %s", attributeValue)
}
}
*/
res := ldapserver.NewModifyResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleDelete(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetDeleteRequest()
logrus.Debugf("Deleting entry: %s", r)
*/
res := ldapserver.NewDeleteResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleExtended(w ldapserver.ResponseWriter, m *ldapserver.Message) {
/*
r := m.GetExtendedRequest()
logrus.Debugf("Extended request received, name=%s", r.GetResponseName())
logrus.Debugf("Extended request received, value=%x", r.GetResponseValue())
*/
res := ldapserver.NewExtendedResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleWhoAmI(w ldapserver.ResponseWriter, m *ldapserver.Message) {
res := ldapserver.NewExtendedResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleSearchDSE(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetSearchRequest()
attr := make([]string, 0)
for _, v := range r.GetAttributes() {
attr = append(attr, string(v))
}
/*
logrus.Debugf("Request BaseDn=%s", r.GetBaseObject())
logrus.Debugf("Request Filter=%s", r.GetFilter())
logrus.Debugf("Request Attributes=%s", strings.Join(attr, ","))
logrus.Debugf("Request TimeLimit=%d", r.GetTimeLimit())
*/
e := ldapserver.NewSearchResultEntry()
e.AddAttribute("vendorName", "Test Vendor")
e.AddAttribute("vendorVersion", "0.0.1")
e.AddAttribute("objectClass", "top", "extensibleObject")
e.AddAttribute("supportedLDAPVersion", "3")
e.AddAttribute("namingContexts", "o=Test Company, c=US")
w.Write(e)
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleSearchMyCompany(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetSearchRequest()
//logrus.Debugf("handleSearchMyCompany - Request BaseDn=%s", r.GetBaseObject())
e := ldapserver.NewSearchResultEntry()
e.SetDn(string(r.GetBaseObject()))
e.AddAttribute("objectClass", "top", "organizationalUnit")
w.Write(e)
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
w.Write(res)
}
func handleSearch(w ldapserver.ResponseWriter, m *ldapserver.Message) {
r := m.GetSearchRequest()
if string(r.GetBaseObject()) == "" && r.GetScope() == ldapserver.SearchRequestScopeBaseObject && r.GetFilter() == "(objectclass=*)" {
handleSearchDSE(w, m)
return
}
if string(r.GetBaseObject()) == "o=My Company, c=US" && r.GetScope() == ldapserver.SearchRequestScopeBaseObject {
handleSearchMyCompany(w, m)
return
}
attr := make([]string, 0)
for _, v := range r.GetAttributes() {
attr = append(attr, string(v))
}
/*
logrus.Debugf("Request BaseDn=%s", string(r.GetBaseObject()))
logrus.Debugf("Request Filter=%s", r.GetFilter())
logrus.Debugf("Request Attributes=%s", strings.Join(attr, ","))
logrus.Debugf("Request TimeLimit=%d", r.GetTimeLimit())
*/
// Handle Stop Signal (server stop / client disconnected / Abandoned request....)
select {
case <-m.Done:
//logrus.Info("Leaving handleSearch...")
return
default:
}
if r.GetFilter() == "(uid=Test1)" {
//logrus.Debugf("Prepare Result Test1 for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test1," + string(r.GetBaseObject()))
e.AddAttribute("mail", "test.ldap@example.com", "testldap@example.com")
e.AddAttribute("uid", "Test1")
e.AddAttribute("cn", "Test1")
e.AddAttribute("ou", "People")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("memberOf", "cn=Test - Group1,dc=example,dc=com", "cn=Test - Group2,dc=example,dc=com", "cn=Test - Group3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(uid=Test2)" {
//logrus.Debugf("Prepare Result Test2 for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test2," + string(r.GetBaseObject()))
e.AddAttribute("mail", "test.2.ldap@example.com")
e.AddAttribute("uid", "Test2")
e.AddAttribute("cn", "Test2")
e.AddAttribute("ou", "People")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("memberOf", "cn=Test - Group1,dc=example,dc=com", "cn=Test - Group2,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(uid=Test3)" {
//logrus.Debugf("Prepare Result Test3 for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test3," + string(r.GetBaseObject()))
e.AddAttribute("mail", "test.3.ldap@example.com")
e.AddAttribute("uid", "Test3")
e.AddAttribute("cn", "Test3")
e.AddAttribute("ou", "People")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("memberOf", "cn=Test - Group1,dc=example,dc=com", "cn=Test - Group3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(&(objectClass=groupOfNames)(cn=Test - Group1))" {
//logrus.Debugf("Prepare Result [Test - Group1] for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test - Group1," + string(r.GetBaseObject()))
e.AddAttribute("cn", "Test - Group1")
e.AddAttribute("ou", "Group")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("member", "uid=Test1,dc=example,dc=com", "uid=Test2,dc=example,dc=com", "uid=Test3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(&(objectClass=groupOfNames)(cn=Test - Group2))" {
//logrus.Debugf("Prepare Result [Test - Group2] for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test - Group2," + string(r.GetBaseObject()))
e.AddAttribute("cn", "Test - Group2")
e.AddAttribute("ou", "Group")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("member", "uid=Test1,dc=example,dc=com", "uid=Test3,dc=example,dc=com")
w.Write(e)
}
if r.GetFilter() == "(&(objectClass=groupOfNames)(cn=Test - Group3))" {
//logrus.Debugf("Prepare Result [Test - Group3] for %s", r.GetFilter())
e := ldapserver.NewSearchResultEntry()
e.SetDn("uid=Test - Group3," + string(r.GetBaseObject()))
e.AddAttribute("cn", "Test - Group3")
e.AddAttribute("ou", "Group")
e.AddAttribute("dc", "example", "com")
e.AddAttribute("member", "uid=Test1,dc=example,dc=com", "uid=Test2,dc=example,dc=com")
w.Write(e)
}
res := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess)
//logrus.Debugf("Res Found : %v", res)
w.Write(res)
}
// localhostCert is a PEM-encoded TLS cert with SAN DNS names
// "127.0.0.1" and "[::1]", expiring at the last second of 2049 (the end
// of ASN.1 time).
var localhostCert = []byte(`-----BEGIN CERTIFICATE-----
MIIBOTCB5qADAgECAgEAMAsGCSqGSIb3DQEBBTAAMB4XDTcwMDEwMTAwMDAwMFoX
DTQ5MTIzMTIzNTk1OVowADBaMAsGCSqGSIb3DQEBAQNLADBIAkEAsuA5mAFMj6Q7
qoBzcvKzIq4kzuT5epSp2AkcQfyBHm7K13Ws7u+0b5Vb9gqTf5cAiIKcrtrXVqkL
8i1UQF6AzwIDAQABo08wTTAOBgNVHQ8BAf8EBAMCACQwDQYDVR0OBAYEBAECAwQw
DwYDVR0jBAgwBoAEAQIDBDAbBgNVHREEFDASggkxMjcuMC4wLjGCBVs6OjFdMAsG
CSqGSIb3DQEBBQNBAJH30zjLWRztrWpOCgJL8RQWLaKzhK79pVhAx6q/3NrF16C7
+l1BRZstTwIGdoGId8BRpErK1TXkniFb95ZMynM=
-----END CERTIFICATE-----
`)
// localhostKey is the private key for localhostCert.
var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIBPQIBAAJBALLgOZgBTI+kO6qAc3LysyKuJM7k+XqUqdgJHEH8gR5uytd1rO7v
tG+VW/YKk3+XAIiCnK7a11apC/ItVEBegM8CAwEAAQJBAI5sxq7naeR9ahyqRkJi
SIv2iMxLuPEHaezf5CYOPWjSjBPyVhyRevkhtqEjF/WkgL7C2nWpYHsUcBDBQVF0
3KECIQDtEGB2ulnkZAahl3WuJziXGLB+p8Wgx7wzSM6bHu1c6QIhAMEp++CaS+SJ
/TrU0zwY/fW4SvQeb49BPZUF3oqR8Xz3AiEA1rAJHBzBgdOQKdE3ksMUPcnvNJSN
poCcELmz2clVXtkCIQCLytuLV38XHToTipR4yMl6O+6arzAjZ56uq7m7ZRV0TwIh
AM65XAOw8Dsg9Kq78aYXiOEDc5DL0sbFUu/SlmRcCg93
-----END RSA PRIVATE KEY-----
`)
// getTLSconfig returns a tls configuration used
// to build a TLSlistener for TLS or StartTLS
func getTLSconfig() (*tls.Config, error) {
cert, err := tls.X509KeyPair(localhostCert, localhostKey)
if err != nil {
return &tls.Config{}, err
}
return &tls.Config{
MinVersion: tls.VersionTLS12,
MaxVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
ServerName: "127.0.0.1",
}, nil
}
func handleStartTLS(w ldapserver.ResponseWriter, m *ldapserver.Message) {
tlsconfig, e := getTLSconfig()
if e != nil {
logrus.Errorf("error while retrieve TLS config: %v", e)
}
tlsConn := tls.Server(m.Client.GetConn(), tlsconfig)
res := ldapserver.NewExtendedResponse(ldapserver.LDAPResultSuccess)
res.ResponseName = ldapserver.NoticeOfStartTLS
w.Write(res)
if err := tlsConn.Handshake(); err != nil {
logrus.Errorf("StartTLS Handshake error %v", err)
res.DiagnosticMessage = fmt.Sprintf("StartTLS Handshake error : \"%s\"", err.Error())
res.ResultCode = ldapserver.LDAPResultOperationsError
w.Write(res)
return
}
m.Client.SetConn(tlsConn)
logrus.Info("StartTLS OK")
}

103
njs-ldap/model.go Normal file
View File

@@ -0,0 +1,103 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_ldap
import (
"fmt"
)
type TLSMode uint8
const (
tlsmode_init TLSMode = iota
//TLSModeNone no tls connection
TLSMODE_NONE TLSMode = iota + 1
//TLSModeTLS strict tls connection
TLSMODE_TLS
//TLSModeStartTLS starttls connection (tls into a no tls connection)
TLSMODE_STARTTLS
)
func (m TLSMode) String() string {
switch m {
case TLSMODE_STARTTLS:
return "starttls"
case TLSMODE_TLS:
return "tls"
case TLSMODE_NONE:
return "none"
default:
return "no defined"
}
}
func GetDefaultAttributes() []string {
return []string{"givenName", "mail", "uid", "dn"}
}
type Config struct {
Uri string `cloud:"uri" mapstructure:"uri" json:"uri" yaml:"uri" toml:"uri"`
PortLdap int `cloud:"port-ldap" mapstructure:"port-ldap" json:"port-ldap" yaml:"port-ldap" toml:"port-ldap"`
Portldaps int `cloud:"port-ldaps" mapstructure:"port-ldaps" json:"port-ldaps" yaml:"port-ldaps" toml:"port-ldaps"`
Basedn string `cloud:"basedn" mapstructure:"basedn" json:"basedn" yaml:"basedn" toml:"basedn"`
FilterGroup string `cloud:"filter-group" mapstructure:"filter-group" json:"filter-group" yaml:"filter-group" toml:"filter-group"`
FilterUser string `cloud:"filter-user" mapstructure:"filter-user" json:"filter-user" yaml:"filter-user" toml:"filter-user"`
}
func NewConfig() *Config {
return &Config{}
}
func (cnf Config) Clone() *Config {
return &Config{
Uri: cnf.Uri,
PortLdap: cnf.PortLdap,
Portldaps: cnf.Portldaps,
Basedn: cnf.Basedn,
FilterGroup: cnf.FilterGroup,
FilterUser: cnf.FilterUser,
}
}
func (cnf Config) BaseDN() string {
return cnf.Basedn
}
func (cnf Config) ServerAddr(withTls bool) string {
if withTls {
return fmt.Sprintf("%s:%d", cnf.Uri, cnf.Portldaps)
}
return fmt.Sprintf("%s:%d", cnf.Uri, cnf.PortLdap)
}
func (cnf Config) PatternFilterGroup() string {
return cnf.FilterGroup
}
func (cnf Config) PatternFilterUser() string {
return cnf.FilterUser
}

10
njs-ldap/test.yml Normal file
View File

@@ -0,0 +1,10 @@
---
uri: "127.0.0.1"
port-ldap: 10389
port-ldaps: 0
certificats: ""
basedn: "dc=example,dc=com"
bind_dn: "uid=bindMainReadOnly,dc=example,dc=com"
bind_password: "abc123def"
filter-group: "(&(objectClass=groupOfNames)(cn=%s))"
filter-user: "(uid=%s)"

21
njs-logger/LICENSE Normal file
View File

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

11
njs-logger/README.md Normal file
View File

@@ -0,0 +1,11 @@
GoDoc | Travis | Snyk
:-: | :-: | :-:
[![Documentation Status](https://godoc.org/github.com/nabbar/gopkg-njs-logger?status.png "Documentation Status")](https://godoc.org/github.com/nabbar/gopkg-njs-logger) | [![Build Status](https://travis-ci.com/nabbar/gopkg-njs-logger.svg?branch=master)](https://travis-ci.com/nabbar/gopkg-njs-logger) | [![Known Vulnerabilities](https://snyk.io/test/github/nabbar/gopkg-njs-logger/badge.svg?style=plastic "Known Vulnerabilities")](https://snyk.io/test/github/nabbar/gopkg-njs-logger)
# gopkg-njs-logger
This lib is a more an helper than a lib.
This lib is use to simplify integration and common use of the lib logrus
... in construction

124
njs-logger/formatter.go Normal file
View File

@@ -0,0 +1,124 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_logger
import (
"strings"
"time"
"github.com/sirupsen/logrus"
)
// Format a uint8 type customized with function to manage the result logger format
type Format uint8
const (
nilFormat Format = iota
// TextFormat a text format for logger entry
TextFormat
// JsonFormat a json format for logger entry
JsonFormat
)
var (
curFormat = TextFormat
)
func updateFormatter(newFormat Format) {
if newFormat != nilFormat {
curFormat = newFormat
}
switch curFormat {
case TextFormat:
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: modeColor,
DisableColors: !modeColor,
DisableLevelTruncation: !modeColor,
FullTimestamp: true,
TimestampFormat: time.RFC3339Nano,
DisableTimestamp: !modeApi,
DisableSorting: true,
})
case JsonFormat:
logrus.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
DisableTimestamp: !modeApi,
})
}
}
// GetFormatListString return the full list (slice of string) of all available formats
func GetFormatListString() []string {
return []string{
strings.ToLower(TextFormat.String()),
strings.ToLower(JsonFormat.String()),
}
}
// SetFormat Change the format of all log entry with the Format type given in parameter. The change is apply for next entry only
//
// If the given Format type is not matching a correct Format type, no change will be apply.
/*
fmt a Format type for the format to use
*/
func SetFormat(fmt Format) {
switch fmt {
case TextFormat, JsonFormat:
updateFormatter(fmt)
}
}
// GetCurrentFormat Return the current Format Type used for all log entry
func GetCurrentFormat() Format {
return curFormat
}
// GetFormatString return a valid Format Type matching the given string parameter
/*
format the string representation of a Format type
*/
func GetFormatString(format string) Format {
switch strings.ToLower(format) {
case strings.ToLower(TextFormat.String()):
return TextFormat
case strings.ToLower(JsonFormat.String()):
return JsonFormat
default:
return TextFormat
}
}
// String Return the string name of the Format Type
func (f Format) String() string {
switch f {
case JsonFormat:
return "Json"
default:
return "Text"
}
}

62
njs-logger/iowriter.go Normal file
View File

@@ -0,0 +1,62 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_logger
import (
"fmt"
"io"
)
// IOWriter is struct redirected all entry to the current logger
type IOWriter struct {
lvl Level
prf string
}
// GetIOWriter return a io.Writer instance to Write on logger with a specified log level
/*
level specify the log level to use to redirect all entry to current logger
msgPrefixPattern is a string pattern to prefix all entry
msgPrefixArgs is a list of args to apply on the msgPrefixPattern pattern to prefix all entry
*/
func GetIOWriter(level Level, msgPrefixPattern string, msgPrefixArgs ...interface{}) io.Writer {
return &IOWriter{
lvl: level,
prf: fmt.Sprintf(msgPrefixPattern, msgPrefixArgs...),
}
}
// Write implement the Write function of the io.Writer interface and redirect all entry to current logger
//
// the return n will always return the len on the p parameter and err will always be nil
/*
p the entry to be redirect to current logger
*/
func (iow IOWriter) Write(p []byte) (n int, err error) {
n = len(p)
err = nil
iow.lvl.Log(iow.prf + " " + string(p))
return
}

390
njs-logger/level.go Normal file
View File

@@ -0,0 +1,390 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_logger
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
//Level a uint8 type customized with function to log message with the current log level
type Level uint8
const (
// PanicLevel Panic level for entry log, will result on a Panic() call (trace + fatal)
PanicLevel Level = iota
// FatalLevel Fatal level for entry log, will result on os.Exit with error
FatalLevel
// ErrorLevel Error level for entry log who's meaning the caller stop his process and return to the pre caller
ErrorLevel
// WarnLevel Warning level for entry log who's meaning the caller don't stop his process and try to continue it
WarnLevel
// InfoLevel Info level for entry log who's meaning it is just an information who's have no impact on caller's process but can be useful to inform human of a state, event, success, ...
InfoLevel
// DebugLevel Debug level for entry log who's meaning the caller has no problem and the information is only useful to identify a potential problem who's can arrive later
DebugLevel
// NilLevel Nil level will never log anything and is used to completely disable current log entry. It cannot be used in the SetLogLevel function
NilLevel
)
var (
curLevel = InfoLevel
)
//GetCurrentLevel return the current loglevel setting in the logger. All log entry matching this level or below will be logged
func GetCurrentLevel() Level {
return curLevel
}
// GetLevelListString return a list ([]string) of all string loglevel available
func GetLevelListString() []string {
return []string{
strings.ToLower(PanicLevel.String()),
strings.ToLower(FatalLevel.String()),
strings.ToLower(ErrorLevel.String()),
strings.ToLower(WarnLevel.String()),
strings.ToLower(InfoLevel.String()),
strings.ToLower(DebugLevel.String()),
}
}
// SetLevel Change the Level of all log entry with the Level type given in parameter. The change is apply for next log entry only
//
// If the given Level type is not matching a correct Level type, no change will be apply.
/*
level a Level type to use to specify the new level of logger message
*/
func SetLevel(level Level) {
switch level {
case PanicLevel:
curLevel = PanicLevel
logrus.SetLevel(logrus.PanicLevel)
case FatalLevel:
curLevel = FatalLevel
logrus.SetLevel(logrus.FatalLevel)
case ErrorLevel:
curLevel = ErrorLevel
logrus.SetLevel(logrus.ErrorLevel)
case WarnLevel:
curLevel = WarnLevel
logrus.SetLevel(logrus.WarnLevel)
case InfoLevel:
curLevel = InfoLevel
logrus.SetLevel(logrus.InfoLevel)
case DebugLevel:
curLevel = DebugLevel
logrus.SetLevel(logrus.DebugLevel)
}
DebugLevel.Logf("Change Log Level to %s", logrus.GetLevel().String())
}
// GetLevelString return a valid Level Type matching the given string parameter. If the given parameter don't represent a valid level, the InfoLevel will be return
/*
level the string representation of a Level type
*/
func GetLevelString(level string) Level {
switch strings.ToLower(level) {
case strings.ToLower(PanicLevel.String()):
return PanicLevel
case strings.ToLower(FatalLevel.String()):
return FatalLevel
case strings.ToLower(ErrorLevel.String()):
return ErrorLevel
case strings.ToLower(WarnLevel.String()):
return WarnLevel
case strings.ToLower(DebugLevel.String()):
return DebugLevel
default:
return InfoLevel
}
}
// Uint8 Convert the current Level type to a uint8 value. E.g. FatalLevel becomes 1.
func (level Level) Uint8() uint8 {
return uint8(level)
}
// String Convert the current Level type to a string. E.g. PanicLevel becomes "Critical Error".
func (level Level) String() string {
switch level {
case DebugLevel:
return "Debug"
case InfoLevel:
return "Info"
case WarnLevel:
return "Warning"
case ErrorLevel:
return "Error"
case FatalLevel:
return "Fatal Error"
case PanicLevel:
return "Critical Error"
}
return "unknown"
}
// Log Simple function to log directly the given message with the attached log Level
/*
message a string message to be logged with the attached log Level
*/
func (level Level) Log(message string) {
level.logDetails(message, nil, nil, nil)
}
// Logf Simple function to log (to the attached log Level) with a fmt function a given pattern and arguments in parameters
/*
format a string pattern for fmt function
args a list of interface to match the references in the pattern
*/
func (level Level) Logf(format string, args ...interface{}) {
level.logDetails(fmt.Sprintf(format, args...), nil, nil, nil)
}
// LogData Simple function to log directly the given message with given data with the attached log Level
/*
message a string message to be logged with the attached log Level
data an interface of data to be logged with the message. (In Text format, the data will be json marshalled)
*/
func (level Level) LogData(message string, data interface{}) {
level.logDetails(message, data, nil, nil)
}
// WithFields Simple function to log directly the given message with given fields with the attached log Level
/*
message a string message to be logged with the attached log Level
fields a map of string key and interfaces value for a complete list of field ("field name" => value interface)
*/
func (level Level) WithFields(message string, fields map[string]interface{}) {
level.logDetails(message, nil, nil, fields)
}
// LogError Simple function to log directly the given error with the attached log Level.
//
// How iot works :
// + when the err is a valid error, this function will :
// +--- log the Error with the attached log Level
// +--- return true
// + when the err is nil, this function will :
// +--- return false
/*
err an error object message to be logged with the attached log Level
*/
func (level Level) LogError(err error) bool {
return level.LogGinErrorCtx(NilLevel, "", err, nil)
}
// LogErrorCtx Function to test, log and inform about the given error object
//
// How iot works :
// + when the err is a valid error, this function will :
// +--- log the Error with the attached log Level
// +--- return true
// + when the err is nil, this function will :
// +--- use the levelElse if valid to inform with context there is no error found
// +--- return false
/*
levelElse level used if the err is nil before returning a False result
context a string for the context of the current test of the error
err a error object to be log with the attached log level before return true, if the err is nil, the levelElse is used to log there are no error and return false
*/
func (level Level) LogErrorCtx(levelElse Level, context string, err error) bool {
return level.LogGinErrorCtx(levelElse, context, err, nil)
}
// LogErrorCtxf Function to test, log and inform about the given error object, but with a context based on a pattern and matching args
//
// How iot works :
// + when the err is a valid error, this function will :
// +--- log the Error with the attached log Level
// +--- return true
// + when the err is nil, this function will :
// +--- use the levelElse if valid to inform with context there is no error found
// +--- return false
/*
levelElse level used if the err is nil before returning a False result
contextPattern a pattern string for the context of the current test of the error. This string will be used in a fmt function as pattern string
err a error object to be log with the attached log level before return true, if the err is nil, the levelElse is used to log there are no error and return false
args a list of interface for the context of the current test of the error. This list of interface will be used in a fmt function as the matching args for the pattern string
*/
func (level Level) LogErrorCtxf(levelElse Level, contextPattern string, err error, args ...interface{}) bool {
return level.LogGinErrorCtx(levelElse, fmt.Sprintf(contextPattern, args...), err, nil)
}
// LogGinErrorCtxf Function to test, log and inform about the given error object, but with a context based on a couple of pattern and matching args.
// This function will also add an Gin Tonic Error if the c parameters is a valid GinTonic Context reference.
//
// How iot works :
// + when the err is a valid error, this function will :
// +--- log the Error with the attached log Level
// +--- if the Context Gin Tonic is valid, add the Error into this context
// +--- return true
// + when the err is nil, this function will :
// +--- use the levelElse if valid to inform with context there is no error found
// +--- return false
/*
levelElse level used if the err is nil before returning a False result
contextPattern a pattern string for the context of the current test of the error. This string will be used in a fmt function as pattern string
err a error object to be log with the attached log level before return true, if the err is nil, the levelElse is used to log there are no error and return false
c a valid Go GinTonic Context reference to add current error to the Gin Tonic Error Context
args a list of interface for the context of the current test of the error. This list of interface will be used in a fmt function as the matching args for the pattern string
*/
func (level Level) LogGinErrorCtxf(levelElse Level, contextPattern string, err error, c *gin.Context, args ...interface{}) bool {
return level.LogGinErrorCtx(levelElse, fmt.Sprintf(contextPattern, args...), err, c)
}
// LogGinErrorCtx Function to test, log and inform about the given error object
// This function will also add an Gin Tonic Error if the c parameters is a valid GinTonic Context reference.
//
// How iot works :
// + when the err is a valid error, this function will :
// +--- log the Error with the attached log Level
// +--- if the Context Gin Tonic is valid, add the Error into this context
// +--- return true
// + when the err is nil, this function will :
// +--- use the levelElse if valid to inform with context there is no error found
// +--- return false
/*
levelElse level used if the err is nil before returning a False result
context a string for the context of the current test of the error
err a error object to be log with the attached log level before return true, if the err is nil, the levelElse is used to log there are no error and return false
c a valid Go GinTonic Context reference to add current error to the Gin Tonic Error Context
*/
func (level Level) LogGinErrorCtx(levelElse Level, context string, err error, c *gin.Context) bool {
if err != nil {
level.logDetails(fmt.Sprintf("KO : %s", context), nil, err, nil)
ginTonicAddError(c, err)
return true
} else if proceed(levelElse) {
levelElse.logDetails(fmt.Sprintf("OK : %s", context), nil, err, nil)
}
return false
}
func (level Level) logDetails(message string, data interface{}, err error, fields logrus.Fields) {
if !proceed(level) {
return
}
frame := getFrame()
tags := map[string]interface{}{
tagStack: getGID(),
tagTime: time.Now().Format(time.RFC3339Nano),
tagLevel: level.String(),
tagCaller: frame.Function,
tagFile: frame.File,
tagLine: frame.Line,
tagMsg: message,
tagErr: err,
tagData: data,
}
var (
ent = logrus.NewEntry(logrus.StandardLogger())
msg string
)
if fields != nil && len(fields) > 0 {
ent.WithFields(fields)
}
switch curFormat {
case TextFormat:
if tags[tagErr] != nil {
tags[tagErr] = fmt.Sprintf(" -- err : %v", err)
}
if tags[tagData] != nil {
if str, err := json.MarshalIndent(data, "", " "); err == nil {
tags[tagData] = fmt.Sprintf(" -- data : \n%s", string(str))
} else {
tags[tagData] = fmt.Sprintf(" -- data : %v", err)
}
}
if modeApi {
msg = fmt.Sprintf("[%d] [%s] [(%d) %s] %s%s%s", tags[tagStack], tags[tagCaller], tags[tagLine], tags[tagFile], tags[tagMsg], tags[tagErr], tags[tagData])
} else if level == DebugLevel {
msg = fmt.Sprintf("[%s] [(%d) %s] %s%s%s", tags[tagCaller], tags[tagLine], tags[tagFile], tags[tagMsg], tags[tagErr], tags[tagData])
} else {
msg = fmt.Sprintf("%s%s%s", tags[tagMsg], tags[tagErr], tags[tagData])
}
case JsonFormat:
if modeApi {
ent.WithFields(tags)
msg = tags[tagMsg].(string)
} else if level == DebugLevel {
ent.WithField(tagCaller, tags[tagCaller])
ent.WithField(tagLine, tags[tagLine])
ent.WithField(tagFile, tags[tagFile])
ent.WithField(tagMsg, tags[tagMsg])
ent.WithField(tagErr, tags[tagErr])
ent.WithField(tagData, tags[tagData])
msg = tags[tagMsg].(string)
} else {
ent.WithField(tagMsg, tags[tagMsg])
ent.WithField(tagErr, tags[tagErr])
ent.WithField(tagData, tags[tagData])
msg = tags[tagMsg].(string)
}
}
switch level {
case DebugLevel:
ent.Debugln(msg)
case InfoLevel:
ent.Infoln(msg)
case WarnLevel:
ent.Warnln(msg)
case ErrorLevel:
ent.Errorln(msg)
case FatalLevel:
ent.Fatalln(msg)
case PanicLevel:
ent.Panicln(msg)
}
}

148
njs-logger/logger.go Normal file
View File

@@ -0,0 +1,148 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_logger
import (
"log"
"path"
"reflect"
"runtime"
"strings"
"github.com/gin-gonic/gin"
"bytes"
"strconv"
)
const (
tagStack = "stack"
tagTime = "time"
tagLevel = "level"
tagCaller = "func"
tagFile = "file"
tagLine = "line"
tagMsg = "message"
tagErr = "error"
tagData = "data"
)
var (
currPkgs = path.Base(reflect.TypeOf(IOWriter{}).PkgPath())
modeApi = true
modeColor = true
)
// GetLogger return a golang log.logger instance linked with this main logger
//
// This function is useful to keep the format, mode, color, output... same as current config
/*
msgPrefixPattern a pattern prefix to identify or comment all message passed throw this log.logger instance
msgPrefixArgs a list of interface to apply on pattern with a fmt function
*/
func GetLogger(msgPrefixPattern string, msgPrefixArgs ...interface{}) *log.Logger {
return log.New(GetIOWriter(ErrorLevel, msgPrefixPattern, msgPrefixArgs...), "", 0)
}
// SetModeApi Reconfigure the current logger for an API (webserver) messages format.
//
// This mode is more details than the CLI mode. This apply only for next message
func SetModeApi() {
modeApi = true
updateFormatter(nilFormat)
}
// SetModeCli Reconfigure the current logger for an CLI (console) messages format.
//
// This mode is less details than the API mode. This apply only for next message
func SetModeCli() {
modeApi = false
updateFormatter(nilFormat)
}
// EnableColor Reconfigure the current logger to use color in messages format.
//
// This apply only for next message and only for TextFormat
func EnableColor() {
modeColor = true
updateFormatter(nilFormat)
}
// DisableColor Reconfigure the current logger to not use color in messages format.
//
// This apply only for next message and only for TextFormat
func DisableColor() {
modeColor = false
updateFormatter(nilFormat)
}
func getFrame() runtime.Frame {
// Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need
programCounters := make([]uintptr, 0)
n := runtime.Callers(0, programCounters)
if n > 0 {
frames := runtime.CallersFrames(programCounters[:n])
more := true
for more {
var (
frame runtime.Frame
)
frame, more = frames.Next()
if strings.Contains(frame.Function, currPkgs) {
continue
}
return frame
}
}
return runtime.Frame{Function: "unknown", File: "unknown", Line: 0}
}
func getGID() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64) // #nosec
return n
}
func ginTonicAddError(c *gin.Context, err error) {
if c != nil && err != nil {
_ = c.Error(err)
}
}
func proceed(lvl Level) bool {
return lvl != NilLevel && lvl <= curLevel
}

21
njs-password/LICENSE Normal file
View File

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

0
njs-password/README.md Normal file
View File

77
njs-password/password.go Normal file
View File

@@ -0,0 +1,77 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_password
import (
"math/rand"
"time"
)
const letterBytes = "abcdefghijklmnopqrstuvwxyz,;:.!&'(-_)=+/*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const (
// If we have 77 chars, that means 7 bits code a letter index.
// So 63 random bits can designate 63/7 = 9 different letter indices.
// Let's use all those 10
letterIdxBits = 7 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
var src = rand.NewSource(time.Now().UnixNano())
func init() {
rand.Seed(time.Now().UnixNano())
}
func randStringBytesMaskImprSrc(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func Generate(n int) string {
if n > 10 {
var s = ""
for i := n; i > 0; i -= 10 {
s += randStringBytesMaskImprSrc(10)
}
return s[0 : n-1]
}
return randStringBytesMaskImprSrc(n)
}

21
njs-router/LICENSE Normal file
View File

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

0
njs-router/README.md Normal file
View File

145
njs-router/auth.go Normal file
View File

@@ -0,0 +1,145 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_router
import (
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
njs_logger "github.com/nabbar/golib/njs-logger"
)
type AuthCode uint8
const (
AUTH_CODE_SUCCESS = iota
AUTH_CODE_REQUIRE
AUTH_CODE_FORBIDDEN
)
const (
HEAD_AUTH_REQR = "WWW-Authenticate"
HEAD_AUTH_SEND = "Authorization"
HEAD_AUTH_REAL = "Basic realm=LDAP Authorization Required"
)
func AuthRequire(c *gin.Context, err error) {
if err != nil {
c.Errors = append(c.Errors, &gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
}
// Credentials doesn't match, we return 401 and abort handlers chain.
c.Header(HEAD_AUTH_REQR, HEAD_AUTH_REAL)
c.AbortWithStatus(http.StatusUnauthorized)
}
func AuthForbidden(c *gin.Context, err error) {
if err != nil {
c.Errors = append(c.Errors, &gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
}
c.AbortWithStatus(http.StatusForbidden)
}
type authorization struct {
check func(AuthHeader string) (AuthCode, error)
router []gin.HandlerFunc
authType string
}
type Authorization interface {
Handler(c *gin.Context)
Register(router ...gin.HandlerFunc) gin.HandlerFunc
Append(router ...gin.HandlerFunc)
}
func NewAuthorization(HeadAuthType string, authCheckFunc func(AuthHeader string) (AuthCode, error)) Authorization {
return &authorization{
check: authCheckFunc,
authType: HeadAuthType,
router: make([]gin.HandlerFunc, 0),
}
}
func (a *authorization) Register(router ...gin.HandlerFunc) gin.HandlerFunc {
a.router = router
return a.Handler
}
func (a *authorization) Append(router ...gin.HandlerFunc) {
a.router = append(a.router, router...)
}
func (a authorization) Handler(c *gin.Context) {
// Search user in the slice of allowed credentials
auth := c.Request.Header.Get(HEAD_AUTH_SEND)
if auth == "" {
AuthRequire(c, fmt.Errorf("header '%s' is missing", HEAD_AUTH_SEND))
return
}
authValue := ""
if strings.ContainsAny(auth, " ") {
sAuth := strings.SplitN(auth, " ", 2)
if len(sAuth) == 2 && strings.ToUpper(sAuth[0]) == a.authType {
authValue = sAuth[1]
}
}
if authValue == "" {
AuthRequire(c, fmt.Errorf("reading authorization error : auth string is empty"))
return
} else {
code, err := a.check(authValue)
switch code {
case AUTH_CODE_SUCCESS:
for _, r := range a.router {
njs_logger.DebugLevel.Logf("Calling router '%s=%s'", c.Request.Method, c.Request.URL.RawPath)
r(c)
}
case AUTH_CODE_REQUIRE:
AuthRequire(c, fmt.Errorf("authorization error : %v", err))
case AUTH_CODE_FORBIDDEN:
AuthForbidden(c, fmt.Errorf("authorization error : %v", err))
default:
err := fmt.Errorf("auth response code is not valid")
c.Errors = append(c.Errors, &gin.Error{
Err: err,
Type: gin.ErrorTypePrivate,
})
c.AbortWithStatus(http.StatusInternalServerError)
}
}
}

111
njs-router/headers.go Normal file
View File

@@ -0,0 +1,111 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_router
import (
"net/http"
"github.com/gin-gonic/gin"
)
type headers struct {
head http.Header
}
type Headers interface {
Add(key, value string)
Set(key, value string)
Get(key string) string
Del(key string)
Header() map[string]string
Register(router ...gin.HandlerFunc) []gin.HandlerFunc
Handler(c *gin.Context)
Clone() Headers
}
func NewHeaders() Headers {
return &headers{}
}
func (h headers) Clone() Headers {
return &headers{
head: h.head,
}
}
func (h headers) Register(router ...gin.HandlerFunc) []gin.HandlerFunc {
res := make([]gin.HandlerFunc, 0)
res = append(res, h.Handler)
res = append(res, router...)
return res
}
func (h headers) Header() map[string]string {
res := make(map[string]string)
for k := range h.head {
res[k] = h.head.Get(k)
}
return res
}
func (h headers) Handler(c *gin.Context) {
for k := range h.head {
c.Header(k, h.head.Get(k))
}
}
// Add adds the key, value pair to the header.
// It appends to any existing values associated with key.
func (h headers) Add(key, value string) {
h.head.Add(key, value)
}
// Set sets the header entries associated with key to
// the single element value. It replaces any existing
// values associated with key.
func (h headers) Set(key, value string) {
h.head.Set(key, value)
}
// Get gets the first value associated with the given key.
// It is case insensitive; textproto.CanonicalMIMEHeaderKey is used
// to canonicalize the provided key.
// If there are no values associated with the key, Get returns "".
// To access multiple values of a key, or to use non-canonical keys,
// access the map directly.
func (h headers) Get(key string) string {
return h.head.Get(key)
}
// Del deletes the values associated with key.
func (h headers) Del(key string) {
h.head.Del(key)
}

79
njs-router/register.go Normal file
View File

@@ -0,0 +1,79 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_router
import (
"github.com/gin-gonic/gin"
)
var (
defaultRouters = NewRouterList()
)
type routerItem struct {
method string
relative string
router []gin.HandlerFunc
}
type routerList struct {
list []routerItem
}
type RegisterRouter func(method string, relativePath string, router ...gin.HandlerFunc)
type RouterList interface {
Register(method string, relativePath string, router ...gin.HandlerFunc)
Handler(handle func(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes)
}
func RoutersRegister(method string, relativePath string, router ...gin.HandlerFunc) {
defaultRouters.Register(method, relativePath, router...)
}
func RoutersHandler(handle func(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes) {
defaultRouters.Handler(handle)
}
func NewRouterList() RouterList {
return &routerList{
list: make([]routerItem, 0),
}
}
func (l routerList) Handler(handle func(httpMethod, relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes) {
for _, r := range l.list {
handle(r.method, r.relative, r.router...)
}
}
func (l *routerList) Register(method string, relativePath string, router ...gin.HandlerFunc) {
l.list = append(l.list, routerItem{
method: method,
relative: relativePath,
router: router,
})
}

56
njs-router/router.go Normal file
View File

@@ -0,0 +1,56 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_router
import (
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func init() {
if os.Getenv("GIN_MODE") == "" {
gin.SetMode(gin.ReleaseMode)
}
}
func SetGinHnadler(fct func(c *gin.Context)) gin.HandlerFunc {
return fct
}
func Handler(routerList RouterList) http.Handler {
engine := gin.New()
engine.Use(gin.Logger(), gin.Recovery())
if routerList == nil {
RoutersHandler(engine.Handle)
} else {
routerList.Handler(engine.Handle)
}
return engine
}

21
njs-static/LICENSE Normal file
View File

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

0
njs-static/README.md Normal file
View File

181
njs-static/static.go Normal file
View File

@@ -0,0 +1,181 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_static
import (
"bytes"
"fmt"
"mime"
"net/http"
"path/filepath"
"strings"
njs_router "github.com/nabbar/golib/njs-router"
"github.com/gin-gonic/gin/render"
njs_logger "github.com/nabbar/golib/njs-logger"
"github.com/gin-gonic/gin"
"github.com/gobuffalo/packr"
)
const (
FileIndex = "index.html"
)
type staticHandler struct {
box packr.Box
debug bool
index bool
prefix string
download []string
allDwnld bool
head func() map[string]string
}
type Static interface {
Register(register njs_router.RegisterRouter)
SetDownloadAll()
SetDownload(file string)
IsDownload(file string) bool
Has(file string) bool
Find(file string) ([]byte, error)
Health() error
Get(c *gin.Context)
}
func NewStatic(hasIndex bool, prefix string, box packr.Box, Header func() map[string]string) Static {
return &staticHandler{
box: box,
debug: false,
index: hasIndex,
prefix: "/" + strings.Trim(prefix, "/"),
head: Header,
download: make([]string, 0),
}
}
func (s staticHandler) Register(register njs_router.RegisterRouter) {
if s.prefix == "/" {
for _, f := range s.box.List() {
register(http.MethodGet, s.prefix+f, s.Get)
}
} else {
register(http.MethodGet, s.prefix, s.Get)
register(http.MethodGet, s.prefix+"/*file", s.Get)
}
}
func (s staticHandler) print() {
if s.debug {
return
}
for _, f := range s.box.List() {
njs_logger.DebugLevel.Logf("Embedded file : %s", f)
}
s.debug = true
}
func (s staticHandler) Health() error {
s.print()
if len(s.box.List()) < 1 {
return fmt.Errorf("empty packed file stored")
}
if s.index && !s.box.Has("index.html") && !s.box.Has("index.htm") {
return fmt.Errorf("cannot find 'index.html' file")
}
return nil
}
func (s staticHandler) Has(file string) bool {
return s.box.Has(file)
}
func (s staticHandler) Find(file string) ([]byte, error) {
return s.box.Find(file)
}
func (s staticHandler) Get(c *gin.Context) {
partPath := strings.SplitN(c.Request.URL.Path, s.prefix, 2)
requestPath := partPath[1]
requestPath = strings.TrimLeft(requestPath, "./")
requestPath = strings.Trim(requestPath, "/")
calledFile := filepath.Base(requestPath)
if requestPath == "" || requestPath == "/" {
if s.index {
calledFile = FileIndex
requestPath = FileIndex
} else {
c.Abort()
return
}
}
if obj, err := s.box.Find(requestPath); !njs_logger.ErrorLevel.LogErrorCtxf(njs_logger.NilLevel, "find file '%s' error for request '%s%s' :", err, calledFile, s.prefix, requestPath) {
head := s.head()
if s.allDwnld || s.IsDownload(requestPath) {
head["Content-Disposition"] = fmt.Sprintf("attachment; filename=\"%s\"", calledFile)
}
c.Render(http.StatusOK, render.Reader{
ContentLength: int64(len(obj)),
ContentType: mime.TypeByExtension(filepath.Ext(calledFile)),
Headers: head,
Reader: bytes.NewReader(obj),
})
} else {
c.Abort()
}
}
func (s *staticHandler) SetDownload(file string) {
s.download = append(s.download, file)
}
func (s *staticHandler) SetDownloadAll() {
s.allDwnld = true
}
func (s staticHandler) IsDownload(file string) bool {
for _, f := range s.download {
if f == file {
return true
}
}
return false
}

21
njs-status/LICENSE Normal file
View File

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

0
njs-status/README.md Normal file
View File

180
njs-status/status.go Normal file
View File

@@ -0,0 +1,180 @@
/*
* MIT License
*
* Copyright (c) 2019 Nicolas JUHEL
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package njs_status
import (
"fmt"
"net/http"
"strings"
njs_router "github.com/nabbar/golib/njs-router"
njs_version "github.com/nabbar/golib/njs-version"
"github.com/gin-gonic/gin"
)
type StatusItemResponse struct {
Name string
Status string
Message string
Release string
HashBuild string
}
type StatusResponse struct {
StatusItemResponse
Partner []StatusItemResponse
}
const statusOK = "OK"
const statusKO = "KO"
type statusItem struct {
name string
build string
msgOK string
msgKO string
health func() error
release string
}
type statusPartner struct {
statusItem
WarnIfErr bool
}
type mainPackage struct {
statusItem
ptn []statusPartner
header func(c *gin.Context)
}
type Status interface {
Register(prefix string, register njs_router.RegisterRouter)
AddPartner(name, msgOK, msgKO, release, build string, WarnIfError bool, health func() error)
AddVersionPartner(vers njs_version.Version, msgOK, msgKO string, WarnIfError bool, health func() error)
Get(c *gin.Context)
}
func NewStatus(name, msgOK, msgKO, release, build string, health func() error, Header func(c *gin.Context)) Status {
return &mainPackage{
newItem(name, msgOK, msgKO, release, build, health),
make([]statusPartner, 0),
Header,
}
}
func NewVersionStatus(vers njs_version.Version, msgOK, msgKO string, health func() error, Header func(c *gin.Context)) Status {
return NewStatus(vers.GetPackage(), msgOK, msgKO, vers.GetRelease(), vers.GetBuild(), health, Header)
}
func newItem(name, msgOK, msgKO, release, build string, health func() error) statusItem {
return statusItem{
name: name,
build: build,
msgOK: msgOK,
msgKO: msgKO,
health: health,
release: release,
}
}
func (p *mainPackage) AddPartner(name, msgOK, msgKO, release, build string, WarnIfError bool, health func() error) {
p.ptn = append(p.ptn, statusPartner{
newItem(name, msgOK, msgKO, release, build, health),
WarnIfError,
})
}
func (p *mainPackage) AddVersionPartner(vers njs_version.Version, msgOK, msgKO string, WarnIfError bool, health func() error) {
p.AddPartner(vers.GetPackage(), msgOK, msgKO, vers.GetRelease(), vers.GetBuild(), WarnIfError, health)
}
func (s mainPackage) Register(prefix string, register njs_router.RegisterRouter) {
prefix = "/" + strings.Trim(prefix, "/")
register(http.MethodGet, prefix, s.header, s.Get)
if prefix != "/" {
register(http.MethodGet, prefix+"/", s.header, s.Get)
}
}
func (p statusItem) GetStatusResponse(c *gin.Context) StatusItemResponse {
res := StatusItemResponse{
Name: p.name,
Status: statusOK,
Message: p.msgOK,
Release: p.release,
HashBuild: p.build,
}
if p.health != nil {
if err := p.health(); err != nil {
msg := fmt.Sprintf("%s: %v", p.msgKO, err)
c.Errors = append(c.Errors, &gin.Error{
Err: fmt.Errorf(msg),
Type: gin.ErrorTypePrivate,
})
res = StatusItemResponse{
Name: p.name,
Status: statusKO,
Message: msg,
Release: p.release,
HashBuild: p.build,
}
}
}
return res
}
func (p mainPackage) Get(c *gin.Context) {
hasError := false
res := StatusResponse{
p.GetStatusResponse(c),
make([]StatusItemResponse, 0),
}
for _, pkg := range p.ptn {
pres := pkg.GetStatusResponse(c)
if res.Status == statusOK && pres.Status == statusKO && !pkg.WarnIfErr {
res.Status = statusKO
} else if pres.Status == statusKO {
hasError = true
}
res.Partner = append(res.Partner, pres)
}
if res.Status != statusOK {
c.AbortWithStatusJSON(http.StatusInternalServerError, &res)
} else if hasError {
c.JSON(http.StatusMultiStatus, &res)
} else {
c.JSON(http.StatusOK, &res)
}
}

21
njs-version/LICENSE Normal file
View File

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

0
njs-version/README.md Normal file
View File

283
njs-version/license.go Normal file
View File

@@ -0,0 +1,283 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
import "fmt"
type license uint8
const (
License_MIT license = iota
License_GNU_GPL_v3
License_GNU_Affero_GPL_v3
License_GNU_Lesser_GPL_v3
License_Mozilla_PL_v2
License_Apache_v2
License_Unlicense
License_Creative_Common_Zero_v1
License_Creative_Common_Attribution_v4_int
License_Creative_Common_Attribution_Share_Alike_v4_int
License_SIL_Open_Font_1_1
)
func (lic license) GetBoilerPlate(Package, Description, Year, Author string) string {
switch lic {
case License_Apache_v2:
return boiler_Apache2(Year, Author)
case License_GNU_Affero_GPL_v3:
return boiler_AGPLv3(Package, Description, Year, Author)
case License_GNU_GPL_v3:
return boiler_GPLv3(Package, Description, Year, Author)
case License_GNU_Lesser_GPL_v3:
return boiler_LGPLv3(Package, Description, Year, Author)
case License_MIT:
return boiler_MIT(Year, Author)
case License_Mozilla_PL_v2:
return boiler_MPLv2(Package, Year, Author)
case License_Unlicense:
return boiler_Unlicence()
case License_Creative_Common_Zero_v1:
return boiler_CC0v1(Year, Author)
case License_Creative_Common_Attribution_v4_int:
return boiler_CC_BY_4(Year, Author)
case License_Creative_Common_Attribution_Share_Alike_v4_int:
return boiler_CC_SA_4(Year, Author)
case License_SIL_Open_Font_1_1:
return boiler_SIL_OFL_11(Year, Author)
}
return ""
}
func (lic license) GetLicense() string {
switch lic {
case License_Apache_v2:
return licence_apache2()
case License_GNU_Affero_GPL_v3:
return licence_agpl_v3()
case License_GNU_GPL_v3:
return licence_gpl_v3()
case License_GNU_Lesser_GPL_v3:
return licence_lgpl_v3()
case License_MIT:
return license_mit()
case License_Mozilla_PL_v2:
return license_mozilla_v2()
case License_Unlicense:
return boiler_Unlicence()
case License_Creative_Common_Zero_v1:
return licence_cc0_v1()
case License_Creative_Common_Attribution_v4_int:
return license_cc_by_4()
case License_Creative_Common_Attribution_Share_Alike_v4_int:
return license_cc_sa_4()
case License_SIL_Open_Font_1_1:
return license_sil_ofl_v11()
}
return ""
}
func boiler_MIT(Year, Author string) string {
return fmt.Sprintf(`
MIT License
Copyright (c) %s %s
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`, Year, Author)
}
func boiler_AGPLv3(Package, Description, Year, Author string) string {
return fmt.Sprintf(`
%s %s
Copyright (C) %s %s
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
`, Package, Description, Year, Author)
}
func boiler_GPLv3(Package, Description, Year, Author string) string {
return fmt.Sprintf(`
%s %s
Copyright (C) %s %s
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.
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 <https://www.gnu.org/licenses/>.
`, Package, Description, Year, Author)
}
func boiler_LGPLv3(Package, Description, Year, Author string) string {
return fmt.Sprintf(`
%s %s
Copyright (C) %s %s
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License.
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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
`, Package, Description, Year, Author)
}
func boiler_MPLv2(Package, Year, Author string) string {
return fmt.Sprintf(`
Copyright (C) %s %s
This material '%s' is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
`, Year, Author, Package)
}
func boiler_Apache2(year, author string) string {
return fmt.Sprintf(`
Copyright %s %s
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
`, year, author)
}
func boiler_Unlicence() string {
return `
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
`
}
func boiler_CC0v1(Year, Author string) string {
return fmt.Sprintf(`
Copyright %s by %s
To the extent possible under law, the author(s) have dedicated all
copyright and related and neighboring rights to this software to the
public domain worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication
along with this software. If not, see
<http://creativecommons.org/publicdomain/zero/1.0/>.
`, Year, Author)
}
func boiler_CC_BY_4(Year, Author string) string {
return fmt.Sprintf(`
Copyright %s by %s
The text of and illustrations in this document are licensed under a
Creative Commons Attribution 4.0 International Public License ("CC-BY-4.0").
`, Year, Author)
}
func boiler_CC_SA_4(Year, Author string) string {
return fmt.Sprintf(`
Copyright %s by %s
The text of and illustrations in this document are licensed under a
Creative Commons Attribution Share Alike 4.0 International Public License ("CC-SA-4.0").
`, Year, Author)
}
func boiler_SIL_OFL_11(Year, Author string) string {
return fmt.Sprintf(`
Copyright (c) %s %s
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
`, Year, Author)
}

View File

@@ -0,0 +1,649 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func licence_agpl_v3() string {
return `
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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
`
}

View File

@@ -0,0 +1,206 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func licence_apache2() string {
return `
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
`
}

View File

@@ -0,0 +1,425 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func license_cc_by_4() string {
return `
Attribution 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution 4.0 International Public License ("Public License"). To the
extent this Public License may be interpreted as a contract, You are
granted the Licensed Rights in consideration of Your acceptance of
these terms and conditions, and the Licensor grants You such rights in
consideration of benefits the Licensor receives from making the
Licensed Material available under these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
d. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
g. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
`
}

View File

@@ -0,0 +1,457 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func license_cc_sa_4() string {
return `
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
`
}

View File

@@ -0,0 +1,146 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func licence_cc0_v1() string {
return `
CC0 1.0 Universal
Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.
For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.
1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.
2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.
3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.
4. Limitations and Disclaimers.
a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.
For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>
`
}

View File

@@ -0,0 +1,651 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func licence_gpl_v3() string {
return `
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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
`
}

View File

@@ -0,0 +1,195 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func licence_lgpl_v3() string {
return `
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
`
}

View File

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

View File

@@ -0,0 +1,403 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func license_mozilla_v2() string {
return `
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
`
}

View File

@@ -0,0 +1,116 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
func license_sil_ofl_v11() string {
return `
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
`
}

221
njs-version/version.go Normal file
View File

@@ -0,0 +1,221 @@
/*
MIT License
Copyright (c) 2019 Nicolas JUHEL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package njs_version
import (
"bytes"
"fmt"
"path"
"reflect"
"runtime"
"time"
"strings"
govers "github.com/hashicorp/go-version"
)
type versionModel struct {
versionRelease string
versionBuild string
versionDate string
versionPackage string
versionDescription string
versionAuthor string
versionPrefix string
versionSource string
licenceType license
}
type Version interface {
CheckGo(RequireGoVersion, RequireGoContraint string) error
GetAppId() string
GetAuthor() string
GetBuild() string
GetDescription() string
GetHeader() string
GetInfo() string
GetPackage() string
GetPrefix() string
GetRelease() string
GetLicenseLegal(addMoreLicence ...license) string
GetLicenseFull(addMoreLicence ...license) string
GetLicenseBoiler(addMoreLicence ...license) string
PrintInfo()
PrintLicense(addlicence ...license)
}
func NewVersion(License license, Package, Description, Date, Build, Release, Author, Prefix string, emptyInterface interface{}, numSubPackage int) Version {
rfl := reflect.TypeOf(emptyInterface)
//println("reflect typeOf name : " + rfl.Name())
//println("reflect typeOf package path : " + rfl.PkgPath())
Source := rfl.PkgPath()
for i := 1; i <= numSubPackage; i++ {
Source = path.Dir(Source)
}
if Package == "" || Package == "noname" {
Package = path.Base(Source)
}
return &versionModel{
versionRelease: Release,
versionBuild: Build,
versionDate: Date,
versionPackage: Package,
versionDescription: Description,
versionAuthor: Author,
versionPrefix: Prefix,
versionSource: Source,
licenceType: License,
}
}
func (vers versionModel) CheckGo(RequireGoVersion, RequireGoContraint string) error {
constraint, err := govers.NewConstraint(RequireGoContraint + RequireGoVersion)
if err != nil {
return fmt.Errorf("cannot init GoVersion contraint : %v", err)
}
goVersion, err := govers.NewVersion(runtime.Version()[2:])
if err != nil {
return fmt.Errorf("cannot extract GoVersion runtime : %v", err)
}
if !constraint.Check(goVersion) {
return fmt.Errorf("%s is not compiled with Go %s, please use Go %s to recompile", vers.versionPackage, goVersion, RequireGoVersion)
}
return nil
}
func (vers versionModel) getYearOfDate() string {
dt, err := time.Parse(time.RFC3339, vers.versionDate)
if err != nil {
dt = time.Now()
}
return fmt.Sprintf("%d", dt.Year())
}
// Info print all information about current build and version
func (vers versionModel) PrintInfo() {
println(fmt.Sprintf("Running %s", vers.GetHeader()))
}
// GetInfo return string about current build and version
func (vers versionModel) GetInfo() string {
return fmt.Sprintf("Release: %s, Build: %s, Date: %s", vers.versionRelease, vers.versionBuild, vers.versionDate)
}
// GetAppId return string about package name, release and runtime info
func (vers versionModel) GetAppId() string {
return fmt.Sprintf("%s (OS: %s; Arch: %s; Runtime: %s)", vers.versionRelease, runtime.GOOS, runtime.GOARCH, runtime.Version()[2:])
}
// GetAuthor return string about author name and repository info
func (vers versionModel) GetAuthor() string {
return fmt.Sprintf("by %s (source : %s)", vers.versionAuthor, vers.versionSource)
}
func (vers versionModel) GetDescription() string {
return vers.versionDescription
}
// GetAuthor return string about author name and repository info
func (vers versionModel) GetHeader() string {
return fmt.Sprintf("%s (%s)", vers.versionPackage, vers.GetInfo())
}
func (vers versionModel) GetBuild() string {
return vers.versionBuild
}
func (vers versionModel) GetPackage() string {
return vers.versionPackage
}
func (vers versionModel) GetPrefix() string {
return strings.ToUpper(vers.versionPrefix)
}
func (vers versionModel) GetRelease() string {
return vers.versionRelease
}
func (vers versionModel) GetLicenseLegal(addMoreLicence ...license) string {
if len(addMoreLicence) == 0 {
return vers.licenceType.GetLicense()
}
buff := bytes.NewBufferString(vers.licenceType.GetLicense())
for _, l := range addMoreLicence {
_, _ = buff.WriteString("\n\n") // #nosec
_, _ = buff.WriteString(strings.Repeat("*", 80)) // #nosec
_, _ = buff.WriteString(strings.Repeat("*", 80)) // #nosec
_, _ = buff.WriteString("\n\n") // #nosec
_, _ = buff.WriteString(l.GetLicense()) // #nosec
}
return buff.String()
}
func (vers versionModel) GetLicenseFull(addMoreLicence ...license) string {
buff := bytes.NewBufferString(vers.GetLicenseBoiler(addMoreLicence...))
_, _ = buff.WriteString("\n\n") // #nosec
_, _ = buff.WriteString(strings.Repeat("*", 80)) // #nosec
_, _ = buff.WriteString(strings.Repeat("*", 80)) // #nosec
_, _ = buff.WriteString("\n\n") // #nosec
_, _ = buff.WriteString(vers.GetLicenseLegal(addMoreLicence...)) // #nosec
return buff.String()
}
func (vers versionModel) GetLicenseBoiler(addMoreLicence ...license) string {
if len(addMoreLicence) == 0 {
return vers.licenceType.GetBoilerPlate(vers.versionPackage, vers.versionDescription, vers.getYearOfDate(), vers.versionAuthor)
}
year := vers.getYearOfDate()
buff := bytes.NewBufferString(vers.licenceType.GetBoilerPlate(vers.versionPackage, vers.versionDescription, year, vers.versionAuthor))
for _, l := range addMoreLicence {
_, _ = buff.WriteString("\n\n") // #nosec
_, _ = buff.WriteString(l.GetBoilerPlate(vers.versionPackage, vers.versionDescription, year, vers.versionAuthor)) // #nosec
}
return buff.String()
}
func (vers versionModel) PrintLicense(addMoreLicence ...license) {
println(vers.GetLicenseBoiler(addMoreLicence...))
}