Compare commits
212 Commits
20211026.2
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fac3aa3098 | ||
|
|
7341b404af | ||
|
|
890b9210c0 | ||
|
|
50233633a5 | ||
|
|
c309a8fc58 | ||
|
|
0cc52eee46 | ||
|
|
8131751045 | ||
|
|
56076bc107 | ||
|
|
fbd60c320b | ||
|
|
9a152ef3b3 | ||
|
|
11d0d8ac67 | ||
|
|
475b6b8ef8 | ||
|
|
44cd26db29 | ||
|
|
6e7015b3eb | ||
|
|
54f5aa75e5 | ||
|
|
e395971cfd | ||
|
|
37d428cdf5 | ||
|
|
7da8e5e9ab | ||
|
|
fee1f1a67d | ||
|
|
df4cd39c57 | ||
|
|
2c0ee146ee | ||
|
|
4eaab6b0e0 | ||
|
|
c0e3512a23 | ||
|
|
6ecc586aaa | ||
|
|
b84d19d11f | ||
|
|
d471db7f6c | ||
|
|
c198541542 | ||
|
|
f6d3341085 | ||
|
|
5274fd73f2 | ||
|
|
01798bb978 | ||
|
|
70b6aed937 | ||
|
|
488f8e4aa2 | ||
|
|
a4634a63b2 | ||
|
|
8b327fdbab | ||
|
|
e849e933a0 | ||
|
|
bf9f639dce | ||
|
|
c14ce15f5d | ||
|
|
0b504445ea | ||
|
|
553324103e | ||
|
|
46dd8a04d2 | ||
|
|
a0992a39e4 | ||
|
|
c27487330e | ||
|
|
bacd610e7d | ||
|
|
38fbd4ead9 | ||
|
|
f3c55a99c2 | ||
|
|
1f725a816f | ||
|
|
6e4e588bec | ||
|
|
9aee12a948 | ||
|
|
763d57d142 | ||
|
|
8c80934f70 | ||
|
|
971f1cc9c4 | ||
|
|
7b8a219237 | ||
|
|
0c155736b5 | ||
|
|
af349be575 | ||
|
|
439482cc04 | ||
|
|
e6f0ad39db | ||
|
|
7c4d2eac3c | ||
|
|
e85b925581 | ||
|
|
0b5b6818ad | ||
|
|
07612794be | ||
|
|
e2c7a199d2 | ||
|
|
b2a0c3885c | ||
|
|
7346a983e8 | ||
|
|
e2a643ddaf | ||
|
|
bd349e28f8 | ||
|
|
1683280c45 | ||
|
|
58c6aa5702 | ||
|
|
b362647ef3 | ||
|
|
f1d4f43fc7 | ||
|
|
585e970906 | ||
|
|
88d068a452 | ||
|
|
6cd395e190 | ||
|
|
4e710699f4 | ||
|
|
49f9422525 | ||
|
|
4513b84ec9 | ||
|
|
595761d045 | ||
|
|
7f0cb911a1 | ||
|
|
5acaafb691 | ||
|
|
613fbf8d61 | ||
|
|
ef8e1fc21b | ||
|
|
5c315eeffe | ||
|
|
58d637d212 | ||
|
|
216fd2d8f3 | ||
|
|
201a0192be | ||
|
|
73fa1f317b | ||
|
|
27f2a7ce76 | ||
|
|
35d96545fb | ||
|
|
879b9be298 | ||
|
|
61bac85a3d | ||
|
|
ce689bf154 | ||
|
|
27ad3fa481 | ||
|
|
a112241c76 | ||
|
|
555f4f8c5f | ||
|
|
ff7fdf4350 | ||
|
|
0ab8841cd1 | ||
|
|
ae899e1ed0 | ||
|
|
10c8000e18 | ||
|
|
96ad176c96 | ||
|
|
18c231c469 | ||
|
|
6dbfa84fc3 | ||
|
|
419deb34c1 | ||
|
|
a4f3fc6bd4 | ||
|
|
8e1251ab4f | ||
|
|
193c34d325 | ||
|
|
8aeed47955 | ||
|
|
374c2b74ad | ||
|
|
c50302622e | ||
|
|
144e58aa7a | ||
|
|
81ab381551 | ||
|
|
d9202cfca6 | ||
|
|
7c55c713a0 | ||
|
|
5bb568e6e5 | ||
|
|
1ff33d19b7 | ||
|
|
41d0618fa2 | ||
|
|
0750caa4e9 | ||
|
|
ebabfd3790 | ||
|
|
fdf9842025 | ||
|
|
2773554b0a | ||
|
|
288c04f5e8 | ||
|
|
2fb8972eb3 | ||
|
|
43cf7695f1 | ||
|
|
ae2f8c4baf | ||
|
|
642ee0513e | ||
|
|
7f6b6718e1 | ||
|
|
7f0f69d7b5 | ||
|
|
b90cdfc2a1 | ||
|
|
e8f7a1b0bb | ||
|
|
7d78f5161e | ||
|
|
46e5a624be | ||
|
|
5e4c3bb21a | ||
|
|
75d7307134 | ||
|
|
ece420b56b | ||
|
|
c87861b4d6 | ||
|
|
69ea717d13 | ||
|
|
ff87416602 | ||
|
|
231518cb79 | ||
|
|
0950175e43 | ||
|
|
d7c0c2ed79 | ||
|
|
e8d7ae0889 | ||
|
|
9aa7040976 | ||
|
|
5d6b1cdfe2 | ||
|
|
feadcf47e9 | ||
|
|
13a22dce68 | ||
|
|
b91fe8ab0c | ||
|
|
1d868a27a8 | ||
|
|
17aa4a6a89 | ||
|
|
7a3b02b445 | ||
|
|
492db60e81 | ||
|
|
5bc042c0a5 | ||
|
|
32c599c3a5 | ||
|
|
5f597b596b | ||
|
|
09833807a8 | ||
|
|
fad9a4cded | ||
|
|
55c96bb2c7 | ||
|
|
0bb4f046ca | ||
|
|
33c78444a0 | ||
|
|
0f9201e8c2 | ||
|
|
83c285c50f | ||
|
|
618b56d4ad | ||
|
|
0253c84d3d | ||
|
|
ba136c2da2 | ||
|
|
bb0c49d980 | ||
|
|
83f0b1b3b9 | ||
|
|
e08a37694f | ||
|
|
9432d96e4d | ||
|
|
522434b2d0 | ||
|
|
c303f3912d | ||
|
|
705922a619 | ||
|
|
c03c28d4e2 | ||
|
|
5c999d5fda | ||
|
|
9a0fa8eb42 | ||
|
|
db59b50993 | ||
|
|
26d3a80d97 | ||
|
|
c36d5087d4 | ||
|
|
32d26e664d | ||
|
|
abe3248e2e | ||
|
|
5dddbfce7b | ||
|
|
f08ff9d409 | ||
|
|
5694be560d | ||
|
|
925addace2 | ||
|
|
5a7abc0ed6 | ||
|
|
3a741ec512 | ||
|
|
8be1fd752e | ||
|
|
d09a38eca5 | ||
|
|
fa586b6b01 | ||
|
|
c60f91900b | ||
|
|
f5307aef4b | ||
|
|
015f50b5f7 | ||
|
|
f91eed84db | ||
|
|
970d1ca866 | ||
|
|
c0737a289d | ||
|
|
34a0b876f7 | ||
|
|
1938f71181 | ||
|
|
de24030f6b | ||
|
|
a9fc78fad1 | ||
|
|
3138045c76 | ||
|
|
ff985bb80e | ||
|
|
5bf122f623 | ||
|
|
fcbf3b7daf | ||
|
|
171b1b0c51 | ||
|
|
596c9312ec | ||
|
|
a0eaf9ec3a | ||
|
|
a0d38582f8 | ||
|
|
9354bf7c76 | ||
|
|
60ce18914d | ||
|
|
daf09ba161 | ||
|
|
d0c6835db2 | ||
|
|
0257de1195 | ||
|
|
1af3f66039 | ||
|
|
31cf50b63f | ||
|
|
de031db282 | ||
|
|
49707775bc |
19
.github/dependabot.yml
vendored
Normal file
19
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "gomod"
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
22
.github/workflows/docker-hub-description.yml
vendored
Normal file
22
.github/workflows/docker-hub-description.yml
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
name: Update Docker Hub description
|
||||
|
||||
on:
|
||||
release:
|
||||
types:
|
||||
- created
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Update Docker Hub description
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
- name: Update Docker Hub description
|
||||
uses: peter-evans/dockerhub-description@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
||||
repository: ${{ github.repository }}
|
||||
short-description: ${{ github.event.repository.description }}
|
||||
60
.github/workflows/on-push.yml
vendored
Normal file
60
.github/workflows/on-push.yml
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
name: On push
|
||||
|
||||
on:
|
||||
push:
|
||||
branches-ignore:
|
||||
- release
|
||||
paths-ignore:
|
||||
- 'dashboard/*'
|
||||
- 'examples/*'
|
||||
- 'README.md'
|
||||
- 'LICENSE'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7"
|
||||
|
||||
jobs:
|
||||
build_and_push:
|
||||
name: Build and push Docker image
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3.2.0
|
||||
- name: Login to docker hub
|
||||
uses: docker/login-action@v3.0.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3.0.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ github.token }}
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
${{ github.repository }}-development
|
||||
ghcr.io/${{ github.repository }}-development
|
||||
tags: |
|
||||
type=raw,value=dev-{{date 'X'}}
|
||||
type=raw,value=latest
|
||||
type=ref,event=branch
|
||||
type=edge,branch=main
|
||||
- name: Build and push ${{ github.repository }}:${{ steps.git.outputs.image_tag }}
|
||||
uses: docker/build-push-action@v5.1.0
|
||||
with:
|
||||
platforms: ${{ env.PLATFORMS }}
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
provenance: false
|
||||
|
||||
|
||||
49
.github/workflows/on-release.yml
vendored
Normal file
49
.github/workflows/on-release.yml
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
name: On release
|
||||
|
||||
on:
|
||||
release:
|
||||
types: # This configuration does not affect the page_build event above
|
||||
- created
|
||||
env:
|
||||
PLATFORMS: "linux/amd64,linux/arm64,linux/arm/v7"
|
||||
|
||||
jobs:
|
||||
build_and_push:
|
||||
name: Build and push Docker image
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3.2.0
|
||||
- name: Login to docker hub
|
||||
uses: docker/login-action@v3.0.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_PASSWORD }}
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3.0.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ github.token }}
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
${{ github.repository }}
|
||||
ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=tag
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5.1.0
|
||||
with:
|
||||
platforms: ${{ env.PLATFORMS }}
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
provenance: false
|
||||
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
endlessh-go
|
||||
20
Dockerfile
Normal file
20
Dockerfile
Normal file
@@ -0,0 +1,20 @@
|
||||
FROM golang AS build
|
||||
|
||||
RUN mkdir /endlessh
|
||||
ADD . /endlessh
|
||||
WORKDIR /endlessh
|
||||
RUN go mod tidy
|
||||
RUN CGO_ENABLED=0 go build -o endlessh .
|
||||
|
||||
FROM gcr.io/distroless/base
|
||||
|
||||
LABEL org.opencontainers.image.title=endlessh-go
|
||||
LABEL org.opencontainers.image.description="Endlessh: an SSH tarpit"
|
||||
LABEL org.opencontainers.image.vendor="Shizun Ge"
|
||||
LABEL org.opencontainers.image.licenses=GPLv3
|
||||
|
||||
COPY --from=build /endlessh/endlessh /endlessh
|
||||
EXPOSE 2222 2112
|
||||
USER nobody
|
||||
ENTRYPOINT ["/endlessh"]
|
||||
CMD ["-logtostderr", "-v=1"]
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
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
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
125
README.md
Normal file
125
README.md
Normal file
@@ -0,0 +1,125 @@
|
||||
# endlessh-go
|
||||
|
||||
A golang implementation of [endlessh](https://nullprogram.com/blog/2019/03/22/) exporting Prometheus metrics, visualized by a Grafana dashboard.
|
||||
|
||||

|
||||
|
||||
## Introduction
|
||||
|
||||
[Endlessh](https://nullprogram.com/blog/2019/03/22/) is a great idea that not only blocks the brute force SSH attacks, but also wastes attackers time as a kind of counter-attack. Besides trapping the attackers, I also want to visualize the Geolocations and other statistics of the sources of attacks. Unfortunately the wonderful original [C implementation of endlessh](https://github.com/skeeto/endlessh) only provides text based log, but I do not like the solution that writes extra scripts to parse the log outputs, then exports the results to a dashboard, because it would introduce extra layers in my current setup and it would depend on the format of the text log file rather than some structured data. Thus I create this golang implementation of endlessh to export [Prometheus](https://prometheus.io/) metrics and a [Grafana](https://grafana.com/) dashboard to visualize them.
|
||||
|
||||
If you want a dashboard of sources of attacks and do not mind the endlessh server, besides trapping the attackers, does extra things including: translating IP to Geohash, exporting Prometheus metrics, and using more memory (about 10MB), this is the solution for you.
|
||||
|
||||
## Getting Started
|
||||
|
||||
Clone the repo then build from source:
|
||||
|
||||
```
|
||||
go build .
|
||||
./endlessh-go &
|
||||
```
|
||||
|
||||
Alternatively, you can use the [docker image](https://hub.docker.com/r/shizunge/endlessh-go):
|
||||
|
||||
```
|
||||
docker run -d -p 2222:2222 shizunge/endlessh-go -logtostderr -v=1
|
||||
```
|
||||
|
||||
It listens to port `2222` by default.
|
||||
|
||||
Then you can try to connect to the endlessh server. Your SSH client should hang there.
|
||||
|
||||
```
|
||||
ssh -p 2222 localhost
|
||||
```
|
||||
|
||||
If you want log like the [C implementation](https://github.com/skeeto/endlessh), you need to set both CLI arguments `-logtostderr` and `-v=1`, then the log will go to stderr. You can set different log destinations via CLI arguments.
|
||||
|
||||
Also check out [examples](./examples/README.md) for the setup of the full stack.
|
||||
|
||||
## Usage
|
||||
|
||||
`./endlessh-go --help`
|
||||
|
||||
```
|
||||
Usage of ./endlessh-go
|
||||
-alsologtostderr
|
||||
log to standard error as well as files
|
||||
-conn_type string
|
||||
Connection type. Possible values are tcp, tcp4, tcp6 (default "tcp")
|
||||
-enable_prometheus
|
||||
Enable prometheus
|
||||
-geoip_supplier string
|
||||
Supplier to obtain Geohash of IPs. Possible values are "off", "ip-api", "max-mind-db" (default "off")
|
||||
-host string
|
||||
SSH listening address (default "0.0.0.0")
|
||||
-interval_ms int
|
||||
Message millisecond delay (default 1000)
|
||||
-line_length int
|
||||
Maximum banner line length (default 32)
|
||||
-log_backtrace_at value
|
||||
when logging hits line file:N, emit a stack trace
|
||||
-log_dir string
|
||||
If non-empty, write log files in this directory
|
||||
-log_link string
|
||||
If non-empty, add symbolic links in this directory to the log files
|
||||
-logbuflevel int
|
||||
Buffer log messages logged at this level or lower (-1 means don't buffer; 0 means buffer INFO only; ...). Has limited applicability on non-prod platforms.
|
||||
-logtostderr
|
||||
log to standard error instead of files
|
||||
-max_clients int
|
||||
Maximum number of clients (default 4096)
|
||||
-max_mind_db string
|
||||
Path to the MaxMind DB file.
|
||||
-port value
|
||||
SSH listening port. You may provide multiple -port flags to listen to multiple ports. (default "2222")
|
||||
-prometheus_clean_unseen_seconds int
|
||||
Remove series if the IP is not seen for the given time. Set to 0 to disable. (default 0)
|
||||
-prometheus_entry string
|
||||
Entry point for prometheus (default "metrics")
|
||||
-prometheus_host string
|
||||
The address for prometheus (default "0.0.0.0")
|
||||
-prometheus_port string
|
||||
The port for prometheus (default "2112")
|
||||
-stderrthreshold value
|
||||
logs at or above this threshold go to stderr (default 2)
|
||||
-v value
|
||||
log level for V logs
|
||||
-vmodule value
|
||||
comma-separated list of pattern=N settings for file-filtered logging
|
||||
```
|
||||
|
||||
## Metrics
|
||||
|
||||
Endlessh-go exports the following Prometheus metrics.
|
||||
|
||||
| Metric | Type | Description |
|
||||
|--------------------------------------|-------|--------------|
|
||||
| endlessh_client_open_count_total | count | Total number of clients that tried to connect to this host. |
|
||||
| endlessh_client_closed_count_total | count | Total number of clients that stopped connecting to this host. |
|
||||
| endlessh_sent_bytes_total | count | Total bytes sent to clients that tried to connect to this host. |
|
||||
| endlessh_trapped_time_seconds_total | count | Total seconds clients spent on endlessh. |
|
||||
| endlessh_client_open_count | count | Number of connections of clients. <br> Labels: <br> <ul><li> `ip`: Remote IP of the client </li> <li> `local_port`: Local port the program listens to </li> <li> `country`: Country of the IP </li> <li> `location`: Country, Region, and City </li> <li> `geohash`: Geohash of the location </li></ul> |
|
||||
| endlessh_client_trapped_time_seconds | count | Seconds a client spends on endlessh. <br> Labels: <br> <ul><li> `ip`: Remote IP of the client </li> <li> `local_port`: Local port the program listens to </li></ul> |
|
||||
|
||||
The metrics is off by default, you can turn it via the CLI argument `-enable_prometheus`.
|
||||
|
||||
It listens to port `2112` and entry point is `/metrics` by default. The port and entry point can be changed via CLI arguments.
|
||||
|
||||
The endlessh-go server stores the geohash of attackers as a label on `endlessh_client_open_count`, which is also off by default. You can turn it on via the CLI argument `-geoip_supplier`. The endlessh-go uses service from [ip-api](https://ip-api.com/), which may enforce a query rate and limit commercial use. Visit their website for their terms and policies.
|
||||
|
||||
You could also use an offline GeoIP database from [MaxMind](https://www.maxmind.com) by setting `-geoip_supplier` to _max-mind-db_ and `-max_mind_db` to the path of the database file.
|
||||
|
||||
## Dashboard
|
||||
|
||||
The dashboard requires Grafana 8.2.
|
||||
|
||||
You can import the dashboard from Grafana.com using ID [15156](https://grafana.com/grafana/dashboards/15156)
|
||||
|
||||
The dashboard visualizes data for the selected time range.
|
||||
|
||||
The IP addresses are clickable and link you to the [ARIN](https://www.arin.net/) database.
|
||||
|
||||
## Contacts
|
||||
|
||||
If you have any problems or questions, please contact me through a [GitHub issue](https://github.com/shizunge/endlessh-go/issues)
|
||||
102
client/client.go
Normal file
102
client/client.go
Normal file
@@ -0,0 +1,102 @@
|
||||
// Copyright (C) 2021-2024 Shizun Ge
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
package client
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/golang/glog"
|
||||
)
|
||||
|
||||
var (
|
||||
numCurrentClients int64
|
||||
letterBytes = []byte(" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-=_+[]{}|;:',./<>?")
|
||||
)
|
||||
|
||||
func randStringBytes(n int64) []byte {
|
||||
b := make([]byte, n+1)
|
||||
for i := range b {
|
||||
b[i] = letterBytes[rand.Intn(len(letterBytes))]
|
||||
}
|
||||
b[n] = '\n'
|
||||
return b
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
conn net.Conn
|
||||
next time.Time
|
||||
start time.Time
|
||||
last time.Time
|
||||
interval time.Duration
|
||||
bytesSent int
|
||||
}
|
||||
|
||||
func NewClient(conn net.Conn, interval time.Duration, maxClients int64) *Client {
|
||||
for numCurrentClients >= maxClients {
|
||||
time.Sleep(interval)
|
||||
}
|
||||
atomic.AddInt64(&numCurrentClients, 1)
|
||||
addr := conn.RemoteAddr().(*net.TCPAddr)
|
||||
glog.V(1).Infof("ACCEPT host=%v port=%v n=%v/%v\n", addr.IP, addr.Port, numCurrentClients, maxClients)
|
||||
return &Client{
|
||||
conn: conn,
|
||||
next: time.Now().Add(interval),
|
||||
start: time.Now(),
|
||||
last: time.Now(),
|
||||
interval: interval,
|
||||
bytesSent: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) RemoteIpAddr() string {
|
||||
return c.conn.RemoteAddr().(*net.TCPAddr).IP.String()
|
||||
}
|
||||
|
||||
func (c *Client) LocalPort() string {
|
||||
return strconv.Itoa(c.conn.LocalAddr().(*net.TCPAddr).Port)
|
||||
}
|
||||
|
||||
func (c *Client) Send(bannerMaxLength int64) (int, error) {
|
||||
if time.Now().Before(c.next) {
|
||||
time.Sleep(c.next.Sub(time.Now()))
|
||||
}
|
||||
c.next = time.Now().Add(c.interval)
|
||||
length := rand.Int63n(bannerMaxLength)
|
||||
bytesSent, err := c.conn.Write(randStringBytes(length))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.bytesSent += bytesSent
|
||||
return bytesSent, nil
|
||||
}
|
||||
|
||||
func (c *Client) MillisecondsSinceLast() int64 {
|
||||
millisecondsSpent := time.Now().Sub(c.last).Milliseconds()
|
||||
c.last = time.Now()
|
||||
return millisecondsSpent
|
||||
}
|
||||
|
||||
func (c *Client) Close() {
|
||||
addr := c.conn.RemoteAddr().(*net.TCPAddr)
|
||||
glog.V(1).Infof("CLOSE host=%v port=%v time=%v bytes=%v\n", addr.IP, addr.Port, time.Now().Sub(c.start).Seconds(), c.bytesSent)
|
||||
c.conn.Close()
|
||||
atomic.AddInt64(&numCurrentClients, -1)
|
||||
}
|
||||
1530
dashboard/endlessh.json
Executable file
1530
dashboard/endlessh.json
Executable file
File diff suppressed because it is too large
Load Diff
BIN
dashboard/screenshot.png
Executable file
BIN
dashboard/screenshot.png
Executable file
Binary file not shown.
|
After Width: | Height: | Size: 297 KiB |
18
examples/README.md
Normal file
18
examples/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Examples
|
||||
|
||||
> The default container user has uid 65534.
|
||||
|
||||
## [docker-simple](./docker-simple)
|
||||
|
||||
An example how to setup endlessh-go, Prometheus, and Grafana using [docker compose](https://docs.docker.com/compose/).
|
||||
|
||||
## [docker-maxmind](./docker-maxmind)
|
||||
|
||||
An example how to setup endlessh-go with the Maxmind GeoIP Database.
|
||||
|
||||
## FAQ
|
||||
### Bind to privileged ports (<1024) in a container
|
||||
|
||||
You need to add capability `NET_BIND_SERVICE` to the program.
|
||||
|
||||
If you are using docker, this can be done via cli argument [`--cap-add`](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) or [`cap_add`](https://docs.docker.com/compose/compose-file/compose-file-v3/#cap_add-cap_drop) in the docker compose file.
|
||||
16
examples/docker-maxmind/README.md
Normal file
16
examples/docker-maxmind/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## docker compose
|
||||
|
||||
This is an example how to setup endlessh-go with the Maxmind GeoIP Database using [docker compose](https://docs.docker.com/compose/). The reference of the compose file can be found [here](https://docs.docker.com/compose/compose-file/).
|
||||
|
||||
To start the stack, in the _examples_ folder, run:
|
||||
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
The GeoIP Database will be saved in a mounted volume in: `./geo-data`. And the endlessh-go container will use this database to do the location lookups.
|
||||
|
||||
This example exposes the following ports. Except the SSH port, you should not expose other ports to public without protections (not included in this example) in production.
|
||||
|
||||
- **2222**: The SSH port. You may test endlessh-go by running `ssh -p 2222 localhost`. Your SSH client should hang. View the log of endlessh-go by running `docker logs endlessh`.
|
||||
- **2112**: The Prometheus metrics exported by endlessh-go. Go to [http://localhost:2112/metrics](http://localhost:2112/metrics) in your web browser to view the metrics.
|
||||
36
examples/docker-maxmind/docker-compose.yml
Normal file
36
examples/docker-maxmind/docker-compose.yml
Normal file
@@ -0,0 +1,36 @@
|
||||
version: "3"
|
||||
services:
|
||||
|
||||
endlessh:
|
||||
container_name: endlessh
|
||||
image: shizunge/endlessh-go:latest
|
||||
restart: unless-stopped
|
||||
#user: root
|
||||
command:
|
||||
- "-logtostderr"
|
||||
- "-v=1"
|
||||
- "-geoip_supplier=max-mind-db"
|
||||
- "-max_mind_db=/geo-data/GeoLite2-City.mmdb"
|
||||
networks:
|
||||
- example_network
|
||||
ports:
|
||||
- 2222:2222 # SSH port
|
||||
- 127.0.0.1:2112:2112 # Prometheus metrics port
|
||||
volumes:
|
||||
- ./geo-data/:/geo-data/:ro # geoip data
|
||||
|
||||
geoipupdate:
|
||||
image: ghcr.io/maxmind/geoipupdate:v5
|
||||
container_name: geoipupdate
|
||||
restart: unless-stopped
|
||||
security_opt: [ "no-new-privileges:true" ]
|
||||
volumes:
|
||||
- ./geo-data/:/usr/share/GeoIP/
|
||||
environment:
|
||||
- GEOIPUPDATE_EDITION_IDS=GeoLite2-City
|
||||
- GEOIPUPDATE_FREQUENCY=72
|
||||
- GEOIPUPDATE_ACCOUNT_ID=xxxxxx
|
||||
- GEOIPUPDATE_LICENSE_KEY=xxxxxx
|
||||
|
||||
networks:
|
||||
example_network:
|
||||
22
examples/docker-simple/README.md
Normal file
22
examples/docker-simple/README.md
Normal file
@@ -0,0 +1,22 @@
|
||||
## docker compose
|
||||
|
||||
This is an example how to setup endlessh-go, Prometheus, and Grafana using [docker compose](https://docs.docker.com/compose/). The reference of the compose file can be found [here](https://docs.docker.com/compose/compose-file/).
|
||||
|
||||
*prometheus.yml* is used as a [Prometheus configuration](https://prometheus.io/docs/prometheus/latest/configuration/configuration/).
|
||||
|
||||
*grafana-datasource.yml* is used to provision a data source for Grafana to ease the setup, though Grafana data source can also be setup manually.
|
||||
|
||||
To start the stack, in the *examples* folder, run:
|
||||
|
||||
```
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
This example exposes the following ports. Except the SSH port, you should not expose other ports to public without protections (not included in this example) in production.
|
||||
|
||||
* **2222**: The SSH port. You may test endlessh-go by running `ssh -p 2222 localhost`. Your SSH client should hang. View the log of endlessh-go by running `docker logs endlessh`.
|
||||
* **2112**: The Prometheus metrics exported by endlessh-go. Go to [http://localhost:2112/metrics](http://localhost:2112/metrics) in your web browser to view the metrics.
|
||||
* **9090**: Prometheus web interface. Go to [http://localhost:9090](http://localhost:9090) in your web browser for Prometheus. You can check whether the target of endlessh-go is up (Click Status, then Targets).
|
||||
* **3000**: Grafana. Go to [http://localhost:3000](http://localhost:3000) in your web browser for Grafana. Use username *examples* and password *examples* to login.
|
||||
|
||||
In this example, we do not provision a dashboard for Grafana. You need to manually load the endlessh-go dashboard, by either importing it from the Grafana.com using ID [15156](https://grafana.com/grafana/dashboards/15156), or pasting the dashboard JSON text to the text area. See the [Grafana documentation](https://grafana.com/docs/grafana/latest/dashboards/export-import/) about import. Then select *Prometheus* as the data source.
|
||||
60
examples/docker-simple/docker-compose.yml
Normal file
60
examples/docker-simple/docker-compose.yml
Normal file
@@ -0,0 +1,60 @@
|
||||
version: '3.5'
|
||||
services:
|
||||
|
||||
endlessh:
|
||||
container_name: endlessh
|
||||
image: shizunge/endlessh-go:latest
|
||||
restart: always
|
||||
command:
|
||||
- -interval_ms=1000
|
||||
- -logtostderr
|
||||
- -v=1
|
||||
- -enable_prometheus
|
||||
- -geoip_supplier=ip-api
|
||||
networks:
|
||||
- example_network
|
||||
ports:
|
||||
- 2222:2222 # SSH port
|
||||
- 127.0.0.1:2112:2112 # Prometheus metrics port
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:latest
|
||||
container_name: prometheus
|
||||
restart: always
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=45d
|
||||
- --web.console.libraries=/usr/share/prometheus/console_libraries
|
||||
- --web.console.templates=/usr/share/prometheus/consoles
|
||||
- --web.enable-admin-api
|
||||
networks:
|
||||
- example_network
|
||||
ports:
|
||||
- 127.0.0.1:9090:9090
|
||||
volumes:
|
||||
- ./prometheus.yml:/etc/prometheus/prometheus.yml
|
||||
- prometheus:/prometheus
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:latest
|
||||
container_name: grafana
|
||||
restart: always
|
||||
networks:
|
||||
- example_network
|
||||
ports:
|
||||
- 127.0.0.1:3000:3000
|
||||
environment:
|
||||
- GF_SECURITY_ADMIN_USER=examples
|
||||
- GF_SECURITY_ADMIN_PASSWORD=examples
|
||||
volumes:
|
||||
- grafana_var:/var/lib/grafana/
|
||||
- ./grafana-datasource.yml:/etc/grafana/provisioning/datasources/prometheus.yml
|
||||
|
||||
networks:
|
||||
example_network:
|
||||
|
||||
|
||||
volumes:
|
||||
prometheus:
|
||||
grafana_var:
|
||||
6
examples/docker-simple/grafana-datasource.yml
Normal file
6
examples/docker-simple/grafana-datasource.yml
Normal file
@@ -0,0 +1,6 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
type: prometheus
|
||||
url: http://prometheus:9090
|
||||
5
examples/docker-simple/prometheus.yml
Normal file
5
examples/docker-simple/prometheus.yml
Normal file
@@ -0,0 +1,5 @@
|
||||
scrape_configs:
|
||||
- job_name: 'endlessh'
|
||||
scrape_interval: 60s
|
||||
static_configs:
|
||||
- targets: ['endlessh:2112']
|
||||
264
geoip/country.go
Normal file
264
geoip/country.go
Normal file
@@ -0,0 +1,264 @@
|
||||
// Copyright (C) 2023-2024 Shizun Ge
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
package geoip
|
||||
|
||||
// Map country's ISO to their capital's latitude and longitude.
|
||||
// Country's ISO see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
|
||||
type location struct {
|
||||
Latitude float64
|
||||
Longitude float64
|
||||
}
|
||||
|
||||
var countryToLocation = map[string]location{
|
||||
"AD": {42.5, 1.5},
|
||||
"AE": {24.4511, 54.3969},
|
||||
"AF": {34.5328, 69.1658},
|
||||
"AG": {17.1211, -61.8447},
|
||||
"AI": {18.2167, -63.05},
|
||||
"AL": {41.33, 19.82},
|
||||
"AM": {40.1814, 44.5144},
|
||||
"AO": {-8.8383, 13.2344},
|
||||
"AR": {-34.5997, -58.3819},
|
||||
"AS": {-14.274, -170.7046},
|
||||
"AT": {48.2083, 16.3725},
|
||||
"AU": {-35.2931, 149.1269},
|
||||
"AW": {12.5186, -70.0358},
|
||||
"AZ": {40.3667, 49.8352},
|
||||
"BA": {43.8563, 18.4132},
|
||||
"BB": {13.0975, -59.6167},
|
||||
"BD": {23.7289, 90.3944},
|
||||
"BE": {50.8353, 4.3314},
|
||||
"BF": {12.3686, -1.5275},
|
||||
"BG": {42.6979, 23.3217},
|
||||
"BH": {26.225, 50.5775},
|
||||
"BI": {-3.3825, 29.3611},
|
||||
"BJ": {6.402, 2.518},
|
||||
"BL": {17.8958, -62.8508},
|
||||
"BM": {32.2942, -64.7839},
|
||||
"BN": {4.9167, 114.9167},
|
||||
"BO": {-16.4942, -68.1475},
|
||||
"BR": {-15.7939, -47.8828},
|
||||
"BS": {25.0667, -77.3333},
|
||||
"BT": {27.4833, 89.6333},
|
||||
"BW": {-24.6569, 25.9086},
|
||||
"BY": {53.9022, 27.5618},
|
||||
"BZ": {17.25, -88.7675},
|
||||
"CA": {45.4247, -75.695},
|
||||
"CD": {-4.3317, 15.3139},
|
||||
"CF": {4.3732, 18.5628},
|
||||
"CG": {-4.2667, 15.2833},
|
||||
"CH": {46.948, 7.4474},
|
||||
"CI": {5.3364, -4.0267},
|
||||
"CK": {-21.207, -159.771},
|
||||
"CL": {-33.45, -70.6667},
|
||||
"CM": {3.8578, 11.5181},
|
||||
"CN": {39.904, 116.4075},
|
||||
"CO": {4.6126, -74.0705},
|
||||
"CR": {9.9333, -84.0833},
|
||||
"CU": {23.1367, -82.3589},
|
||||
"CV": {14.9177, -23.5092},
|
||||
"CW": {12.108, -68.935},
|
||||
"CX": {-10.4167, 105.7167},
|
||||
"CY": {35.1725, 33.365},
|
||||
"CZ": {50.0833, 14.4167},
|
||||
"DE": {52.5167, 13.3833},
|
||||
"DJ": {11.595, 43.1481},
|
||||
"DK": {55.6805, 12.5615},
|
||||
"DM": {15.3, -61.3833},
|
||||
"DO": {18.4764, -69.8933},
|
||||
"DZ": {36.7764, 3.0586},
|
||||
"EC": {-0.22, -78.5125},
|
||||
"EE": {59.4372, 24.745},
|
||||
"EG": {30.0444, 31.2358},
|
||||
"ER": {15.3333, 38.9167},
|
||||
"ES": {40.4167, -3.7167},
|
||||
"ET": {9.0272, 38.7369},
|
||||
"FI": {60.1756, 24.9342},
|
||||
"FJ": {-18.1333, 178.4333},
|
||||
"FK": {-51.7, -57.85},
|
||||
"FM": {6.9178, 158.185},
|
||||
"FO": {62, -6.7833},
|
||||
"FR": {48.8566, 2.3522},
|
||||
"GA": {0.3901, 9.4544},
|
||||
"GB": {51.5072, -0.1275},
|
||||
"GD": {12.0444, -61.7417},
|
||||
"GE": {41.7225, 44.7925},
|
||||
"GF": {4.933, -52.33},
|
||||
"GH": {5.6037, -0.187},
|
||||
"GI": {36.1324, -5.3781},
|
||||
"GL": {64.175, -51.7333},
|
||||
"GM": {13.4531, -16.5775},
|
||||
"GN": {9.538, -13.6773},
|
||||
"GP": {16.0104, -61.7055},
|
||||
"GQ": {3.7521, 8.7737},
|
||||
"GR": {37.9842, 23.7281},
|
||||
"GS": {-54.2833, -36.5},
|
||||
"GT": {14.6099, -90.5252},
|
||||
"GU": {13.4745, 144.7504},
|
||||
"GW": {11.8592, -15.5956},
|
||||
"GY": {6.7833, -58.1667},
|
||||
"HK": {22.3069, 114.1831},
|
||||
"HN": {14.0942, -87.2067},
|
||||
"HR": {45.8131, 15.9772},
|
||||
"HT": {18.5425, -72.3386},
|
||||
"HU": {47.4983, 19.0408},
|
||||
"ID": {-6.2146, 106.8451},
|
||||
"IE": {53.3497, -6.2603},
|
||||
"IL": {31.7833, 35.2167},
|
||||
"IM": {54.15, -4.4819},
|
||||
"IN": {28.6139, 77.209},
|
||||
"IQ": {33.35, 44.4167},
|
||||
"IR": {35.7, 51.4167},
|
||||
"IS": {64.1475, -21.935},
|
||||
"IT": {41.8931, 12.4828},
|
||||
"JE": {49.1858, -2.11},
|
||||
"JM": {17.9714, -76.7931},
|
||||
"JO": {31.95, 35.9333},
|
||||
"JP": {35.6839, 139.7744},
|
||||
"KE": {-1.2864, 36.8172},
|
||||
"KG": {42.8667, 74.5667},
|
||||
"KH": {11.5696, 104.921},
|
||||
"KI": {1.3382, 173.0176},
|
||||
"KM": {-11.7036, 43.2536},
|
||||
"KN": {17.2983, -62.7342},
|
||||
"KP": {39.03, 125.73},
|
||||
"KR": {37.56, 126.99},
|
||||
"KW": {29.375, 47.98},
|
||||
"KY": {19.2866, -81.3744},
|
||||
"KZ": {51.1333, 71.4333},
|
||||
"LA": {17.9667, 102.6},
|
||||
"LB": {33.8869, 35.5131},
|
||||
"LC": {14.0167, -60.9833},
|
||||
"LI": {47.1397, 9.5219},
|
||||
"LK": {6.9, 79.9164},
|
||||
"LR": {6.3106, -10.8047},
|
||||
"LS": {-29.31, 27.48},
|
||||
"LT": {54.6833, 25.2833},
|
||||
"LU": {49.6106, 6.1328},
|
||||
"LV": {56.9475, 24.1069},
|
||||
"LY": {32.8752, 13.1875},
|
||||
"MA": {26.0928, -10.6089},
|
||||
"MC": {43.7396, 7.4069},
|
||||
"MD": {47.0228, 28.8353},
|
||||
"ME": {42.4397, 19.2661},
|
||||
"MF": {18.0706, -63.0847},
|
||||
"MG": {-18.9386, 47.5214},
|
||||
"MH": {7.0918, 171.3802},
|
||||
"MK": {41.9833, 21.4333},
|
||||
"ML": {12.6458, -7.9922},
|
||||
"MM": {16.795, 96.16},
|
||||
"MN": {47.9214, 106.9055},
|
||||
"MP": {15.2137, 145.7546},
|
||||
"MQ": {14.6104, -61.08},
|
||||
"MR": {18.0858, -15.9785},
|
||||
"MS": {16.7928, -62.2106},
|
||||
"MT": {35.8978, 14.5125},
|
||||
"MU": {-20.1667, 57.5},
|
||||
"MV": {4.175, 73.5083},
|
||||
"MW": {-13.9833, 33.7833},
|
||||
"MX": {19.4333, -99.1333},
|
||||
"MY": {3.1478, 101.6953},
|
||||
"MZ": {-25.9153, 32.5764},
|
||||
"NA": {-22.57, 17.0836},
|
||||
"NC": {-22.2625, 166.4443},
|
||||
"NE": {13.5086, 2.1111},
|
||||
"NF": {-29.0569, 167.9617},
|
||||
"NG": {9.0556, 7.4914},
|
||||
"NI": {12.15, -86.2667},
|
||||
"NL": {52.08, 4.31},
|
||||
"NO": {59.9111, 10.7528},
|
||||
"NP": {27.7167, 85.3667},
|
||||
"NR": {-0.5477, 166.9209},
|
||||
"NU": {-19.056, -169.921},
|
||||
"NZ": {-41.2889, 174.7772},
|
||||
"OM": {23.6139, 58.5922},
|
||||
"PA": {9, -79.5},
|
||||
"PE": {-12.06, -77.0375},
|
||||
"PF": {-17.5334, -149.5667},
|
||||
"PG": {-9.4789, 147.1494},
|
||||
"PH": {14.6, 120.9833},
|
||||
"PK": {33.6989, 73.0369},
|
||||
"PL": {52.23, 21.0111},
|
||||
"PM": {46.7811, -56.1764},
|
||||
"PN": {-25.0667, -130.0833},
|
||||
"PR": {18.4037, -66.0636},
|
||||
"PT": {38.708, -9.139},
|
||||
"PW": {7.5006, 134.6242},
|
||||
"PY": {-25.3, -57.6333},
|
||||
"QA": {25.3, 51.5333},
|
||||
"RE": {-20.8789, 55.4481},
|
||||
"RO": {44.4, 26.0833},
|
||||
"RS": {44.8167, 20.4667},
|
||||
"RU": {55.7558, 37.6178},
|
||||
"RW": {-1.9536, 30.0606},
|
||||
"SA": {24.65, 46.71},
|
||||
"SB": {-9.4333, 159.95},
|
||||
"SC": {-4.6236, 55.4544},
|
||||
"SD": {15.6031, 32.5265},
|
||||
"SE": {59.3294, 18.0686},
|
||||
"SG": {1.3, 103.8},
|
||||
"SH": {-15.9251, -5.7179},
|
||||
"SI": {46.05, 14.5167},
|
||||
"SK": {48.1447, 17.1128},
|
||||
"SL": {8.4833, -13.2331},
|
||||
"SM": {43.932, 12.4484},
|
||||
"SN": {14.7319, -17.4572},
|
||||
"SO": {2.0408, 45.3425},
|
||||
"SR": {5.8667, -55.1667},
|
||||
"SS": {4.85, 31.6},
|
||||
"ST": {0.3333, 6.7333},
|
||||
"SV": {13.6989, -89.1914},
|
||||
"SX": {18.0256, -63.0492},
|
||||
"SY": {33.5131, 36.2919},
|
||||
"SZ": {-26.3208, 31.1617},
|
||||
"TC": {21.4664, -71.136},
|
||||
"TD": {12.11, 15.05},
|
||||
"TG": {6.1319, 1.2228},
|
||||
"TH": {13.75, 100.5167},
|
||||
"TJ": {38.5731, 68.7864},
|
||||
"TL": {-8.5536, 125.5783},
|
||||
"TM": {37.95, 58.3833},
|
||||
"TN": {36.8008, 10.18},
|
||||
"TO": {-21.1347, -175.2083},
|
||||
"TR": {39.93, 32.85},
|
||||
"TT": {10.6667, -61.5167},
|
||||
"TV": {-8.5243, 179.1942},
|
||||
"TZ": {-6.8, 39.2833},
|
||||
"UA": {50.45, 30.5236},
|
||||
"UG": {0.3136, 32.5811},
|
||||
"US": {38.9047, -77.0163},
|
||||
"UY": {-34.8667, -56.1667},
|
||||
"UZ": {41.3, 69.2667},
|
||||
"VA": {41.9033, 12.4534},
|
||||
"VC": {13.1667, -61.2333},
|
||||
"VE": {10.5, -66.9333},
|
||||
"VG": {18.4167, -64.6167},
|
||||
"VI": {18.3419, -64.9332},
|
||||
"VN": {21.0245, 105.8412},
|
||||
"VU": {-17.7333, 168.3167},
|
||||
"WF": {-13.2825, -176.1736},
|
||||
"WS": {-13.8333, -171.8333},
|
||||
"XG": {31.5069, 34.456},
|
||||
"XK": {42.6633, 21.1622},
|
||||
"XR": {78.2167, 15.6333},
|
||||
"XW": {31.7764, 35.2269},
|
||||
"YE": {15.35, 44.2},
|
||||
"YT": {-12.7871, 45.275},
|
||||
"ZA": {-25.7464, 28.1881},
|
||||
"ZM": {-15.4167, 28.2833},
|
||||
"ZW": {-17.8292, 31.0522},
|
||||
}
|
||||
148
geoip/geoip.go
Normal file
148
geoip/geoip.go
Normal file
@@ -0,0 +1,148 @@
|
||||
// Copyright (C) 2021-2024 Shizun Ge
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
package geoip
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"github.com/pierrre/geohash"
|
||||
)
|
||||
|
||||
type GeoOption struct {
|
||||
GeoipSupplier string
|
||||
MaxMindDbFileName string
|
||||
}
|
||||
|
||||
func composeLocation(country string, region string, city string) string {
|
||||
var locations []string
|
||||
for _, s := range []string{country, region, city} {
|
||||
if strings.TrimSpace(s) != "" {
|
||||
locations = append(locations, s)
|
||||
}
|
||||
}
|
||||
location := strings.Join(locations, ", ")
|
||||
if location == "" {
|
||||
return "Unknown"
|
||||
}
|
||||
return location
|
||||
}
|
||||
|
||||
func composeCountry(country string) string {
|
||||
if country == "" {
|
||||
return "Unknown"
|
||||
}
|
||||
return country
|
||||
}
|
||||
|
||||
type ipapi struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Ip string `json:"query"`
|
||||
CountryCode string `json:"countryCode"`
|
||||
CountryName string `json:"country"`
|
||||
RegionCode string `json:"region"`
|
||||
RegionName string `json:"regionName"`
|
||||
City string `json:"city"`
|
||||
Zipcode string `json:"zip"`
|
||||
Latitude float64 `json:"lat"`
|
||||
Longitude float64 `json:"lon"`
|
||||
}
|
||||
|
||||
func geohashAndLocationFromIpapi(ipAddr string) (string, string, string, error) {
|
||||
var geo ipapi
|
||||
response, err := http.Get("http://ip-api.com/json/" + ipAddr)
|
||||
if err != nil {
|
||||
return "s000", "Unknown", "Unknown", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return "s000", "Unknown", "Unknown", err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(body, &geo)
|
||||
if err != nil {
|
||||
return "s000", "Unknown", "Unknown", err
|
||||
}
|
||||
|
||||
if geo.Status != "success" {
|
||||
return "s000", "Unknown", "Unknown", fmt.Errorf("failed to query %v via ip-api: status: %v, message: %v", ipAddr, geo.Status, geo.Message)
|
||||
}
|
||||
|
||||
gh := geohash.EncodeAuto(geo.Latitude, geo.Longitude)
|
||||
country := composeCountry(geo.CountryName)
|
||||
location := composeLocation(geo.CountryName, geo.RegionName, geo.City)
|
||||
|
||||
return gh, country, location, nil
|
||||
}
|
||||
|
||||
func geohashAndLocationFromMaxMindDb(ipAddr, maxMindDbFileName string) (string, string, string, error) {
|
||||
db, err := geoip2.Open(maxMindDbFileName)
|
||||
if err != nil {
|
||||
return "s000", "Unknown", "Unknown", err
|
||||
}
|
||||
defer db.Close()
|
||||
// If you are using strings that may be invalid, check that ip is not nil
|
||||
ip := net.ParseIP(ipAddr)
|
||||
cityRecord, err := db.City(ip)
|
||||
if err != nil {
|
||||
return "s000", "Unknown", "Unknown", err
|
||||
}
|
||||
countryName := cityRecord.Country.Names["en"]
|
||||
cityName := cityRecord.City.Names["en"]
|
||||
latitude := cityRecord.Location.Latitude
|
||||
longitude := cityRecord.Location.Longitude
|
||||
iso := cityRecord.Country.IsoCode
|
||||
if latitude == 0 && longitude == 0 {
|
||||
// In case of using Country DB, city is not available.
|
||||
loc, ok := countryToLocation[iso]
|
||||
if ok {
|
||||
latitude = loc.Latitude
|
||||
longitude = loc.Longitude
|
||||
} else {
|
||||
if iso != "" {
|
||||
// For debugging, adding the iso to the country name.
|
||||
countryName = countryName + " (" + iso + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
gh := geohash.EncodeAuto(latitude, longitude)
|
||||
country := composeCountry(countryName)
|
||||
location := composeLocation(countryName, "", cityName)
|
||||
|
||||
return gh, country, location, nil
|
||||
}
|
||||
|
||||
func GeohashAndLocation(ipAddr string, option GeoOption) (string, string, string, error) {
|
||||
switch option.GeoipSupplier {
|
||||
case "off":
|
||||
return "s000", "Geohash off", "Geohash off", nil
|
||||
case "ip-api":
|
||||
return geohashAndLocationFromIpapi(ipAddr)
|
||||
case "max-mind-db":
|
||||
return geohashAndLocationFromMaxMindDb(ipAddr, option.MaxMindDbFileName)
|
||||
default:
|
||||
return "s000", "Unknown", "Unknown", fmt.Errorf("unknown geoipSupplier %v.", option.GeoipSupplier)
|
||||
}
|
||||
}
|
||||
23
go.mod
23
go.mod
@@ -1,3 +1,24 @@
|
||||
module endlessh-go
|
||||
|
||||
go 1.17
|
||||
go 1.21.0
|
||||
|
||||
toolchain go1.21.4
|
||||
|
||||
require (
|
||||
github.com/golang/glog v1.2.0
|
||||
github.com/oschwald/geoip2-golang v1.9.0
|
||||
github.com/pierrre/geohash v1.1.1
|
||||
github.com/prometheus/client_golang v1.18.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect
|
||||
github.com/oschwald/maxminddb-golang v1.11.0 // indirect
|
||||
github.com/prometheus/client_model v0.5.0 // indirect
|
||||
github.com/prometheus/common v0.45.0 // indirect
|
||||
github.com/prometheus/procfs v0.12.0 // indirect
|
||||
golang.org/x/sys v0.15.0 // indirect
|
||||
google.golang.org/protobuf v1.31.0 // indirect
|
||||
)
|
||||
|
||||
60
go.sum
Normal file
60
go.sum
Normal file
@@ -0,0 +1,60 @@
|
||||
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d h1:iG9B49Q218F/XxXNRM7k/vWf7MKmLIS8AcJV9cGN4nA=
|
||||
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d/go.mod h1:RVnhzAX71far8Kc3TQeA0k/dcaEKUnTDSOyet/JCmGI=
|
||||
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb h1:wumPkzt4zaxO4rHPBrjDK8iZMR41C1qs7njNqlacwQg=
|
||||
github.com/TomiHiltunen/geohash-golang v0.0.0-20150112065804-b3e4e625abfb/go.mod h1:QiYsIBRQEO+Z4Rz7GoI+dsHVneZNONvhczuA+llOZNM=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/broady/gogeohash v0.0.0-20120525094510-7b2c40d64042 h1:iEdmkrNMLXbM7ecffOAtZJQOQUTE4iMonxrb5opUgE4=
|
||||
github.com/broady/gogeohash v0.0.0-20120525094510-7b2c40d64042/go.mod h1:f1L9YvXvlt9JTa+A17trQjSMM6bV40f+tHjB+Pi+Fqk=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fanixk/geohash v0.0.0-20150324002647-c1f9b5fa157a h1:Fyfh/dsHFrC6nkX7H7+nFdTd1wROlX/FxEIWVpKYf1U=
|
||||
github.com/fanixk/geohash v0.0.0-20150324002647-c1f9b5fa157a/go.mod h1:UgNw+PTmmGN8rV7RvjvnBMsoTU8ZXXnaT3hYsDTBlgQ=
|
||||
github.com/golang/glog v1.2.0 h1:uCdmnmatrKCgMBlM4rMuJZWOkPDqdbZPnrMXDY4gI68=
|
||||
github.com/golang/glog v1.2.0/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg=
|
||||
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k=
|
||||
github.com/mmcloughlin/geohash v0.10.0 h1:9w1HchfDfdeLc+jFEf/04D27KP7E2QmpDu52wPbJWRE=
|
||||
github.com/mmcloughlin/geohash v0.10.0/go.mod h1:oNZxQo5yWJh0eMQEP/8hwQuVx9Z9tjwFUqcTB1SmG0c=
|
||||
github.com/oschwald/geoip2-golang v1.9.0 h1:uvD3O6fXAXs+usU+UGExshpdP13GAqp4GBrzN7IgKZc=
|
||||
github.com/oschwald/geoip2-golang v1.9.0/go.mod h1:BHK6TvDyATVQhKNbQBdrj9eAvuwOMi2zSFXizL3K81Y=
|
||||
github.com/oschwald/maxminddb-golang v1.11.0 h1:aSXMqYR/EPNjGE8epgqwDay+P30hCBZIveY0WZbAWh0=
|
||||
github.com/oschwald/maxminddb-golang v1.11.0/go.mod h1:YmVI+H0zh3ySFR3w+oz8PCfglAFj3PuCmui13+P9zDg=
|
||||
github.com/pierrre/assert v0.3.2 h1:wXdlkVN5FVSLEKl6pGijcCYkldgfjRgyheU3C1/by9Q=
|
||||
github.com/pierrre/assert v0.3.2/go.mod h1:zwOn9QE9/+eSgqR/4iCS9K9dUpkqyl0iih2APCI5d8E=
|
||||
github.com/pierrre/compare v1.4.2 h1:oabIiWclzAlXG7S/2MYSFDJ/vR34oa/MYrBZh5PNU80=
|
||||
github.com/pierrre/compare v1.4.2/go.mod h1:EBDtLjy0XYVBEFP4T3pWljpfTwL7X8DqPt9RIP1+svY=
|
||||
github.com/pierrre/geohash v1.1.1 h1:XCkvOyv/uesenMPhkvsCfIiUalBmGdHlFY0bIWTqb+s=
|
||||
github.com/pierrre/geohash v1.1.1/go.mod h1:ucAm7cbgGBoVr6cr1t+d3ea5XQ9P5zKHXfS1Qy2iKVY=
|
||||
github.com/pierrre/go-libs v0.2.14 h1:wAPoOrslKLnha6ow5EKkxxZpo76kOea57efs71A/ZnQ=
|
||||
github.com/pierrre/go-libs v0.2.14/go.mod h1:eA3pQD5LHZmavOpTpUfO8FszduBNHoFXDWrevDR6Dy8=
|
||||
github.com/pierrre/pretty v0.0.10 h1:Cb5som+1EpU+x7UA5AMy9I8AY2XkzMBywkLEAdo1JDg=
|
||||
github.com/pierrre/pretty v0.0.10/go.mod h1:F+Z4XV4T5GIvbr/swCAkuQ2ng81qMaQT9CfI8rKOLdY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.18.0 h1:HzFfmkOzH5Q8L8G+kSJKUx5dtG87sewO+FoDDqP5Tbk=
|
||||
github.com/prometheus/client_golang v1.18.0/go.mod h1:T+GXkCk5wSJyOqMIzVgvvjFDlkOQntgjkJWKrN5txjA=
|
||||
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
|
||||
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
|
||||
github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM=
|
||||
github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY=
|
||||
github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo=
|
||||
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/the42/cartconvert v1.0.0 h1:g8kt6ic2GEhdcZ61ZP9GsWwhosVo5nCnH1n2/oAQXUU=
|
||||
github.com/the42/cartconvert v1.0.0/go.mod h1:fWO/msnJVhHqN1yX6OBoxSyfj7TEj1hHiL8bJSQsK30=
|
||||
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
|
||||
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
219
main.go
219
main.go
@@ -1,125 +1,170 @@
|
||||
// Copyright (C) 2021-2024 Shizun Ge
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
package main
|
||||
|
||||
// echo -n "test out the server" | nc localhost 3333
|
||||
|
||||
import (
|
||||
"endlessh-go/client"
|
||||
"endlessh-go/geoip"
|
||||
"endlessh-go/metrics"
|
||||
"flag"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/golang/glog"
|
||||
)
|
||||
|
||||
var (
|
||||
numCurrentClients int64
|
||||
numTotalClients uint64
|
||||
numTotalBytes uint64
|
||||
)
|
||||
|
||||
var letterBytes = []byte(" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-=_+[]{}|;:',./<>?")
|
||||
|
||||
func randStringBytes(n int64) []byte {
|
||||
b := make([]byte, n+1)
|
||||
for i := range b {
|
||||
b[i] = letterBytes[rand.Intn(len(letterBytes))]
|
||||
}
|
||||
b[n] = '\n'
|
||||
return b
|
||||
func startSending(maxClients int64, bannerMaxLength int64, records chan<- metrics.RecordEntry) chan *client.Client {
|
||||
clients := make(chan *client.Client, maxClients)
|
||||
go func() {
|
||||
for {
|
||||
c, more := <-clients
|
||||
if !more {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
bytesSent, err := c.Send(bannerMaxLength)
|
||||
remoteIpAddr := c.RemoteIpAddr()
|
||||
localPort := c.LocalPort()
|
||||
millisecondsSpent := c.MillisecondsSinceLast()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
records <- metrics.RecordEntry{
|
||||
RecordType: metrics.RecordEntryTypeStop,
|
||||
IpAddr: remoteIpAddr,
|
||||
LocalPort: localPort,
|
||||
MillisecondsSpent: millisecondsSpent,
|
||||
}
|
||||
return
|
||||
}
|
||||
clients <- c
|
||||
records <- metrics.RecordEntry{
|
||||
RecordType: metrics.RecordEntryTypeSend,
|
||||
IpAddr: remoteIpAddr,
|
||||
LocalPort: localPort,
|
||||
MillisecondsSpent: millisecondsSpent,
|
||||
BytesSent: bytesSent,
|
||||
}
|
||||
}()
|
||||
}
|
||||
}()
|
||||
return clients
|
||||
}
|
||||
|
||||
type client struct {
|
||||
conn net.Conn
|
||||
next time.Time
|
||||
start time.Time
|
||||
bytes_sent int
|
||||
func startAccepting(maxClients int64, connType, connHost, connPort string, interval time.Duration, clients chan<- *client.Client, records chan<- metrics.RecordEntry) {
|
||||
go func() {
|
||||
l, err := net.Listen(connType, connHost+":"+connPort)
|
||||
if err != nil {
|
||||
glog.Errorf("Error listening: %v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Close the listener when the application closes.
|
||||
defer l.Close()
|
||||
glog.Infof("Listening on %v:%v", connHost, connPort)
|
||||
for {
|
||||
// Listen for an incoming connection.
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
glog.Errorf("Error accepting connection from port %v: %v", connPort, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
c := client.NewClient(conn, interval, maxClients)
|
||||
remoteIpAddr := c.RemoteIpAddr()
|
||||
records <- metrics.RecordEntry{
|
||||
RecordType: metrics.RecordEntryTypeStart,
|
||||
IpAddr: remoteIpAddr,
|
||||
LocalPort: connPort,
|
||||
}
|
||||
clients <- c
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func NewClient(conn net.Conn, interval time.Duration, maxClient int64) *client {
|
||||
atomic.AddInt64(&numCurrentClients, 1)
|
||||
atomic.AddUint64(&numTotalClients, 1)
|
||||
fmt.Printf("%v ACCEPT host=%v n=%v/%v\n", time.Now(), conn.RemoteAddr(), numCurrentClients, maxClient)
|
||||
return &client{
|
||||
conn: conn,
|
||||
next: time.Now().Add(interval),
|
||||
start: time.Now(),
|
||||
bytes_sent: 0,
|
||||
}
|
||||
type arrayStrings []string
|
||||
|
||||
func (a *arrayStrings) String() string {
|
||||
return strings.Join(*a, ", ")
|
||||
}
|
||||
|
||||
func (c *client) Send(bannerMaxLength int64) error {
|
||||
length := rand.Int63n(bannerMaxLength)
|
||||
bytes_sent, err := c.conn.Write(randStringBytes(length))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.bytes_sent += bytes_sent
|
||||
atomic.AddUint64(&numTotalBytes, uint64(bytes_sent))
|
||||
func (a *arrayStrings) Set(value string) error {
|
||||
*a = append(*a, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) Close() {
|
||||
atomic.AddInt64(&numCurrentClients, -1)
|
||||
fmt.Printf("%v CLOSE host=%v time=%v bytes=%v\n", time.Now(), c.conn.RemoteAddr(), time.Now().Sub(c.start), c.bytes_sent)
|
||||
c.conn.Close()
|
||||
}
|
||||
const defaultPort = "2222"
|
||||
|
||||
var connPorts arrayStrings
|
||||
|
||||
func main() {
|
||||
intervalMs := flag.Int("interval_ms", 1000, "Message millisecond delay")
|
||||
bannerMaxLength := flag.Int64("line_length", 32, "Maximum banner line length")
|
||||
maxClients := flag.Int64("max_clients", 4096, "Maximum number of clients")
|
||||
connType := flag.String("conn_type", "tcp", "Connection type. Possible values are tcp, tcp4, tcp6")
|
||||
connHost := flag.String("host", "localhost", "Listening address")
|
||||
connPort := flag.String("port", "2222", "Listening port")
|
||||
connHost := flag.String("host", "0.0.0.0", "SSH listening address")
|
||||
flag.Var(&connPorts, "port", fmt.Sprintf("SSH listening port. You may provide multiple -port flags to listen to multiple ports. (default %q)", defaultPort))
|
||||
prometheusEnabled := flag.Bool("enable_prometheus", false, "Enable prometheus")
|
||||
prometheusHost := flag.String("prometheus_host", "0.0.0.0", "The address for prometheus")
|
||||
prometheusPort := flag.String("prometheus_port", "2112", "The port for prometheus")
|
||||
prometheusEntry := flag.String("prometheus_entry", "metrics", "Entry point for prometheus")
|
||||
prometheusCleanUnseenSeconds := flag.Int("prometheus_clean_unseen_seconds", 0, "Remove series if the IP is not seen for the given time. Set to 0 to disable. (default 0)")
|
||||
geoipSupplier := flag.String("geoip_supplier", "off", "Supplier to obtain Geohash of IPs. Possible values are \"off\", \"ip-api\", \"max-mind-db\"")
|
||||
maxMindDbFileName := flag.String("max_mind_db", "", "Path to the MaxMind DB file.")
|
||||
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %v \n", os.Args[0])
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
flag.Parse()
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
if *prometheusEnabled {
|
||||
if *connType == "tcp6" && *prometheusHost == "0.0.0.0" {
|
||||
*prometheusHost = "[::]"
|
||||
}
|
||||
metrics.InitPrometheus(*prometheusHost, *prometheusPort, *prometheusEntry)
|
||||
}
|
||||
|
||||
records := metrics.StartRecording(*maxClients, *prometheusEnabled, *prometheusCleanUnseenSeconds,
|
||||
geoip.GeoOption{
|
||||
GeoipSupplier: *geoipSupplier,
|
||||
MaxMindDbFileName: *maxMindDbFileName,
|
||||
})
|
||||
clients := startSending(*maxClients, *bannerMaxLength, records)
|
||||
|
||||
interval := time.Duration(*intervalMs) * time.Millisecond
|
||||
// Listen for incoming connections.
|
||||
l, err := net.Listen(*connType, *connHost+":"+*connPort)
|
||||
if err != nil {
|
||||
fmt.Println("Error listening:", err.Error())
|
||||
os.Exit(1)
|
||||
if *connType == "tcp6" && *connHost == "0.0.0.0" {
|
||||
*connHost = "[::]"
|
||||
}
|
||||
if len(connPorts) == 0 {
|
||||
connPorts = append(connPorts, defaultPort)
|
||||
}
|
||||
for _, connPort := range connPorts {
|
||||
startAccepting(*maxClients, *connType, *connHost, connPort, interval, clients, records)
|
||||
}
|
||||
// Close the listener when the application closes.
|
||||
defer l.Close()
|
||||
fmt.Println("Listening on " + *connHost + ":" + *connPort)
|
||||
|
||||
clients := make(chan *client, *maxClients)
|
||||
go func(clients chan *client, interval time.Duration, bannerMaxLength int64) {
|
||||
for {
|
||||
c, more := <-clients
|
||||
if !more {
|
||||
return
|
||||
}
|
||||
if time.Now().Before(c.next) {
|
||||
time.Sleep(c.next.Sub(time.Now()))
|
||||
}
|
||||
err := c.Send(bannerMaxLength)
|
||||
if err != nil {
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
c.next = time.Now().Add(interval)
|
||||
go func() { clients <- c }()
|
||||
}
|
||||
}(clients, interval, *bannerMaxLength)
|
||||
for {
|
||||
// Listen for an incoming connection.
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
fmt.Println("Error accepting: ", err.Error())
|
||||
os.Exit(1)
|
||||
if *prometheusCleanUnseenSeconds <= 0 {
|
||||
time.Sleep(time.Duration(1<<63 - 1))
|
||||
} else {
|
||||
time.Sleep(time.Second * time.Duration(60))
|
||||
records <- metrics.RecordEntry{
|
||||
RecordType: metrics.RecordEntryTypeClean,
|
||||
}
|
||||
}
|
||||
// Handle connections in a new goroutine.
|
||||
for numCurrentClients >= *maxClients {
|
||||
time.Sleep(interval)
|
||||
}
|
||||
clients <- NewClient(conn, interval, *maxClients)
|
||||
}
|
||||
}
|
||||
|
||||
167
metrics/metrics.go
Normal file
167
metrics/metrics.go
Normal file
@@ -0,0 +1,167 @@
|
||||
// Copyright (C) 2024 Shizun Ge
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"endlessh-go/geoip"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/golang/glog"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
var (
|
||||
pq *UpdatablePriorityQueue
|
||||
totalClients *prometheus.CounterVec
|
||||
totalClientsClosed *prometheus.CounterVec
|
||||
totalBytes *prometheus.CounterVec
|
||||
totalSeconds *prometheus.CounterVec
|
||||
clientIP *prometheus.CounterVec
|
||||
clientSeconds *prometheus.CounterVec
|
||||
)
|
||||
|
||||
func InitPrometheus(prometheusHost, prometheusPort, prometheusEntry string) {
|
||||
pq = NewUpdatablePriorityQueue()
|
||||
totalClients = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "endlessh_client_open_count_total",
|
||||
Help: "Total number of clients that tried to connect to this host.",
|
||||
}, []string{"local_port"},
|
||||
)
|
||||
totalClientsClosed = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "endlessh_client_closed_count_total",
|
||||
Help: "Total number of clients that stopped connecting to this host.",
|
||||
}, []string{"local_port"},
|
||||
)
|
||||
totalBytes = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "endlessh_sent_bytes_total",
|
||||
Help: "Total bytes sent to clients that tried to connect to this host.",
|
||||
}, []string{"local_port"},
|
||||
)
|
||||
totalSeconds = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "endlessh_trapped_time_seconds_total",
|
||||
Help: "Total seconds clients spent on endlessh.",
|
||||
}, []string{"local_port"},
|
||||
)
|
||||
clientIP = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "endlessh_client_open_count",
|
||||
Help: "Number of connections of clients.",
|
||||
},
|
||||
[]string{"ip", "local_port", "geohash", "country", "location"},
|
||||
)
|
||||
clientSeconds = prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "endlessh_client_trapped_time_seconds",
|
||||
Help: "Seconds a client spends on endlessh.",
|
||||
},
|
||||
[]string{"ip", "local_port"},
|
||||
)
|
||||
promReg := prometheus.NewRegistry()
|
||||
promReg.MustRegister(totalClients)
|
||||
promReg.MustRegister(totalClientsClosed)
|
||||
promReg.MustRegister(totalBytes)
|
||||
promReg.MustRegister(totalSeconds)
|
||||
promReg.MustRegister(clientIP)
|
||||
promReg.MustRegister(clientSeconds)
|
||||
handler := promhttp.HandlerFor(promReg, promhttp.HandlerOpts{EnableOpenMetrics: true})
|
||||
http.Handle("/"+prometheusEntry, handler)
|
||||
go func() {
|
||||
glog.Infof("Starting Prometheus on %v:%v, entry point is /%v", prometheusHost, prometheusPort, prometheusEntry)
|
||||
if err := http.ListenAndServe(prometheusHost+":"+prometheusPort, nil); err != nil {
|
||||
glog.Errorf("Error starting Prometheus at port %v:%v: %v", prometheusHost, prometheusPort, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
const (
|
||||
RecordEntryTypeStart = iota
|
||||
RecordEntryTypeSend = iota
|
||||
RecordEntryTypeStop = iota
|
||||
RecordEntryTypeClean = iota
|
||||
)
|
||||
|
||||
type RecordEntry struct {
|
||||
RecordType int
|
||||
IpAddr string
|
||||
LocalPort string
|
||||
MillisecondsSpent int64
|
||||
BytesSent int
|
||||
}
|
||||
|
||||
func StartRecording(maxClients int64, prometheusEnabled bool, prometheusCleanUnseenSeconds int, geoOption geoip.GeoOption) chan RecordEntry {
|
||||
records := make(chan RecordEntry, maxClients)
|
||||
go func() {
|
||||
for {
|
||||
r, more := <-records
|
||||
if !more {
|
||||
return
|
||||
}
|
||||
if !prometheusEnabled {
|
||||
continue
|
||||
}
|
||||
switch r.RecordType {
|
||||
case RecordEntryTypeStart:
|
||||
geohash, country, location, err := geoip.GeohashAndLocation(r.IpAddr, geoOption)
|
||||
if err != nil {
|
||||
glog.Warningf("Failed to obatin the geohash of %v: %v.", r.IpAddr, err)
|
||||
}
|
||||
clientIP.With(prometheus.Labels{
|
||||
"ip": r.IpAddr,
|
||||
"local_port": r.LocalPort,
|
||||
"geohash": geohash,
|
||||
"country": country,
|
||||
"location": location}).Inc()
|
||||
totalClients.With(prometheus.Labels{"local_port": r.LocalPort}).Inc()
|
||||
pq.Update(r.IpAddr, time.Now())
|
||||
case RecordEntryTypeSend:
|
||||
secondsSpent := float64(r.MillisecondsSpent) / 1000
|
||||
clientSeconds.With(prometheus.Labels{
|
||||
"ip": r.IpAddr,
|
||||
"local_port": r.LocalPort}).Add(secondsSpent)
|
||||
totalSeconds.With(prometheus.Labels{"local_port": r.LocalPort}).Add(secondsSpent)
|
||||
totalBytes.With(prometheus.Labels{"local_port": r.LocalPort}).Add(float64(r.BytesSent))
|
||||
pq.Update(r.IpAddr, time.Now())
|
||||
case RecordEntryTypeStop:
|
||||
secondsSpent := float64(r.MillisecondsSpent) / 1000
|
||||
clientSeconds.With(prometheus.Labels{
|
||||
"ip": r.IpAddr,
|
||||
"local_port": r.LocalPort}).Add(secondsSpent)
|
||||
totalSeconds.With(prometheus.Labels{"local_port": r.LocalPort}).Add(secondsSpent)
|
||||
totalClientsClosed.With(prometheus.Labels{"local_port": r.LocalPort}).Inc()
|
||||
pq.Update(r.IpAddr, time.Now())
|
||||
case RecordEntryTypeClean:
|
||||
top := pq.Peek()
|
||||
deadline := time.Now().Add(-time.Second * time.Duration(prometheusCleanUnseenSeconds))
|
||||
for top != nil && top.Value.Before(deadline) {
|
||||
clientIP.DeletePartialMatch(prometheus.Labels{"ip": top.Key})
|
||||
clientSeconds.DeletePartialMatch(prometheus.Labels{"ip": top.Key})
|
||||
pq.Pop()
|
||||
top = pq.Peek()
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return records
|
||||
}
|
||||
94
metrics/priority_queue.go
Normal file
94
metrics/priority_queue.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Pair represents a key-value pair with a timestamp
|
||||
type Pair struct {
|
||||
Key string
|
||||
Value time.Time
|
||||
HeapIdx int // Index in the heap for efficient updates
|
||||
}
|
||||
|
||||
// PriorityQueue is a min-heap implementation for Pairs
|
||||
type PriorityQueue []*Pair
|
||||
|
||||
// Len returns the length of the priority queue
|
||||
func (pq PriorityQueue) Len() int { return len(pq) }
|
||||
|
||||
// Less compares two pairs based on their values (timestamps)
|
||||
func (pq PriorityQueue) Less(i, j int) bool {
|
||||
return pq[i].Value.Before(pq[j].Value)
|
||||
}
|
||||
|
||||
// Swap swaps two pairs in the priority queue
|
||||
func (pq PriorityQueue) Swap(i, j int) {
|
||||
pq[i], pq[j] = pq[j], pq[i]
|
||||
pq[i].HeapIdx = i
|
||||
pq[j].HeapIdx = j
|
||||
}
|
||||
|
||||
// Push adds a pair to the priority queue
|
||||
func (pq *PriorityQueue) Push(x interface{}) {
|
||||
pair := x.(*Pair)
|
||||
pair.HeapIdx = len(*pq)
|
||||
*pq = append(*pq, pair)
|
||||
}
|
||||
|
||||
// Pop removes the pair with the minimum value (timestamp) from the priority queue
|
||||
func (pq *PriorityQueue) Pop() interface{} {
|
||||
old := *pq
|
||||
n := len(old)
|
||||
pair := old[n-1]
|
||||
pair.HeapIdx = -1 // for safety
|
||||
*pq = old[0 : n-1]
|
||||
return pair
|
||||
}
|
||||
|
||||
// UpdatablePriorityQueue represents the data structure with the priority queue
|
||||
type UpdatablePriorityQueue struct {
|
||||
pq PriorityQueue
|
||||
keyMap map[string]*Pair
|
||||
}
|
||||
|
||||
// NewUpdatablePriorityQueue initializes a new UpdatablePriorityQueue
|
||||
func NewUpdatablePriorityQueue() *UpdatablePriorityQueue {
|
||||
return &UpdatablePriorityQueue{
|
||||
pq: make(PriorityQueue, 0),
|
||||
keyMap: make(map[string]*Pair),
|
||||
}
|
||||
}
|
||||
|
||||
// Update adds or updates a key-value pair in the data structure
|
||||
func (ds *UpdatablePriorityQueue) Update(key string, value time.Time) {
|
||||
if pair, ok := ds.keyMap[key]; ok {
|
||||
// Key exists, update the time
|
||||
pair.Value = value
|
||||
heap.Fix(&ds.pq, pair.HeapIdx)
|
||||
} else {
|
||||
// Key does not exist, create a new entry
|
||||
pair := &Pair{Key: key, Value: value}
|
||||
heap.Push(&ds.pq, pair)
|
||||
ds.keyMap[key] = pair
|
||||
}
|
||||
}
|
||||
|
||||
// Peek returns the entry with the minimal time
|
||||
func (ds *UpdatablePriorityQueue) Peek() *Pair {
|
||||
if ds.pq.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
return ds.pq[0]
|
||||
}
|
||||
|
||||
// Pop removes the entry with the minimal time
|
||||
func (ds *UpdatablePriorityQueue) Pop() *Pair {
|
||||
if ds.pq.Len() == 0 {
|
||||
return nil
|
||||
}
|
||||
pair := heap.Pop(&ds.pq).(*Pair)
|
||||
delete(ds.keyMap, pair.Key)
|
||||
return pair
|
||||
}
|
||||
Reference in New Issue
Block a user