Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e429b17e63 | ||
|
|
f352ee8f39 | ||
|
|
fadfc24e52 | ||
|
|
78ebeba1bb | ||
|
|
32e3d411ad | ||
|
|
405f41f87f | ||
|
|
9bb8230fc1 | ||
|
|
bd87864e26 | ||
|
|
bfe08e5114 | ||
|
|
aaf79b21f0 | ||
|
|
2ca84c912b | ||
|
|
bc1783cfb6 | ||
|
|
a4bdbb2b54 | ||
|
|
f362c96e1e | ||
|
|
5f58c34c8b | ||
|
|
5f35415849 | ||
|
|
442354db17 | ||
|
|
23b023c562 | ||
|
|
c2f4510a0f | ||
|
|
d23ed2126d | ||
|
|
18ca5d04cc | ||
|
|
f5d5f63366 | ||
|
|
1f8e441090 | ||
|
|
4c8d7b0738 | ||
|
|
d9f9dc6acb | ||
|
|
b3ed822c72 | ||
|
|
d5488f8aa3 | ||
|
|
8bcf5313f4 | ||
|
|
c062cc414a | ||
|
|
a61ff2d200 | ||
|
|
0de2c95934 | ||
|
|
847f0ce1d4 | ||
|
|
a28d7319d8 | ||
|
|
f0201c1039 | ||
|
|
9351c94f35 | ||
|
|
02be614149 | ||
|
|
ee50a67f03 | ||
|
|
445ed1dd60 | ||
|
|
47527d1512 | ||
|
|
af8d4a8c12 | ||
|
|
1bf4cf2347 | ||
|
|
d4a6560d9a | ||
|
|
6157b1a528 | ||
|
|
11d185ad59 | ||
|
|
a05995fba5 | ||
|
|
1c1be202b7 | ||
|
|
5e55b761cf | ||
|
|
fce53fa308 | ||
|
|
9d3df6be7e | ||
|
|
89df38422c | ||
|
|
3413ceb7c2 | ||
|
|
51a3787708 | ||
|
|
bb2cffe10a | ||
|
|
41c282b38b | ||
|
|
53c2e472ae | ||
|
|
4bb7e33b16 | ||
|
|
f35a73f734 | ||
|
|
00900c1315 | ||
|
|
18c11f108b | ||
|
|
3cc4234117 | ||
|
|
fe79fe9fc7 | ||
|
|
57c49089de | ||
|
|
d35e3510a9 | ||
|
|
7178b33807 | ||
|
|
b0d16d3b3d | ||
|
|
5fcbeb60aa | ||
|
|
0435dce9cd | ||
|
|
25e71790c1 | ||
|
|
6aea46e6d5 | ||
|
|
30fc6d1689 | ||
|
|
8078d712f9 | ||
|
|
144f102935 | ||
|
|
4b7b2f4c27 | ||
|
|
fe27d4c9c7 | ||
|
|
41317a4ef9 | ||
|
|
2912246572 | ||
|
|
f6c596f318 | ||
|
|
45521d5680 | ||
|
|
89f1e72c50 | ||
|
|
4a7a0a7b75 | ||
|
|
6a978515ca | ||
|
|
0cc0e82c5d | ||
|
|
c01c61fc6b | ||
|
|
4831e17b38 | ||
|
|
3cb104cd1b | ||
|
|
60c8b0c7bf | ||
|
|
16c97a3c36 | ||
|
|
1e8180014d | ||
|
|
2330935b90 | ||
|
|
7ea9001aa4 | ||
|
|
694ebc5477 | ||
|
|
824b12a2f8 | ||
|
|
0c87b4119a | ||
|
|
f0f50579fc | ||
|
|
a831ccd8fa | ||
|
|
dd65e32fb5 | ||
|
|
b1b91b0c53 | ||
|
|
c29dd2ad36 | ||
|
|
f56b9ea883 | ||
|
|
d69ce38604 | ||
|
|
92ea594ccf | ||
|
|
5bbf247863 | ||
|
|
2b841adb1b | ||
|
|
5fd335f330 | ||
|
|
cd7f99063c | ||
|
|
58cb05e302 | ||
|
|
cc6d053b6d | ||
|
|
4b0aebd6a5 | ||
|
|
07b896550e | ||
|
|
886886197d | ||
|
|
4aefb4ba8a | ||
|
|
3d30f7a4b0 | ||
|
|
b09d3ec22c | ||
|
|
b43abb4b5d | ||
|
|
d42710497c | ||
|
|
42a73fa392 | ||
|
|
00a4a33c5f | ||
|
|
006ddbc871 | ||
|
|
69e60a3337 | ||
|
|
5beee738df | ||
|
|
8fa3e8f785 | ||
|
|
65e0822b63 | ||
|
|
7edc65cfde | ||
|
|
ff030b9c1c | ||
|
|
7637cd448e | ||
|
|
2a5a45a700 | ||
|
|
ec9439564e | ||
|
|
a0e599d96a | ||
|
|
55fd6ec406 | ||
|
|
e9256ab9aa | ||
|
|
e4b08b1b82 | ||
|
|
62bc3c856f | ||
|
|
f0493543ff | ||
|
|
1b475b123c | ||
|
|
b189fb1b6e | ||
|
|
328a068956 | ||
|
|
efa341c7e8 | ||
|
|
f43942413e | ||
|
|
24bd9ce6ba | ||
|
|
a4d429bbc1 | ||
|
|
c0e2b6283c | ||
|
|
a66b465046 | ||
|
|
7ec3e82b0f | ||
|
|
7e93497f1a | ||
|
|
e24b2921ac | ||
|
|
572dcd2aab | ||
|
|
97330bfbdc | ||
|
|
f78e81b452 | ||
|
|
d45bc3c066 | ||
|
|
f81fb7760e | ||
|
|
149b2e467c | ||
|
|
a29a7d4923 | ||
|
|
0d257a95dd | ||
|
|
ad22ada1f1 | ||
|
|
948d931883 | ||
|
|
8afa6b2929 | ||
|
|
7a49e48b89 | ||
|
|
0819afc9da | ||
|
|
eecf1c6c69 | ||
|
|
9428457487 | ||
|
|
f3e90f146d | ||
|
|
7bf54b608d | ||
|
|
496d9f52f9 | ||
|
|
d97b18f51f | ||
|
|
037e7b28f1 | ||
|
|
b3660c3b8d | ||
|
|
cbc3bd2afe | ||
|
|
5fc51f40a7 | ||
|
|
1c1aa5ec5b | ||
|
|
f526c56784 | ||
|
|
fbbd4bace2 | ||
|
|
534d428c6d | ||
|
|
0492268190 | ||
|
|
01fca7d568 | ||
|
|
0711b9befb | ||
|
|
2c13a02bdc | ||
|
|
204c53ddd3 | ||
|
|
6788f24821 | ||
|
|
e65ab33749 | ||
|
|
7f94b3871a | ||
|
|
aa5b869da9 | ||
|
|
f7898e019e | ||
|
|
ca04f19275 | ||
|
|
db43405237 | ||
|
|
750ecb824a | ||
|
|
2c608ddb7f | ||
|
|
934402e97d | ||
|
|
6fe69bc6b1 | ||
|
|
dab51c32a2 | ||
|
|
48c7309973 | ||
|
|
f2329f72f6 | ||
|
|
9f03c2f6eb | ||
|
|
7a8cb3d5b6 | ||
|
|
3b18d66835 | ||
|
|
9f6b33a62b | ||
|
|
44d314515b | ||
|
|
59d789d253 | ||
|
|
2e8af6f120 | ||
|
|
7af09a2f4c | ||
|
|
74b262503e | ||
|
|
87f2c8b2ce | ||
|
|
cbdad1adb0 | ||
|
|
73c297df8e |
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Opening '...'
|
||||
2. Click on '....'
|
||||
3. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots or logs**
|
||||
Add screenshots or logs to help explain your problem.
|
||||
|
||||
**Server (please complete the following information):**
|
||||
- OS: [e.g. Centos, Windows]
|
||||
- ARCH: [e.g. Amd64, Arm]
|
||||
- Tunnel [e.g. TCP, HTTP]
|
||||
- Version [e.g. 0.24.0]
|
||||
|
||||
**Client (please complete the following information):**
|
||||
- OS: [e.g. Centos, Windows]
|
||||
- ARCH: [e.g. Amd64, Arm]
|
||||
- Tunnel [e.g. TCP, HTTP]
|
||||
- Version [e.g. 0.24.0]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,3 @@
|
||||
.idea
|
||||
nps
|
||||
npc
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
FROM golang as builder
|
||||
WORKDIR /go/src/github.com/cnlh/nps
|
||||
COPY . .
|
||||
RUN go get -d -v ./...
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-w -s -extldflags -static" ./cmd/npc/npc.go
|
||||
|
||||
FROM scratch
|
||||
COPY --from=builder /go/src/github.com/cnlh/nps/npc /
|
||||
VOLUME /conf
|
||||
ENTRYPOINT ["/npc"]
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
FROM golang as builder
|
||||
WORKDIR /go/src/github.com/cnlh/nps
|
||||
COPY . .
|
||||
RUN go get -d -v ./...
|
||||
RUN CGO_ENABLED=0 go build -ldflags="-w -s -extldflags -static" ./cmd/nps/nps.go
|
||||
|
||||
FROM scratch
|
||||
COPY --from=builder /go/src/github.com/cnlh/nps/nps /
|
||||
COPY --from=builder /go/src/github.com/cnlh/nps/web /web
|
||||
VOLUME /conf
|
||||
CMD ["/nps"]
|
||||
@@ -1,21 +1,674 @@
|
||||
MIT License
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (c) 2018
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
{one line to give the program's name and a brief idea of what it does.}
|
||||
Copyright (C) {year} {name of author}
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
{project} Copyright (C) {year} {fullname}
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,75 @@
|
||||
SOURCE_FILES?=./...
|
||||
TEST_PATTERN?=.
|
||||
TEST_OPTIONS?=
|
||||
|
||||
export PATH := ./bin:$(PATH)
|
||||
export GO111MODULE := on
|
||||
export GOPROXY := https://gocenter.io
|
||||
|
||||
# Build a beta version of goreleaser
|
||||
build:
|
||||
go build cmd/nps/nps.go
|
||||
go build cmd/npc/npc.go
|
||||
.PHONY: build
|
||||
|
||||
# Install all the build and lint dependencies
|
||||
setup:
|
||||
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh
|
||||
curl -L https://git.io/misspell | sh
|
||||
go mod download
|
||||
.PHONY: setup
|
||||
|
||||
# Run all the tests
|
||||
test:
|
||||
go test $(TEST_OPTIONS) -failfast -race -coverpkg=./... -covermode=atomic -coverprofile=coverage.txt $(SOURCE_FILES) -run $(TEST_PATTERN) -timeout=2m
|
||||
.PHONY: test
|
||||
|
||||
# Run all the tests and opens the coverage report
|
||||
cover: test
|
||||
go tool cover -html=coverage.txt
|
||||
.PHONY: cover
|
||||
|
||||
# gofmt and goimports all go files
|
||||
fmt:
|
||||
find . -name '*.go' -not -wholename './vendor/*' | while read -r file; do gofmt -w -s "$$file"; goimports -w "$$file"; done
|
||||
.PHONY: fmt
|
||||
|
||||
# Run all the linters
|
||||
lint:
|
||||
# TODO: fix tests and lll issues
|
||||
./bin/golangci-lint run --tests=false --enable-all --disable=lll ./...
|
||||
./bin/misspell -error **/*
|
||||
.PHONY: lint
|
||||
|
||||
# Clean go.mod
|
||||
go-mod-tidy:
|
||||
@go mod tidy -v
|
||||
@git diff HEAD
|
||||
@git diff-index --quiet HEAD
|
||||
.PHONY: go-mod-tidy
|
||||
|
||||
# Run all the tests and code checks
|
||||
ci: build test lint go-mod-tidy
|
||||
.PHONY: ci
|
||||
|
||||
# Generate the static documentation
|
||||
static:
|
||||
@hugo --enableGitInfo --source www
|
||||
.PHONY: static
|
||||
|
||||
# Show to-do items per file.
|
||||
todo:
|
||||
@grep \
|
||||
--exclude-dir=vendor \
|
||||
--exclude-dir=node_modules \
|
||||
--exclude=Makefile \
|
||||
--text \
|
||||
--color \
|
||||
-nRo -E ' TODO:.*|SkipNow' .
|
||||
.PHONY: todo
|
||||
|
||||
clean:
|
||||
rm npc nps
|
||||
.PHONY: clean
|
||||
|
||||
.DEFAULT_GOAL := build
|
||||
+458
-235
@@ -1,293 +1,516 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
tunnel *utils.Conn
|
||||
signal *utils.Conn
|
||||
linkMap map[int]*utils.Link
|
||||
linkStatusMap map[int]bool
|
||||
stop chan bool
|
||||
sync.RWMutex
|
||||
tunnel *mux.Mux
|
||||
signal *conn.Conn
|
||||
file *mux.Mux
|
||||
retryTime int // it will be add 1 when ping not ok until to 3 will close the client
|
||||
}
|
||||
|
||||
func NewClient(t, f *mux.Mux, s *conn.Conn) *Client {
|
||||
return &Client{
|
||||
signal: s,
|
||||
tunnel: t,
|
||||
file: f,
|
||||
}
|
||||
}
|
||||
|
||||
type Bridge struct {
|
||||
TunnelPort int //通信隧道端口
|
||||
listener *net.TCPListener //server端监听
|
||||
Client map[int]*Client
|
||||
RunList map[int]interface{} //运行中的任务
|
||||
lock sync.Mutex
|
||||
tunnelLock sync.Mutex
|
||||
clientLock sync.Mutex
|
||||
TunnelPort int //通信隧道端口
|
||||
Client sync.Map
|
||||
Register sync.Map
|
||||
tunnelType string //bridge type kcp or tcp
|
||||
OpenTask chan *file.Tunnel
|
||||
CloseTask chan *file.Tunnel
|
||||
CloseClient chan int
|
||||
SecretChan chan *conn.Secret
|
||||
ipVerify bool
|
||||
runList map[int]interface{}
|
||||
}
|
||||
|
||||
func NewTunnel(tunnelPort int, runList map[int]interface{}) *Bridge {
|
||||
t := new(Bridge)
|
||||
t.TunnelPort = tunnelPort
|
||||
t.Client = make(map[int]*Client)
|
||||
t.RunList = runList
|
||||
return t
|
||||
func NewTunnel(tunnelPort int, tunnelType string, ipVerify bool, runList map[int]interface{}) *Bridge {
|
||||
return &Bridge{
|
||||
TunnelPort: tunnelPort,
|
||||
tunnelType: tunnelType,
|
||||
OpenTask: make(chan *file.Tunnel),
|
||||
CloseTask: make(chan *file.Tunnel),
|
||||
CloseClient: make(chan int),
|
||||
SecretChan: make(chan *conn.Secret),
|
||||
ipVerify: ipVerify,
|
||||
runList: runList,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) StartTunnel() error {
|
||||
var err error
|
||||
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.TunnelPort, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
go s.ping()
|
||||
if s.tunnelType == "kcp" {
|
||||
logs.Info("server start, the bridge type is %s, the bridge port is %d", s.tunnelType, s.TunnelPort)
|
||||
return conn.NewKcpListenerAndProcess(beego.AppConfig.String("bridge_ip")+":"+beego.AppConfig.String("bridge_port"), func(c net.Conn) {
|
||||
s.cliProcess(conn.NewConn(c))
|
||||
})
|
||||
} else {
|
||||
listener, err := connection.GetBridgeListener(s.tunnelType)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return err
|
||||
}
|
||||
conn.Accept(listener, func(c net.Conn) {
|
||||
s.cliProcess(conn.NewConn(c))
|
||||
})
|
||||
}
|
||||
go s.tunnelProcess()
|
||||
return nil
|
||||
}
|
||||
|
||||
//tcp server
|
||||
func (s *Bridge) tunnelProcess() error {
|
||||
var err error
|
||||
//get health information form client
|
||||
func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn) {
|
||||
for {
|
||||
conn, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
utils.Println(err)
|
||||
continue
|
||||
if info, status, err := c.GetHealthInfo(); err != nil {
|
||||
break
|
||||
} else if !status { //the status is true , return target to the targetArr
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if v.Client.Id == id && v.Mode == "tcp" && strings.Contains(v.Target.TargetStr, info) {
|
||||
v.Lock()
|
||||
if v.Target.TargetArr == nil || (len(v.Target.TargetArr) == 0 && len(v.HealthRemoveArr) == 0) {
|
||||
v.Target.TargetArr = common.TrimArr(strings.Split(v.Target.TargetStr, "\n"))
|
||||
}
|
||||
v.Target.TargetArr = common.RemoveArrVal(v.Target.TargetArr, info)
|
||||
if v.HealthRemoveArr == nil {
|
||||
v.HealthRemoveArr = make([]string, 0)
|
||||
}
|
||||
v.HealthRemoveArr = append(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
return true
|
||||
})
|
||||
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Host)
|
||||
if v.Client.Id == id && strings.Contains(v.Target.TargetStr, info) {
|
||||
v.Lock()
|
||||
if v.Target.TargetArr == nil || (len(v.Target.TargetArr) == 0 && len(v.HealthRemoveArr) == 0) {
|
||||
v.Target.TargetArr = common.TrimArr(strings.Split(v.Target.TargetStr, "\n"))
|
||||
}
|
||||
v.Target.TargetArr = common.RemoveArrVal(v.Target.TargetArr, info)
|
||||
if v.HealthRemoveArr == nil {
|
||||
v.HealthRemoveArr = make([]string, 0)
|
||||
}
|
||||
v.HealthRemoveArr = append(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
return true
|
||||
})
|
||||
} else { //the status is false,remove target from the targetArr
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if v.Client.Id == id && v.Mode == "tcp" && common.IsArrContains(v.HealthRemoveArr, info) && !common.IsArrContains(v.Target.TargetArr, info) {
|
||||
v.Lock()
|
||||
v.Target.TargetArr = append(v.Target.TargetArr, info)
|
||||
v.HealthRemoveArr = common.RemoveArrVal(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Host)
|
||||
if v.Client.Id == id && common.IsArrContains(v.HealthRemoveArr, info) && !common.IsArrContains(v.Target.TargetArr, info) {
|
||||
v.Lock()
|
||||
v.Target.TargetArr = append(v.Target.TargetArr, info)
|
||||
v.HealthRemoveArr = common.RemoveArrVal(v.HealthRemoveArr, info)
|
||||
v.Unlock()
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
go s.cliProcess(utils.NewConn(conn))
|
||||
}
|
||||
return err
|
||||
s.DelClient(id)
|
||||
}
|
||||
|
||||
//验证失败,返回错误验证flag,并且关闭连接
|
||||
func (s *Bridge) verifyError(c *utils.Conn) {
|
||||
c.Write([]byte(utils.VERIFY_EER))
|
||||
c.Conn.Close()
|
||||
func (s *Bridge) verifyError(c *conn.Conn) {
|
||||
c.Write([]byte(common.VERIFY_EER))
|
||||
}
|
||||
|
||||
func (s *Bridge) cliProcess(c *utils.Conn) {
|
||||
c.SetReadDeadline(5)
|
||||
var buf []byte
|
||||
var err error
|
||||
if buf, err = c.ReadLen(32); err != nil {
|
||||
func (s *Bridge) verifySuccess(c *conn.Conn) {
|
||||
c.Write([]byte(common.VERIFY_SUCCESS))
|
||||
}
|
||||
|
||||
func (s *Bridge) cliProcess(c *conn.Conn) {
|
||||
//read test flag
|
||||
if _, err := c.GetShortContent(3); err != nil {
|
||||
logs.Info("The client %s connect error", c.Conn.RemoteAddr(), err.Error())
|
||||
return
|
||||
}
|
||||
//version check
|
||||
if b, err := c.GetShortContent(32); err != nil || string(b) != crypt.Md5(version.GetVersion()) {
|
||||
logs.Info("The client %s version does not match", c.Conn.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//验证
|
||||
id, err := utils.GetCsvDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
|
||||
if err != nil {
|
||||
utils.Println("当前客户端连接校验错误,关闭此客户端:", c.Conn.RemoteAddr())
|
||||
s.verifyError(c)
|
||||
//write server version to client
|
||||
c.Write([]byte(crypt.Md5(version.GetVersion())))
|
||||
c.SetReadDeadlineBySecond(5)
|
||||
var buf []byte
|
||||
var err error
|
||||
//get vKey from client
|
||||
if buf, err = c.GetShortContent(32); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//做一个判断 添加到对应的channel里面以供使用
|
||||
//verify
|
||||
id, err := file.GetDb().GetIdByVerifyKey(string(buf), c.Conn.RemoteAddr().String())
|
||||
if err != nil {
|
||||
logs.Info("Current client connection validation error, close this client:", c.Conn.RemoteAddr())
|
||||
s.verifyError(c)
|
||||
return
|
||||
} else {
|
||||
s.verifySuccess(c)
|
||||
}
|
||||
if flag, err := c.ReadFlag(); err == nil {
|
||||
s.typeDeal(flag, c, id)
|
||||
} else {
|
||||
logs.Warn(err, flag)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Bridge) closeClient(id int) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
v.signal.WriteClose()
|
||||
delete(s.Client, id)
|
||||
}
|
||||
}
|
||||
|
||||
//tcp连接类型区分
|
||||
func (s *Bridge) typeDeal(typeVal string, c *utils.Conn, id int) {
|
||||
switch typeVal {
|
||||
case utils.WORK_MAIN:
|
||||
//客户端已经存在,下线
|
||||
s.clientLock.Lock()
|
||||
if _, ok := s.Client[id]; ok {
|
||||
s.clientLock.Unlock()
|
||||
s.closeClient(id)
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
func (s *Bridge) DelClient(id int) {
|
||||
if v, ok := s.Client.Load(id); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.Close()
|
||||
}
|
||||
s.clientLock.Lock()
|
||||
|
||||
s.Client[id] = &Client{
|
||||
linkMap: make(map[int]*utils.Link),
|
||||
stop: make(chan bool),
|
||||
linkStatusMap: make(map[int]bool),
|
||||
}
|
||||
utils.Printf("客户端%d连接成功,地址为:%s", id, c.Conn.RemoteAddr())
|
||||
s.Client[id].signal = c
|
||||
s.clientLock.Unlock()
|
||||
go s.GetStatus(id)
|
||||
case utils.WORK_CHAN:
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[id]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.tunnel = c
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
s.Client.Delete(id)
|
||||
if file.GetDb().IsPubClient(id) {
|
||||
return
|
||||
}
|
||||
go s.clientCopy(id)
|
||||
if c, err := file.GetDb().GetClient(id); err == nil {
|
||||
s.CloseClient <- c.Id
|
||||
}
|
||||
}
|
||||
c.SetAlive()
|
||||
}
|
||||
|
||||
//use different
|
||||
func (s *Bridge) typeDeal(typeVal string, c *conn.Conn, id int) {
|
||||
isPub := file.GetDb().IsPubClient(id)
|
||||
switch typeVal {
|
||||
case common.WORK_MAIN:
|
||||
if isPub {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
//the vKey connect by another ,close the client of before
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, nil, c)); ok {
|
||||
if v.(*Client).signal != nil {
|
||||
v.(*Client).signal.WriteClose()
|
||||
}
|
||||
v.(*Client).signal = c
|
||||
}
|
||||
go s.GetHealthFromClient(id, c)
|
||||
logs.Info("clientId %d connection succeeded, address:%s ", id, c.Conn.RemoteAddr())
|
||||
case common.WORK_CHAN:
|
||||
muxConn := mux.NewMux(c.Conn, s.tunnelType)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(muxConn, nil, nil)); ok {
|
||||
v.(*Client).tunnel = muxConn
|
||||
}
|
||||
case common.WORK_CONFIG:
|
||||
client, err := file.GetDb().GetClient(id)
|
||||
if err != nil || (!isPub && !client.ConfigConnAllow) {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
binary.Write(c, binary.LittleEndian, isPub)
|
||||
go s.getConfig(c, isPub, client)
|
||||
case common.WORK_REGISTER:
|
||||
go s.register(c)
|
||||
case common.WORK_SECRET:
|
||||
if b, err := c.GetShortContent(32); err == nil {
|
||||
s.SecretChan <- conn.NewSecret(string(b), c)
|
||||
} else {
|
||||
logs.Error("secret error, failed to match the key successfully")
|
||||
}
|
||||
case common.WORK_FILE:
|
||||
muxConn := mux.NewMux(c.Conn, s.tunnelType)
|
||||
if v, ok := s.Client.LoadOrStore(id, NewClient(nil, muxConn, nil)); ok {
|
||||
v.(*Client).file = muxConn
|
||||
}
|
||||
case common.WORK_P2P:
|
||||
//read md5 secret
|
||||
if b, err := c.GetShortContent(32); err != nil {
|
||||
logs.Error("p2p error,", err.Error())
|
||||
} else if t := file.GetDb().GetTaskByMd5Password(string(b)); t == nil {
|
||||
logs.Error("p2p error, failed to match the key successfully")
|
||||
} else {
|
||||
if v, ok := s.Client.Load(t.Client.Id); !ok {
|
||||
return
|
||||
} else {
|
||||
//向密钥对应的客户端发送与服务端udp建立连接信息,地址,密钥
|
||||
v.(*Client).signal.Write([]byte(common.NEW_UDP_CONN))
|
||||
svrAddr := beego.AppConfig.String("p2p_ip") + ":" + beego.AppConfig.String("p2p_port")
|
||||
if err != nil {
|
||||
logs.Warn("get local udp addr error")
|
||||
return
|
||||
}
|
||||
v.(*Client).signal.WriteLenContent([]byte(svrAddr))
|
||||
v.(*Client).signal.WriteLenContent(b)
|
||||
//向该请求者发送建立连接请求,服务器地址
|
||||
c.WriteLenContent([]byte(svrAddr))
|
||||
}
|
||||
}
|
||||
}
|
||||
c.SetAlive(s.tunnelType)
|
||||
return
|
||||
}
|
||||
|
||||
//等待
|
||||
func (s *Bridge) waitStatus(clientId, id int) (bool) {
|
||||
ticker := time.NewTicker(time.Millisecond * 100)
|
||||
stop := time.After(time.Second * 10)
|
||||
//register ip
|
||||
func (s *Bridge) register(c *conn.Conn) {
|
||||
var hour int32
|
||||
if err := binary.Read(c, binary.LittleEndian, &hour); err == nil {
|
||||
s.Register.Store(common.GetIpByAddr(c.Conn.RemoteAddr().String()), time.Now().Add(time.Hour*time.Duration(hour)))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error) {
|
||||
//if the proxy type is local
|
||||
if link.LocalProxy {
|
||||
target, err = net.Dial("tcp", link.Host)
|
||||
return
|
||||
}
|
||||
if v, ok := s.Client.Load(clientId); ok {
|
||||
//If ip is restricted to do ip verification
|
||||
if s.ipVerify {
|
||||
ip := common.GetIpByAddr(link.RemoteAddr)
|
||||
if v, ok := s.Register.Load(ip); !ok {
|
||||
return nil, errors.New(fmt.Sprintf("The ip %s is not in the validation list", ip))
|
||||
} else {
|
||||
if !v.(time.Time).After(time.Now()) {
|
||||
return nil, errors.New(fmt.Sprintf("The validity of the ip %s has expired", ip))
|
||||
}
|
||||
}
|
||||
}
|
||||
var tunnel *mux.Mux
|
||||
if t != nil && t.Mode == "file" {
|
||||
tunnel = v.(*Client).file
|
||||
} else {
|
||||
tunnel = v.(*Client).tunnel
|
||||
}
|
||||
if tunnel == nil {
|
||||
err = errors.New("the client connect error")
|
||||
return
|
||||
}
|
||||
if target, err = tunnel.NewConn(); err != nil {
|
||||
return
|
||||
}
|
||||
if t != nil && t.Mode == "file" {
|
||||
//TODO if t.mode is file ,not use crypt or compress
|
||||
link.Crypt = false
|
||||
link.Compress = false
|
||||
return
|
||||
}
|
||||
if _, err = conn.NewConn(target).SendInfo(link, ""); err != nil {
|
||||
logs.Info("new connect error ,the target %s refuse to connect", link.Host)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
err = errors.New(fmt.Sprintf("the client %d is not connect", clientId))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Bridge) ping() {
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[clientId]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.Lock()
|
||||
if vv, ok := v.linkStatusMap[id]; ok {
|
||||
ticker.Stop()
|
||||
v.Unlock()
|
||||
return vv
|
||||
}
|
||||
v.Unlock()
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
}
|
||||
case <-stop:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Bridge) SendLinkInfo(clientId int, link *utils.Link) (tunnel *utils.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
if v, ok := s.Client[clientId]; ok {
|
||||
s.clientLock.Unlock()
|
||||
v.signal.SendLinkInfo(link)
|
||||
if err != nil {
|
||||
utils.Println("send error:", err, link.Id)
|
||||
s.DelClient(clientId)
|
||||
return
|
||||
}
|
||||
if v.tunnel == nil {
|
||||
err = errors.New("tunnel获取错误")
|
||||
return
|
||||
} else {
|
||||
tunnel = v.tunnel
|
||||
}
|
||||
v.Lock()
|
||||
v.linkMap[link.Id] = link
|
||||
v.Unlock()
|
||||
if !s.waitStatus(clientId, link.Id) {
|
||||
err = errors.New("连接失败")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
s.clientLock.Unlock()
|
||||
err = errors.New("客户端未连接")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//得到一个tcp隧道
|
||||
func (s *Bridge) GetTunnel(id int, en, de int, crypt, mux bool) (conn *utils.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; !ok {
|
||||
err = errors.New("客户端未连接")
|
||||
} else {
|
||||
conn = v.tunnel
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//得到一个通信通道
|
||||
func (s *Bridge) GetSignal(id int) (conn *utils.Conn, err error) {
|
||||
s.clientLock.Lock()
|
||||
defer s.clientLock.Unlock()
|
||||
if v, ok := s.Client[id]; !ok {
|
||||
err = errors.New("客户端未连接")
|
||||
} else {
|
||||
conn = v.signal
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//删除通信通道
|
||||
func (s *Bridge) DelClient(id int) {
|
||||
s.closeClient(id)
|
||||
}
|
||||
|
||||
func (s *Bridge) verify(id int) bool {
|
||||
for k := range s.RunList {
|
||||
if k == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (s *Bridge) GetStatus(clientId int) {
|
||||
s.clientLock.Lock()
|
||||
client := s.Client[clientId]
|
||||
s.clientLock.Unlock()
|
||||
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
if id, status, err := client.signal.GetConnStatus(); err != nil {
|
||||
s.closeClient(clientId)
|
||||
return
|
||||
} else {
|
||||
client.Lock()
|
||||
client.linkStatusMap[id] = status
|
||||
client.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Bridge) clientCopy(clientId int) {
|
||||
|
||||
s.clientLock.Lock()
|
||||
client := s.Client[clientId]
|
||||
s.clientLock.Unlock()
|
||||
|
||||
for {
|
||||
if id, err := client.tunnel.GetLen(); err != nil {
|
||||
s.closeClient(clientId)
|
||||
utils.Println("读取msg id 错误", err, id)
|
||||
break
|
||||
} else {
|
||||
client.Lock()
|
||||
if link, ok := client.linkMap[id]; ok {
|
||||
client.Unlock()
|
||||
if content, err := client.tunnel.GetMsgContent(link); err != nil {
|
||||
utils.PutBufPoolCopy(content)
|
||||
s.closeClient(clientId)
|
||||
utils.Println("read msg content error", err, "close client")
|
||||
break
|
||||
} else {
|
||||
if len(content) == len(utils.IO_EOF) && string(content) == utils.IO_EOF {
|
||||
if link.Conn != nil {
|
||||
link.Conn.Close()
|
||||
}
|
||||
} else {
|
||||
if link.UdpListener != nil && link.UdpRemoteAddr != nil {
|
||||
link.UdpListener.WriteToUDP(content, link.UdpRemoteAddr)
|
||||
} else {
|
||||
link.Conn.Write(content)
|
||||
}
|
||||
link.Flow.Add(0, len(content))
|
||||
arr := make([]int, 0)
|
||||
s.Client.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if v.tunnel == nil || v.signal == nil {
|
||||
v.retryTime += 1
|
||||
if v.retryTime >= 3 {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
utils.PutBufPoolCopy(content)
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
client.Unlock()
|
||||
continue
|
||||
if v.tunnel.IsClose {
|
||||
arr = append(arr, key.(int))
|
||||
}
|
||||
return true
|
||||
})
|
||||
for _, v := range arr {
|
||||
logs.Info("the client %d closed", v)
|
||||
s.DelClient(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//get config and add task from client config
|
||||
func (s *Bridge) getConfig(c *conn.Conn, isPub bool, client *file.Client) {
|
||||
var fail bool
|
||||
loop:
|
||||
for {
|
||||
flag, err := c.ReadFlag()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch flag {
|
||||
case common.WORK_STATUS:
|
||||
if b, err := c.GetShortContent(32); err != nil {
|
||||
break loop
|
||||
} else {
|
||||
var str string
|
||||
id, err := file.GetDb().GetClientIdByVkey(string(b))
|
||||
if err != nil {
|
||||
break loop
|
||||
}
|
||||
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Host)
|
||||
if v.Client.Id == id {
|
||||
str += v.Remark + common.CONN_DATA_SEQ
|
||||
}
|
||||
return true
|
||||
})
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if _, ok := s.runList[v.Id]; ok && v.Client.Id == id {
|
||||
str += v.Remark + common.CONN_DATA_SEQ
|
||||
}
|
||||
return true
|
||||
})
|
||||
binary.Write(c, binary.LittleEndian, int32(len([]byte(str))))
|
||||
binary.Write(c, binary.LittleEndian, []byte(str))
|
||||
}
|
||||
case common.NEW_CONF:
|
||||
var err error
|
||||
if client, err = c.GetConfigInfo(); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
if err = file.GetDb().NewClient(client); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
c.WriteAddOk()
|
||||
c.Write([]byte(client.VerifyKey))
|
||||
s.Client.Store(client.Id, NewClient(nil, nil, nil))
|
||||
}
|
||||
case common.NEW_HOST:
|
||||
h, err := c.GetHostInfo()
|
||||
if err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
h.Client = client
|
||||
if h.Location == "" {
|
||||
h.Location = "/"
|
||||
}
|
||||
if !client.HasHost(h) {
|
||||
if file.GetDb().IsHostExist(h) {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
file.GetDb().NewHost(h)
|
||||
c.WriteAddOk()
|
||||
}
|
||||
} else {
|
||||
c.WriteAddOk()
|
||||
}
|
||||
case common.NEW_TASK:
|
||||
if t, err := c.GetTaskInfo(); err != nil {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
ports := common.GetPorts(t.Ports)
|
||||
targets := common.GetPorts(t.Target.TargetStr)
|
||||
if len(ports) > 1 && (t.Mode == "tcp" || t.Mode == "udp") && (len(ports) != len(targets)) {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else if t.Mode == "secret" || t.Mode == "p2p" {
|
||||
ports = append(ports, 0)
|
||||
}
|
||||
if len(ports) == 0 {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
for i := 0; i < len(ports); i++ {
|
||||
tl := new(file.Tunnel)
|
||||
tl.Mode = t.Mode
|
||||
tl.Port = ports[i]
|
||||
tl.ServerIp = t.ServerIp
|
||||
if len(ports) == 1 {
|
||||
tl.Target = t.Target
|
||||
tl.Remark = t.Remark
|
||||
} else {
|
||||
tl.Remark = t.Remark + "_" + strconv.Itoa(tl.Port)
|
||||
tl.Target = new(file.Target)
|
||||
if t.TargetAddr != "" {
|
||||
tl.Target.TargetStr = t.TargetAddr + ":" + strconv.Itoa(targets[i])
|
||||
} else {
|
||||
tl.Target.TargetStr = strconv.Itoa(targets[i])
|
||||
}
|
||||
}
|
||||
tl.Id = int(file.GetDb().JsonDb.GetTaskId())
|
||||
tl.Status = true
|
||||
tl.Flow = new(file.Flow)
|
||||
tl.NoStore = true
|
||||
tl.Client = client
|
||||
tl.Password = t.Password
|
||||
tl.LocalPath = t.LocalPath
|
||||
tl.StripPre = t.StripPre
|
||||
tl.MultiAccount = t.MultiAccount
|
||||
if !client.HasTunnel(tl) {
|
||||
if err := file.GetDb().NewTask(tl); err != nil {
|
||||
logs.Notice("Add task error ", err.Error())
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
}
|
||||
if b := tool.TestServerPort(tl.Port, tl.Mode); !b && t.Mode != "secret" && t.Mode != "p2p" {
|
||||
fail = true
|
||||
c.WriteAddFail()
|
||||
break loop
|
||||
} else {
|
||||
s.OpenTask <- tl
|
||||
}
|
||||
}
|
||||
c.WriteAddOk()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if fail && client != nil {
|
||||
s.DelClient(client.Id)
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
|
||||
+191
-144
@@ -1,179 +1,226 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"bufio"
|
||||
"net"
|
||||
"sync"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/xtaci/kcp-go"
|
||||
)
|
||||
|
||||
type TRPClient struct {
|
||||
svrAddr string
|
||||
linkMap map[int]*utils.Link
|
||||
stop chan bool
|
||||
tunnel *utils.Conn
|
||||
sync.Mutex
|
||||
vKey string
|
||||
svrAddr string
|
||||
bridgeConnType string
|
||||
proxyUrl string
|
||||
vKey string
|
||||
p2pAddr map[string]string
|
||||
tunnel *mux.Mux
|
||||
signal *conn.Conn
|
||||
ticker *time.Ticker
|
||||
cnf *config.Config
|
||||
}
|
||||
|
||||
//new client
|
||||
func NewRPClient(svraddr string, vKey string) *TRPClient {
|
||||
func NewRPClient(svraddr string, vKey string, bridgeConnType string, proxyUrl string, cnf *config.Config) *TRPClient {
|
||||
return &TRPClient{
|
||||
svrAddr: svraddr,
|
||||
linkMap: make(map[int]*utils.Link),
|
||||
stop: make(chan bool),
|
||||
tunnel: nil,
|
||||
Mutex: sync.Mutex{},
|
||||
vKey: vKey,
|
||||
svrAddr: svraddr,
|
||||
p2pAddr: make(map[string]string, 0),
|
||||
vKey: vKey,
|
||||
bridgeConnType: bridgeConnType,
|
||||
proxyUrl: proxyUrl,
|
||||
cnf: cnf,
|
||||
}
|
||||
}
|
||||
|
||||
//start
|
||||
func (s *TRPClient) Start() error {
|
||||
s.NewConn()
|
||||
return nil
|
||||
}
|
||||
|
||||
//新建
|
||||
func (s *TRPClient) NewConn() {
|
||||
func (s *TRPClient) Start() {
|
||||
retry:
|
||||
conn, err := net.Dial("tcp", s.svrAddr)
|
||||
c, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_MAIN, s.proxyUrl)
|
||||
if err != nil {
|
||||
utils.Println("连接服务端失败,五秒后将重连")
|
||||
logs.Error("The connection server failed and will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
goto retry
|
||||
return
|
||||
}
|
||||
s.processor(utils.NewConn(conn))
|
||||
if c == nil {
|
||||
logs.Error("Error data from server, and will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
goto retry
|
||||
}
|
||||
logs.Info("Successful connection with server %s", s.svrAddr)
|
||||
//monitor the connection
|
||||
go s.ping()
|
||||
s.signal = c
|
||||
//start a channel connection
|
||||
go s.newChan()
|
||||
//start health check if the it's open
|
||||
if s.cnf != nil && len(s.cnf.Healths) > 0 {
|
||||
go heathCheck(s.cnf.Healths, s.signal)
|
||||
}
|
||||
//msg connection, eg udp
|
||||
s.handleMain()
|
||||
}
|
||||
|
||||
//处理
|
||||
func (s *TRPClient) processor(c *utils.Conn) {
|
||||
c.SetAlive()
|
||||
if _, err := c.Write([]byte(utils.Getverifyval(s.vKey))); err != nil {
|
||||
return
|
||||
}
|
||||
c.WriteMain()
|
||||
|
||||
go s.dealChan()
|
||||
|
||||
//handle main connection
|
||||
func (s *TRPClient) handleMain() {
|
||||
for {
|
||||
flags, err := c.ReadFlag()
|
||||
flags, err := s.signal.ReadFlag()
|
||||
if err != nil {
|
||||
utils.Println("服务端断开,正在重新连接")
|
||||
logs.Error("Accept server data error %s, end this service", err.Error())
|
||||
break
|
||||
}
|
||||
switch flags {
|
||||
case utils.VERIFY_EER:
|
||||
utils.Fatalf("vKey:%s不正确,服务端拒绝连接,请检查", s.vKey)
|
||||
case utils.NEW_CONN:
|
||||
if link, err := c.GetLinkInfo(); err != nil {
|
||||
break
|
||||
} else {
|
||||
s.Lock()
|
||||
s.linkMap[link.Id] = link
|
||||
s.Unlock()
|
||||
go s.linkProcess(link, c)
|
||||
}
|
||||
case utils.RES_CLOSE:
|
||||
utils.Fatalln("该vkey被另一客户连接")
|
||||
case utils.RES_MSG:
|
||||
utils.Println("服务端返回错误,重新连接")
|
||||
break
|
||||
default:
|
||||
utils.Println("无法解析该错误,重新连接")
|
||||
break
|
||||
}
|
||||
}
|
||||
s.stop <- true
|
||||
s.linkMap = make(map[int]*utils.Link)
|
||||
go s.NewConn()
|
||||
}
|
||||
func (s *TRPClient) linkProcess(link *utils.Link, c *utils.Conn) {
|
||||
//与目标建立连接
|
||||
server, err := net.DialTimeout(link.ConnType, link.Host, time.Second*3)
|
||||
|
||||
if err != nil {
|
||||
c.WriteFail(link.Id)
|
||||
utils.Println("connect to ", link.Host, "error:", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.WriteSuccess(link.Id)
|
||||
|
||||
link.Conn = utils.NewConn(server)
|
||||
|
||||
for {
|
||||
buf := utils.BufPoolCopy.Get().([]byte)
|
||||
if n, err := server.Read(buf); err != nil {
|
||||
utils.PutBufPoolCopy(buf)
|
||||
s.tunnel.SendMsg([]byte(utils.IO_EOF), link)
|
||||
break
|
||||
} else {
|
||||
if _, err := s.tunnel.SendMsg(buf[:n], link); err != nil {
|
||||
utils.PutBufPoolCopy(buf)
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
utils.PutBufPoolCopy(buf)
|
||||
//if link.ConnType == utils.CONN_UDP {
|
||||
// c.Close()
|
||||
// break
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
delete(s.linkMap, link.Id)
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
//隧道模式处理
|
||||
func (s *TRPClient) dealChan() {
|
||||
var err error
|
||||
//创建一个tcp连接
|
||||
conn, err := net.Dial("tcp", s.svrAddr)
|
||||
if err != nil {
|
||||
utils.Println("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
//验证
|
||||
if _, err := conn.Write([]byte(utils.Getverifyval(s.vKey))); err != nil {
|
||||
utils.Println("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
//默认长连接保持
|
||||
s.tunnel = utils.NewConn(conn)
|
||||
s.tunnel.SetAlive()
|
||||
//写标志
|
||||
s.tunnel.WriteChan()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
if id, err := s.tunnel.GetLen(); err != nil {
|
||||
utils.Println("get msg id error")
|
||||
break
|
||||
} else {
|
||||
s.Lock()
|
||||
if v, ok := s.linkMap[id]; ok {
|
||||
s.Unlock()
|
||||
if content, err := s.tunnel.GetMsgContent(v); err != nil {
|
||||
utils.Println("get msg content error:", err, id)
|
||||
break
|
||||
} else {
|
||||
if len(content) == len(utils.IO_EOF) && string(content) == utils.IO_EOF {
|
||||
v.Conn.Close()
|
||||
} else if v.Conn != nil {
|
||||
v.Conn.Write(content)
|
||||
}
|
||||
case common.NEW_UDP_CONN:
|
||||
//read server udp addr and password
|
||||
if lAddr, err := s.signal.GetShortLenContent(); err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
} else if pwd, err := s.signal.GetShortLenContent(); err == nil {
|
||||
var localAddr string
|
||||
//The local port remains unchanged for a certain period of time
|
||||
if v, ok := s.p2pAddr[crypt.Md5(string(pwd)+strconv.Itoa(int(time.Now().Unix()/100)))]; !ok {
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
localAddr = tmpConn.LocalAddr().String()
|
||||
} else {
|
||||
s.Unlock()
|
||||
localAddr = v
|
||||
}
|
||||
go s.newUdpConn(localAddr, string(lAddr), string(pwd))
|
||||
}
|
||||
}
|
||||
}
|
||||
s.Close()
|
||||
}
|
||||
|
||||
func (s *TRPClient) newUdpConn(localAddr, rAddr string, md5Password string) {
|
||||
var localConn net.PacketConn
|
||||
var err error
|
||||
var remoteAddress string
|
||||
if remoteAddress, localConn, err = handleP2PUdp(localAddr, rAddr, md5Password, common.WORK_P2P_PROVIDER); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
l, err := kcp.ServeConn(nil, 150, 3, localConn)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
logs.Trace("start local p2p udp listen, local address", localConn.LocalAddr().String())
|
||||
for {
|
||||
udpTunnel, err := l.AcceptKCP()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
l.Close()
|
||||
return
|
||||
}
|
||||
if udpTunnel.RemoteAddr().String() == string(remoteAddress) {
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
logs.Trace("successful connection with client ,address %s", udpTunnel.RemoteAddr().String())
|
||||
//read link info from remote
|
||||
conn.Accept(mux.NewMux(udpTunnel, s.bridgeConnType), func(c net.Conn) {
|
||||
go s.handleChan(c)
|
||||
})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//mux tunnel
|
||||
func (s *TRPClient) newChan() {
|
||||
tunnel, err := NewConn(s.bridgeConnType, s.vKey, s.svrAddr, common.WORK_CHAN, s.proxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("connect to ", s.svrAddr, "error:", err)
|
||||
return
|
||||
}
|
||||
s.tunnel = mux.NewMux(tunnel.Conn, s.bridgeConnType)
|
||||
for {
|
||||
src, err := s.tunnel.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
go s.handleChan(src)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TRPClient) handleChan(src net.Conn) {
|
||||
lk, err := conn.NewConn(src).GetLinkInfo()
|
||||
if err != nil {
|
||||
src.Close()
|
||||
logs.Error("get connection info from server error ", err)
|
||||
return
|
||||
}
|
||||
//host for target processing
|
||||
lk.Host = common.FormatAddress(lk.Host)
|
||||
//if Conn type is http, read the request and log
|
||||
if lk.ConnType == "http" {
|
||||
if targetConn, err := net.Dial(common.CONN_TCP, lk.Host); err != nil {
|
||||
logs.Warn("connect to %s error %s", lk.Host, err.Error())
|
||||
src.Close()
|
||||
} else {
|
||||
srcConn := conn.GetConn(src, lk.Crypt, lk.Compress, nil, false)
|
||||
go func() {
|
||||
common.CopyBuffer(srcConn, targetConn)
|
||||
srcConn.Close()
|
||||
targetConn.Close()
|
||||
}()
|
||||
for {
|
||||
if r, err := http.ReadRequest(bufio.NewReader(srcConn)); err != nil {
|
||||
srcConn.Close()
|
||||
targetConn.Close()
|
||||
break
|
||||
} else {
|
||||
logs.Trace("http request, method %s, host %s, url %s, remote address %s", r.Method, r.Host, r.URL.Path, r.RemoteAddr)
|
||||
r.Write(targetConn)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
select {
|
||||
case <-s.stop:
|
||||
return
|
||||
}
|
||||
//connect to target if conn type is tcp or udp
|
||||
if targetConn, err := net.Dial(lk.ConnType, lk.Host); err != nil {
|
||||
logs.Warn("connect to %s error %s", lk.Host, err.Error())
|
||||
src.Close()
|
||||
} else {
|
||||
logs.Trace("new %s connection with the goal of %s, remote address:%s", lk.ConnType, lk.Host, lk.RemoteAddr)
|
||||
conn.CopyWaitGroup(src, targetConn, lk.Crypt, lk.Compress, nil, nil, false, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// Whether the monitor channel is closed
|
||||
func (s *TRPClient) ping() {
|
||||
s.ticker = time.NewTicker(time.Second * 5)
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case <-s.ticker.C:
|
||||
if s.tunnel != nil && s.tunnel.IsClose {
|
||||
s.Close()
|
||||
break loop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TRPClient) Close() {
|
||||
if s.tunnel != nil {
|
||||
s.tunnel.Close()
|
||||
}
|
||||
if s.signal != nil {
|
||||
s.signal.Close()
|
||||
}
|
||||
if s.ticker != nil {
|
||||
s.ticker.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
conn2 "github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
)
|
||||
|
||||
func TestConfig(t *testing.T) {
|
||||
conn, err := net.Dial("tcp", "127.0.0.1:8284")
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
c := conn2.NewConn(conn)
|
||||
c.SetAlive("tcp")
|
||||
if _, err := c.Write([]byte(common.Getverifyval("123"))); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
c.WriteConfig()
|
||||
config := &file.Config{
|
||||
U: "1",
|
||||
P: "2",
|
||||
Compress: "snappy",
|
||||
Crypt: true,
|
||||
CompressEncode: 0,
|
||||
CompressDecode: 0,
|
||||
}
|
||||
host := &file.Host{
|
||||
Host: "a.o.com",
|
||||
Target: "127.0.0.1:8080",
|
||||
HeaderChange: "",
|
||||
HostChange: "",
|
||||
Flow: nil,
|
||||
Client: nil,
|
||||
Remark: "111",
|
||||
NowIndex: 0,
|
||||
TargetArr: nil,
|
||||
NoStore: false,
|
||||
RWMutex: sync.RWMutex{},
|
||||
}
|
||||
tunnel := &file.Tunnel{
|
||||
Port: 9001,
|
||||
Mode: "tcp",
|
||||
Target: "127.0.0.1:8082",
|
||||
Remark: "333",
|
||||
}
|
||||
var b []byte
|
||||
if b, err = c.ReadLen(16); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if _, err := c.SendConfigInfo(config); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
t.Fail()
|
||||
}
|
||||
if _, err := c.SendHostInfo(host); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
t.Fail()
|
||||
}
|
||||
if _, err := c.SendTaskInfo(tunnel); err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
t.Fail()
|
||||
}
|
||||
c.Close()
|
||||
NewRPClient("127.0.0.1:8284", string(b), "tcp").Start()
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/xtaci/kcp-go"
|
||||
"golang.org/x/net/proxy"
|
||||
)
|
||||
|
||||
func GetTaskStatus(path string) {
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if _, err := c.Write([]byte(common.WORK_STATUS)); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
//read now vKey and write to server
|
||||
if f, err := common.ReadAllFromFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt")); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if _, err := c.Write([]byte(crypt.Md5(string(f)))); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
var isPub bool
|
||||
binary.Read(c, binary.LittleEndian, &isPub)
|
||||
if l, err := c.GetLen(); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else if b, err := c.GetShortContent(l); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else {
|
||||
arr := strings.Split(string(b), common.CONN_DATA_SEQ)
|
||||
for _, v := range cnf.Hosts {
|
||||
if common.InStrArr(arr, v.Remark) {
|
||||
log.Println(v.Remark, "ok")
|
||||
} else {
|
||||
log.Println(v.Remark, "not running")
|
||||
}
|
||||
}
|
||||
for _, v := range cnf.Tasks {
|
||||
ports := common.GetPorts(v.Ports)
|
||||
if v.Mode == "secret" {
|
||||
ports = append(ports, 0)
|
||||
}
|
||||
for _, vv := range ports {
|
||||
var remark string
|
||||
if len(ports) > 1 {
|
||||
remark = v.Remark + "_" + strconv.Itoa(vv)
|
||||
} else {
|
||||
remark = v.Remark
|
||||
}
|
||||
if common.InStrArr(arr, remark) {
|
||||
log.Println(remark, "ok")
|
||||
} else {
|
||||
log.Println(remark, "not running")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
var errAdd = errors.New("The server returned an error, which port or host may have been occupied or not allowed to open.")
|
||||
|
||||
func StartFromFile(path string) {
|
||||
first := true
|
||||
cnf, err := config.NewConfig(path)
|
||||
if err != nil || cnf.CommonConfig == nil {
|
||||
logs.Error("Config file %s loading error %s", path, err.Error())
|
||||
os.Exit(0)
|
||||
}
|
||||
logs.Info("Loading configuration file %s successfully", path)
|
||||
|
||||
re:
|
||||
if first || cnf.CommonConfig.AutoReconnection {
|
||||
if !first {
|
||||
logs.Info("Reconnecting...")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
first = false
|
||||
c, err := NewConn(cnf.CommonConfig.Tp, cnf.CommonConfig.VKey, cnf.CommonConfig.Server, common.WORK_CONFIG, cnf.CommonConfig.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
var isPub bool
|
||||
binary.Read(c, binary.LittleEndian, &isPub)
|
||||
|
||||
// get tmp password
|
||||
var b []byte
|
||||
vkey := cnf.CommonConfig.VKey
|
||||
if isPub {
|
||||
// send global configuration to server and get status of config setting
|
||||
if _, err := c.SendInfo(cnf.CommonConfig.Client, common.NEW_CONF); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error("the web_user may have been occupied!")
|
||||
goto re
|
||||
}
|
||||
|
||||
if b, err = c.GetShortContent(16); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
vkey = string(b)
|
||||
}
|
||||
ioutil.WriteFile(filepath.Join(common.GetTmpPath(), "npc_vkey.txt"), []byte(vkey), 0600)
|
||||
|
||||
//send hosts to server
|
||||
for _, v := range cnf.Hosts {
|
||||
if _, err := c.SendInfo(v, common.NEW_HOST); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd, v.Host)
|
||||
goto re
|
||||
}
|
||||
}
|
||||
|
||||
//send task to server
|
||||
for _, v := range cnf.Tasks {
|
||||
if _, err := c.SendInfo(v, common.NEW_TASK); err != nil {
|
||||
logs.Error(err)
|
||||
goto re
|
||||
}
|
||||
if !c.GetAddStatus() {
|
||||
logs.Error(errAdd, v.Ports, v.Remark)
|
||||
goto re
|
||||
}
|
||||
if v.Mode == "file" {
|
||||
//start local file server
|
||||
go startLocalFileServer(cnf.CommonConfig, v, vkey)
|
||||
}
|
||||
}
|
||||
|
||||
//create local server secret or p2p
|
||||
for _, v := range cnf.LocalServer {
|
||||
go StartLocalServer(v, cnf.CommonConfig)
|
||||
}
|
||||
|
||||
c.Close()
|
||||
if cnf.CommonConfig.Client.WebUserName == "" || cnf.CommonConfig.Client.WebPassword == "" {
|
||||
logs.Notice("web access login username:user password:%s", vkey)
|
||||
} else {
|
||||
logs.Notice("web access login username:%s password:%s", cnf.CommonConfig.Client.WebUserName, cnf.CommonConfig.Client.WebPassword)
|
||||
}
|
||||
NewRPClient(cnf.CommonConfig.Server, vkey, cnf.CommonConfig.Tp, cnf.CommonConfig.ProxyUrl, cnf).Start()
|
||||
CloseLocalServer()
|
||||
goto re
|
||||
}
|
||||
|
||||
// Create a new connection with the server and verify it
|
||||
func NewConn(tp string, vkey string, server string, connType string, proxyUrl string) (*conn.Conn, error) {
|
||||
var err error
|
||||
var connection net.Conn
|
||||
var sess *kcp.UDPSession
|
||||
if tp == "tcp" {
|
||||
if proxyUrl != "" {
|
||||
u, er := url.Parse(proxyUrl)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "socks5":
|
||||
n, er := proxy.FromURL(u, nil)
|
||||
if er != nil {
|
||||
return nil, er
|
||||
}
|
||||
connection, err = n.Dial("tcp", server)
|
||||
case "http":
|
||||
connection, err = NewHttpProxyConn(u, server)
|
||||
}
|
||||
} else {
|
||||
connection, err = net.Dial("tcp", server)
|
||||
}
|
||||
} else {
|
||||
sess, err = kcp.DialWithOptions(server, nil, 10, 3)
|
||||
if err == nil {
|
||||
conn.SetUdpSession(sess)
|
||||
connection = sess
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
connection.SetDeadline(time.Now().Add(time.Second * 10))
|
||||
defer connection.SetDeadline(time.Time{})
|
||||
c := conn.NewConn(connection)
|
||||
if _, err := c.Write([]byte(common.CONN_TEST)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := c.Write([]byte(crypt.Md5(version.GetVersion()))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := c.GetShortContent(32)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return nil, err
|
||||
}
|
||||
if crypt.Md5(version.GetVersion()) != string(b) {
|
||||
logs.Error("The client does not match the server version. The current core version of the client is", version.GetVersion())
|
||||
return nil, err
|
||||
}
|
||||
if _, err := c.Write([]byte(common.Getverifyval(vkey))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s, err := c.ReadFlag(); err != nil {
|
||||
return nil, err
|
||||
} else if s == common.VERIFY_EER {
|
||||
logs.Error("Validation key %s incorrect", vkey)
|
||||
os.Exit(0)
|
||||
}
|
||||
if _, err := c.Write([]byte(connType)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.SetAlive(tp)
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
//http proxy connection
|
||||
func NewHttpProxyConn(url *url.URL, remoteAddr string) (net.Conn, error) {
|
||||
req := &http.Request{
|
||||
Method: "CONNECT",
|
||||
URL: url,
|
||||
Host: remoteAddr,
|
||||
Header: http.Header{},
|
||||
Proto: "HTTP/1.1",
|
||||
}
|
||||
password, _ := url.User.Password()
|
||||
req.Header.Set("Proxy-Authorization", "Basic "+basicAuth(url.User.Username(), password))
|
||||
b, err := httputil.DumpRequest(req, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
proxyConn, err := net.Dial("tcp", url.Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := proxyConn.Write(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf := make([]byte, 1024)
|
||||
if _, err := proxyConn.Read(buf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return proxyConn, nil
|
||||
}
|
||||
|
||||
//get a basic auth string
|
||||
func basicAuth(username, password string) string {
|
||||
auth := username + ":" + password
|
||||
return base64.StdEncoding.EncodeToString([]byte(auth))
|
||||
}
|
||||
|
||||
func getRemoteAddressFromServer(rAddr string, localConn *net.UDPConn, md5Password, role string, add int) error {
|
||||
rAddr, err := getNextAddr(rAddr, add)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return err
|
||||
}
|
||||
addr, err := net.ResolveUDPAddr("udp", rAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := localConn.WriteTo(common.GetWriteStr(md5Password, role), addr); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleP2PUdp(localAddr, rAddr, md5Password, role string) (remoteAddress string, c net.PacketConn, err error) {
|
||||
localConn, err := newUdpConnByAddr(localAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = getRemoteAddressFromServer(rAddr, localConn, md5Password, role, 0)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
err = getRemoteAddressFromServer(rAddr, localConn, md5Password, role, 1)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
err = getRemoteAddressFromServer(rAddr, localConn, md5Password, role, 2)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
var remoteAddr1, remoteAddr2, remoteAddr3 string
|
||||
for {
|
||||
buf := make([]byte, 1024)
|
||||
if n, addr, er := localConn.ReadFromUDP(buf); er != nil {
|
||||
err = er
|
||||
return
|
||||
} else {
|
||||
rAddr2, _ := getNextAddr(rAddr, 1)
|
||||
rAddr3, _ := getNextAddr(rAddr, 2)
|
||||
switch addr.String() {
|
||||
case rAddr:
|
||||
remoteAddr1 = string(buf[:n])
|
||||
case rAddr2:
|
||||
remoteAddr2 = string(buf[:n])
|
||||
case rAddr3:
|
||||
remoteAddr3 = string(buf[:n])
|
||||
}
|
||||
}
|
||||
if remoteAddr1 != "" && remoteAddr2 != "" && remoteAddr3 != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if remoteAddress, err = sendP2PTestMsg(localConn, remoteAddr1, remoteAddr2, remoteAddr3); err != nil {
|
||||
return
|
||||
}
|
||||
c, err = newUdpConnByAddr(localAddr)
|
||||
return
|
||||
}
|
||||
|
||||
func sendP2PTestMsg(localConn *net.UDPConn, remoteAddr1, remoteAddr2, remoteAddr3 string) (string, error) {
|
||||
logs.Trace(remoteAddr3, remoteAddr2, remoteAddr1)
|
||||
defer localConn.Close()
|
||||
isClose := false
|
||||
defer func() { isClose = true }()
|
||||
interval, err := getAddrInterval(remoteAddr1, remoteAddr2, remoteAddr3)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
go func() {
|
||||
addr, err := getNextAddr(remoteAddr3, interval)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
remoteUdpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
logs.Trace("try send test packet to target %s", addr)
|
||||
ticker := time.NewTicker(time.Millisecond * 500)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
if interval != 0 {
|
||||
ip := common.GetIpByAddr(remoteAddr2)
|
||||
go func() {
|
||||
ports := getRandomPortArr(common.GetPortByAddr(remoteAddr3), common.GetPortByAddr(remoteAddr3)+interval*50)
|
||||
for i := 0; i <= 50; i++ {
|
||||
go func(port int) {
|
||||
trueAddress := ip + ":" + strconv.Itoa(port)
|
||||
logs.Trace("try send test packet to target %s", trueAddress)
|
||||
remoteUdpAddr, err := net.ResolveUDPAddr("udp", trueAddress)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ticker := time.NewTicker(time.Second * 2)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if isClose {
|
||||
return
|
||||
}
|
||||
if _, err := localConn.WriteTo([]byte(common.WORK_P2P_CONNECT), remoteUdpAddr); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}(ports[i])
|
||||
time.Sleep(time.Millisecond * 10)
|
||||
}
|
||||
}()
|
||||
|
||||
}
|
||||
|
||||
buf := make([]byte, 10)
|
||||
for {
|
||||
localConn.SetReadDeadline(time.Now().Add(time.Second * 10))
|
||||
n, addr, err := localConn.ReadFromUDP(buf)
|
||||
localConn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch string(buf[:n]) {
|
||||
case common.WORK_P2P_SUCCESS:
|
||||
for i := 20; i > 0; i-- {
|
||||
if _, err = localConn.WriteTo([]byte(common.WORK_P2P_END), addr); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
return addr.String(), nil
|
||||
case common.WORK_P2P_END:
|
||||
logs.Trace("Remotely Address %s Reply Packet Successfully Received", addr.String())
|
||||
return addr.String(), nil
|
||||
case common.WORK_P2P_CONNECT:
|
||||
go func() {
|
||||
for i := 20; i > 0; i-- {
|
||||
logs.Trace("try send receive success packet to target %s", addr.String())
|
||||
if _, err = localConn.WriteTo([]byte(common.WORK_P2P_SUCCESS), addr); err != nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}()
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
return "", errors.New("connect to the target failed, maybe the nat type is not support p2p")
|
||||
}
|
||||
|
||||
func newUdpConnByAddr(addr string) (*net.UDPConn, error) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return udpConn, nil
|
||||
}
|
||||
|
||||
func getNextAddr(addr string, n int) (string, error) {
|
||||
arr := strings.Split(addr, ":")
|
||||
if len(arr) != 2 {
|
||||
return "", errors.New(fmt.Sprintf("the format of %s incorrect", addr))
|
||||
}
|
||||
if p, err := strconv.Atoi(arr[1]); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
return arr[0] + ":" + strconv.Itoa(p+n), nil
|
||||
}
|
||||
}
|
||||
|
||||
func getAddrInterval(addr1, addr2, addr3 string) (int, error) {
|
||||
arr1 := strings.Split(addr1, ":")
|
||||
if len(arr1) != 2 {
|
||||
return 0, errors.New(fmt.Sprintf("the format of %s incorrect", addr1))
|
||||
}
|
||||
arr2 := strings.Split(addr2, ":")
|
||||
if len(arr2) != 2 {
|
||||
return 0, errors.New(fmt.Sprintf("the format of %s incorrect", addr2))
|
||||
}
|
||||
arr3 := strings.Split(addr3, ":")
|
||||
if len(arr3) != 2 {
|
||||
return 0, errors.New(fmt.Sprintf("the format of %s incorrect", addr3))
|
||||
}
|
||||
p1, err := strconv.Atoi(arr1[1])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
p2, err := strconv.Atoi(arr2[1])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
p3, err := strconv.Atoi(arr3[1])
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
interVal := int(math.Floor(math.Min(math.Abs(float64(p3-p2)), math.Abs(float64(p2-p1)))))
|
||||
if p3-p1 < 0 {
|
||||
return -interVal, nil
|
||||
}
|
||||
return interVal, nil
|
||||
}
|
||||
|
||||
func getRandomPortArr(min, max int) []int {
|
||||
if min > max {
|
||||
min, max = max, min
|
||||
}
|
||||
addrAddr := make([]int, max-min+1)
|
||||
for i := min; i <= max; i++ {
|
||||
addrAddr[max-i] = i
|
||||
}
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var r, temp int
|
||||
for i := max - min; i > 0; i-- {
|
||||
r = rand.Int() % i
|
||||
temp = addrAddr[i]
|
||||
addrAddr[i] = addrAddr[r]
|
||||
addrAddr[r] = temp
|
||||
}
|
||||
return addrAddr
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/sheap"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var isStart bool
|
||||
var serverConn *conn.Conn
|
||||
|
||||
func heathCheck(healths []*file.Health, c *conn.Conn) bool {
|
||||
serverConn = c
|
||||
if isStart {
|
||||
for _, v := range healths {
|
||||
v.HealthMap = make(map[string]int)
|
||||
}
|
||||
return true
|
||||
}
|
||||
isStart = true
|
||||
h := &sheap.IntHeap{}
|
||||
for _, v := range healths {
|
||||
if v.HealthMaxFail > 0 && v.HealthCheckTimeout > 0 && v.HealthCheckInterval > 0 {
|
||||
v.HealthNextTime = time.Now().Add(time.Duration(v.HealthCheckInterval) * time.Second)
|
||||
heap.Push(h, v.HealthNextTime.Unix())
|
||||
v.HealthMap = make(map[string]int)
|
||||
}
|
||||
}
|
||||
go session(healths, h)
|
||||
return true
|
||||
}
|
||||
|
||||
func session(healths []*file.Health, h *sheap.IntHeap) {
|
||||
for {
|
||||
if h.Len() == 0 {
|
||||
logs.Error("health check error")
|
||||
break
|
||||
}
|
||||
rs := heap.Pop(h).(int64) - time.Now().Unix()
|
||||
if rs <= 0 {
|
||||
continue
|
||||
}
|
||||
timer := time.NewTimer(time.Duration(rs) * time.Second)
|
||||
select {
|
||||
case <-timer.C:
|
||||
for _, v := range healths {
|
||||
if v.HealthNextTime.Before(time.Now()) {
|
||||
v.HealthNextTime = time.Now().Add(time.Duration(v.HealthCheckInterval) * time.Second)
|
||||
//check
|
||||
go check(v)
|
||||
//reset time
|
||||
heap.Push(h, v.HealthNextTime.Unix())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// work when just one port and many target
|
||||
func check(t *file.Health) {
|
||||
arr := strings.Split(t.HealthCheckTarget, ",")
|
||||
var err error
|
||||
var rs *http.Response
|
||||
for _, v := range arr {
|
||||
if t.HealthCheckType == "tcp" {
|
||||
var c net.Conn
|
||||
c, err = net.DialTimeout("tcp", v, time.Duration(t.HealthCheckTimeout)*time.Second)
|
||||
if err == nil {
|
||||
c.Close()
|
||||
}
|
||||
} else {
|
||||
client := &http.Client{}
|
||||
client.Timeout = time.Duration(t.HealthCheckTimeout) * time.Second
|
||||
rs, err = client.Get("http://" + v + t.HttpHealthUrl)
|
||||
if err == nil && rs.StatusCode != 200 {
|
||||
err = errors.New("status code is not match")
|
||||
}
|
||||
}
|
||||
t.Lock()
|
||||
if err != nil {
|
||||
t.HealthMap[v] += 1
|
||||
} else if t.HealthMap[v] >= t.HealthMaxFail {
|
||||
//send recovery add
|
||||
serverConn.SendHealthInfo(v, "1")
|
||||
t.HealthMap[v] = 0
|
||||
}
|
||||
|
||||
if t.HealthMap[v] > 0 && t.HealthMap[v]%t.HealthMaxFail == 0 {
|
||||
//send fail remove
|
||||
serverConn.SendHealthInfo(v, "0")
|
||||
}
|
||||
t.Unlock()
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/server/proxy"
|
||||
"github.com/xtaci/kcp-go"
|
||||
)
|
||||
|
||||
var (
|
||||
LocalServer []*net.TCPListener
|
||||
udpConn net.Conn
|
||||
muxSession *mux.Mux
|
||||
fileServer []*http.Server
|
||||
p2pNetBridge *p2pBridge
|
||||
lock sync.RWMutex
|
||||
udpConnStatus bool
|
||||
)
|
||||
|
||||
type p2pBridge struct {
|
||||
}
|
||||
|
||||
func (p2pBridge *p2pBridge) SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error) {
|
||||
nowConn, err := muxSession.NewConn()
|
||||
if err != nil {
|
||||
udpConn = nil
|
||||
return nil, err
|
||||
}
|
||||
if _, err := conn.NewConn(nowConn).SendInfo(link, ""); err != nil {
|
||||
udpConnStatus = false
|
||||
return nil, err
|
||||
}
|
||||
return nowConn, nil
|
||||
}
|
||||
|
||||
func CloseLocalServer() {
|
||||
for _, v := range LocalServer {
|
||||
v.Close()
|
||||
}
|
||||
for _, v := range fileServer {
|
||||
v.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func startLocalFileServer(config *config.CommonConfig, t *file.Tunnel, vkey string) {
|
||||
remoteConn, err := NewConn(config.Tp, vkey, config.Server, common.WORK_FILE, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
srv := &http.Server{
|
||||
Handler: http.StripPrefix(t.StripPre, http.FileServer(http.Dir(t.LocalPath))),
|
||||
}
|
||||
logs.Info("start local file system, local path %s, strip prefix %s ,remote port %s ", t.LocalPath, t.StripPre, t.Ports)
|
||||
fileServer = append(fileServer, srv)
|
||||
listener := mux.NewMux(remoteConn.Conn, common.CONN_TCP)
|
||||
logs.Error(srv.Serve(listener))
|
||||
}
|
||||
|
||||
func StartLocalServer(l *config.LocalServer, config *config.CommonConfig) error {
|
||||
if l.Type != "secret" {
|
||||
go handleUdpMonitor(config, l)
|
||||
}
|
||||
task := &file.Tunnel{
|
||||
Port: l.Port,
|
||||
ServerIp: "0.0.0.0",
|
||||
Status: true,
|
||||
Client: &file.Client{
|
||||
Cnf: &file.Config{
|
||||
U: "",
|
||||
P: "",
|
||||
Compress: config.Client.Cnf.Compress,
|
||||
},
|
||||
Status: true,
|
||||
RateLimit: 0,
|
||||
Flow: &file.Flow{},
|
||||
},
|
||||
Flow: &file.Flow{},
|
||||
Target: &file.Target{},
|
||||
}
|
||||
switch l.Type {
|
||||
case "p2ps":
|
||||
logs.Info("successful start-up of local socks5 monitoring, port", l.Port)
|
||||
return proxy.NewSock5ModeServer(p2pNetBridge, task).Start()
|
||||
case "p2pt":
|
||||
logs.Info("successful start-up of local tcp trans monitoring, port", l.Port)
|
||||
return proxy.NewTunnelModeServer(proxy.HandleTrans, p2pNetBridge, task).Start()
|
||||
case "p2p", "secret":
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), l.Port, ""})
|
||||
if err != nil {
|
||||
logs.Error("local listener startup failed port %d, error %s", l.Port, err.Error())
|
||||
return err
|
||||
}
|
||||
LocalServer = append(LocalServer, listener)
|
||||
logs.Info("successful start-up of local tcp monitoring, port", l.Port)
|
||||
conn.Accept(listener, func(c net.Conn) {
|
||||
logs.Trace("new %s connection", l.Type)
|
||||
if l.Type == "secret" {
|
||||
handleSecret(c, config, l)
|
||||
} else if l.Type == "p2p" {
|
||||
handleP2PVisitor(c, config, l)
|
||||
}
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func handleUdpMonitor(config *config.CommonConfig, l *config.LocalServer) {
|
||||
ticker := time.NewTicker(time.Second * 1)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if !udpConnStatus {
|
||||
udpConn = nil
|
||||
tmpConn, err := common.GetLocalUdpAddr()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
logs.Notice("try to connect to the server", i+1)
|
||||
newUdpConn(tmpConn.LocalAddr().String(), config, l)
|
||||
if udpConn != nil {
|
||||
udpConnStatus = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleSecret(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_SECRET, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := remoteConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
conn.CopyWaitGroup(remoteConn.Conn, localTcpConn, false, false, nil, nil, false, nil)
|
||||
}
|
||||
|
||||
func handleP2PVisitor(localTcpConn net.Conn, config *config.CommonConfig, l *config.LocalServer) {
|
||||
if udpConn == nil {
|
||||
logs.Notice("new conn, P2P can not penetrate successfully, traffic will be transferred through the server")
|
||||
handleSecret(localTcpConn, config, l)
|
||||
}
|
||||
logs.Trace("start trying to connect with the server")
|
||||
//TODO just support compress now because there is not tls file in client packages
|
||||
link := conn.NewLink(common.CONN_TCP, l.Target, false, config.Client.Cnf.Compress, localTcpConn.LocalAddr().String(), false)
|
||||
if target, err := p2pNetBridge.SendLinkInfo(0, link, nil); err != nil {
|
||||
logs.Error(err)
|
||||
udpConnStatus = false
|
||||
return
|
||||
} else {
|
||||
conn.CopyWaitGroup(target, localTcpConn, false, config.Client.Cnf.Compress, nil, nil, false, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func newUdpConn(localAddr string, config *config.CommonConfig, l *config.LocalServer) {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
remoteConn, err := NewConn(config.Tp, config.VKey, config.Server, common.WORK_P2P, config.ProxyUrl)
|
||||
if err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
if _, err := remoteConn.Write([]byte(crypt.Md5(l.Password))); err != nil {
|
||||
logs.Error("Local connection server failed ", err.Error())
|
||||
return
|
||||
}
|
||||
var rAddr []byte
|
||||
//读取服务端地址、密钥 继续做处理
|
||||
if rAddr, err = remoteConn.GetShortLenContent(); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
var localConn net.PacketConn
|
||||
var remoteAddress string
|
||||
if remoteAddress, localConn, err = handleP2PUdp(localAddr, string(rAddr), crypt.Md5(l.Password), common.WORK_P2P_VISITOR); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
udpTunnel, err := kcp.NewConn(remoteAddress, nil, 150, 3, localConn)
|
||||
if err != nil || udpTunnel == nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
}
|
||||
logs.Trace("successful create a connection with server", remoteAddress)
|
||||
conn.SetUdpSession(udpTunnel)
|
||||
udpConn = udpTunnel
|
||||
muxSession = mux.NewMux(udpConn, "kcp")
|
||||
p2pNetBridge = &p2pBridge{}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
func RegisterLocalIp(server string, vKey string, tp string, proxyUrl string, hour int) {
|
||||
c, err := NewConn(tp, vKey, server, common.WORK_REGISTER, proxyUrl)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := binary.Write(c, binary.LittleEndian, int32(hour)); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
log.Printf("Successful ip registration for local public network, the validity period is %d hours.", hour)
|
||||
os.Exit(0)
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/ccding/go-stun/stun"
|
||||
"github.com/cnlh/nps/client"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/config"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
)
|
||||
|
||||
var (
|
||||
serverAddr = flag.String("server", "", "Server addr (ip:port)")
|
||||
configPath = flag.String("config", "", "Configuration file path")
|
||||
verifyKey = flag.String("vkey", "", "Authentication key")
|
||||
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
|
||||
connType = flag.String("type", "tcp", "Connection type with the server(kcp|tcp)")
|
||||
proxyUrl = flag.String("proxy", "", "proxy socks5 url(eg:socks5://111:222@127.0.0.1:9007)")
|
||||
logLevel = flag.String("log_level", "7", "log level 0~7")
|
||||
registerTime = flag.Int("time", 2, "register time long /h")
|
||||
localPort = flag.Int("local_port", 2000, "p2p local port")
|
||||
password = flag.String("password", "", "p2p password flag")
|
||||
target = flag.String("target", "", "p2p target")
|
||||
localType = flag.String("local_type", "p2p", "p2p target")
|
||||
logPath = flag.String("log_path", "npc.log", "npc log path")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
if len(os.Args) >= 2 {
|
||||
switch os.Args[1] {
|
||||
case "status":
|
||||
if len(os.Args) > 2 {
|
||||
path := strings.Replace(os.Args[2], "-config=", "", -1)
|
||||
client.GetTaskStatus(path)
|
||||
}
|
||||
case "register":
|
||||
flag.CommandLine.Parse(os.Args[2:])
|
||||
client.RegisterLocalIp(*serverAddr, *verifyKey, *connType, *proxyUrl, *registerTime)
|
||||
case "nat":
|
||||
nat, host, err := stun.NewClient().Discover()
|
||||
if err != nil || host == nil {
|
||||
logs.Error("get nat type error", err)
|
||||
return
|
||||
}
|
||||
fmt.Printf("nat type: %s \npublic address: %s\n", nat.String(), host.String())
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
daemon.InitDaemon("npc", common.GetRunPath(), common.GetTmpPath())
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
if *logType == "stdout" {
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+*logLevel+`,"color":true}`)
|
||||
} else {
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+*logLevel+`,"filename":"`+*logPath+`","daily":false,"maxlines":100000,"color":true}`)
|
||||
}
|
||||
//p2p or secret command
|
||||
if *password != "" {
|
||||
commonConfig := new(config.CommonConfig)
|
||||
commonConfig.Server = *serverAddr
|
||||
commonConfig.VKey = *verifyKey
|
||||
commonConfig.Tp = *connType
|
||||
localServer := new(config.LocalServer)
|
||||
localServer.Type = *localType
|
||||
localServer.Password = *password
|
||||
localServer.Target = *target
|
||||
localServer.Port = *localPort
|
||||
commonConfig.Client = new(file.Client)
|
||||
commonConfig.Client.Cnf = new(file.Config)
|
||||
client.StartLocalServer(localServer, commonConfig)
|
||||
return
|
||||
}
|
||||
env := common.GetEnvMap()
|
||||
if *serverAddr == "" {
|
||||
*serverAddr, _ = env["NPC_SERVER_ADDR"]
|
||||
}
|
||||
if *verifyKey == "" {
|
||||
*verifyKey, _ = env["NPC_SERVER_VKEY"]
|
||||
}
|
||||
logs.Info("the version of client is %s, the core version of client is %s", version.VERSION, version.GetVersion())
|
||||
if *verifyKey != "" && *serverAddr != "" && *configPath == "" {
|
||||
for {
|
||||
client.NewRPClient(*serverAddr, *verifyKey, *connType, *proxyUrl, nil).Start()
|
||||
logs.Info("It will be reconnected in five seconds")
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
} else {
|
||||
if *configPath == "" {
|
||||
*configPath = "npc.conf"
|
||||
}
|
||||
client.StartFromFile(*configPath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/daemon"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/install"
|
||||
"github.com/cnlh/nps/lib/version"
|
||||
"github.com/cnlh/nps/server"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
"github.com/cnlh/nps/server/test"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
_ "github.com/cnlh/nps/web/routers"
|
||||
)
|
||||
|
||||
var (
|
||||
level string
|
||||
logType = flag.String("log", "stdout", "Log output mode(stdout|file)")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf"))
|
||||
if len(os.Args) > 1 {
|
||||
switch os.Args[1] {
|
||||
case "test":
|
||||
test.TestServerConfig()
|
||||
log.Println("test ok, no error")
|
||||
return
|
||||
case "start", "restart", "stop", "status", "reload":
|
||||
daemon.InitDaemon("nps", common.GetRunPath(), common.GetTmpPath())
|
||||
case "install":
|
||||
install.InstallNps()
|
||||
return
|
||||
}
|
||||
}
|
||||
if level = beego.AppConfig.String("log_level"); level == "" {
|
||||
level = "7"
|
||||
}
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
if *logType == "stdout" {
|
||||
logs.SetLogger(logs.AdapterConsole, `{"level":`+level+`,"color":true}`)
|
||||
} else {
|
||||
logs.SetLogger(logs.AdapterFile, `{"level":`+level+`,"filename":"`+beego.AppConfig.String("log_path")+`","daily":false,"maxlines":100000,"color":true}`)
|
||||
}
|
||||
task := &file.Tunnel{
|
||||
Mode: "webServer",
|
||||
}
|
||||
bridgePort, err := beego.AppConfig.Int("bridge_port")
|
||||
if err != nil {
|
||||
logs.Error("Getting bridge_port error", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
logs.Info("the version of server is %s ,allow client core version to be %s", version.VERSION, version.GetVersion())
|
||||
connection.InitConnectionService()
|
||||
crypt.InitTls(filepath.Join(common.GetRunPath(), "conf", "server.pem"), filepath.Join(common.GetRunPath(), "conf", "server.key"))
|
||||
tool.InitAllowPort()
|
||||
tool.StartSystemInfo()
|
||||
server.StartNewServer(bridgePort, task, beego.AppConfig.String("bridge_type"))
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"github.com/cnlh/easyProxy/client"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
_ "github.com/cnlh/easyProxy/utils"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const VERSION = "v0.0.13"
|
||||
|
||||
var (
|
||||
serverAddr = flag.String("server", "", "服务器地址ip:端口")
|
||||
verifyKey = flag.String("vkey", "", "验证密钥")
|
||||
logType = flag.String("log", "stdout", "日志输出方式(stdout|file)")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
utils.InitDaemon("client")
|
||||
if *logType == "stdout" {
|
||||
utils.InitLogFile("client", true)
|
||||
} else {
|
||||
utils.InitLogFile("client", false)
|
||||
}
|
||||
stop := make(chan int)
|
||||
for _, v := range strings.Split(*verifyKey, ",") {
|
||||
utils.Println("客户端启动,连接:", *serverAddr, " 验证令牌:", v)
|
||||
go client.NewRPClient(*serverAddr, v).Start()
|
||||
}
|
||||
<-stop
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/cnlh/easyProxy/server"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
_ "github.com/cnlh/easyProxy/web/routers"
|
||||
"os"
|
||||
)
|
||||
|
||||
const VERSION = "v0.0.13"
|
||||
|
||||
var (
|
||||
TcpPort = flag.Int("tcpport", 0, "客户端与服务端通信端口")
|
||||
httpPort = flag.Int("httpport", 8024, "对外监听的端口")
|
||||
rpMode = flag.String("mode", "webServer", "启动模式")
|
||||
tunnelTarget = flag.String("target", "127.0.0.1:80", "远程目标")
|
||||
VerifyKey = flag.String("vkey", "", "验证密钥")
|
||||
u = flag.String("u", "", "验证用户名(socks5和web)")
|
||||
p = flag.String("p", "", "验证密码(socks5和web)")
|
||||
compress = flag.String("compress", "", "数据压缩方式(snappy)")
|
||||
crypt = flag.String("crypt", "false", "是否加密(true|false)")
|
||||
logType = flag.String("log", "stdout", "日志输出方式(stdout|file)")
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.Parse()
|
||||
var test bool
|
||||
if len(os.Args) > 1 && os.Args[1] == "test" {
|
||||
test = true
|
||||
}
|
||||
utils.InitDaemon("server")
|
||||
if *logType == "stdout" || test {
|
||||
utils.InitLogFile("server", true)
|
||||
} else {
|
||||
utils.InitLogFile("server", false)
|
||||
}
|
||||
task := &utils.Tunnel{
|
||||
TcpPort: *httpPort,
|
||||
Mode: *rpMode,
|
||||
Target: *tunnelTarget,
|
||||
Config: &utils.Config{
|
||||
U: *u,
|
||||
P: *p,
|
||||
Compress: *compress,
|
||||
Crypt: utils.GetBoolByStr(*crypt),
|
||||
},
|
||||
Flow: &utils.Flow{},
|
||||
UseClientCnf: false,
|
||||
}
|
||||
if *VerifyKey != "" {
|
||||
c := &utils.Client{
|
||||
Id: 0,
|
||||
VerifyKey: *VerifyKey,
|
||||
Addr: "",
|
||||
Remark: "",
|
||||
Status: true,
|
||||
IsConnect: false,
|
||||
Cnf: &utils.Config{},
|
||||
Flow: &utils.Flow{},
|
||||
}
|
||||
c.Cnf.CompressDecode, c.Cnf.CompressEncode = utils.GetCompressType(c.Cnf.Compress)
|
||||
server.CsvDb.Clients[0] = c
|
||||
task.Client = c
|
||||
}
|
||||
if *TcpPort == 0 {
|
||||
p, err := beego.AppConfig.Int("tcpport")
|
||||
if err == nil && *rpMode == "webServer" {
|
||||
*TcpPort = p
|
||||
} else {
|
||||
*TcpPort = 8284
|
||||
}
|
||||
}
|
||||
utils.Println("服务端启动,监听tcp服务端端口:", *TcpPort)
|
||||
task.Config.CompressDecode, task.Config.CompressEncode = utils.GetCompressType(task.Config.Compress)
|
||||
if *rpMode != "webServer" {
|
||||
server.CsvDb.Tasks[0] = task
|
||||
}
|
||||
server.StartNewServer(*TcpPort, task, test)
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
appname = easyProxy
|
||||
|
||||
#web管理端口
|
||||
httpport = 8080
|
||||
|
||||
#启动模式dev|pro
|
||||
runmode = dev
|
||||
|
||||
#web管理密码
|
||||
password=123
|
||||
|
||||
##客户端与服务端通信端口
|
||||
tcpport=8284
|
||||
|
||||
#web api免验证IP地址
|
||||
authip=127.0.0.1
|
||||
|
||||
##http代理端口
|
||||
httpProxyPort=80
|
||||
|
||||
##https代理端口
|
||||
httpsProxyPort=
|
||||
|
||||
##certFile绝对路径
|
||||
pemPath=/etc/nginx/certificate.crt
|
||||
|
||||
##keyFile绝对路径
|
||||
keyPath=/etc/nginx/private.key
|
||||
@@ -1 +0,0 @@
|
||||
1,wajajb6bl086s2aq,111,true,1,2,1,,20000,1000
|
||||
|
@@ -1,2 +0,0 @@
|
||||
a.o.com,"127.0.0.1:8082
|
||||
127.0.0.1:8080",1,,www.baidu.com,测试
|
||||
|
@@ -0,0 +1,2 @@
|
||||
# key -> user | value -> pwd
|
||||
npc=npc.pwd
|
||||
@@ -0,0 +1,76 @@
|
||||
[common]
|
||||
server_addr=127.0.0.1:8024
|
||||
conn_type=tcp
|
||||
vkey=123
|
||||
auto_reconnection=true
|
||||
max_conn=1000
|
||||
flow_limit=1000
|
||||
rate_limit=1000
|
||||
basic_username=11
|
||||
basic_password=3
|
||||
web_username=user
|
||||
web_password=1234
|
||||
crypt=true
|
||||
compress=true
|
||||
|
||||
[health_check_test1]
|
||||
health_check_timeout=1
|
||||
health_check_max_failed=3
|
||||
health_check_interval=1
|
||||
health_http_url=/
|
||||
health_check_type=http
|
||||
health_check_target=127.0.0.1:8083,127.0.0.1:8082
|
||||
|
||||
[health_check_test2]
|
||||
health_check_timeout=1
|
||||
health_check_max_failed=3
|
||||
health_check_interval=1
|
||||
health_check_type=tcp
|
||||
health_check_target=127.0.0.1:8083,127.0.0.1:8082
|
||||
|
||||
[web]
|
||||
host=c.o.com
|
||||
target_addr=127.0.0.1:8083,127.0.0.1:8082
|
||||
|
||||
[tcp]
|
||||
mode=tcp
|
||||
target_addr=127.0.0.1:8080
|
||||
server_port=10000
|
||||
|
||||
[socks5]
|
||||
mode=socks5
|
||||
server_port=19009
|
||||
multi_account=multi_account.conf
|
||||
|
||||
[file]
|
||||
mode=file
|
||||
server_port=19008
|
||||
local_path=/Users/liuhe/Downloads
|
||||
strip_pre=/web/
|
||||
|
||||
[http]
|
||||
mode=httpProxy
|
||||
server_port=19004
|
||||
|
||||
[udp]
|
||||
mode=udp
|
||||
server_port=12253
|
||||
target_addr=114.114.114.114:53
|
||||
|
||||
[ssh_secret]
|
||||
mode=secret
|
||||
password=ssh2
|
||||
target_addr=123.206.77.88:22
|
||||
|
||||
[ssh_p2p]
|
||||
mode=p2p
|
||||
password=ssh3
|
||||
|
||||
[secret_ssh]
|
||||
local_port=2001
|
||||
password=ssh2
|
||||
|
||||
[p2p_ssh]
|
||||
local_port=2002
|
||||
password=ssh3
|
||||
target_addr=123.206.77.88:22
|
||||
Executable
+70
@@ -0,0 +1,70 @@
|
||||
appname = nps
|
||||
#Boot mode(dev|pro)
|
||||
runmode = dev
|
||||
|
||||
#HTTP(S) proxy port, no startup if empty
|
||||
http_proxy_ip=0.0.0.0
|
||||
http_proxy_port=80
|
||||
https_proxy_port=443
|
||||
https_just_proxy=true
|
||||
#default https certificate setting
|
||||
https_default_cert_file=conf/server.pem
|
||||
https_default_key_file=conf/server.key
|
||||
|
||||
##bridge
|
||||
bridge_type=tcp
|
||||
bridge_port=8024
|
||||
bridge_ip=0.0.0.0
|
||||
|
||||
# Public password, which clients can use to connect to the server
|
||||
# After the connection, the server will be able to open relevant ports and parse related domain names according to its own configuration file.
|
||||
public_vkey=123
|
||||
|
||||
#Traffic data persistence interval(minute)
|
||||
#Ignorance means no persistence
|
||||
#flow_store_interval=1
|
||||
|
||||
# log level LevelEmergency->0 LevelAlert->1 LevelCritical->2 LevelError->3 LevelWarning->4 LevelNotice->5 LevelInformational->6 LevelDebug->7
|
||||
log_level=7
|
||||
log_path=nps.log
|
||||
|
||||
#Whether to restrict IP access, true or false or ignore
|
||||
#ip_limit=true
|
||||
|
||||
#p2p
|
||||
#p2p_ip=127.0.0.1
|
||||
#p2p_port=6000
|
||||
|
||||
#web
|
||||
web_host=a.o.com
|
||||
web_username=admin
|
||||
web_password=123
|
||||
web_port = 8080
|
||||
web_ip=0.0.0.0
|
||||
|
||||
#Web API unauthenticated IP address(the len of auth_crypt_key must be 16)
|
||||
auth_key=test
|
||||
auth_crypt_key =1234567812345678
|
||||
|
||||
#allow_ports=9001-9009,10001,11000-12000
|
||||
|
||||
#Web management multi-user login
|
||||
allow_user_login=false
|
||||
allow_user_register=false
|
||||
allow_user_change_username=false
|
||||
|
||||
|
||||
#extension
|
||||
allow_flow_limit=false
|
||||
allow_rate_limit=false
|
||||
allow_tunnel_num_limit=false
|
||||
allow_local_proxy=false
|
||||
allow_connection_num_limit=false
|
||||
allow_multi_ip=false
|
||||
system_info_display=false
|
||||
|
||||
#cache
|
||||
http_cache=false
|
||||
http_cache_length=100
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEpAIBAAKCAQEA2MVLOHvgU8FCp6LgQrPfaWcGygrsRk7TL9hbT8MxbCRUSLV7
|
||||
Lbt3q5Knz8eTN4NWmwE6L5glOcH2x3Hnn+hPjbvgq35XBBIccAm0cYYKqoKkikeK
|
||||
FZM0Gp/WhSrhJ4laTyQqyleIFKpwD9kHDiC/sxjGDhSFmHKhhAnsQIRm2tppFXX0
|
||||
aAMqJEm88jzk1BN2QtKjEAn1u8v1+QW1KP3WuzdXH4L7hhMll66/KIm6Hfs2FRHQ
|
||||
pRUWqZeJY4q79NW5p5f+siGwOsGpxb/p11pM+0xnCH3UIFbm3zCTzP4sLvkfFGAe
|
||||
yAHsAwmaP8dJxh40ej3NN8uNiNvt8nw2Vb/1LwIDAQABAoIBAD40x/RKoEKIyE8B
|
||||
D6g0pB1EQo+CePFoN3SYewO1uR4WgtVmtxWVoa7r5BpdZGLe3uCWhpMX7z7W6bGs
|
||||
f1LFQOckjkHIfMIfTGfecRjO5Yqu+Pbxtq+gUah+S/plJr3IzdC+SUVNvzBnBMeX
|
||||
eU3Vmg2UQ2nQ+9GWu8D/c/vDwxx0X8oQ2G8QaxX0tUurlSMNA3M7xySwEvhx54fO
|
||||
UrDF3Q4yF48eA4butxVLFWf3cnlY+nR8uYd2vKfmp689/8C6kkfoM9igB78e93sm
|
||||
uDM2eRLm4kU5WLl301T42n6AF7w8J0MhLLVOIeLs4l5gZPa3uKvYFmuHQao7e/5R
|
||||
U/jHKrECgYEA8alPXuxFSVOvdhIsSN//Frj9CdExVdYmaLkt/2LO4FMnOaWh1xh7
|
||||
5iCY1bJT8D9dhfbqRg3qW2oguZD8gu04R8fTRegQ89qmAIwsEYqVf9salR41lZU4
|
||||
Rc+5yc7O11WIe9Lzu+ONFBFkAh3UFMR4zVZ/JhKIG/P5Srm7SUdKW2cCgYEA5aHo
|
||||
x2LR+yKhjkrBzHG3Qrfy1PtlYHjOpYYAKHQcBFuiG08W3CK/vkYl+mhv0uyhT7mn
|
||||
q6NDqrpZPRnDlOoEqgRS1X/QWKN6Pgd4HNLIawvp0vK9jYXDPcAXFzVthXCIwFcn
|
||||
3a3m4cHiuLdRNOHkydiHQyTOF6eEneN07TDvwvkCgYEApzOd1u9igPmFzQuF2GYi
|
||||
+HXFnaU/nUQuDwcQ7EJRIKRn31raPxiRoQesty5LJU6yRp4wOYgnPliPi9Tk4TGA
|
||||
XynC4/tMv2vorzhMxVY9Wdke602bhYNZC/RNd3O/aP2lEQdD3Bv04I2nxE8fDb9i
|
||||
VbAjCRSJV83WDf2zt1+78sECgYEAzezjRiKdcZu9y0/I+WEk2cUCE/MaF2he0FsZ
|
||||
uy1cjp/qAJltQ5452xUnK6cKWNlxU4CHF0mC/hC8xCldliZCZoEYE3PaUBLSJdwm
|
||||
35o6tpxpZI3gZJCG5NJlIp/8BkVDrVC7ZHV17hAkFEf4n/bPaB8wNYtE8jt8luaK
|
||||
TcarzGkCgYBn2alN0RLN2PHDurraFZB6GuCvh/arEjSCY3SDFQPF10CVjTDV7sx3
|
||||
eqJkwJ81syTmfJwZIceWbOFGgsuSx37UrQAVlHZSvzeqEg9dA5HqSoOACyidJI7j
|
||||
RG2+HB+KpsIZjGgLrEM4i7VOpYUDRdaouIXngFq/t9HNT+MDck5/Lw==
|
||||
-----END RSA PRIVATE KEY-----
|
||||
@@ -0,0 +1,22 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDtTCCAp2gAwIBAgIJAPXRSiP0Fs7sMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
|
||||
BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX
|
||||
aWRnaXRzIFB0eSBMdGQwHhcNMTcxMTA3MDg1MzQ2WhcNMjcxMTA1MDg1MzQ2WjBF
|
||||
MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50
|
||||
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
|
||||
CgKCAQEA2MVLOHvgU8FCp6LgQrPfaWcGygrsRk7TL9hbT8MxbCRUSLV7Lbt3q5Kn
|
||||
z8eTN4NWmwE6L5glOcH2x3Hnn+hPjbvgq35XBBIccAm0cYYKqoKkikeKFZM0Gp/W
|
||||
hSrhJ4laTyQqyleIFKpwD9kHDiC/sxjGDhSFmHKhhAnsQIRm2tppFXX0aAMqJEm8
|
||||
8jzk1BN2QtKjEAn1u8v1+QW1KP3WuzdXH4L7hhMll66/KIm6Hfs2FRHQpRUWqZeJ
|
||||
Y4q79NW5p5f+siGwOsGpxb/p11pM+0xnCH3UIFbm3zCTzP4sLvkfFGAeyAHsAwma
|
||||
P8dJxh40ej3NN8uNiNvt8nw2Vb/1LwIDAQABo4GnMIGkMB0GA1UdDgQWBBQdPc0R
|
||||
a8alY6Ab7voidkTGaH4PxzB1BgNVHSMEbjBsgBQdPc0Ra8alY6Ab7voidkTGaH4P
|
||||
x6FJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV
|
||||
BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAPXRSiP0Fs7sMAwGA1UdEwQF
|
||||
MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAH1IZNkjuvt2nZPzXsuiVNyCE1vm346z
|
||||
naE0Uzt3aseAN9m/iiB8mLz+ryvWc2aFMX5lTdsHdm2rqmqBCBXeRwTLf4OeHIju
|
||||
ZQW6makWt6PxANEo6gbdPbQXbS420ssUhnR2irIH1SdI31iikVFPdiS0baRRE/gS
|
||||
+440M1jOOOnKm0Qin92ejsshmji/0qaD2+6D5TNw4HmIZaFTBw+kfjxCL6trfeBn
|
||||
4fT0RJ121V3G3+AtG5sWQ93B3pCg+jtD+fGKkNSLhphq84bD1Zv7l73QGOoylkEn
|
||||
Sc0ajTLOXFBb83yRdlgV3Da95jH9rDZ4jSod48m+KemoZTDQw0vSwAU=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -1,4 +0,0 @@
|
||||
9002,tunnelServer,127.0.0.1:8082,2,2,,1,1,0,0,1,1,false,123
|
||||
53,udpServer,114.114.114.114:53,,,,1,0,0,0,2,1,true,udp测试
|
||||
9003,httpProxyServer,,,,,1,0,0,0,3,1,false,
|
||||
8024,socks5Server,,,,,1,0,0,0,4,1,true,
|
||||
|
@@ -0,0 +1,29 @@
|
||||
module github.com/cnlh/nps
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
|
||||
github.com/astaxie/beego v1.12.0
|
||||
github.com/belogik/goes v0.0.0-20151229125003-e54d722c3aff // indirect
|
||||
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d
|
||||
github.com/go-ole/go-ole v1.2.4 // indirect
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db
|
||||
github.com/klauspost/cpuid v1.2.1 // indirect
|
||||
github.com/klauspost/reedsolomon v1.9.2 // indirect
|
||||
github.com/onsi/gomega v1.5.0 // indirect
|
||||
github.com/panjf2000/ants/v2 v2.2.2
|
||||
github.com/pkg/errors v0.8.0
|
||||
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
|
||||
github.com/shirou/gopsutil v2.18.12+incompatible
|
||||
github.com/stretchr/testify v1.3.0 // indirect
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 // indirect
|
||||
github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b // indirect
|
||||
github.com/tjfoc/gmsm v1.0.1 // indirect
|
||||
github.com/xtaci/kcp-go v5.4.4+incompatible
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae // indirect
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a
|
||||
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa // indirect
|
||||
)
|
||||
|
||||
replace github.com/astaxie/beego => github.com/exfly/beego v1.12.0-export-init
|
||||
@@ -0,0 +1,92 @@
|
||||
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
|
||||
github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM=
|
||||
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
|
||||
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
|
||||
github.com/astaxie/beego v1.12.0 h1:MRhVoeeye5N+Flul5PoVfD9CslfdoH+xqC/xvSQ5u2Y=
|
||||
github.com/astaxie/beego v1.12.0/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
|
||||
github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ=
|
||||
github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU=
|
||||
github.com/belogik/goes v0.0.0-20151229125003-e54d722c3aff/go.mod h1:PhH1ZhyCzHKt4uAasyx+ljRCgoezetRNf59CUtwUkqY=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60=
|
||||
github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE=
|
||||
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d h1:As4937T5NVbJ/DmZT9z33pyLEprMd6CUSfhbmMY57Io=
|
||||
github.com/ccding/go-stun v0.0.0-20180726100737-be486d185f3d/go.mod h1:3FK1bMar37f7jqVY7q/63k3OMX1c47pGCufzt3X0sYE=
|
||||
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80=
|
||||
github.com/couchbase/go-couchbase v0.0.0-20181122212707-3e9b6e1258bb/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U=
|
||||
github.com/couchbase/gomemcached v0.0.0-20181122193126-5125a94a666c/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c=
|
||||
github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs=
|
||||
github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
|
||||
github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk=
|
||||
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
|
||||
github.com/exfly/beego v1.12.0-export-init h1:VQNYKdXhAwZGUaFmQv8Aj921O3rQJZRIF8xeGrhsjrI=
|
||||
github.com/exfly/beego v1.12.0-export-init/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
|
||||
github.com/exfly/beego v1.12.0 h1:OXwIwngaAx35Mga+jLiZmArusBxj8/H0jYXzGDAdwOg=
|
||||
github.com/exfly/beego v1.12.0/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/go-ole/go-ole v1.2.4 h1:nNBDSCOigTSiarFpYE9J/KtEA1IOW4CNeqT9TQDqCxI=
|
||||
github.com/go-ole/go-ole v1.2.4/go.mod h1:XCwSNxSkXRo4vlyPy93sltvi/qJq0jqQhjqQNIwKuxM=
|
||||
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db h1:woRePGFeVFfLKN/pOkfl+p/TAqKOfFu+7KPlMVpok/w=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/klauspost/cpuid v1.2.1 h1:vJi+O/nMdFt0vqm8NZBI6wzALWdA2X+egi0ogNyrC/w=
|
||||
github.com/klauspost/cpuid v1.2.1/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
|
||||
github.com/klauspost/reedsolomon v1.9.2 h1:E9CMS2Pqbv+C7tsrYad4YC9MfhnMVWhMRsTi7U0UB18=
|
||||
github.com/klauspost/reedsolomon v1.9.2/go.mod h1:CwCi+NUr9pqSVktrkN+Ondf06rkhYZ/pcNv7fu+8Un4=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/panjf2000/ants/v2 v2.2.2 h1:TWzusBjq/IflXhy+/S6u5wmMLCBdJnB9tPIx9Zmhvok=
|
||||
github.com/panjf2000/ants/v2 v2.2.2/go.mod h1:1GFm8bV8nyCQvU5K4WvBCTG1/YBFOD2VzjffD8fV55A=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
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/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
|
||||
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
|
||||
github.com/shirou/gopsutil v2.18.12+incompatible h1:1eaJvGomDnH74/5cF4CTmTbLHAriGFsTZppLXDX93OM=
|
||||
github.com/shirou/gopsutil v2.18.12+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
|
||||
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
|
||||
github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373/go.mod h1:mF1DpOSOUiJRMR+FDqaqu3EBqrybQtrDDszLUZ6oxPg=
|
||||
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
|
||||
github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161 h1:89CEmDvlq/F7SJEOqkIdNDGJXrQIhuIx9D2DBXjavSU=
|
||||
github.com/templexxx/cpufeat v0.0.0-20180724012125-cef66df7f161/go.mod h1:wM7WEvslTq+iOEAMDLSzhVuOt5BRZ05WirO+b09GHQU=
|
||||
github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b h1:mnG1fcsIB1d/3vbkBak2MM0u+vhGhlQwpeimUi7QncM=
|
||||
github.com/templexxx/xor v0.0.0-20181023030647-4e92f724b73b/go.mod h1:5XA7W9S6mni3h5uvOC75dA3m9CCCaS83lltmc0ukdi4=
|
||||
github.com/tjfoc/gmsm v1.0.1 h1:R11HlqhXkDospckjZEihx9SW/2VW0RgdwrykyWMFOQU=
|
||||
github.com/tjfoc/gmsm v1.0.1/go.mod h1:XxO4hdhhrzAd+G4CjDqaOkd0hUzmtPR/d3EiBBMn/wc=
|
||||
github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc=
|
||||
github.com/xtaci/kcp-go v5.4.4+incompatible h1:QIJ0a0Q0N1G20yLHL2+fpdzyy2v/Cb3PI+xiwx/KK9c=
|
||||
github.com/xtaci/kcp-go v5.4.4+incompatible/go.mod h1:bN6vIwHQbfHaHtFpEssmWsN45a+AZwO7eyRCmEIbtvE=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM=
|
||||
github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE=
|
||||
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 h1:et7+NAX3lLIk5qUCTA9QelBjGE/NkhzYw/mhnr0s7nI=
|
||||
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a h1:gOpx8G595UYyvj8UK4+OFyY4rx037g3fmfhe5SasG3U=
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa h1:KIDDMLT1O0Nr7TSxp8xM5tJcdn8tgyAONntO829og1M=
|
||||
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 233 KiB After Width: | Height: | Size: 290 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 281 KiB After Width: | Height: | Size: 232 KiB |
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Cache is an LRU cache. It is safe for concurrent access.
|
||||
type Cache struct {
|
||||
// MaxEntries is the maximum number of cache entries before
|
||||
// an item is evicted. Zero means no limit.
|
||||
MaxEntries int
|
||||
|
||||
//Execute this callback function when an element is culled
|
||||
OnEvicted func(key Key, value interface{})
|
||||
|
||||
ll *list.List //list
|
||||
cache sync.Map
|
||||
}
|
||||
|
||||
// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators
|
||||
type Key interface{}
|
||||
|
||||
type entry struct {
|
||||
key Key
|
||||
value interface{}
|
||||
}
|
||||
|
||||
// New creates a new Cache.
|
||||
// If maxEntries is 0, the cache has no length limit.
|
||||
// that eviction is done by the caller.
|
||||
func New(maxEntries int) *Cache {
|
||||
return &Cache{
|
||||
MaxEntries: maxEntries,
|
||||
ll: list.New(),
|
||||
//cache: make(map[interface{}]*list.Element),
|
||||
}
|
||||
}
|
||||
|
||||
// If the key value already exists, move the key to the front
|
||||
func (c *Cache) Add(key Key, value interface{}) {
|
||||
if ee, ok := c.cache.Load(key); ok {
|
||||
c.ll.MoveToFront(ee.(*list.Element)) // move to the front
|
||||
ee.(*list.Element).Value.(*entry).value = value
|
||||
return
|
||||
}
|
||||
ele := c.ll.PushFront(&entry{key, value})
|
||||
c.cache.Store(key, ele)
|
||||
if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { // Remove the oldest element if the limit is exceeded
|
||||
c.RemoveOldest()
|
||||
}
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *Cache) Get(key Key) (value interface{}, ok bool) {
|
||||
if ele, hit := c.cache.Load(key); hit {
|
||||
c.ll.MoveToFront(ele.(*list.Element))
|
||||
return ele.(*list.Element).Value.(*entry).value, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache.
|
||||
func (c *Cache) Remove(key Key) {
|
||||
if ele, hit := c.cache.Load(key); hit {
|
||||
c.removeElement(ele.(*list.Element))
|
||||
}
|
||||
}
|
||||
|
||||
// RemoveOldest removes the oldest item from the cache.
|
||||
func (c *Cache) RemoveOldest() {
|
||||
ele := c.ll.Back()
|
||||
if ele != nil {
|
||||
c.removeElement(ele)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) removeElement(e *list.Element) {
|
||||
c.ll.Remove(e)
|
||||
kv := e.Value.(*entry)
|
||||
c.cache.Delete(kv.key)
|
||||
if c.OnEvicted != nil {
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *Cache) Len() int {
|
||||
return c.ll.Len()
|
||||
}
|
||||
|
||||
// Clear purges all stored items from the cache.
|
||||
func (c *Cache) Clear() {
|
||||
if c.OnEvicted != nil {
|
||||
c.cache.Range(func(key, value interface{}) bool {
|
||||
kv := value.(*list.Element).Value.(*entry)
|
||||
c.OnEvicted(kv.key, kv.value)
|
||||
return true
|
||||
})
|
||||
}
|
||||
c.ll = nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package common
|
||||
|
||||
const (
|
||||
CONN_DATA_SEQ = "*#*" //Separator
|
||||
VERIFY_EER = "vkey"
|
||||
VERIFY_SUCCESS = "sucs"
|
||||
WORK_MAIN = "main"
|
||||
WORK_CHAN = "chan"
|
||||
WORK_CONFIG = "conf"
|
||||
WORK_REGISTER = "rgst"
|
||||
WORK_SECRET = "sert"
|
||||
WORK_FILE = "file"
|
||||
WORK_P2P = "p2pm"
|
||||
WORK_P2P_VISITOR = "p2pv"
|
||||
WORK_P2P_PROVIDER = "p2pp"
|
||||
WORK_P2P_CONNECT = "p2pc"
|
||||
WORK_P2P_SUCCESS = "p2ps"
|
||||
WORK_P2P_END = "p2pe"
|
||||
WORK_P2P_LAST = "p2pl"
|
||||
WORK_STATUS = "stus"
|
||||
RES_MSG = "msg0"
|
||||
RES_CLOSE = "clse"
|
||||
NEW_UDP_CONN = "udpc" //p2p udp conn
|
||||
NEW_TASK = "task"
|
||||
NEW_CONF = "conf"
|
||||
NEW_HOST = "host"
|
||||
CONN_TCP = "tcp"
|
||||
CONN_UDP = "udp"
|
||||
CONN_TEST = "TST"
|
||||
UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
WWW-Authenticate: Basic realm="easyProxy"
|
||||
|
||||
401 Unauthorized`
|
||||
ConnectionFailBytes = `HTTP/1.1 404 Not Found
|
||||
|
||||
`
|
||||
)
|
||||
|
||||
const (
|
||||
MUX_PING_FLAG uint8 = iota
|
||||
MUX_NEW_CONN_OK
|
||||
MUX_NEW_CONN_Fail
|
||||
MUX_NEW_MSG
|
||||
MUX_NEW_MSG_PART
|
||||
MUX_MSG_SEND_OK
|
||||
MUX_NEW_CONN
|
||||
MUX_CONN_CLOSE
|
||||
MUX_PING_RETURN
|
||||
MUX_PING int32 = -1
|
||||
MAXIMUM_SEGMENT_SIZE = PoolSizeWindow
|
||||
MAXIMUM_WINDOW_SIZE = 1 << 25 // 1<<31-1 TCP slide window size is very large,
|
||||
// we use 32M, reduce memory usage
|
||||
)
|
||||
@@ -0,0 +1,235 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type NetPackager interface {
|
||||
Pack(writer io.Writer) (err error)
|
||||
UnPack(reader io.Reader) (err error)
|
||||
}
|
||||
|
||||
type BasePackager struct {
|
||||
Length uint16
|
||||
Content []byte
|
||||
}
|
||||
|
||||
func (Self *BasePackager) NewPac(contents ...interface{}) (err error) {
|
||||
Self.clean()
|
||||
for _, content := range contents {
|
||||
switch content.(type) {
|
||||
case nil:
|
||||
Self.Content = Self.Content[:0]
|
||||
case []byte:
|
||||
err = Self.appendByte(content.([]byte))
|
||||
case string:
|
||||
err = Self.appendByte([]byte(content.(string)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = Self.appendByte([]byte(CONN_DATA_SEQ))
|
||||
default:
|
||||
err = Self.marshal(content)
|
||||
}
|
||||
}
|
||||
Self.setLength()
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *BasePackager) appendByte(data []byte) (err error) {
|
||||
m := len(Self.Content)
|
||||
n := m + len(data)
|
||||
if n <= cap(Self.Content) {
|
||||
Self.Content = Self.Content[0:n] // grow the length for copy
|
||||
copy(Self.Content[m:n], data)
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("pack content too large")
|
||||
}
|
||||
}
|
||||
|
||||
//似乎这里涉及到父类作用域问题,当子类调用父类的方法时,其struct仅仅为父类的
|
||||
func (Self *BasePackager) Pack(writer io.Writer) (err error) {
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.Length)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.Content)
|
||||
return
|
||||
}
|
||||
|
||||
//Unpack 会导致传入的数字类型转化成float64!!
|
||||
//主要原因是json unmarshal并未传入正确的数据类型
|
||||
func (Self *BasePackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
Self.clean()
|
||||
n += 2 // uint16
|
||||
err = binary.Read(reader, binary.LittleEndian, &Self.Length)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if int(Self.Length) > cap(Self.Content) {
|
||||
err = errors.New("unpack err, content length too large")
|
||||
}
|
||||
Self.Content = Self.Content[:int(Self.Length)]
|
||||
//n, err := io.ReadFull(reader, Self.Content)
|
||||
//if n != int(Self.Length) {
|
||||
// err = io.ErrUnexpectedEOF
|
||||
//}
|
||||
err = binary.Read(reader, binary.LittleEndian, Self.Content)
|
||||
n += Self.Length
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *BasePackager) marshal(content interface{}) (err error) {
|
||||
tmp, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = Self.appendByte(tmp)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *BasePackager) Unmarshal(content interface{}) (err error) {
|
||||
err = json.Unmarshal(Self.Content, content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *BasePackager) setLength() {
|
||||
Self.Length = uint16(len(Self.Content))
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *BasePackager) clean() {
|
||||
Self.Length = 0
|
||||
Self.Content = Self.Content[:0] // reset length
|
||||
}
|
||||
|
||||
func (Self *BasePackager) Split() (strList []string) {
|
||||
n := bytes.IndexByte(Self.Content, 0)
|
||||
strList = strings.Split(string(Self.Content[:n]), CONN_DATA_SEQ)
|
||||
strList = strList[0 : len(strList)-1]
|
||||
return
|
||||
}
|
||||
|
||||
type ConnPackager struct { // Todo
|
||||
ConnType uint8
|
||||
BasePackager
|
||||
}
|
||||
|
||||
func (Self *ConnPackager) NewPac(connType uint8, content ...interface{}) (err error) {
|
||||
Self.ConnType = connType
|
||||
err = Self.BasePackager.NewPac(content...)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ConnPackager) Pack(writer io.Writer) (err error) {
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.ConnType)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = Self.BasePackager.Pack(writer)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ConnPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
err = binary.Read(reader, binary.LittleEndian, &Self.ConnType)
|
||||
if err != nil && err != io.EOF {
|
||||
return
|
||||
}
|
||||
n, err = Self.BasePackager.UnPack(reader)
|
||||
n += 2
|
||||
return
|
||||
}
|
||||
|
||||
type MuxPackager struct {
|
||||
Flag uint8
|
||||
Id int32
|
||||
Window uint32
|
||||
ReadLength uint32
|
||||
BasePackager
|
||||
}
|
||||
|
||||
func (Self *MuxPackager) NewPac(flag uint8, id int32, content ...interface{}) (err error) {
|
||||
Self.Flag = flag
|
||||
Self.Id = id
|
||||
switch flag {
|
||||
case MUX_PING_FLAG, MUX_PING_RETURN, MUX_NEW_MSG, MUX_NEW_MSG_PART:
|
||||
Self.Content = WindowBuff.Get()
|
||||
err = Self.BasePackager.NewPac(content...)
|
||||
//logs.Warn(Self.Length, string(Self.Content))
|
||||
case MUX_MSG_SEND_OK:
|
||||
// MUX_MSG_SEND_OK contains two data
|
||||
switch content[0].(type) {
|
||||
case int:
|
||||
Self.Window = uint32(content[0].(int))
|
||||
case uint32:
|
||||
Self.Window = content[0].(uint32)
|
||||
}
|
||||
switch content[1].(type) {
|
||||
case int:
|
||||
Self.ReadLength = uint32(content[1].(int))
|
||||
case uint32:
|
||||
Self.ReadLength = content[1].(uint32)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *MuxPackager) Pack(writer io.Writer) (err error) {
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.Flag)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.Id)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch Self.Flag {
|
||||
case MUX_NEW_MSG, MUX_NEW_MSG_PART, MUX_PING_FLAG, MUX_PING_RETURN:
|
||||
err = Self.BasePackager.Pack(writer)
|
||||
WindowBuff.Put(Self.Content)
|
||||
case MUX_MSG_SEND_OK:
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.Window)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = binary.Write(writer, binary.LittleEndian, Self.ReadLength)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *MuxPackager) UnPack(reader io.Reader) (n uint16, err error) {
|
||||
err = binary.Read(reader, binary.LittleEndian, &Self.Flag)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = binary.Read(reader, binary.LittleEndian, &Self.Id)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch Self.Flag {
|
||||
case MUX_NEW_MSG, MUX_NEW_MSG_PART, MUX_PING_FLAG, MUX_PING_RETURN:
|
||||
Self.Content = WindowBuff.Get() // need get a window buf from pool
|
||||
Self.BasePackager.clean() // also clean the content
|
||||
n, err = Self.BasePackager.UnPack(reader)
|
||||
//logs.Warn("unpack", Self.Length, string(Self.Content))
|
||||
case MUX_MSG_SEND_OK:
|
||||
err = binary.Read(reader, binary.LittleEndian, &Self.Window)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
n += 4 // uint32
|
||||
err = binary.Read(reader, binary.LittleEndian, &Self.ReadLength)
|
||||
n += 4 // uint32
|
||||
}
|
||||
n += 5 //uint8 int32
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const PoolSize = 64 * 1024
|
||||
const PoolSizeSmall = 100
|
||||
const PoolSizeUdp = 1472
|
||||
const PoolSizeCopy = 32 << 10
|
||||
const PoolSizeBuffer = 4096
|
||||
const PoolSizeWindow = PoolSizeBuffer - 2 - 4 - 4 - 1
|
||||
|
||||
var BufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSize)
|
||||
},
|
||||
}
|
||||
|
||||
var BufPoolUdp = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeUdp)
|
||||
},
|
||||
}
|
||||
var BufPoolMax = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSize)
|
||||
},
|
||||
}
|
||||
var BufPoolSmall = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeSmall)
|
||||
},
|
||||
}
|
||||
var BufPoolCopy = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeCopy)
|
||||
},
|
||||
}
|
||||
|
||||
func PutBufPoolUdp(buf []byte) {
|
||||
if cap(buf) == PoolSizeUdp {
|
||||
BufPoolUdp.Put(buf[:PoolSizeUdp])
|
||||
}
|
||||
}
|
||||
|
||||
func PutBufPoolCopy(buf []byte) {
|
||||
if cap(buf) == PoolSizeCopy {
|
||||
BufPoolCopy.Put(buf[:PoolSizeCopy])
|
||||
}
|
||||
}
|
||||
|
||||
func GetBufPoolCopy() []byte {
|
||||
return (BufPoolCopy.Get().([]byte))[:PoolSizeCopy]
|
||||
}
|
||||
|
||||
func PutBufPoolMax(buf []byte) {
|
||||
if cap(buf) == PoolSize {
|
||||
BufPoolMax.Put(buf[:PoolSize])
|
||||
}
|
||||
}
|
||||
|
||||
type copyBufferPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (Self *copyBufferPool) New() {
|
||||
Self.pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeCopy, PoolSizeCopy)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *copyBufferPool) Get() []byte {
|
||||
buf := Self.pool.Get().([]byte)
|
||||
return buf[:PoolSizeCopy] // just like make a new slice, but data may not be 0
|
||||
}
|
||||
|
||||
func (Self *copyBufferPool) Put(x []byte) {
|
||||
if len(x) == PoolSizeCopy {
|
||||
Self.pool.Put(x)
|
||||
} else {
|
||||
x = nil // buf is not full, not allowed, New method returns a full buf
|
||||
}
|
||||
}
|
||||
|
||||
type windowBufferPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (Self *windowBufferPool) New() {
|
||||
Self.pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, PoolSizeWindow, PoolSizeWindow)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *windowBufferPool) Get() (buf []byte) {
|
||||
buf = Self.pool.Get().([]byte)
|
||||
return buf[:PoolSizeWindow]
|
||||
}
|
||||
|
||||
func (Self *windowBufferPool) Put(x []byte) {
|
||||
Self.pool.Put(x[:PoolSizeWindow]) // make buf to full
|
||||
}
|
||||
|
||||
type bufferPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (Self *bufferPool) New() {
|
||||
Self.pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return bytes.NewBuffer(make([]byte, 0, PoolSizeBuffer))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *bufferPool) Get() *bytes.Buffer {
|
||||
return Self.pool.Get().(*bytes.Buffer)
|
||||
}
|
||||
|
||||
func (Self *bufferPool) Put(x *bytes.Buffer) {
|
||||
x.Reset()
|
||||
Self.pool.Put(x)
|
||||
}
|
||||
|
||||
type muxPackagerPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (Self *muxPackagerPool) New() {
|
||||
Self.pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
pack := MuxPackager{}
|
||||
return &pack
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *muxPackagerPool) Get() *MuxPackager {
|
||||
return Self.pool.Get().(*MuxPackager)
|
||||
}
|
||||
|
||||
func (Self *muxPackagerPool) Put(pack *MuxPackager) {
|
||||
Self.pool.Put(pack)
|
||||
}
|
||||
|
||||
type ListElement struct {
|
||||
Buf []byte
|
||||
L uint16
|
||||
Part bool
|
||||
}
|
||||
|
||||
type listElementPool struct {
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (Self *listElementPool) New() {
|
||||
Self.pool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
element := ListElement{}
|
||||
return &element
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *listElementPool) Get() *ListElement {
|
||||
return Self.pool.Get().(*ListElement)
|
||||
}
|
||||
|
||||
func (Self *listElementPool) Put(element *ListElement) {
|
||||
element.L = 0
|
||||
element.Buf = nil
|
||||
element.Part = false
|
||||
Self.pool.Put(element)
|
||||
}
|
||||
|
||||
var once = sync.Once{}
|
||||
var BuffPool = bufferPool{}
|
||||
var CopyBuff = copyBufferPool{}
|
||||
var MuxPack = muxPackagerPool{}
|
||||
var WindowBuff = windowBufferPool{}
|
||||
var ListElementPool = listElementPool{}
|
||||
|
||||
func newPool() {
|
||||
BuffPool.New()
|
||||
CopyBuff.New()
|
||||
MuxPack.New()
|
||||
WindowBuff.New()
|
||||
ListElementPool.New()
|
||||
}
|
||||
|
||||
func init() {
|
||||
once.Do(newPool)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
//Get the currently selected configuration file directory
|
||||
//For non-Windows systems, select the /etc/nps as config directory if exist, or select ./
|
||||
//windows system, select the C:\Program Files\nps as config directory if exist, or select ./
|
||||
func GetRunPath() string {
|
||||
var path string
|
||||
if path = GetInstallPath(); !FileExists(path) {
|
||||
return GetAppPath()
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//Different systems get different installation paths
|
||||
func GetInstallPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = `C:\Program Files\nps`
|
||||
} else {
|
||||
path = "/etc/nps"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//Get the absolute path to the running directory
|
||||
func GetAppPath() string {
|
||||
if path, err := filepath.Abs(filepath.Dir(os.Args[0])); err == nil {
|
||||
return path
|
||||
}
|
||||
return os.Args[0]
|
||||
}
|
||||
|
||||
//Determine whether the current system is a Windows system?
|
||||
func IsWindows() bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//interface log file path
|
||||
func GetLogPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = GetAppPath()
|
||||
} else {
|
||||
path = "/tmp"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
//interface pid file path
|
||||
func GetTmpPath() string {
|
||||
var path string
|
||||
if IsWindows() {
|
||||
path = GetAppPath()
|
||||
} else {
|
||||
path = "/tmp"
|
||||
}
|
||||
return path
|
||||
}
|
||||
Executable
+397
@@ -0,0 +1,397 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
)
|
||||
|
||||
//Get the corresponding IP address through domain name
|
||||
func GetHostByName(hostname string) string {
|
||||
if !DomainCheck(hostname) {
|
||||
return hostname
|
||||
}
|
||||
ips, _ := net.LookupIP(hostname)
|
||||
if ips != nil {
|
||||
for _, v := range ips {
|
||||
if v.To4() != nil {
|
||||
return v.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//Check the legality of domain
|
||||
func DomainCheck(domain string) bool {
|
||||
var match bool
|
||||
IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
|
||||
NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
|
||||
match, _ = regexp.MatchString(IsLine, domain)
|
||||
if !match {
|
||||
match, _ = regexp.MatchString(NotLine, domain)
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
//Check if the Request request is validated
|
||||
func CheckAuth(r *http.Request, user, passwd string) bool {
|
||||
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
||||
if len(s) != 2 {
|
||||
return false
|
||||
}
|
||||
|
||||
b, err := base64.StdEncoding.DecodeString(s[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pair := strings.SplitN(string(b), ":", 2)
|
||||
if len(pair) != 2 {
|
||||
return false
|
||||
}
|
||||
return pair[0] == user && pair[1] == passwd
|
||||
}
|
||||
|
||||
//get bool by str
|
||||
func GetBoolByStr(s string) bool {
|
||||
switch s {
|
||||
case "1", "true":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//get str by bool
|
||||
func GetStrByBool(b bool) string {
|
||||
if b {
|
||||
return "1"
|
||||
}
|
||||
return "0"
|
||||
}
|
||||
|
||||
//int
|
||||
func GetIntNoErrByStr(str string) int {
|
||||
i, _ := strconv.Atoi(strings.TrimSpace(str))
|
||||
return i
|
||||
}
|
||||
|
||||
//Get verify value
|
||||
func Getverifyval(vkey string) string {
|
||||
return crypt.Md5(vkey)
|
||||
}
|
||||
|
||||
//Change headers and host of request
|
||||
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
|
||||
if host != "" {
|
||||
r.Host = host
|
||||
}
|
||||
if header != "" {
|
||||
h := strings.Split(header, "\n")
|
||||
for _, v := range h {
|
||||
hd := strings.Split(v, ":")
|
||||
if len(hd) == 2 {
|
||||
r.Header.Set(hd[0], hd[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
addr = strings.Split(addr, ":")[0]
|
||||
if prior, ok := r.Header["X-Forwarded-For"]; ok {
|
||||
addr = strings.Join(prior, ", ") + ", " + addr
|
||||
}
|
||||
r.Header.Set("X-Forwarded-For", addr)
|
||||
r.Header.Set("X-Real-IP", addr)
|
||||
}
|
||||
|
||||
//Read file content by file path
|
||||
func ReadAllFromFile(filePath string) ([]byte, error) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ioutil.ReadAll(f)
|
||||
}
|
||||
|
||||
// FileExists reports whether the named file or directory exists.
|
||||
func FileExists(name string) bool {
|
||||
if _, err := os.Stat(name); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//Judge whether the TCP port can open normally
|
||||
func TestTcpPort(port int) bool {
|
||||
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer func() {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//Judge whether the UDP port can open normally
|
||||
func TestUdpPort(port int) bool {
|
||||
l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer func() {
|
||||
if l != nil {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//Write length and individual byte data
|
||||
//Length prevents sticking
|
||||
//# Characters are used to separate data
|
||||
func BinaryWrite(raw *bytes.Buffer, v ...string) {
|
||||
b := GetWriteStr(v...)
|
||||
binary.Write(raw, binary.LittleEndian, int32(len(b)))
|
||||
binary.Write(raw, binary.LittleEndian, b)
|
||||
}
|
||||
|
||||
// get seq str
|
||||
func GetWriteStr(v ...string) []byte {
|
||||
buffer := new(bytes.Buffer)
|
||||
var l int32
|
||||
for _, v := range v {
|
||||
l += int32(len([]byte(v))) + int32(len([]byte(CONN_DATA_SEQ)))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte(v))
|
||||
binary.Write(buffer, binary.LittleEndian, []byte(CONN_DATA_SEQ))
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
//inArray str interface
|
||||
func InStrArr(arr []string, val string) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//inArray int interface
|
||||
func InIntArr(arr []int, val int) bool {
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//format ports str to a int array
|
||||
func GetPorts(p string) []int {
|
||||
var ps []int
|
||||
arr := strings.Split(p, ",")
|
||||
for _, v := range arr {
|
||||
fw := strings.Split(v, "-")
|
||||
if len(fw) == 2 {
|
||||
if IsPort(fw[0]) && IsPort(fw[1]) {
|
||||
start, _ := strconv.Atoi(fw[0])
|
||||
end, _ := strconv.Atoi(fw[1])
|
||||
for i := start; i <= end; i++ {
|
||||
ps = append(ps, i)
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
} else if IsPort(v) {
|
||||
p, _ := strconv.Atoi(v)
|
||||
ps = append(ps, p)
|
||||
}
|
||||
}
|
||||
return ps
|
||||
}
|
||||
|
||||
//is the string a port
|
||||
func IsPort(p string) bool {
|
||||
pi, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if pi > 65536 || pi < 1 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
//if the s is just a port,return 127.0.0.1:s
|
||||
func FormatAddress(s string) string {
|
||||
if strings.Contains(s, ":") {
|
||||
return s
|
||||
}
|
||||
return "127.0.0.1:" + s
|
||||
}
|
||||
|
||||
//get address from the complete address
|
||||
func GetIpByAddr(addr string) string {
|
||||
arr := strings.Split(addr, ":")
|
||||
return arr[0]
|
||||
}
|
||||
|
||||
//get port from the complete address
|
||||
func GetPortByAddr(addr string) int {
|
||||
arr := strings.Split(addr, ":")
|
||||
if len(arr) < 2 {
|
||||
return 0
|
||||
}
|
||||
p, err := strconv.Atoi(arr[1])
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func CopyBuffer(dst io.Writer, src io.Reader, label ...string) (written int64, err error) {
|
||||
buf := CopyBuff.Get()
|
||||
defer CopyBuff.Put(buf)
|
||||
for {
|
||||
nr, er := src.Read(buf)
|
||||
//if len(pr)>0 && pr[0] && nr > 50 {
|
||||
// logs.Warn(string(buf[:50]))
|
||||
//}
|
||||
if nr > 0 {
|
||||
nw, ew := dst.Write(buf[0:nr])
|
||||
if nw > 0 {
|
||||
written += int64(nw)
|
||||
}
|
||||
if ew != nil {
|
||||
err = ew
|
||||
break
|
||||
}
|
||||
if nr != nw {
|
||||
err = io.ErrShortWrite
|
||||
break
|
||||
}
|
||||
}
|
||||
if er != nil {
|
||||
err = er
|
||||
break
|
||||
}
|
||||
}
|
||||
return written, err
|
||||
}
|
||||
|
||||
//send this ip forget to get a local udp port
|
||||
func GetLocalUdpAddr() (net.Conn, error) {
|
||||
tmpConn, err := net.Dial("udp", "114.114.114.114:53")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tmpConn, tmpConn.Close()
|
||||
}
|
||||
|
||||
//parse template
|
||||
func ParseStr(str string) (string, error) {
|
||||
tmp := template.New("npc")
|
||||
var err error
|
||||
w := new(bytes.Buffer)
|
||||
if tmp, err = tmp.Parse(str); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = tmp.Execute(w, GetEnvMap()); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return w.String(), nil
|
||||
}
|
||||
|
||||
//get env
|
||||
func GetEnvMap() map[string]string {
|
||||
m := make(map[string]string)
|
||||
environ := os.Environ()
|
||||
for i := range environ {
|
||||
tmp := strings.Split(environ[i], "=")
|
||||
if len(tmp) == 2 {
|
||||
m[tmp[0]] = tmp[1]
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
//throw the empty element of the string array
|
||||
func TrimArr(arr []string) []string {
|
||||
newArr := make([]string, 0)
|
||||
for _, v := range arr {
|
||||
if v != "" {
|
||||
newArr = append(newArr, v)
|
||||
}
|
||||
}
|
||||
return newArr
|
||||
}
|
||||
|
||||
//
|
||||
func IsArrContains(arr []string, val string) bool {
|
||||
if arr == nil {
|
||||
return false
|
||||
}
|
||||
for _, v := range arr {
|
||||
if v == val {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//remove value from string array
|
||||
func RemoveArrVal(arr []string, val string) []string {
|
||||
for k, v := range arr {
|
||||
if v == val {
|
||||
arr = append(arr[:k], arr[k+1:]...)
|
||||
return arr
|
||||
}
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
//convert bytes to num
|
||||
func BytesToNum(b []byte) int {
|
||||
var str string
|
||||
for i := 0; i < len(b); i++ {
|
||||
str += strconv.Itoa(int(b[i]))
|
||||
}
|
||||
x, _ := strconv.Atoi(str)
|
||||
return int(x)
|
||||
}
|
||||
|
||||
//get the length of the sync map
|
||||
func GeSynctMapLen(m sync.Map) int {
|
||||
var c int
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
c++
|
||||
return true
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
func GetExtFromPath(path string) string {
|
||||
s := strings.Split(path, ".")
|
||||
re, err := regexp.Compile(`(\w+)`)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(re.Find([]byte(s[0])))
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
)
|
||||
|
||||
type CommonConfig struct {
|
||||
Server string
|
||||
VKey string
|
||||
Tp string //bridgeType kcp or tcp
|
||||
AutoReconnection bool
|
||||
ProxyUrl string
|
||||
Client *file.Client
|
||||
}
|
||||
|
||||
type LocalServer struct {
|
||||
Type string
|
||||
Port int
|
||||
Ip string
|
||||
Password string
|
||||
Target string
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
content string
|
||||
title []string
|
||||
CommonConfig *CommonConfig
|
||||
Hosts []*file.Host
|
||||
Tasks []*file.Tunnel
|
||||
Healths []*file.Health
|
||||
LocalServer []*LocalServer
|
||||
}
|
||||
|
||||
func NewConfig(path string) (c *Config, err error) {
|
||||
c = new(Config)
|
||||
var b []byte
|
||||
if b, err = common.ReadAllFromFile(path); err != nil {
|
||||
return
|
||||
} else {
|
||||
if c.content, err = common.ParseStr(string(b)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.title, err = getAllTitle(c.content); err != nil {
|
||||
return
|
||||
}
|
||||
var nowIndex int
|
||||
var nextIndex int
|
||||
var nowContent string
|
||||
for i := 0; i < len(c.title); i++ {
|
||||
nowIndex = strings.Index(c.content, c.title[i]) + len(c.title[i])
|
||||
if i < len(c.title)-1 {
|
||||
nextIndex = strings.Index(c.content, c.title[i+1])
|
||||
} else {
|
||||
nextIndex = len(c.content)
|
||||
}
|
||||
nowContent = c.content[nowIndex:nextIndex]
|
||||
|
||||
if strings.Index(getTitleContent(c.title[i]), "secret") == 0 && !strings.Contains(nowContent, "mode") {
|
||||
local := delLocalService(nowContent)
|
||||
local.Type = "secret"
|
||||
c.LocalServer = append(c.LocalServer, local)
|
||||
continue
|
||||
}
|
||||
//except mode
|
||||
if strings.Index(getTitleContent(c.title[i]), "p2p") == 0 && !strings.Contains(nowContent, "mode") {
|
||||
local := delLocalService(nowContent)
|
||||
local.Type = "p2p"
|
||||
c.LocalServer = append(c.LocalServer, local)
|
||||
continue
|
||||
}
|
||||
//health set
|
||||
if strings.Index(getTitleContent(c.title[i]), "health") == 0 {
|
||||
c.Healths = append(c.Healths, dealHealth(nowContent))
|
||||
continue
|
||||
}
|
||||
switch c.title[i] {
|
||||
case "[common]":
|
||||
c.CommonConfig = dealCommon(nowContent)
|
||||
default:
|
||||
if strings.Index(nowContent, "host") > -1 {
|
||||
h := dealHost(nowContent)
|
||||
h.Remark = getTitleContent(c.title[i])
|
||||
c.Hosts = append(c.Hosts, h)
|
||||
} else {
|
||||
t := dealTunnel(nowContent)
|
||||
t.Remark = getTitleContent(c.title[i])
|
||||
c.Tasks = append(c.Tasks, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func getTitleContent(s string) string {
|
||||
re, _ := regexp.Compile(`[\[\]]`)
|
||||
return re.ReplaceAllString(s, "")
|
||||
}
|
||||
|
||||
func dealCommon(s string) *CommonConfig {
|
||||
c := &CommonConfig{}
|
||||
c.Client = file.NewClient("", true, true)
|
||||
c.Client.Cnf = new(file.Config)
|
||||
for _, v := range splitStr(s) {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch item[0] {
|
||||
case "server_addr":
|
||||
c.Server = item[1]
|
||||
case "vkey":
|
||||
c.VKey = item[1]
|
||||
case "conn_type":
|
||||
c.Tp = item[1]
|
||||
case "auto_reconnection":
|
||||
c.AutoReconnection = common.GetBoolByStr(item[1])
|
||||
case "basic_username":
|
||||
c.Client.Cnf.U = item[1]
|
||||
case "basic_password":
|
||||
c.Client.Cnf.P = item[1]
|
||||
case "web_password":
|
||||
c.Client.WebPassword = item[1]
|
||||
case "web_username":
|
||||
c.Client.WebUserName = item[1]
|
||||
case "compress":
|
||||
c.Client.Cnf.Compress = common.GetBoolByStr(item[1])
|
||||
case "crypt":
|
||||
c.Client.Cnf.Crypt = common.GetBoolByStr(item[1])
|
||||
case "proxy_url":
|
||||
c.ProxyUrl = item[1]
|
||||
case "rate_limit":
|
||||
c.Client.RateLimit = common.GetIntNoErrByStr(item[1])
|
||||
case "flow_limit":
|
||||
c.Client.Flow.FlowLimit = int64(common.GetIntNoErrByStr(item[1]))
|
||||
case "max_conn":
|
||||
c.Client.MaxConn = common.GetIntNoErrByStr(item[1])
|
||||
case "remark":
|
||||
c.Client.Remark = item[1]
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func dealHost(s string) *file.Host {
|
||||
h := &file.Host{}
|
||||
h.Target = new(file.Target)
|
||||
h.Scheme = "all"
|
||||
var headerChange string
|
||||
for _, v := range splitStr(s) {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch strings.TrimSpace(item[0]) {
|
||||
case "host":
|
||||
h.Host = item[1]
|
||||
case "target_addr":
|
||||
h.Target.TargetStr = strings.Replace(item[1], ",", "\n", -1)
|
||||
case "host_change":
|
||||
h.HostChange = item[1]
|
||||
case "scheme":
|
||||
h.Scheme = item[1]
|
||||
case "location":
|
||||
h.Location = item[1]
|
||||
default:
|
||||
if strings.Contains(item[0], "header") {
|
||||
headerChange += strings.Replace(item[0], "header_", "", -1) + ":" + item[1] + "\n"
|
||||
}
|
||||
h.HeaderChange = headerChange
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func dealHealth(s string) *file.Health {
|
||||
h := &file.Health{}
|
||||
for _, v := range splitStr(s) {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch strings.TrimSpace(item[0]) {
|
||||
case "health_check_timeout":
|
||||
h.HealthCheckTimeout = common.GetIntNoErrByStr(item[1])
|
||||
case "health_check_max_failed":
|
||||
h.HealthMaxFail = common.GetIntNoErrByStr(item[1])
|
||||
case "health_check_interval":
|
||||
h.HealthCheckInterval = common.GetIntNoErrByStr(item[1])
|
||||
case "health_http_url":
|
||||
h.HttpHealthUrl = item[1]
|
||||
case "health_check_type":
|
||||
h.HealthCheckType = item[1]
|
||||
case "health_check_target":
|
||||
h.HealthCheckTarget = item[1]
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func dealTunnel(s string) *file.Tunnel {
|
||||
t := &file.Tunnel{}
|
||||
t.Target = new(file.Target)
|
||||
for _, v := range splitStr(s) {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch strings.TrimSpace(item[0]) {
|
||||
case "server_port":
|
||||
t.Ports = item[1]
|
||||
case "server_ip":
|
||||
t.ServerIp = item[1]
|
||||
case "mode":
|
||||
t.Mode = item[1]
|
||||
case "target_addr":
|
||||
t.Target.TargetStr = strings.Replace(item[1], ",", "\n", -1)
|
||||
case "target_port":
|
||||
t.Target.TargetStr = item[1]
|
||||
case "target_ip":
|
||||
t.TargetAddr = item[1]
|
||||
case "password":
|
||||
t.Password = item[1]
|
||||
case "local_path":
|
||||
t.LocalPath = item[1]
|
||||
case "strip_pre":
|
||||
t.StripPre = item[1]
|
||||
case "multi_account":
|
||||
t.MultiAccount = &file.MultiAccount{}
|
||||
if b, err := common.ReadAllFromFile(item[1]); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
if content, err := common.ParseStr(string(b)); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
t.MultiAccount.AccountMap = dealMultiUser(content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return t
|
||||
|
||||
}
|
||||
|
||||
func dealMultiUser(s string) map[string]string {
|
||||
multiUserMap := make(map[string]string)
|
||||
for _, v := range splitStr(s) {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
multiUserMap[strings.TrimSpace(item[0])] = item[1]
|
||||
}
|
||||
return multiUserMap
|
||||
}
|
||||
|
||||
func delLocalService(s string) *LocalServer {
|
||||
l := new(LocalServer)
|
||||
for _, v := range splitStr(s) {
|
||||
item := strings.Split(v, "=")
|
||||
if len(item) == 0 {
|
||||
continue
|
||||
} else if len(item) == 1 {
|
||||
item = append(item, "")
|
||||
}
|
||||
switch item[0] {
|
||||
case "local_port":
|
||||
l.Port = common.GetIntNoErrByStr(item[1])
|
||||
case "local_ip":
|
||||
l.Ip = item[1]
|
||||
case "password":
|
||||
l.Password = item[1]
|
||||
case "target_addr":
|
||||
l.Target = item[1]
|
||||
}
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func getAllTitle(content string) (arr []string, err error) {
|
||||
var re *regexp.Regexp
|
||||
re, err = regexp.Compile(`\[.+?\]`)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
arr = re.FindAllString(content, -1)
|
||||
m := make(map[string]bool)
|
||||
for _, v := range arr {
|
||||
if _, ok := m[v]; ok {
|
||||
err = errors.New(fmt.Sprintf("Item names %s are not allowed to be duplicated", v))
|
||||
return
|
||||
}
|
||||
m[v] = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func splitStr(s string) (configDataArr []string) {
|
||||
if common.IsWindows() {
|
||||
configDataArr = strings.Split(s, "\r\n")
|
||||
}
|
||||
if len(configDataArr) < 3 {
|
||||
configDataArr = strings.Split(s, "\n")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReg(t *testing.T) {
|
||||
content := `
|
||||
[common]
|
||||
server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
vkey=123
|
||||
[web2]
|
||||
host=www.baidu.com
|
||||
host_change=www.sina.com
|
||||
target=127.0.0.1:8080,127.0.0.1:8082
|
||||
header_cookkile=122123
|
||||
header_user-Agent=122123
|
||||
[web2]
|
||||
host=www.baidu.com
|
||||
host_change=www.sina.com
|
||||
target=127.0.0.1:8080,127.0.0.1:8082
|
||||
header_cookkile="122123"
|
||||
header_user-Agent=122123
|
||||
[tunnel1]
|
||||
type=udp
|
||||
target=127.0.0.1:8080
|
||||
port=9001
|
||||
compress=snappy
|
||||
crypt=true
|
||||
u=1
|
||||
p=2
|
||||
[tunnel2]
|
||||
type=tcp
|
||||
target=127.0.0.1:8080
|
||||
port=9001
|
||||
compress=snappy
|
||||
crypt=true
|
||||
u=1
|
||||
p=2
|
||||
`
|
||||
re, err := regexp.Compile(`\[.+?\]`)
|
||||
if err != nil {
|
||||
t.Fail()
|
||||
}
|
||||
log.Println(re.FindAllString(content, -1))
|
||||
}
|
||||
|
||||
func TestDealCommon(t *testing.T) {
|
||||
s := `server=127.0.0.1:8284
|
||||
tp=tcp
|
||||
vkey=123`
|
||||
f := new(CommonConfig)
|
||||
f.Server = "127.0.0.1:8284"
|
||||
f.Tp = "tcp"
|
||||
f.VKey = "123"
|
||||
if c := dealCommon(s); *c != *f {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTitleContent(t *testing.T) {
|
||||
s := "[common]"
|
||||
if getTitleContent(s) != "common" {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
Executable
+405
@@ -0,0 +1,405 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/goroutine"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/xtaci/kcp-go"
|
||||
)
|
||||
|
||||
type Conn struct {
|
||||
Conn net.Conn
|
||||
Rb []byte
|
||||
}
|
||||
|
||||
//new conn
|
||||
func NewConn(conn net.Conn) *Conn {
|
||||
return &Conn{Conn: conn}
|
||||
}
|
||||
|
||||
//get host 、connection type、method...from connection
|
||||
func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
|
||||
var b [32 * 1024]byte
|
||||
var n int
|
||||
if n, err = s.Read(b[:]); err != nil {
|
||||
return
|
||||
}
|
||||
rb = b[:n]
|
||||
r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hostPortURL, err := url.Parse(r.Host)
|
||||
if err != nil {
|
||||
address = r.Host
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
if hostPortURL.Opaque == "443" {
|
||||
if strings.Index(r.Host, ":") == -1 {
|
||||
address = r.Host + ":443"
|
||||
} else {
|
||||
address = r.Host
|
||||
}
|
||||
} else {
|
||||
if strings.Index(r.Host, ":") == -1 {
|
||||
address = r.Host + ":80"
|
||||
} else {
|
||||
address = r.Host
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Conn) GetShortLenContent() (b []byte, err error) {
|
||||
var l int
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
}
|
||||
if l < 0 || l > 32<<10 {
|
||||
err = errors.New("read length error")
|
||||
return
|
||||
}
|
||||
return s.GetShortContent(l)
|
||||
}
|
||||
|
||||
func (s *Conn) GetShortContent(l int) (b []byte, err error) {
|
||||
buf := make([]byte, l)
|
||||
return buf, binary.Read(s, binary.LittleEndian, &buf)
|
||||
}
|
||||
|
||||
//读取指定长度内容
|
||||
func (s *Conn) ReadLen(cLen int, buf []byte) (int, error) {
|
||||
if cLen > len(buf) {
|
||||
return 0, errors.New("长度错误" + strconv.Itoa(cLen))
|
||||
}
|
||||
if n, err := io.ReadFull(s, buf[:cLen]); err != nil || n != cLen {
|
||||
return n, errors.New("Error reading specified length " + err.Error())
|
||||
}
|
||||
return cLen, nil
|
||||
}
|
||||
|
||||
func (s *Conn) GetLen() (int, error) {
|
||||
var l int32
|
||||
err := binary.Read(s, binary.LittleEndian, &l)
|
||||
return int(l), err
|
||||
}
|
||||
|
||||
func (s *Conn) WriteLenContent(buf []byte) (err error) {
|
||||
var b []byte
|
||||
if b, err = GetLenBytes(buf); err != nil {
|
||||
return
|
||||
}
|
||||
return binary.Write(s.Conn, binary.LittleEndian, b)
|
||||
}
|
||||
|
||||
//read flag
|
||||
func (s *Conn) ReadFlag() (string, error) {
|
||||
buf := make([]byte, 4)
|
||||
return string(buf), binary.Read(s, binary.LittleEndian, &buf)
|
||||
}
|
||||
|
||||
//set alive
|
||||
func (s *Conn) SetAlive(tp string) {
|
||||
switch s.Conn.(type) {
|
||||
case *kcp.UDPSession:
|
||||
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Time{})
|
||||
case *net.TCPConn:
|
||||
conn := s.Conn.(*net.TCPConn)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
conn.SetKeepAlive(true)
|
||||
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
|
||||
case *mux.PortConn:
|
||||
s.Conn.(*mux.PortConn).SetReadDeadline(time.Time{})
|
||||
}
|
||||
}
|
||||
|
||||
//set read deadline
|
||||
func (s *Conn) SetReadDeadlineBySecond(t time.Duration) {
|
||||
switch s.Conn.(type) {
|
||||
case *kcp.UDPSession:
|
||||
s.Conn.(*kcp.UDPSession).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
case *net.TCPConn:
|
||||
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
case *mux.PortConn:
|
||||
s.Conn.(*mux.PortConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
}
|
||||
}
|
||||
|
||||
//get link info from conn
|
||||
func (s *Conn) GetLinkInfo() (lk *Link, err error) {
|
||||
err = s.getInfo(&lk)
|
||||
return
|
||||
}
|
||||
|
||||
//send info for link
|
||||
func (s *Conn) SendHealthInfo(info, status string) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
common.BinaryWrite(raw, info, status)
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//get health info from conn
|
||||
func (s *Conn) GetHealthInfo() (info string, status bool, err error) {
|
||||
var l int
|
||||
buf := common.BufPoolMax.Get().([]byte)
|
||||
defer common.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
arr := strings.Split(string(buf[:l]), common.CONN_DATA_SEQ)
|
||||
if len(arr) >= 2 {
|
||||
return arr[0], common.GetBoolByStr(arr[1]), nil
|
||||
}
|
||||
}
|
||||
return "", false, errors.New("receive health info error")
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) GetHostInfo() (h *file.Host, err error) {
|
||||
err = s.getInfo(&h)
|
||||
h.Id = int(file.GetDb().JsonDb.GetHostId())
|
||||
h.Flow = new(file.Flow)
|
||||
h.NoStore = true
|
||||
return
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) GetConfigInfo() (c *file.Client, err error) {
|
||||
err = s.getInfo(&c)
|
||||
c.NoStore = true
|
||||
c.Status = true
|
||||
if c.Flow == nil {
|
||||
c.Flow = new(file.Flow)
|
||||
}
|
||||
c.NoDisplay = false
|
||||
return
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) GetTaskInfo() (t *file.Tunnel, err error) {
|
||||
err = s.getInfo(&t)
|
||||
t.Id = int(file.GetDb().JsonDb.GetTaskId())
|
||||
t.NoStore = true
|
||||
t.Flow = new(file.Flow)
|
||||
return
|
||||
}
|
||||
|
||||
//send info
|
||||
func (s *Conn) SendInfo(t interface{}, flag string) (int, error) {
|
||||
/*
|
||||
The task info is formed as follows:
|
||||
+----+-----+---------+
|
||||
|type| len | content |
|
||||
+----+---------------+
|
||||
| 4 | 4 | ... |
|
||||
+----+---------------+
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
if flag != "" {
|
||||
binary.Write(raw, binary.LittleEndian, []byte(flag))
|
||||
}
|
||||
b, err := json.Marshal(t)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
lenBytes, err := GetLenBytes(b)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
binary.Write(raw, binary.LittleEndian, lenBytes)
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//get task info
|
||||
func (s *Conn) getInfo(t interface{}) (err error) {
|
||||
var l int
|
||||
buf := common.BufPoolMax.Get().([]byte)
|
||||
defer common.PutBufPoolMax(buf)
|
||||
if l, err = s.GetLen(); err != nil {
|
||||
return
|
||||
} else if _, err = s.ReadLen(l, buf); err != nil {
|
||||
return
|
||||
} else {
|
||||
json.Unmarshal(buf[:l], &t)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *Conn) Close() error {
|
||||
return s.Conn.Close()
|
||||
}
|
||||
|
||||
//write
|
||||
func (s *Conn) Write(b []byte) (int, error) {
|
||||
return s.Conn.Write(b)
|
||||
}
|
||||
|
||||
//read
|
||||
func (s *Conn) Read(b []byte) (n int, err error) {
|
||||
if s.Rb != nil {
|
||||
//if the rb is not nil ,read rb first
|
||||
if len(s.Rb) > 0 {
|
||||
n = copy(b, s.Rb)
|
||||
s.Rb = s.Rb[n:]
|
||||
return
|
||||
}
|
||||
s.Rb = nil
|
||||
}
|
||||
return s.Conn.Read(b)
|
||||
}
|
||||
|
||||
//write sign flag
|
||||
func (s *Conn) WriteClose() (int, error) {
|
||||
return s.Write([]byte(common.RES_CLOSE))
|
||||
}
|
||||
|
||||
//write main
|
||||
func (s *Conn) WriteMain() (int, error) {
|
||||
return s.Write([]byte(common.WORK_MAIN))
|
||||
}
|
||||
|
||||
//write main
|
||||
func (s *Conn) WriteConfig() (int, error) {
|
||||
return s.Write([]byte(common.WORK_CONFIG))
|
||||
}
|
||||
|
||||
//write chan
|
||||
func (s *Conn) WriteChan() (int, error) {
|
||||
return s.Write([]byte(common.WORK_CHAN))
|
||||
}
|
||||
|
||||
//get task or host result of add
|
||||
func (s *Conn) GetAddStatus() (b bool) {
|
||||
binary.Read(s.Conn, binary.LittleEndian, &b)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Conn) WriteAddOk() error {
|
||||
return binary.Write(s.Conn, binary.LittleEndian, true)
|
||||
}
|
||||
|
||||
func (s *Conn) WriteAddFail() error {
|
||||
defer s.Close()
|
||||
return binary.Write(s.Conn, binary.LittleEndian, false)
|
||||
}
|
||||
|
||||
func (s *Conn) LocalAddr() net.Addr {
|
||||
return s.Conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *Conn) RemoteAddr() net.Addr {
|
||||
return s.Conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (s *Conn) SetDeadline(t time.Time) error {
|
||||
return s.Conn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (s *Conn) SetWriteDeadline(t time.Time) error {
|
||||
return s.Conn.SetWriteDeadline(t)
|
||||
}
|
||||
|
||||
func (s *Conn) SetReadDeadline(t time.Time) error {
|
||||
return s.Conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
//get the assembled amount data(len 4 and content)
|
||||
func GetLenBytes(buf []byte) (b []byte, err error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
|
||||
return
|
||||
}
|
||||
if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
|
||||
return
|
||||
}
|
||||
b = raw.Bytes()
|
||||
return
|
||||
}
|
||||
|
||||
//udp connection setting
|
||||
func SetUdpSession(sess *kcp.UDPSession) {
|
||||
sess.SetStreamMode(true)
|
||||
sess.SetWindowSize(1024, 1024)
|
||||
sess.SetReadBuffer(64 * 1024)
|
||||
sess.SetWriteBuffer(64 * 1024)
|
||||
sess.SetNoDelay(1, 10, 2, 1)
|
||||
sess.SetMtu(1600)
|
||||
sess.SetACKNoDelay(true)
|
||||
sess.SetWriteDelay(false)
|
||||
}
|
||||
|
||||
//conn1 mux conn
|
||||
func CopyWaitGroup(conn1, conn2 net.Conn, crypt bool, snappy bool, rate *rate.Rate, flow *file.Flow, isServer bool, rb []byte) {
|
||||
//var in, out int64
|
||||
//var wg sync.WaitGroup
|
||||
connHandle := GetConn(conn1, crypt, snappy, rate, isServer)
|
||||
if rb != nil {
|
||||
connHandle.Write(rb)
|
||||
}
|
||||
//go func(in *int64) {
|
||||
// wg.Add(1)
|
||||
// *in, _ = common.CopyBuffer(connHandle, conn2)
|
||||
// connHandle.Close()
|
||||
// conn2.Close()
|
||||
// wg.Done()
|
||||
//}(&in)
|
||||
//out, _ = common.CopyBuffer(conn2, connHandle)
|
||||
//connHandle.Close()
|
||||
//conn2.Close()
|
||||
//wg.Wait()
|
||||
//if flow != nil {
|
||||
// flow.Add(in, out)
|
||||
//}
|
||||
err := goroutine.CopyConnsPool.Invoke(goroutine.NewConns(connHandle, conn2, flow))
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
//get crypt or snappy conn
|
||||
func GetConn(conn net.Conn, cpt, snappy bool, rt *rate.Rate, isServer bool) io.ReadWriteCloser {
|
||||
if cpt {
|
||||
if isServer {
|
||||
return rate.NewRateConn(crypt.NewTlsServerConn(conn), rt)
|
||||
}
|
||||
return rate.NewRateConn(crypt.NewTlsClientConn(conn), rt)
|
||||
} else if snappy {
|
||||
return rate.NewRateConn(NewSnappyConn(conn), rt)
|
||||
}
|
||||
return rate.NewRateConn(conn, rt)
|
||||
}
|
||||
|
||||
type LenConn struct {
|
||||
conn io.Writer
|
||||
Len int
|
||||
}
|
||||
|
||||
func NewLenConn(conn io.Writer) *LenConn {
|
||||
return &LenConn{conn: conn}
|
||||
}
|
||||
func (c *LenConn) Write(p []byte) (n int, err error) {
|
||||
n, err = c.conn.Write(p)
|
||||
c.Len += n
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package conn
|
||||
|
||||
type Secret struct {
|
||||
Password string
|
||||
Conn *Conn
|
||||
}
|
||||
|
||||
func NewSecret(p string, conn *Conn) *Secret {
|
||||
return &Secret{
|
||||
Password: p,
|
||||
Conn: conn,
|
||||
}
|
||||
}
|
||||
|
||||
type Link struct {
|
||||
ConnType string //连接类型
|
||||
Host string //目标
|
||||
Crypt bool //加密
|
||||
Compress bool
|
||||
LocalProxy bool
|
||||
RemoteAddr string
|
||||
}
|
||||
|
||||
func NewLink(connType string, host string, crypt bool, compress bool, remoteAddr string, localProxy bool) *Link {
|
||||
return &Link{
|
||||
RemoteAddr: remoteAddr,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
Crypt: crypt,
|
||||
Compress: compress,
|
||||
LocalProxy: localProxy,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/xtaci/kcp-go"
|
||||
)
|
||||
|
||||
func NewTcpListenerAndProcess(addr string, f func(c net.Conn), listener *net.Listener) error {
|
||||
var err error
|
||||
*listener, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
Accept(*listener, f)
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewKcpListenerAndProcess(addr string, f func(c net.Conn)) error {
|
||||
kcpListener, err := kcp.ListenWithOptions(addr, nil, 150, 3)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
return err
|
||||
}
|
||||
for {
|
||||
c, err := kcpListener.AcceptKCP()
|
||||
SetUdpSession(c)
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
go f(c)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Accept(l net.Listener, f func(c net.Conn)) {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
if strings.Contains(err.Error(), "the mux has closed") {
|
||||
break
|
||||
}
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
if c == nil {
|
||||
logs.Warn("nil connection")
|
||||
break
|
||||
}
|
||||
go f(c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package conn
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/golang/snappy"
|
||||
)
|
||||
|
||||
type SnappyConn struct {
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
}
|
||||
|
||||
func NewSnappyConn(conn io.ReadWriteCloser) *SnappyConn {
|
||||
c := new(SnappyConn)
|
||||
c.w = snappy.NewBufferedWriter(conn)
|
||||
c.r = snappy.NewReader(conn)
|
||||
return c
|
||||
}
|
||||
|
||||
//snappy压缩写
|
||||
func (s *SnappyConn) Write(b []byte) (n int, err error) {
|
||||
if n, err = s.w.Write(b); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.w.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//snappy压缩读
|
||||
func (s *SnappyConn) Read(b []byte) (n int, err error) {
|
||||
buf := common.BufPool.Get().([]byte)
|
||||
defer common.BufPool.Put(buf)
|
||||
if n, err = s.r.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
copy(b, buf[:n])
|
||||
return
|
||||
}
|
||||
|
||||
func (s *SnappyConn) Close() error {
|
||||
s.w.Close()
|
||||
return s.w.Close()
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package crypt
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
type CurveID uint16
|
||||
type SignatureScheme uint16
|
||||
|
||||
const (
|
||||
statusTypeOCSP uint8 = 1
|
||||
extensionServerName uint16 = 0
|
||||
extensionStatusRequest uint16 = 5
|
||||
extensionSupportedCurves uint16 = 10
|
||||
extensionSupportedPoints uint16 = 11
|
||||
extensionSignatureAlgorithms uint16 = 13
|
||||
extensionALPN uint16 = 16
|
||||
extensionSCT uint16 = 18 // https://tools.ietf.org/html/rfc6962#section-6
|
||||
extensionSessionTicket uint16 = 35
|
||||
extensionNextProtoNeg uint16 = 13172 // not IANA assigned
|
||||
extensionRenegotiationInfo uint16 = 0xff01
|
||||
scsvRenegotiation uint16 = 0x00ff
|
||||
)
|
||||
|
||||
type ClientHelloMsg struct {
|
||||
raw []byte
|
||||
vers uint16
|
||||
random []byte
|
||||
sessionId []byte
|
||||
cipherSuites []uint16
|
||||
compressionMethods []uint8
|
||||
nextProtoNeg bool
|
||||
serverName string
|
||||
ocspStapling bool
|
||||
scts bool
|
||||
supportedCurves []CurveID
|
||||
supportedPoints []uint8
|
||||
ticketSupported bool
|
||||
sessionTicket []uint8
|
||||
supportedSignatureAlgorithms []SignatureScheme
|
||||
secureRenegotiation []byte
|
||||
secureRenegotiationSupported bool
|
||||
alpnProtocols []string
|
||||
}
|
||||
|
||||
func (m *ClientHelloMsg) GetServerName() string {
|
||||
return m.serverName
|
||||
}
|
||||
|
||||
func (m *ClientHelloMsg) Unmarshal(data []byte) bool {
|
||||
if len(data) < 42 {
|
||||
return false
|
||||
}
|
||||
m.raw = data
|
||||
m.vers = uint16(data[4])<<8 | uint16(data[5])
|
||||
m.random = data[6:38]
|
||||
sessionIdLen := int(data[38])
|
||||
if sessionIdLen > 32 || len(data) < 39+sessionIdLen {
|
||||
return false
|
||||
}
|
||||
m.sessionId = data[39 : 39+sessionIdLen]
|
||||
data = data[39+sessionIdLen:]
|
||||
if len(data) < 2 {
|
||||
return false
|
||||
}
|
||||
// cipherSuiteLen is the number of bytes of cipher suite numbers. Since
|
||||
// they are uint16s, the number must be even.
|
||||
cipherSuiteLen := int(data[0])<<8 | int(data[1])
|
||||
if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen {
|
||||
return false
|
||||
}
|
||||
numCipherSuites := cipherSuiteLen / 2
|
||||
m.cipherSuites = make([]uint16, numCipherSuites)
|
||||
for i := 0; i < numCipherSuites; i++ {
|
||||
m.cipherSuites[i] = uint16(data[2+2*i])<<8 | uint16(data[3+2*i])
|
||||
if m.cipherSuites[i] == scsvRenegotiation {
|
||||
m.secureRenegotiationSupported = true
|
||||
}
|
||||
}
|
||||
data = data[2+cipherSuiteLen:]
|
||||
if len(data) < 1 {
|
||||
return false
|
||||
}
|
||||
compressionMethodsLen := int(data[0])
|
||||
if len(data) < 1+compressionMethodsLen {
|
||||
return false
|
||||
}
|
||||
m.compressionMethods = data[1 : 1+compressionMethodsLen]
|
||||
data = data[1+compressionMethodsLen:]
|
||||
|
||||
m.nextProtoNeg = false
|
||||
m.serverName = ""
|
||||
m.ocspStapling = false
|
||||
m.ticketSupported = false
|
||||
m.sessionTicket = nil
|
||||
m.supportedSignatureAlgorithms = nil
|
||||
m.alpnProtocols = nil
|
||||
m.scts = false
|
||||
|
||||
if len(data) == 0 {
|
||||
// ClientHello is optionally followed by extension data
|
||||
return true
|
||||
}
|
||||
if len(data) < 2 {
|
||||
return false
|
||||
}
|
||||
|
||||
extensionsLength := int(data[0])<<8 | int(data[1])
|
||||
data = data[2:]
|
||||
if extensionsLength != len(data) {
|
||||
return false
|
||||
}
|
||||
|
||||
for len(data) != 0 {
|
||||
if len(data) < 4 {
|
||||
return false
|
||||
}
|
||||
extension := uint16(data[0])<<8 | uint16(data[1])
|
||||
length := int(data[2])<<8 | int(data[3])
|
||||
data = data[4:]
|
||||
if len(data) < length {
|
||||
return false
|
||||
}
|
||||
|
||||
switch extension {
|
||||
case extensionServerName:
|
||||
d := data[:length]
|
||||
if len(d) < 2 {
|
||||
return false
|
||||
}
|
||||
namesLen := int(d[0])<<8 | int(d[1])
|
||||
d = d[2:]
|
||||
if len(d) != namesLen {
|
||||
return false
|
||||
}
|
||||
for len(d) > 0 {
|
||||
if len(d) < 3 {
|
||||
return false
|
||||
}
|
||||
nameType := d[0]
|
||||
nameLen := int(d[1])<<8 | int(d[2])
|
||||
d = d[3:]
|
||||
if len(d) < nameLen {
|
||||
return false
|
||||
}
|
||||
if nameType == 0 {
|
||||
m.serverName = string(d[:nameLen])
|
||||
// An SNI value may not include a
|
||||
// trailing dot. See
|
||||
// https://tools.ietf.org/html/rfc6066#section-3.
|
||||
if strings.HasSuffix(m.serverName, ".") {
|
||||
return false
|
||||
}
|
||||
break
|
||||
}
|
||||
d = d[nameLen:]
|
||||
}
|
||||
case extensionNextProtoNeg:
|
||||
if length > 0 {
|
||||
return false
|
||||
}
|
||||
m.nextProtoNeg = true
|
||||
case extensionStatusRequest:
|
||||
m.ocspStapling = length > 0 && data[0] == statusTypeOCSP
|
||||
case extensionSupportedCurves:
|
||||
// https://tools.ietf.org/html/rfc4492#section-5.5.1
|
||||
if length < 2 {
|
||||
return false
|
||||
}
|
||||
l := int(data[0])<<8 | int(data[1])
|
||||
if l%2 == 1 || length != l+2 {
|
||||
return false
|
||||
}
|
||||
numCurves := l / 2
|
||||
m.supportedCurves = make([]CurveID, numCurves)
|
||||
d := data[2:]
|
||||
for i := 0; i < numCurves; i++ {
|
||||
m.supportedCurves[i] = CurveID(d[0])<<8 | CurveID(d[1])
|
||||
d = d[2:]
|
||||
}
|
||||
case extensionSupportedPoints:
|
||||
// https://tools.ietf.org/html/rfc4492#section-5.5.2
|
||||
if length < 1 {
|
||||
return false
|
||||
}
|
||||
l := int(data[0])
|
||||
if length != l+1 {
|
||||
return false
|
||||
}
|
||||
m.supportedPoints = make([]uint8, l)
|
||||
copy(m.supportedPoints, data[1:])
|
||||
case extensionSessionTicket:
|
||||
// https://tools.ietf.org/html/rfc5077#section-3.2
|
||||
m.ticketSupported = true
|
||||
m.sessionTicket = data[:length]
|
||||
case extensionSignatureAlgorithms:
|
||||
// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
|
||||
if length < 2 || length&1 != 0 {
|
||||
return false
|
||||
}
|
||||
l := int(data[0])<<8 | int(data[1])
|
||||
if l != length-2 {
|
||||
return false
|
||||
}
|
||||
n := l / 2
|
||||
d := data[2:]
|
||||
m.supportedSignatureAlgorithms = make([]SignatureScheme, n)
|
||||
for i := range m.supportedSignatureAlgorithms {
|
||||
m.supportedSignatureAlgorithms[i] = SignatureScheme(d[0])<<8 | SignatureScheme(d[1])
|
||||
d = d[2:]
|
||||
}
|
||||
case extensionRenegotiationInfo:
|
||||
if length == 0 {
|
||||
return false
|
||||
}
|
||||
d := data[:length]
|
||||
l := int(d[0])
|
||||
d = d[1:]
|
||||
if l != len(d) {
|
||||
return false
|
||||
}
|
||||
|
||||
m.secureRenegotiation = d
|
||||
m.secureRenegotiationSupported = true
|
||||
case extensionALPN:
|
||||
if length < 2 {
|
||||
return false
|
||||
}
|
||||
l := int(data[0])<<8 | int(data[1])
|
||||
if l != length-2 {
|
||||
return false
|
||||
}
|
||||
d := data[2:length]
|
||||
for len(d) != 0 {
|
||||
stringLen := int(d[0])
|
||||
d = d[1:]
|
||||
if stringLen == 0 || stringLen > len(d) {
|
||||
return false
|
||||
}
|
||||
m.alpnProtocols = append(m.alpnProtocols, string(d[:stringLen]))
|
||||
d = d[stringLen:]
|
||||
}
|
||||
case extensionSCT:
|
||||
m.scts = true
|
||||
if length != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
data = data[length:]
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package utils
|
||||
package crypt
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -19,11 +19,8 @@ func AesEncrypt(origData, key []byte) ([]byte, error) {
|
||||
}
|
||||
blockSize := block.BlockSize()
|
||||
origData = PKCS5Padding(origData, blockSize)
|
||||
// origData = ZeroPadding(origData, block.BlockSize())
|
||||
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
||||
crypted := make([]byte, len(origData))
|
||||
// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
|
||||
// crypted := origData
|
||||
blockMode.CryptBlocks(crypted, origData)
|
||||
return crypted, nil
|
||||
}
|
||||
@@ -37,24 +34,21 @@ func AesDecrypt(crypted, key []byte) ([]byte, error) {
|
||||
blockSize := block.BlockSize()
|
||||
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
||||
origData := make([]byte, len(crypted))
|
||||
// origData := crypted
|
||||
blockMode.CryptBlocks(origData, crypted)
|
||||
err, origData = PKCS5UnPadding(origData)
|
||||
// origData = ZeroUnPadding(origData)
|
||||
return origData, err
|
||||
}
|
||||
|
||||
//补全
|
||||
//Completion when the length is insufficient
|
||||
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
//去补
|
||||
//Remove excess
|
||||
func PKCS5UnPadding(origData []byte) (error, []byte) {
|
||||
length := len(origData)
|
||||
// 去掉最后一个字节 unpadding 次
|
||||
unpadding := int(origData[length-1])
|
||||
if (length - unpadding) < 0 {
|
||||
return errors.New("len error"), nil
|
||||
@@ -62,14 +56,14 @@ func PKCS5UnPadding(origData []byte) (error, []byte) {
|
||||
return nil, origData[:(length - unpadding)]
|
||||
}
|
||||
|
||||
//生成32位md5字串
|
||||
//Generate 32-bit MD5 strings
|
||||
func Md5(s string) string {
|
||||
h := md5.New()
|
||||
h.Write([]byte(s))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
//生成随机验证密钥
|
||||
//Generating Random Verification Key
|
||||
func GetRandomString(l int) string {
|
||||
str := "0123456789abcdefghijklmnopqrstuvwxyz"
|
||||
bytes := []byte(str)
|
||||
@@ -0,0 +1,34 @@
|
||||
package crypt
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"os"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
var pemPath, keyPath string
|
||||
|
||||
func InitTls(pem, key string) {
|
||||
pemPath = pem
|
||||
keyPath = key
|
||||
}
|
||||
|
||||
func NewTlsServerConn(conn net.Conn) net.Conn {
|
||||
cert, err := tls.LoadX509KeyPair(pemPath, keyPath)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
return nil
|
||||
}
|
||||
config := &tls.Config{Certificates: []tls.Certificate{cert}}
|
||||
return tls.Server(conn, config)
|
||||
}
|
||||
|
||||
func NewTlsClientConn(conn net.Conn) net.Conn {
|
||||
conf := &tls.Config{
|
||||
InsecureSkipVerify: true,
|
||||
}
|
||||
return tls.Client(conn, conf)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
func InitDaemon(f string, runPath string, pidPath string) {
|
||||
if len(os.Args) < 2 {
|
||||
return
|
||||
}
|
||||
var args []string
|
||||
args = append(args, os.Args[0])
|
||||
if len(os.Args) >= 2 {
|
||||
args = append(args, os.Args[2:]...)
|
||||
}
|
||||
args = append(args, "-log=file")
|
||||
switch os.Args[1] {
|
||||
case "start":
|
||||
start(args, f, pidPath, runPath)
|
||||
os.Exit(0)
|
||||
case "stop":
|
||||
stop(f, args[0], pidPath)
|
||||
os.Exit(0)
|
||||
case "restart":
|
||||
stop(f, args[0], pidPath)
|
||||
start(args, f, pidPath, runPath)
|
||||
os.Exit(0)
|
||||
case "status":
|
||||
if status(f, pidPath) {
|
||||
log.Printf("%s is running", f)
|
||||
} else {
|
||||
log.Printf("%s is not running", f)
|
||||
}
|
||||
os.Exit(0)
|
||||
case "reload":
|
||||
reload(f, pidPath)
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
func reload(f string, pidPath string) {
|
||||
if f == "nps" && !common.IsWindows() && !status(f, pidPath) {
|
||||
log.Println("reload fail")
|
||||
return
|
||||
}
|
||||
var c *exec.Cmd
|
||||
var err error
|
||||
b, err := ioutil.ReadFile(filepath.Join(pidPath, f+".pid"))
|
||||
if err == nil {
|
||||
c = exec.Command("/bin/bash", "-c", `kill -30 `+string(b))
|
||||
} else {
|
||||
log.Fatalln("reload error,pid file does not exist")
|
||||
}
|
||||
if c.Run() == nil {
|
||||
log.Println("reload success")
|
||||
} else {
|
||||
log.Println("reload fail")
|
||||
}
|
||||
}
|
||||
|
||||
func status(f string, pidPath string) bool {
|
||||
var cmd *exec.Cmd
|
||||
b, err := ioutil.ReadFile(filepath.Join(pidPath, f+".pid"))
|
||||
if err == nil {
|
||||
if !common.IsWindows() {
|
||||
cmd = exec.Command("/bin/sh", "-c", "ps -ax | awk '{ print $1 }' | grep "+string(b))
|
||||
} else {
|
||||
cmd = exec.Command("tasklist")
|
||||
}
|
||||
out, _ := cmd.Output()
|
||||
if strings.Index(string(out), string(b)) > -1 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func start(osArgs []string, f string, pidPath, runPath string) {
|
||||
if status(f, pidPath) {
|
||||
log.Printf(" %s is running", f)
|
||||
return
|
||||
}
|
||||
cmd := exec.Command(osArgs[0], osArgs[1:]...)
|
||||
cmd.Start()
|
||||
if cmd.Process.Pid > 0 {
|
||||
log.Println("start ok , pid:", cmd.Process.Pid, "config path:", runPath)
|
||||
d1 := []byte(strconv.Itoa(cmd.Process.Pid))
|
||||
ioutil.WriteFile(filepath.Join(pidPath, f+".pid"), d1, 0600)
|
||||
} else {
|
||||
log.Println("start error")
|
||||
}
|
||||
}
|
||||
|
||||
func stop(f string, p string, pidPath string) {
|
||||
if !status(f, pidPath) {
|
||||
log.Printf(" %s is not running", f)
|
||||
return
|
||||
}
|
||||
var c *exec.Cmd
|
||||
var err error
|
||||
if common.IsWindows() {
|
||||
p := strings.Split(p, `\`)
|
||||
c = exec.Command("taskkill", "/F", "/IM", p[len(p)-1])
|
||||
} else {
|
||||
b, err := ioutil.ReadFile(filepath.Join(pidPath, f+".pid"))
|
||||
if err == nil {
|
||||
c = exec.Command("/bin/bash", "-c", `kill -9 `+string(b))
|
||||
} else {
|
||||
log.Fatalln("stop error,pid file does not exist")
|
||||
}
|
||||
}
|
||||
err = c.Run()
|
||||
if err != nil {
|
||||
log.Println("stop error,", err)
|
||||
} else {
|
||||
log.Println("stop ok")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// +build !windows
|
||||
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
func init() {
|
||||
s := make(chan os.Signal, 1)
|
||||
signal.Notify(s, syscall.SIGUSR1)
|
||||
go func() {
|
||||
for {
|
||||
<-s
|
||||
beego.LoadAppConfig("ini", filepath.Join(common.GetRunPath(), "conf", "nps.conf"))
|
||||
}
|
||||
}()
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
)
|
||||
|
||||
type DbUtils struct {
|
||||
JsonDb *JsonDb
|
||||
}
|
||||
|
||||
var (
|
||||
Db *DbUtils
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
//init csv from file
|
||||
func GetDb() *DbUtils {
|
||||
once.Do(func() {
|
||||
jsonDb := NewJsonDb(common.GetRunPath())
|
||||
jsonDb.LoadClientFromJsonFile()
|
||||
jsonDb.LoadTaskFromJsonFile()
|
||||
jsonDb.LoadHostFromJsonFile()
|
||||
Db = &DbUtils{JsonDb: jsonDb}
|
||||
})
|
||||
return Db
|
||||
}
|
||||
|
||||
func GetMapKeys(m sync.Map, isSort bool, sortKey, order string) (keys []int) {
|
||||
if sortKey != "" && isSort {
|
||||
return sortClientByKey(m, sortKey, order)
|
||||
}
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
keys = append(keys, key.(int))
|
||||
return true
|
||||
})
|
||||
sort.Ints(keys)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetClientList(start, length int, search, sort, order string, clientId int) ([]*Client, int) {
|
||||
list := make([]*Client, 0)
|
||||
var cnt int
|
||||
keys := GetMapKeys(s.JsonDb.Clients, true, sort, order)
|
||||
for _, key := range keys {
|
||||
if value, ok := s.JsonDb.Clients.Load(key); ok {
|
||||
v := value.(*Client)
|
||||
if v.NoDisplay {
|
||||
continue
|
||||
}
|
||||
if clientId != 0 && clientId != v.Id {
|
||||
continue
|
||||
}
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.VerifyKey, search) || strings.Contains(v.Remark, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, cnt
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetIdByVerifyKey(vKey string, addr string) (id int, err error) {
|
||||
var exist bool
|
||||
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if common.Getverifyval(v.VerifyKey) == vKey && v.Status {
|
||||
v.Addr = common.GetIpByAddr(addr)
|
||||
id = v.Id
|
||||
exist = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if exist {
|
||||
return
|
||||
}
|
||||
return 0, errors.New("not found")
|
||||
}
|
||||
|
||||
func (s *DbUtils) NewTask(t *Tunnel) (err error) {
|
||||
s.JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Tunnel)
|
||||
if (v.Mode == "secret" || v.Mode == "p2p") && v.Password == t.Password {
|
||||
err = errors.New(fmt.Sprintf("secret mode keys %s must be unique", t.Password))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
t.Flow = new(Flow)
|
||||
s.JsonDb.Tasks.Store(t.Id, t)
|
||||
s.JsonDb.StoreTasksToJsonFile()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) UpdateTask(t *Tunnel) error {
|
||||
s.JsonDb.Tasks.Store(t.Id, t)
|
||||
s.JsonDb.StoreTasksToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) DelTask(id int) error {
|
||||
s.JsonDb.Tasks.Delete(id)
|
||||
s.JsonDb.StoreTasksToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
//md5 password
|
||||
func (s *DbUtils) GetTaskByMd5Password(p string) (t *Tunnel) {
|
||||
s.JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
if crypt.Md5(value.(*Tunnel).Password) == p {
|
||||
t = value.(*Tunnel)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetTask(id int) (t *Tunnel, err error) {
|
||||
if v, ok := s.JsonDb.Tasks.Load(id); ok {
|
||||
t = v.(*Tunnel)
|
||||
return
|
||||
}
|
||||
err = errors.New("not found")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) DelHost(id int) error {
|
||||
s.JsonDb.Hosts.Delete(id)
|
||||
s.JsonDb.StoreHostToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) IsHostExist(h *Host) bool {
|
||||
var exist bool
|
||||
s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Host)
|
||||
if v.Id != h.Id && v.Host == h.Host && h.Location == v.Location && (v.Scheme == "all" || v.Scheme == h.Scheme) {
|
||||
exist = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return exist
|
||||
}
|
||||
|
||||
func (s *DbUtils) NewHost(t *Host) error {
|
||||
if t.Location == "" {
|
||||
t.Location = "/"
|
||||
}
|
||||
if s.IsHostExist(t) {
|
||||
return errors.New("host has exist")
|
||||
}
|
||||
t.Flow = new(Flow)
|
||||
s.JsonDb.Hosts.Store(t.Id, t)
|
||||
s.JsonDb.StoreHostToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetHost(start, length int, id int, search string) ([]*Host, int) {
|
||||
list := make([]*Host, 0)
|
||||
var cnt int
|
||||
keys := GetMapKeys(s.JsonDb.Hosts, false, "", "")
|
||||
for _, key := range keys {
|
||||
if value, ok := s.JsonDb.Hosts.Load(key); ok {
|
||||
v := value.(*Host)
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || strings.Contains(v.Host, search) || strings.Contains(v.Remark, search)) {
|
||||
continue
|
||||
}
|
||||
if id == 0 || v.Client.Id == id {
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, cnt
|
||||
}
|
||||
|
||||
func (s *DbUtils) DelClient(id int) error {
|
||||
s.JsonDb.Clients.Delete(id)
|
||||
s.JsonDb.StoreClientsToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) NewClient(c *Client) error {
|
||||
var isNotSet bool
|
||||
if c.WebUserName != "" && !s.VerifyUserName(c.WebUserName, c.Id) {
|
||||
return errors.New("web login username duplicate, please reset")
|
||||
}
|
||||
reset:
|
||||
if c.VerifyKey == "" || isNotSet {
|
||||
isNotSet = true
|
||||
c.VerifyKey = crypt.GetRandomString(16)
|
||||
}
|
||||
if c.RateLimit == 0 {
|
||||
c.Rate = rate.NewRate(int64(2 << 23))
|
||||
} else if c.Rate == nil {
|
||||
c.Rate = rate.NewRate(int64(c.RateLimit * 1024))
|
||||
}
|
||||
c.Rate.Start()
|
||||
if !s.VerifyVkey(c.VerifyKey, c.Id) {
|
||||
if isNotSet {
|
||||
goto reset
|
||||
}
|
||||
return errors.New("Vkey duplicate, please reset")
|
||||
}
|
||||
if c.Id == 0 {
|
||||
c.Id = int(s.JsonDb.GetClientId())
|
||||
}
|
||||
if c.Flow == nil {
|
||||
c.Flow = new(Flow)
|
||||
}
|
||||
s.JsonDb.Clients.Store(c.Id, c)
|
||||
s.JsonDb.StoreClientsToJsonFile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) VerifyVkey(vkey string, id int) (res bool) {
|
||||
res = true
|
||||
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if v.VerifyKey == vkey && v.Id != id {
|
||||
res = false
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *DbUtils) VerifyUserName(username string, id int) (res bool) {
|
||||
res = true
|
||||
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if v.WebUserName == username && v.Id != id {
|
||||
res = false
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
func (s *DbUtils) UpdateClient(t *Client) error {
|
||||
s.JsonDb.Clients.Store(t.Id, t)
|
||||
if t.RateLimit == 0 {
|
||||
t.Rate = rate.NewRate(int64(2 << 23))
|
||||
t.Rate.Start()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *DbUtils) IsPubClient(id int) bool {
|
||||
client, err := s.GetClient(id)
|
||||
if err == nil {
|
||||
return client.NoDisplay
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetClient(id int) (c *Client, err error) {
|
||||
if v, ok := s.JsonDb.Clients.Load(id); ok {
|
||||
c = v.(*Client)
|
||||
return
|
||||
}
|
||||
err = errors.New("未找到客户端")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetClientIdByVkey(vkey string) (id int, err error) {
|
||||
var exist bool
|
||||
s.JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Client)
|
||||
if crypt.Md5(v.VerifyKey) == vkey {
|
||||
exist = true
|
||||
id = v.Id
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if exist {
|
||||
return
|
||||
}
|
||||
err = errors.New("未找到客户端")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *DbUtils) GetHostById(id int) (h *Host, err error) {
|
||||
if v, ok := s.JsonDb.Hosts.Load(id); ok {
|
||||
h = v.(*Host)
|
||||
return
|
||||
}
|
||||
err = errors.New("The host could not be parsed")
|
||||
return
|
||||
}
|
||||
|
||||
//get key by host from x
|
||||
func (s *DbUtils) GetInfoByHost(host string, r *http.Request) (h *Host, err error) {
|
||||
var hosts []*Host
|
||||
//Handling Ported Access
|
||||
host = common.GetIpByAddr(host)
|
||||
s.JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Host)
|
||||
if v.IsClose {
|
||||
return true
|
||||
}
|
||||
//Remove http(s) http(s)://a.proxy.com
|
||||
//*.proxy.com *.a.proxy.com Do some pan-parsing
|
||||
tmp := strings.Replace(v.Host, "*", `\w+?`, -1)
|
||||
var re *regexp.Regexp
|
||||
if re, err = regexp.Compile(tmp); err != nil {
|
||||
return true
|
||||
}
|
||||
if len(re.FindAllString(host, -1)) > 0 && (v.Scheme == "all" || v.Scheme == r.URL.Scheme) {
|
||||
//URL routing
|
||||
hosts = append(hosts, v)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
for _, v := range hosts {
|
||||
//If not set, default matches all
|
||||
if v.Location == "" {
|
||||
v.Location = "/"
|
||||
}
|
||||
if strings.Index(r.RequestURI, v.Location) == 0 {
|
||||
if h == nil || (len(v.Location) > len(h.Location)) {
|
||||
h = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if h != nil {
|
||||
return
|
||||
}
|
||||
err = errors.New("The host could not be parsed")
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
)
|
||||
|
||||
func NewJsonDb(runPath string) *JsonDb {
|
||||
return &JsonDb{
|
||||
RunPath: runPath,
|
||||
TaskFilePath: filepath.Join(runPath, "conf", "tasks.json"),
|
||||
HostFilePath: filepath.Join(runPath, "conf", "hosts.json"),
|
||||
ClientFilePath: filepath.Join(runPath, "conf", "clients.json"),
|
||||
}
|
||||
}
|
||||
|
||||
type JsonDb struct {
|
||||
Tasks sync.Map
|
||||
Hosts sync.Map
|
||||
HostsTmp sync.Map
|
||||
Clients sync.Map
|
||||
RunPath string
|
||||
ClientIncreaseId int32 //client increased id
|
||||
TaskIncreaseId int32 //task increased id
|
||||
HostIncreaseId int32 //host increased id
|
||||
TaskFilePath string //task file path
|
||||
HostFilePath string //host file path
|
||||
ClientFilePath string //client file path
|
||||
}
|
||||
|
||||
func (s *JsonDb) LoadTaskFromJsonFile() {
|
||||
loadSyncMapFromFile(s.TaskFilePath, func(v string) {
|
||||
var err error
|
||||
post := new(Tunnel)
|
||||
if json.Unmarshal([]byte(v), &post) != nil {
|
||||
return
|
||||
}
|
||||
if post.Client, err = s.GetClient(post.Client.Id); err != nil {
|
||||
return
|
||||
}
|
||||
s.Tasks.Store(post.Id, post)
|
||||
if post.Id > int(s.TaskIncreaseId) {
|
||||
s.TaskIncreaseId = int32(post.Id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *JsonDb) LoadClientFromJsonFile() {
|
||||
loadSyncMapFromFile(s.ClientFilePath, func(v string) {
|
||||
post := new(Client)
|
||||
if json.Unmarshal([]byte(v), &post) != nil {
|
||||
return
|
||||
}
|
||||
if post.RateLimit > 0 {
|
||||
post.Rate = rate.NewRate(int64(post.RateLimit * 1024))
|
||||
} else {
|
||||
post.Rate = rate.NewRate(int64(2 << 23))
|
||||
}
|
||||
post.Rate.Start()
|
||||
post.NowConn = 0
|
||||
s.Clients.Store(post.Id, post)
|
||||
if post.Id > int(s.ClientIncreaseId) {
|
||||
s.ClientIncreaseId = int32(post.Id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *JsonDb) LoadHostFromJsonFile() {
|
||||
loadSyncMapFromFile(s.HostFilePath, func(v string) {
|
||||
var err error
|
||||
post := new(Host)
|
||||
if json.Unmarshal([]byte(v), &post) != nil {
|
||||
return
|
||||
}
|
||||
if post.Client, err = s.GetClient(post.Client.Id); err != nil {
|
||||
return
|
||||
}
|
||||
s.Hosts.Store(post.Id, post)
|
||||
if post.Id > int(s.HostIncreaseId) {
|
||||
s.HostIncreaseId = int32(post.Id)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (s *JsonDb) GetClient(id int) (c *Client, err error) {
|
||||
if v, ok := s.Clients.Load(id); ok {
|
||||
c = v.(*Client)
|
||||
return
|
||||
}
|
||||
err = errors.New("未找到客户端")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *JsonDb) StoreHostToJsonFile() {
|
||||
storeSyncMapToFile(s.Hosts, s.HostFilePath)
|
||||
}
|
||||
|
||||
func (s *JsonDb) StoreTasksToJsonFile() {
|
||||
storeSyncMapToFile(s.Tasks, s.TaskFilePath)
|
||||
}
|
||||
|
||||
func (s *JsonDb) StoreClientsToJsonFile() {
|
||||
storeSyncMapToFile(s.Clients, s.ClientFilePath)
|
||||
}
|
||||
|
||||
func (s *JsonDb) GetClientId() int32 {
|
||||
return atomic.AddInt32(&s.ClientIncreaseId, 1)
|
||||
}
|
||||
|
||||
func (s *JsonDb) GetTaskId() int32 {
|
||||
return atomic.AddInt32(&s.TaskIncreaseId, 1)
|
||||
}
|
||||
|
||||
func (s *JsonDb) GetHostId() int32 {
|
||||
return atomic.AddInt32(&s.HostIncreaseId, 1)
|
||||
}
|
||||
|
||||
func loadSyncMapFromFile(filePath string, f func(value string)) {
|
||||
b, err := common.ReadAllFromFile(filePath)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
for _, v := range strings.Split(string(b), "\n"+common.CONN_DATA_SEQ) {
|
||||
f(v)
|
||||
}
|
||||
}
|
||||
|
||||
func storeSyncMapToFile(m sync.Map, filePath string) {
|
||||
file, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer file.Close()
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
var b []byte
|
||||
var err error
|
||||
switch value.(type) {
|
||||
case *Tunnel:
|
||||
obj := value.(*Tunnel)
|
||||
if obj.NoStore {
|
||||
return true
|
||||
}
|
||||
b, err = json.Marshal(obj)
|
||||
case *Host:
|
||||
obj := value.(*Host)
|
||||
if obj.NoStore {
|
||||
return true
|
||||
}
|
||||
b, err = json.Marshal(obj)
|
||||
case *Client:
|
||||
obj := value.(*Client)
|
||||
if obj.NoStore {
|
||||
return true
|
||||
}
|
||||
b, err = json.Marshal(obj)
|
||||
default:
|
||||
return true
|
||||
}
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
_, err = file.Write(b)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = file.Write([]byte("\n" + common.CONN_DATA_SEQ))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/cnlh/nps/lib/rate"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Flow struct {
|
||||
ExportFlow int64
|
||||
InletFlow int64
|
||||
FlowLimit int64
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Flow) Add(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.InletFlow += int64(in)
|
||||
s.ExportFlow += int64(out)
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
U string
|
||||
P string
|
||||
Compress bool
|
||||
Crypt bool
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
Cnf *Config
|
||||
Id int //id
|
||||
VerifyKey string //verify key
|
||||
Addr string //the ip of client
|
||||
Remark string //remark
|
||||
Status bool //is allow connect
|
||||
IsConnect bool //is the client connect
|
||||
RateLimit int //rate /kb
|
||||
Flow *Flow //flow setting
|
||||
Rate *rate.Rate //rate limit
|
||||
NoStore bool //no store to file
|
||||
NoDisplay bool //no display on web
|
||||
MaxConn int //the max connection num of client allow
|
||||
NowConn int32 //the connection num of now
|
||||
WebUserName string //the username of web login
|
||||
WebPassword string //the password of web login
|
||||
ConfigConnAllow bool //is allow connected by config file
|
||||
MaxTunnelNum int
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewClient(vKey string, noStore bool, noDisplay bool) *Client {
|
||||
return &Client{
|
||||
Cnf: new(Config),
|
||||
Id: 0,
|
||||
VerifyKey: vKey,
|
||||
Addr: "",
|
||||
Remark: "",
|
||||
Status: true,
|
||||
IsConnect: false,
|
||||
RateLimit: 0,
|
||||
Flow: new(Flow),
|
||||
Rate: nil,
|
||||
NoStore: noStore,
|
||||
RWMutex: sync.RWMutex{},
|
||||
NoDisplay: noDisplay,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Client) CutConn() {
|
||||
atomic.AddInt32(&s.NowConn, 1)
|
||||
}
|
||||
|
||||
func (s *Client) AddConn() {
|
||||
atomic.AddInt32(&s.NowConn, -1)
|
||||
}
|
||||
|
||||
func (s *Client) GetConn() bool {
|
||||
if s.MaxConn == 0 || int(s.NowConn) < s.MaxConn {
|
||||
s.CutConn()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Client) HasTunnel(t *Tunnel) (exist bool) {
|
||||
GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Tunnel)
|
||||
if v.Client.Id == s.Id && v.Port == t.Port && t.Port != 0 {
|
||||
exist = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Client) GetTunnelNum() (num int) {
|
||||
GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Tunnel)
|
||||
if v.Client.Id == s.Id {
|
||||
num++
|
||||
}
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Client) HasHost(h *Host) bool {
|
||||
var has bool
|
||||
GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*Host)
|
||||
if v.Client.Id == s.Id && v.Host == h.Host && h.Location == v.Location {
|
||||
has = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return has
|
||||
}
|
||||
|
||||
type Tunnel struct {
|
||||
Id int
|
||||
Port int
|
||||
ServerIp string
|
||||
Mode string
|
||||
Status bool
|
||||
RunStatus bool
|
||||
Client *Client
|
||||
Ports string
|
||||
Flow *Flow
|
||||
Password string
|
||||
Remark string
|
||||
TargetAddr string
|
||||
NoStore bool
|
||||
LocalPath string
|
||||
StripPre string
|
||||
Target *Target
|
||||
MultiAccount *MultiAccount
|
||||
Health
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type Health struct {
|
||||
HealthCheckTimeout int
|
||||
HealthMaxFail int
|
||||
HealthCheckInterval int
|
||||
HealthNextTime time.Time
|
||||
HealthMap map[string]int
|
||||
HttpHealthUrl string
|
||||
HealthRemoveArr []string
|
||||
HealthCheckType string
|
||||
HealthCheckTarget string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type Host struct {
|
||||
Id int
|
||||
Host string //host
|
||||
HeaderChange string //header change
|
||||
HostChange string //host change
|
||||
Location string //url router
|
||||
Remark string //remark
|
||||
Scheme string //http https all
|
||||
CertFilePath string
|
||||
KeyFilePath string
|
||||
NoStore bool
|
||||
IsClose bool
|
||||
Flow *Flow
|
||||
Client *Client
|
||||
Target *Target //目标
|
||||
Health `json:"-"`
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type Target struct {
|
||||
nowIndex int
|
||||
TargetStr string
|
||||
TargetArr []string
|
||||
LocalProxy bool
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
type MultiAccount struct {
|
||||
AccountMap map[string]string // multi account and pwd
|
||||
}
|
||||
|
||||
func (s *Target) GetRandomTarget() (string, error) {
|
||||
if s.TargetArr == nil {
|
||||
s.TargetArr = strings.Split(s.TargetStr, "\n")
|
||||
}
|
||||
if len(s.TargetArr) == 1 {
|
||||
return s.TargetArr[0], nil
|
||||
}
|
||||
if len(s.TargetArr) == 0 {
|
||||
return "", errors.New("all inward-bending targets are offline")
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.nowIndex >= len(s.TargetArr)-1 {
|
||||
s.nowIndex = -1
|
||||
}
|
||||
s.nowIndex++
|
||||
return s.TargetArr[s.nowIndex], nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A data structure to hold a key/value pair.
|
||||
type Pair struct {
|
||||
key string //sort key
|
||||
cId int
|
||||
order string
|
||||
clientFlow *Flow
|
||||
}
|
||||
|
||||
// A slice of Pairs that implements sort.Interface to sort by Value.
|
||||
type PairList []*Pair
|
||||
|
||||
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
|
||||
func (p PairList) Len() int { return len(p) }
|
||||
func (p PairList) Less(i, j int) bool {
|
||||
if p[i].order == "desc" {
|
||||
return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() < reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
|
||||
}
|
||||
return reflect.ValueOf(*p[i].clientFlow).FieldByName(p[i].key).Int() > reflect.ValueOf(*p[j].clientFlow).FieldByName(p[j].key).Int()
|
||||
}
|
||||
|
||||
// A function to turn a map into a PairList, then sort and return it.
|
||||
func sortClientByKey(m sync.Map, sortKey, order string) (res []int) {
|
||||
p := make(PairList, 0)
|
||||
m.Range(func(key, value interface{}) bool {
|
||||
p = append(p, &Pair{sortKey, value.(*Client).Id, order, value.(*Client).Flow})
|
||||
return true
|
||||
})
|
||||
sort.Sort(p)
|
||||
for _, v := range p {
|
||||
res = append(res, v.cId)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package goroutine
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/panjf2000/ants/v2"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type connGroup struct {
|
||||
src io.ReadWriteCloser
|
||||
dst io.ReadWriteCloser
|
||||
wg *sync.WaitGroup
|
||||
n *int64
|
||||
}
|
||||
|
||||
func newConnGroup(dst, src io.ReadWriteCloser, wg *sync.WaitGroup, n *int64) connGroup {
|
||||
return connGroup{
|
||||
src: src,
|
||||
dst: dst,
|
||||
wg: wg,
|
||||
n: n,
|
||||
}
|
||||
}
|
||||
|
||||
func copyConnGroup(group interface{}) {
|
||||
cg, ok := group.(connGroup)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
*cg.n, err = common.CopyBuffer(cg.dst, cg.src)
|
||||
if err != nil {
|
||||
cg.src.Close()
|
||||
cg.dst.Close()
|
||||
//logs.Warn("close npc by copy from nps", err, c.connId)
|
||||
}
|
||||
cg.wg.Done()
|
||||
}
|
||||
|
||||
type Conns struct {
|
||||
conn1 io.ReadWriteCloser // mux connection
|
||||
conn2 net.Conn // outside connection
|
||||
flow *file.Flow
|
||||
}
|
||||
|
||||
func NewConns(c1 io.ReadWriteCloser, c2 net.Conn, flow *file.Flow) Conns {
|
||||
return Conns{
|
||||
conn1: c1,
|
||||
conn2: c2,
|
||||
flow: flow,
|
||||
}
|
||||
}
|
||||
|
||||
func copyConns(group interface{}) {
|
||||
conns := group.(Conns)
|
||||
wg := new(sync.WaitGroup)
|
||||
wg.Add(2)
|
||||
var in, out int64
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn1, conns.conn2, wg, &in))
|
||||
// outside to mux : incoming
|
||||
_ = connCopyPool.Invoke(newConnGroup(conns.conn2, conns.conn1, wg, &out))
|
||||
// mux to outside : outgoing
|
||||
wg.Wait()
|
||||
if conns.flow != nil {
|
||||
conns.flow.Add(in, out)
|
||||
}
|
||||
}
|
||||
|
||||
var connCopyPool, _ = ants.NewPoolWithFunc(200000, copyConnGroup, ants.WithNonblocking(false))
|
||||
var CopyConnsPool, _ = ants.NewPoolWithFunc(100000, copyConns, ants.WithNonblocking(false))
|
||||
@@ -0,0 +1,173 @@
|
||||
package install
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
func InstallNps() {
|
||||
unit := `[Unit]
|
||||
Description=nps - convenient proxy server
|
||||
Documentation=https://github.com/cnlh/nps/
|
||||
After=network-online.target remote-fs.target nss-lookup.target
|
||||
Wants=network-online.target`
|
||||
service := `[Service]
|
||||
Type=simple
|
||||
KillMode=process
|
||||
Restart=always
|
||||
RestartSec=15s
|
||||
StandardOutput=append:/var/log/nps/nps.log
|
||||
ExecStartPre=/bin/echo 'Starting nps'
|
||||
ExecStopPost=/bin/echo 'Stopping nps'
|
||||
ExecStart=`
|
||||
install := `[Install]
|
||||
WantedBy=multi-user.target`
|
||||
|
||||
path := common.GetInstallPath()
|
||||
if common.FileExists(path) {
|
||||
log.Fatalf("the path %s has exist, does not support install", path)
|
||||
}
|
||||
MkidrDirAll(path, "conf", "web/static", "web/views")
|
||||
//复制文件到对应目录
|
||||
if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "views"), filepath.Join(path, "web", "views")); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := CopyDir(filepath.Join(common.GetAppPath(), "web", "static"), filepath.Join(path, "web", "static")); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
if err := CopyDir(filepath.Join(common.GetAppPath(), "conf"), filepath.Join(path, "conf")); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
|
||||
if !common.IsWindows() {
|
||||
if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/bin/nps"); err != nil {
|
||||
if _, err := copyFile(filepath.Join(common.GetAppPath(), "nps"), "/usr/local/bin/nps"); err != nil {
|
||||
log.Fatalln(err)
|
||||
} else {
|
||||
os.Chmod("/usr/local/bin/nps", 0755)
|
||||
service += "/usr/local/bin/nps"
|
||||
log.Println("Executable files have been copied to", "/usr/local/bin/nps")
|
||||
}
|
||||
} else {
|
||||
os.Chmod("/usr/bin/nps", 0755)
|
||||
service += "/usr/bin/nps"
|
||||
log.Println("Executable files have been copied to", "/usr/bin/nps")
|
||||
}
|
||||
systemd := unit + "\n\n" + service + "\n\n" + install
|
||||
_ = os.Remove("/usr/lib/systemd/system/nps.service")
|
||||
err := ioutil.WriteFile("/usr/lib/systemd/system/nps.service", []byte(systemd), 0644)
|
||||
if err != nil {
|
||||
log.Println("Write systemd service err ", err)
|
||||
}
|
||||
_ = os.Mkdir("/var/log/nps", 644)
|
||||
}
|
||||
log.Println("install ok!")
|
||||
log.Println("Static files and configuration files in the current directory will be useless")
|
||||
log.Println("The new configuration file is located in", path, "you can edit them")
|
||||
if !common.IsWindows() {
|
||||
log.Println(`You can start with:
|
||||
sudo systemctl enable|disable|start|stop|restart|status nps
|
||||
or:
|
||||
nps test|start|stop|restart|status
|
||||
anywhere!`)
|
||||
} else {
|
||||
log.Println(`You can copy executable files to any directory and start working with:
|
||||
nps.exe test|start|stop|restart|status
|
||||
now!`)
|
||||
}
|
||||
}
|
||||
func MkidrDirAll(path string, v ...string) {
|
||||
for _, item := range v {
|
||||
if err := os.MkdirAll(filepath.Join(path, item), 0755); err != nil {
|
||||
log.Fatalf("Failed to create directory %s error:%s", path, err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func CopyDir(srcPath string, destPath string) error {
|
||||
//检测目录正确性
|
||||
if srcInfo, err := os.Stat(srcPath); err != nil {
|
||||
fmt.Println(err.Error())
|
||||
return err
|
||||
} else {
|
||||
if !srcInfo.IsDir() {
|
||||
e := errors.New("SrcPath is not the right directory!")
|
||||
return e
|
||||
}
|
||||
}
|
||||
if destInfo, err := os.Stat(destPath); err != nil {
|
||||
return err
|
||||
} else {
|
||||
if !destInfo.IsDir() {
|
||||
e := errors.New("DestInfo is not the right directory!")
|
||||
return e
|
||||
}
|
||||
}
|
||||
err := filepath.Walk(srcPath, func(path string, f os.FileInfo, err error) error {
|
||||
if f == nil {
|
||||
return err
|
||||
}
|
||||
if !f.IsDir() {
|
||||
destNewPath := strings.Replace(path, srcPath, destPath, -1)
|
||||
log.Println("copy file ::" + path + " to " + destNewPath)
|
||||
copyFile(path, destNewPath)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
//生成目录并拷贝文件
|
||||
func copyFile(src, dest string) (w int64, err error) {
|
||||
srcFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer srcFile.Close()
|
||||
//分割path目录
|
||||
destSplitPathDirs := strings.Split(dest, string(filepath.Separator))
|
||||
|
||||
//检测时候存在目录
|
||||
destSplitPath := ""
|
||||
for index, dir := range destSplitPathDirs {
|
||||
if index < len(destSplitPathDirs)-1 {
|
||||
destSplitPath = destSplitPath + dir + string(filepath.Separator)
|
||||
b, _ := pathExists(destSplitPath)
|
||||
if b == false {
|
||||
log.Println("mkdir:" + destSplitPath)
|
||||
//创建目录
|
||||
err := os.Mkdir(destSplitPath, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
dstFile, err := os.Create(dest)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
return io.Copy(dstFile, srcFile)
|
||||
}
|
||||
|
||||
//检测文件夹路径时候存在
|
||||
func pathExists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
//write bytes with int32 length
|
||||
func WriteLenBytes(buf []byte, w io.Writer) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
if err := binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err := binary.Write(raw, binary.LittleEndian, buf); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return w.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//read bytes by length
|
||||
func ReadLenBytes(buf []byte, r io.Reader) (int, error) {
|
||||
var l uint32
|
||||
var err error
|
||||
if binary.Read(r, binary.LittleEndian, &l) != nil {
|
||||
return 0, err
|
||||
}
|
||||
if _, err = io.ReadFull(r, buf[:l]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(l), nil
|
||||
}
|
||||
+635
@@ -0,0 +1,635 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
type conn struct {
|
||||
net.Conn
|
||||
getStatusCh chan struct{}
|
||||
connStatusOkCh chan struct{}
|
||||
connStatusFailCh chan struct{}
|
||||
connId int32
|
||||
isClose bool
|
||||
closeFlag bool // close conn flag
|
||||
receiveWindow *ReceiveWindow
|
||||
sendWindow *SendWindow
|
||||
once sync.Once
|
||||
//label string
|
||||
}
|
||||
|
||||
func NewConn(connId int32, mux *Mux, label ...string) *conn {
|
||||
c := &conn{
|
||||
getStatusCh: make(chan struct{}),
|
||||
connStatusOkCh: make(chan struct{}),
|
||||
connStatusFailCh: make(chan struct{}),
|
||||
connId: connId,
|
||||
receiveWindow: new(ReceiveWindow),
|
||||
sendWindow: new(SendWindow),
|
||||
once: sync.Once{},
|
||||
}
|
||||
//if len(label) > 0 {
|
||||
// c.label = label[0]
|
||||
//}
|
||||
c.receiveWindow.New(mux)
|
||||
c.sendWindow.New(mux)
|
||||
//logm := &connLog{
|
||||
// startTime: time.Now(),
|
||||
// isClose: false,
|
||||
// logs: []string{c.label + "new conn success"},
|
||||
//}
|
||||
//setM(label[0], int(connId), logm)
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *conn) Read(buf []byte) (n int, err error) {
|
||||
if s.isClose || buf == nil {
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
// waiting for takeout from receive window finish or timeout
|
||||
//now := time.Now()
|
||||
n, err = s.receiveWindow.Read(buf, s.connId)
|
||||
//t := time.Now().Sub(now)
|
||||
//if t.Seconds() > 0.5 {
|
||||
//logs.Warn("conn read long", n, t.Seconds())
|
||||
//}
|
||||
//var errstr string
|
||||
//if err == nil {
|
||||
// errstr = "err:nil"
|
||||
//} else {
|
||||
// errstr = err.Error()
|
||||
//}
|
||||
//d := getM(s.label, int(s.connId))
|
||||
//d.logs = append(d.logs, s.label+"read "+strconv.Itoa(n)+" "+errstr+" "+string(buf[:100]))
|
||||
//setM(s.label, int(s.connId), d)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) Write(buf []byte) (n int, err error) {
|
||||
if s.isClose {
|
||||
return 0, errors.New("the conn has closed")
|
||||
}
|
||||
if s.closeFlag {
|
||||
//s.Close()
|
||||
return 0, errors.New("io: write on closed conn")
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
//logs.Warn("write buf", len(buf))
|
||||
//now := time.Now()
|
||||
n, err = s.sendWindow.WriteFull(buf, s.connId)
|
||||
//t := time.Now().Sub(now)
|
||||
//if t.Seconds() > 0.5 {
|
||||
// logs.Warn("conn write long", n, t.Seconds())
|
||||
//}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) Close() (err error) {
|
||||
s.once.Do(s.closeProcess)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) closeProcess() {
|
||||
s.isClose = true
|
||||
s.receiveWindow.mux.connMap.Delete(s.connId)
|
||||
if !s.receiveWindow.mux.IsClose {
|
||||
// if server or user close the conn while reading, will get a io.EOF
|
||||
// and this Close method will be invoke, send this signal to close other side
|
||||
s.receiveWindow.mux.sendInfo(common.MUX_CONN_CLOSE, s.connId, nil)
|
||||
}
|
||||
s.sendWindow.CloseWindow()
|
||||
s.receiveWindow.CloseWindow()
|
||||
//d := getM(s.label, int(s.connId))
|
||||
//d.isClose = true
|
||||
//d.logs = append(d.logs, s.label+"close "+time.Now().String())
|
||||
//setM(s.label, int(s.connId), d)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *conn) LocalAddr() net.Addr {
|
||||
return s.receiveWindow.mux.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *conn) RemoteAddr() net.Addr {
|
||||
return s.receiveWindow.mux.conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (s *conn) SetDeadline(t time.Time) error {
|
||||
_ = s.SetReadDeadline(t)
|
||||
_ = s.SetWriteDeadline(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) SetReadDeadline(t time.Time) error {
|
||||
s.receiveWindow.SetTimeOut(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *conn) SetWriteDeadline(t time.Time) error {
|
||||
s.sendWindow.SetTimeOut(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
type window struct {
|
||||
remainingWait uint64 // 64bit alignment
|
||||
off uint32
|
||||
maxSize uint32
|
||||
closeOp bool
|
||||
closeOpCh chan struct{}
|
||||
mux *Mux
|
||||
}
|
||||
|
||||
func (Self *window) unpack(ptrs uint64) (remaining, wait uint32) {
|
||||
const mask = 1<<dequeueBits - 1
|
||||
remaining = uint32((ptrs >> dequeueBits) & mask)
|
||||
wait = uint32(ptrs & mask)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *window) pack(remaining, wait uint32) uint64 {
|
||||
const mask = 1<<dequeueBits - 1
|
||||
return (uint64(remaining) << dequeueBits) |
|
||||
uint64(wait&mask)
|
||||
}
|
||||
|
||||
func (Self *window) New() {
|
||||
Self.closeOpCh = make(chan struct{}, 2)
|
||||
}
|
||||
|
||||
func (Self *window) CloseWindow() {
|
||||
if !Self.closeOp {
|
||||
Self.closeOp = true
|
||||
Self.closeOpCh <- struct{}{}
|
||||
Self.closeOpCh <- struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
type ReceiveWindow struct {
|
||||
window
|
||||
bufQueue ReceiveWindowQueue
|
||||
element *common.ListElement
|
||||
count int8
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) New(mux *Mux) {
|
||||
// initial a window for receive
|
||||
Self.bufQueue.New()
|
||||
Self.element = common.ListElementPool.Get()
|
||||
Self.maxSize = common.MAXIMUM_SEGMENT_SIZE * 10
|
||||
Self.mux = mux
|
||||
Self.window.New()
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) remainingSize(delta uint16) (n uint32) {
|
||||
// receive window remaining
|
||||
l := int64(atomic.LoadUint32(&Self.maxSize)) - int64(Self.bufQueue.Len())
|
||||
l -= int64(delta)
|
||||
if l > 0 {
|
||||
n = uint32(l)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) calcSize() {
|
||||
// calculating maximum receive window size
|
||||
if Self.count == 0 {
|
||||
//logs.Warn("ping, bw", Self.mux.latency, Self.bw.Get())
|
||||
conns := Self.mux.connMap.Size()
|
||||
n := uint32(math.Float64frombits(atomic.LoadUint64(&Self.mux.latency)) *
|
||||
Self.mux.bw.Get() / float64(conns))
|
||||
if n < common.MAXIMUM_SEGMENT_SIZE*10 {
|
||||
n = common.MAXIMUM_SEGMENT_SIZE * 10
|
||||
}
|
||||
bufLen := Self.bufQueue.Len()
|
||||
if n < bufLen {
|
||||
n = bufLen
|
||||
}
|
||||
if n < Self.maxSize/2 {
|
||||
n = Self.maxSize / 2
|
||||
}
|
||||
// set the minimal size
|
||||
if n > 2*Self.maxSize {
|
||||
n = 2 * Self.maxSize
|
||||
}
|
||||
if n > (common.MAXIMUM_WINDOW_SIZE / uint32(conns)) {
|
||||
n = common.MAXIMUM_WINDOW_SIZE / uint32(conns)
|
||||
}
|
||||
// set the maximum size
|
||||
//logs.Warn("n", n)
|
||||
atomic.StoreUint32(&Self.maxSize, n)
|
||||
Self.count = -10
|
||||
}
|
||||
Self.count += 1
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) Write(buf []byte, l uint16, part bool, id int32) (err error) {
|
||||
if Self.closeOp {
|
||||
return errors.New("conn.receiveWindow: write on closed window")
|
||||
}
|
||||
element, err := NewListElement(buf, l, part)
|
||||
//logs.Warn("push the buf", len(buf), l, (&element).l)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
Self.calcSize() // calculate the max window size
|
||||
var wait uint32
|
||||
start:
|
||||
ptrs := atomic.LoadUint64(&Self.remainingWait)
|
||||
_, wait = Self.unpack(ptrs)
|
||||
newRemaining := Self.remainingSize(l)
|
||||
// calculate the remaining window size now, plus the element we will push
|
||||
if newRemaining == 0 {
|
||||
//logs.Warn("window full true", remaining)
|
||||
wait = 1
|
||||
}
|
||||
if !atomic.CompareAndSwapUint64(&Self.remainingWait, ptrs, Self.pack(0, wait)) {
|
||||
goto start
|
||||
// another goroutine change the status, make sure shall we need wait
|
||||
}
|
||||
Self.bufQueue.Push(element)
|
||||
// status check finish, now we can push the element into the queue
|
||||
if wait == 0 {
|
||||
Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, Self.maxSize, newRemaining)
|
||||
// send the remaining window size, not including zero size
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) Read(p []byte, id int32) (n int, err error) {
|
||||
if Self.closeOp {
|
||||
return 0, io.EOF // receive close signal, returns eof
|
||||
}
|
||||
pOff := 0
|
||||
l := 0
|
||||
//logs.Warn("receive window read off, element.l", Self.off, Self.element.l)
|
||||
copyData:
|
||||
if Self.off == uint32(Self.element.L) {
|
||||
// on the first Read method invoked, Self.off and Self.element.l
|
||||
// both zero value
|
||||
common.ListElementPool.Put(Self.element)
|
||||
if Self.closeOp {
|
||||
return 0, io.EOF
|
||||
}
|
||||
Self.element, err = Self.bufQueue.Pop()
|
||||
// if the queue is empty, Pop method will wait until one element push
|
||||
// into the queue successful, or timeout.
|
||||
// timer start on timeout parameter is set up ,
|
||||
// reset to 60s if timeout and data still available
|
||||
Self.off = 0
|
||||
if err != nil {
|
||||
return // queue receive stop or time out, break the loop and return
|
||||
}
|
||||
//logs.Warn("pop element", Self.element.l, Self.element.part)
|
||||
}
|
||||
l = copy(p[pOff:], Self.element.Buf[Self.off:Self.element.L])
|
||||
pOff += l
|
||||
Self.off += uint32(l)
|
||||
//logs.Warn("window read length buf len", Self.readLength, Self.bufQueue.Len())
|
||||
n += l
|
||||
l = 0
|
||||
if Self.off == uint32(Self.element.L) {
|
||||
//logs.Warn("put the element end ", string(Self.element.buf[:15]))
|
||||
common.WindowBuff.Put(Self.element.Buf)
|
||||
Self.sendStatus(id, Self.element.L)
|
||||
// check the window full status
|
||||
}
|
||||
if pOff < len(p) && Self.element.Part {
|
||||
// element is a part of the segments, trying to fill up buf p
|
||||
goto copyData
|
||||
}
|
||||
return // buf p is full or all of segments in buf, return
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) sendStatus(id int32, l uint16) {
|
||||
var remaining, wait uint32
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.remainingWait)
|
||||
remaining, wait = Self.unpack(ptrs)
|
||||
remaining += uint32(l)
|
||||
if atomic.CompareAndSwapUint64(&Self.remainingWait, ptrs, Self.pack(remaining, 0)) {
|
||||
break
|
||||
}
|
||||
runtime.Gosched()
|
||||
// another goroutine change remaining or wait status, make sure
|
||||
// we need acknowledge other side
|
||||
}
|
||||
// now we get the current window status success
|
||||
if wait == 1 {
|
||||
//logs.Warn("send the wait status", remaining)
|
||||
Self.mux.sendInfo(common.MUX_MSG_SEND_OK, id, atomic.LoadUint32(&Self.maxSize), remaining)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) SetTimeOut(t time.Time) {
|
||||
// waiting for FIFO queue Pop method
|
||||
Self.bufQueue.SetTimeOut(t)
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) Stop() {
|
||||
// queue has no more data to push, so unblock pop method
|
||||
Self.once.Do(Self.bufQueue.Stop)
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) CloseWindow() {
|
||||
Self.window.CloseWindow()
|
||||
Self.Stop()
|
||||
Self.release()
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindow) release() {
|
||||
//if Self.element != nil {
|
||||
// if Self.element.Buf != nil {
|
||||
// common.WindowBuff.Put(Self.element.Buf)
|
||||
// }
|
||||
// common.ListElementPool.Put(Self.element)
|
||||
//}
|
||||
for {
|
||||
Self.element = Self.bufQueue.TryPop()
|
||||
if Self.element == nil {
|
||||
return
|
||||
}
|
||||
if Self.element.Buf != nil {
|
||||
common.WindowBuff.Put(Self.element.Buf)
|
||||
}
|
||||
common.ListElementPool.Put(Self.element)
|
||||
} // release resource
|
||||
}
|
||||
|
||||
type SendWindow struct {
|
||||
window
|
||||
buf []byte
|
||||
setSizeCh chan struct{}
|
||||
timeout time.Time
|
||||
}
|
||||
|
||||
func (Self *SendWindow) New(mux *Mux) {
|
||||
Self.setSizeCh = make(chan struct{})
|
||||
Self.maxSize = common.MAXIMUM_SEGMENT_SIZE * 10
|
||||
atomic.AddUint64(&Self.remainingWait, uint64(common.MAXIMUM_SEGMENT_SIZE*10)<<dequeueBits)
|
||||
Self.mux = mux
|
||||
Self.window.New()
|
||||
}
|
||||
|
||||
func (Self *SendWindow) SetSendBuf(buf []byte) {
|
||||
// send window buff from conn write method, set it to send window
|
||||
Self.buf = buf
|
||||
Self.off = 0
|
||||
}
|
||||
|
||||
func (Self *SendWindow) SetSize(windowSize, newRemaining uint32) (closed bool) {
|
||||
// set the window size from receive window
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
closed = true
|
||||
}
|
||||
}()
|
||||
if Self.closeOp {
|
||||
close(Self.setSizeCh)
|
||||
return true
|
||||
}
|
||||
//logs.Warn("set send window size to ", windowSize, newRemaining)
|
||||
var remaining, wait, newWait uint32
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.remainingWait)
|
||||
remaining, wait = Self.unpack(ptrs)
|
||||
if remaining == newRemaining {
|
||||
//logs.Warn("waiting for another window size")
|
||||
return false // waiting for receive another usable window size
|
||||
}
|
||||
if newRemaining == 0 && wait == 1 {
|
||||
newWait = 1 // keep the wait status,
|
||||
// also if newRemaining is not zero, change wait to 0
|
||||
}
|
||||
if atomic.CompareAndSwapUint64(&Self.remainingWait, ptrs, Self.pack(newRemaining, newWait)) {
|
||||
break
|
||||
}
|
||||
// anther goroutine change wait status or window size
|
||||
}
|
||||
if wait == 1 {
|
||||
// send window into the wait status, need notice the channel
|
||||
//logs.Warn("send window remaining size is 0")
|
||||
Self.allow()
|
||||
}
|
||||
// send window not into the wait status, so just do slide
|
||||
return false
|
||||
}
|
||||
|
||||
func (Self *SendWindow) allow() {
|
||||
select {
|
||||
case Self.setSizeCh <- struct{}{}:
|
||||
//logs.Warn("send window remaining size is 0 finish")
|
||||
return
|
||||
case <-Self.closeOpCh:
|
||||
close(Self.setSizeCh)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *SendWindow) sent(sentSize uint32) {
|
||||
atomic.AddUint64(&Self.remainingWait, ^(uint64(sentSize)<<dequeueBits - 1))
|
||||
}
|
||||
|
||||
func (Self *SendWindow) WriteTo() (p []byte, sendSize uint32, part bool, err error) {
|
||||
// returns buf segments, return only one segments, need a loop outside
|
||||
// until err = io.EOF
|
||||
if Self.closeOp {
|
||||
return nil, 0, false, errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
if Self.off == uint32(len(Self.buf)) {
|
||||
return nil, 0, false, io.EOF
|
||||
// send window buff is drain, return eof and get another one
|
||||
}
|
||||
var remaining uint32
|
||||
start:
|
||||
ptrs := atomic.LoadUint64(&Self.remainingWait)
|
||||
remaining, _ = Self.unpack(ptrs)
|
||||
if remaining == 0 {
|
||||
if !atomic.CompareAndSwapUint64(&Self.remainingWait, ptrs, Self.pack(0, 1)) {
|
||||
goto start // another goroutine change the window, try again
|
||||
}
|
||||
// into the wait status
|
||||
//logs.Warn("send window into wait status")
|
||||
err = Self.waitReceiveWindow()
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
//logs.Warn("rem into wait finish")
|
||||
goto start
|
||||
}
|
||||
// there are still remaining window
|
||||
//logs.Warn("rem", remaining)
|
||||
if len(Self.buf[Self.off:]) > common.MAXIMUM_SEGMENT_SIZE {
|
||||
sendSize = common.MAXIMUM_SEGMENT_SIZE
|
||||
//logs.Warn("cut buf by mss")
|
||||
} else {
|
||||
sendSize = uint32(len(Self.buf[Self.off:]))
|
||||
}
|
||||
if remaining < sendSize {
|
||||
// usable window size is small than
|
||||
// window MAXIMUM_SEGMENT_SIZE or send buf left
|
||||
sendSize = remaining
|
||||
//logs.Warn("cut buf by remainingsize", sendSize, len(Self.buf[Self.off:]))
|
||||
}
|
||||
//logs.Warn("send size", sendSize)
|
||||
if sendSize < uint32(len(Self.buf[Self.off:])) {
|
||||
part = true
|
||||
}
|
||||
p = Self.buf[Self.off : sendSize+Self.off]
|
||||
Self.off += sendSize
|
||||
Self.sent(sendSize)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *SendWindow) waitReceiveWindow() (err error) {
|
||||
t := Self.timeout.Sub(time.Now())
|
||||
if t < 0 {
|
||||
t = time.Minute * 5
|
||||
}
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
// waiting for receive usable window size, or timeout
|
||||
select {
|
||||
case _, ok := <-Self.setSizeCh:
|
||||
if !ok {
|
||||
return errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
return nil
|
||||
case <-timer.C:
|
||||
return errors.New("conn.writeWindow: write to time out")
|
||||
case <-Self.closeOpCh:
|
||||
return errors.New("conn.writeWindow: window closed")
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *SendWindow) WriteFull(buf []byte, id int32) (n int, err error) {
|
||||
Self.SetSendBuf(buf) // set the buf to send window
|
||||
//logs.Warn("set the buf to send window")
|
||||
var bufSeg []byte
|
||||
var part bool
|
||||
var l uint32
|
||||
for {
|
||||
bufSeg, l, part, err = Self.WriteTo()
|
||||
//logs.Warn("buf seg", len(bufSeg), part, err)
|
||||
// get the buf segments from send window
|
||||
if bufSeg == nil && part == false && err == io.EOF {
|
||||
// send window is drain, break the loop
|
||||
err = nil
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
n += int(l)
|
||||
l = 0
|
||||
if part {
|
||||
Self.mux.sendInfo(common.MUX_NEW_MSG_PART, id, bufSeg)
|
||||
} else {
|
||||
Self.mux.sendInfo(common.MUX_NEW_MSG, id, bufSeg)
|
||||
//logs.Warn("buf seg sent", len(bufSeg), part, err)
|
||||
}
|
||||
// send to other side, not send nil data to other side
|
||||
}
|
||||
//logs.Warn("buf seg write success")
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *SendWindow) SetTimeOut(t time.Time) {
|
||||
// waiting for receive a receive window size
|
||||
Self.timeout = t
|
||||
}
|
||||
|
||||
//type bandwidth struct {
|
||||
// readStart time.Time
|
||||
// lastReadStart time.Time
|
||||
// readEnd time.Time
|
||||
// lastReadEnd time.Time
|
||||
// bufLength int
|
||||
// lastBufLength int
|
||||
// count int8
|
||||
// readBW float64
|
||||
// writeBW float64
|
||||
// readBandwidth float64
|
||||
//}
|
||||
//
|
||||
//func (Self *bandwidth) StartRead() {
|
||||
// Self.lastReadStart, Self.readStart = Self.readStart, time.Now()
|
||||
// if !Self.lastReadStart.IsZero() {
|
||||
// if Self.count == -5 {
|
||||
// Self.calcBandWidth()
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//func (Self *bandwidth) EndRead() {
|
||||
// Self.lastReadEnd, Self.readEnd = Self.readEnd, time.Now()
|
||||
// if Self.count == -5 {
|
||||
// Self.calcWriteBandwidth()
|
||||
// }
|
||||
// if Self.count == 0 {
|
||||
// Self.calcReadBandwidth()
|
||||
// Self.count = -6
|
||||
// }
|
||||
// Self.count += 1
|
||||
//}
|
||||
//
|
||||
//func (Self *bandwidth) SetCopySize(n int) {
|
||||
// // must be invoke between StartRead and EndRead
|
||||
// Self.lastBufLength, Self.bufLength = Self.bufLength, n
|
||||
//}
|
||||
//// calculating
|
||||
//// start end start end
|
||||
//// read read
|
||||
//// write
|
||||
//
|
||||
//func (Self *bandwidth) calcBandWidth() {
|
||||
// t := Self.readStart.Sub(Self.lastReadStart)
|
||||
// if Self.lastBufLength >= 32768 {
|
||||
// Self.readBandwidth = float64(Self.lastBufLength) / t.Seconds()
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//func (Self *bandwidth) calcReadBandwidth() {
|
||||
// // Bandwidth between nps and npc
|
||||
// readTime := Self.readEnd.Sub(Self.readStart)
|
||||
// Self.readBW = float64(Self.bufLength) / readTime.Seconds()
|
||||
// //logs.Warn("calc read bw", Self.readBW, Self.bufLength, readTime.Seconds())
|
||||
//}
|
||||
//
|
||||
//func (Self *bandwidth) calcWriteBandwidth() {
|
||||
// // Bandwidth between nps and user, npc and application
|
||||
// writeTime := Self.readStart.Sub(Self.lastReadEnd)
|
||||
// Self.writeBW = float64(Self.lastBufLength) / writeTime.Seconds()
|
||||
// //logs.Warn("calc write bw", Self.writeBW, Self.bufLength, writeTime.Seconds())
|
||||
//}
|
||||
//
|
||||
//func (Self *bandwidth) Get() (bw float64) {
|
||||
// // The zero value, 0 for numeric types
|
||||
// if Self.writeBW == 0 && Self.readBW == 0 {
|
||||
// //logs.Warn("bw both 0")
|
||||
// return 100
|
||||
// }
|
||||
// if Self.writeBW == 0 && Self.readBW != 0 {
|
||||
// return Self.readBW
|
||||
// }
|
||||
// if Self.readBW == 0 && Self.writeBW != 0 {
|
||||
// return Self.writeBW
|
||||
// }
|
||||
// return Self.readBandwidth
|
||||
//}
|
||||
@@ -0,0 +1,75 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type connMap struct {
|
||||
connMap map[int32]*conn
|
||||
//closeCh chan struct{}
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func NewConnMap() *connMap {
|
||||
connMap := &connMap{
|
||||
connMap: make(map[int32]*conn),
|
||||
//closeCh: make(chan struct{}),
|
||||
}
|
||||
//go connMap.clean()
|
||||
return connMap
|
||||
}
|
||||
|
||||
func (s *connMap) Size() (n int) {
|
||||
s.Lock()
|
||||
n = len(s.connMap)
|
||||
s.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *connMap) Get(id int32) (*conn, bool) {
|
||||
s.Lock()
|
||||
v, ok := s.connMap[id]
|
||||
s.Unlock()
|
||||
if ok && v != nil {
|
||||
return v, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (s *connMap) Set(id int32, v *conn) {
|
||||
s.Lock()
|
||||
s.connMap[id] = v
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
func (s *connMap) Close() {
|
||||
//s.closeCh <- struct{}{} // stop the clean goroutine first
|
||||
for _, v := range s.connMap {
|
||||
v.Close() // close all the connections in the mux
|
||||
}
|
||||
}
|
||||
|
||||
func (s *connMap) Delete(id int32) {
|
||||
s.Lock()
|
||||
delete(s.connMap, id)
|
||||
s.Unlock()
|
||||
}
|
||||
|
||||
//func (s *connMap) clean() {
|
||||
// ticker := time.NewTimer(time.Minute * 1)
|
||||
// for {
|
||||
// select {
|
||||
// case <-ticker.C:
|
||||
// s.Lock()
|
||||
// for _, v := range s.connMap {
|
||||
// if v.isClose {
|
||||
// delete(s.connMap, v.connId)
|
||||
// }
|
||||
// }
|
||||
// s.Unlock()
|
||||
// case <-s.closeCh:
|
||||
// ticker.Stop()
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
+508
@@ -0,0 +1,508 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
type Mux struct {
|
||||
latency uint64 // we store latency in bits, but it's float64
|
||||
net.Listener
|
||||
conn net.Conn
|
||||
connMap *connMap
|
||||
newConnCh chan *conn
|
||||
id int32
|
||||
closeChan chan struct{}
|
||||
IsClose bool
|
||||
pingOk uint32
|
||||
counter *latencyCounter
|
||||
bw *bandwidth
|
||||
pingCh chan []byte
|
||||
pingCheckTime uint32
|
||||
connType string
|
||||
writeQueue PriorityQueue
|
||||
newConnQueue ConnQueue
|
||||
}
|
||||
|
||||
func NewMux(c net.Conn, connType string) *Mux {
|
||||
//c.(*net.TCPConn).SetReadBuffer(0)
|
||||
//c.(*net.TCPConn).SetWriteBuffer(0)
|
||||
m := &Mux{
|
||||
conn: c,
|
||||
connMap: NewConnMap(),
|
||||
id: 0,
|
||||
closeChan: make(chan struct{}, 1),
|
||||
newConnCh: make(chan *conn),
|
||||
bw: new(bandwidth),
|
||||
IsClose: false,
|
||||
connType: connType,
|
||||
pingCh: make(chan []byte),
|
||||
counter: newLatencyCounter(),
|
||||
}
|
||||
m.writeQueue.New()
|
||||
m.newConnQueue.New()
|
||||
//read session by flag
|
||||
m.readSession()
|
||||
//ping
|
||||
m.ping()
|
||||
m.pingReturn()
|
||||
m.writeSession()
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Mux) NewConn() (*conn, error) {
|
||||
if s.IsClose {
|
||||
return nil, errors.New("the mux has closed")
|
||||
}
|
||||
conn := NewConn(s.getId(), s, "nps ")
|
||||
//it must be set before send
|
||||
s.connMap.Set(conn.connId, conn)
|
||||
s.sendInfo(common.MUX_NEW_CONN, conn.connId, nil)
|
||||
//set a timer timeout 30 second
|
||||
timer := time.NewTimer(time.Minute * 2)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-conn.connStatusOkCh:
|
||||
return conn, nil
|
||||
case <-conn.connStatusFailCh:
|
||||
case <-timer.C:
|
||||
}
|
||||
return nil, errors.New("create connection fail,the server refused the connection")
|
||||
}
|
||||
|
||||
func (s *Mux) Accept() (net.Conn, error) {
|
||||
if s.IsClose {
|
||||
return nil, errors.New("accpet error,the mux has closed")
|
||||
}
|
||||
conn := <-s.newConnCh
|
||||
if conn == nil {
|
||||
return nil, errors.New("accpet error,the conn has closed")
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (s *Mux) Addr() net.Addr {
|
||||
return s.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *Mux) sendInfo(flag uint8, id int32, data ...interface{}) {
|
||||
if s.IsClose {
|
||||
return
|
||||
}
|
||||
var err error
|
||||
pack := common.MuxPack.Get()
|
||||
err = pack.NewPac(flag, id, data...)
|
||||
if err != nil {
|
||||
common.MuxPack.Put(pack)
|
||||
logs.Error("mux: new pack err", err)
|
||||
s.Close()
|
||||
return
|
||||
}
|
||||
s.writeQueue.Push(pack)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Mux) writeSession() {
|
||||
go s.packBuf()
|
||||
//go s.writeBuf()
|
||||
}
|
||||
|
||||
func (s *Mux) packBuf() {
|
||||
//buffer := common.BuffPool.Get()
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
//buffer.Reset()
|
||||
pack := s.writeQueue.Pop()
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
//buffer := common.BuffPool.Get()
|
||||
err := pack.Pack(s.conn)
|
||||
common.MuxPack.Put(pack)
|
||||
if err != nil {
|
||||
logs.Error("mux: pack err", err)
|
||||
//common.BuffPool.Put(buffer)
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
//logs.Warn(buffer.String())
|
||||
//s.bufQueue.Push(buffer)
|
||||
//l := buffer.Len()
|
||||
//n, err := buffer.WriteTo(s.conn)
|
||||
//common.BuffPool.Put(buffer)
|
||||
//if err != nil || int(n) != l {
|
||||
// logs.Error("mux: close from write session fail ", err, n, l)
|
||||
// s.Close()
|
||||
// break
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
//func (s *Mux) writeBuf() {
|
||||
// for {
|
||||
// if s.IsClose {
|
||||
// break
|
||||
// }
|
||||
// buffer, err := s.bufQueue.Pop()
|
||||
// if err != nil {
|
||||
// break
|
||||
// }
|
||||
// l := buffer.Len()
|
||||
// n, err := buffer.WriteTo(s.conn)
|
||||
// common.BuffPool.Put(buffer)
|
||||
// if err != nil || int(n) != l {
|
||||
// logs.Warn("close from write session fail ", err, n, l)
|
||||
// s.Close()
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
func (s *Mux) ping() {
|
||||
go func() {
|
||||
now, _ := time.Now().UTC().MarshalText()
|
||||
s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, now)
|
||||
// send the ping flag and get the latency first
|
||||
ticker := time.NewTicker(time.Second * 5)
|
||||
for {
|
||||
if s.IsClose {
|
||||
ticker.Stop()
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ticker.C:
|
||||
}
|
||||
if atomic.LoadUint32(&s.pingCheckTime) >= 60 {
|
||||
logs.Error("mux: ping time out")
|
||||
s.Close()
|
||||
// more than 5 minutes not receive the ping return package,
|
||||
// mux conn is damaged, maybe a packet drop, close it
|
||||
break
|
||||
}
|
||||
now, _ := time.Now().UTC().MarshalText()
|
||||
s.sendInfo(common.MUX_PING_FLAG, common.MUX_PING, now)
|
||||
atomic.AddUint32(&s.pingCheckTime, 1)
|
||||
if atomic.LoadUint32(&s.pingOk) > 10 && s.connType == "kcp" {
|
||||
logs.Error("mux: kcp ping err")
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
atomic.AddUint32(&s.pingOk, 1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Mux) pingReturn() {
|
||||
go func() {
|
||||
var now time.Time
|
||||
var data []byte
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case data = <-s.pingCh:
|
||||
atomic.StoreUint32(&s.pingCheckTime, 0)
|
||||
case <-s.closeChan:
|
||||
break
|
||||
}
|
||||
_ = now.UnmarshalText(data)
|
||||
latency := time.Now().UTC().Sub(now).Seconds() / 2
|
||||
if latency > 0 {
|
||||
atomic.StoreUint64(&s.latency, math.Float64bits(s.counter.Latency(latency)))
|
||||
// convert float64 to bits, store it atomic
|
||||
}
|
||||
//logs.Warn("latency", math.Float64frombits(atomic.LoadUint64(&s.latency)))
|
||||
if cap(data) > 0 {
|
||||
common.WindowBuff.Put(data)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Mux) readSession() {
|
||||
go func() {
|
||||
var connection *conn
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
connection = s.newConnQueue.Pop()
|
||||
if s.IsClose {
|
||||
break // make sure that is closed
|
||||
}
|
||||
s.connMap.Set(connection.connId, connection) //it has been set before send ok
|
||||
s.newConnCh <- connection
|
||||
s.sendInfo(common.MUX_NEW_CONN_OK, connection.connId, nil)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
pack := common.MuxPack.Get()
|
||||
var l uint16
|
||||
var err error
|
||||
for {
|
||||
if s.IsClose {
|
||||
break
|
||||
}
|
||||
pack = common.MuxPack.Get()
|
||||
s.bw.StartRead()
|
||||
if l, err = pack.UnPack(s.conn); err != nil {
|
||||
logs.Error("mux: read session unpack from connection err", err)
|
||||
s.Close()
|
||||
break
|
||||
}
|
||||
s.bw.SetCopySize(l)
|
||||
atomic.StoreUint32(&s.pingOk, 0)
|
||||
switch pack.Flag {
|
||||
case common.MUX_NEW_CONN: //new connection
|
||||
connection := NewConn(pack.Id, s)
|
||||
s.newConnQueue.Push(connection)
|
||||
continue
|
||||
case common.MUX_PING_FLAG: //ping
|
||||
s.sendInfo(common.MUX_PING_RETURN, common.MUX_PING, pack.Content)
|
||||
common.WindowBuff.Put(pack.Content)
|
||||
continue
|
||||
case common.MUX_PING_RETURN:
|
||||
//go func(content []byte) {
|
||||
s.pingCh <- pack.Content
|
||||
//}(pack.Content)
|
||||
continue
|
||||
}
|
||||
if connection, ok := s.connMap.Get(pack.Id); ok && !connection.isClose {
|
||||
switch pack.Flag {
|
||||
case common.MUX_NEW_MSG, common.MUX_NEW_MSG_PART: //new msg from remote connection
|
||||
err = s.newMsg(connection, pack)
|
||||
if err != nil {
|
||||
logs.Error("mux: read session connection new msg err", err)
|
||||
connection.Close()
|
||||
}
|
||||
continue
|
||||
case common.MUX_NEW_CONN_OK: //connection ok
|
||||
connection.connStatusOkCh <- struct{}{}
|
||||
continue
|
||||
case common.MUX_NEW_CONN_Fail:
|
||||
connection.connStatusFailCh <- struct{}{}
|
||||
continue
|
||||
case common.MUX_MSG_SEND_OK:
|
||||
if connection.isClose {
|
||||
continue
|
||||
}
|
||||
connection.sendWindow.SetSize(pack.Window, pack.ReadLength)
|
||||
continue
|
||||
case common.MUX_CONN_CLOSE: //close the connection
|
||||
connection.closeFlag = true
|
||||
//s.connMap.Delete(pack.Id)
|
||||
//go func(connection *conn) {
|
||||
connection.receiveWindow.Stop() // close signal to receive window
|
||||
//}(connection)
|
||||
continue
|
||||
}
|
||||
} else if pack.Flag == common.MUX_CONN_CLOSE {
|
||||
continue
|
||||
}
|
||||
common.MuxPack.Put(pack)
|
||||
}
|
||||
common.MuxPack.Put(pack)
|
||||
s.Close()
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Mux) newMsg(connection *conn, pack *common.MuxPackager) (err error) {
|
||||
if connection.isClose {
|
||||
err = io.ErrClosedPipe
|
||||
return
|
||||
}
|
||||
//logs.Warn("read session receive new msg", pack.Length)
|
||||
//go func(connection *conn, pack *common.MuxPackager) { // do not block read session
|
||||
//insert into queue
|
||||
if pack.Flag == common.MUX_NEW_MSG_PART {
|
||||
err = connection.receiveWindow.Write(pack.Content, pack.Length, true, pack.Id)
|
||||
}
|
||||
if pack.Flag == common.MUX_NEW_MSG {
|
||||
err = connection.receiveWindow.Write(pack.Content, pack.Length, false, pack.Id)
|
||||
}
|
||||
//logs.Warn("read session write success", pack.Length)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Mux) Close() (err error) {
|
||||
logs.Warn("close mux")
|
||||
if s.IsClose {
|
||||
return errors.New("the mux has closed")
|
||||
}
|
||||
s.IsClose = true
|
||||
s.connMap.Close()
|
||||
s.connMap = nil
|
||||
//s.bufQueue.Stop()
|
||||
s.closeChan <- struct{}{}
|
||||
close(s.newConnCh)
|
||||
err = s.conn.Close()
|
||||
s.release()
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Mux) release() {
|
||||
for {
|
||||
pack := s.writeQueue.TryPop()
|
||||
if pack == nil {
|
||||
break
|
||||
}
|
||||
if pack.BasePackager.Content != nil {
|
||||
common.WindowBuff.Put(pack.BasePackager.Content)
|
||||
}
|
||||
common.MuxPack.Put(pack)
|
||||
}
|
||||
for {
|
||||
connection := s.newConnQueue.TryPop()
|
||||
if connection == nil {
|
||||
break
|
||||
}
|
||||
connection = nil
|
||||
}
|
||||
s.writeQueue.Stop()
|
||||
s.newConnQueue.Stop()
|
||||
}
|
||||
|
||||
//get new connId as unique flag
|
||||
func (s *Mux) getId() (id int32) {
|
||||
//Avoid going beyond the scope
|
||||
if (math.MaxInt32 - s.id) < 10000 {
|
||||
atomic.StoreInt32(&s.id, 0)
|
||||
}
|
||||
id = atomic.AddInt32(&s.id, 1)
|
||||
if _, ok := s.connMap.Get(id); ok {
|
||||
return s.getId()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type bandwidth struct {
|
||||
readBandwidth uint64 // store in bits, but it's float64
|
||||
readStart time.Time
|
||||
lastReadStart time.Time
|
||||
bufLength uint32
|
||||
}
|
||||
|
||||
func (Self *bandwidth) StartRead() {
|
||||
if Self.readStart.IsZero() {
|
||||
Self.readStart = time.Now()
|
||||
}
|
||||
if Self.bufLength >= common.MAXIMUM_SEGMENT_SIZE*300 {
|
||||
Self.lastReadStart, Self.readStart = Self.readStart, time.Now()
|
||||
Self.calcBandWidth()
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *bandwidth) SetCopySize(n uint16) {
|
||||
Self.bufLength += uint32(n)
|
||||
}
|
||||
|
||||
func (Self *bandwidth) calcBandWidth() {
|
||||
t := Self.readStart.Sub(Self.lastReadStart)
|
||||
atomic.StoreUint64(&Self.readBandwidth, math.Float64bits(float64(Self.bufLength)/t.Seconds()))
|
||||
Self.bufLength = 0
|
||||
}
|
||||
|
||||
func (Self *bandwidth) Get() (bw float64) {
|
||||
// The zero value, 0 for numeric types
|
||||
bw = math.Float64frombits(atomic.LoadUint64(&Self.readBandwidth))
|
||||
if bw <= 0 {
|
||||
bw = 100
|
||||
}
|
||||
//logs.Warn(bw)
|
||||
return
|
||||
}
|
||||
|
||||
const counterBits = 4
|
||||
const counterMask = 1<<counterBits - 1
|
||||
|
||||
func newLatencyCounter() *latencyCounter {
|
||||
return &latencyCounter{
|
||||
buf: make([]float64, 1<<counterBits, 1<<counterBits),
|
||||
headMin: 0,
|
||||
}
|
||||
}
|
||||
|
||||
type latencyCounter struct {
|
||||
buf []float64 //buf is a fixed length ring buffer,
|
||||
// if buffer is full, new value will replace the oldest one.
|
||||
headMin uint8 //head indicate the head in ring buffer,
|
||||
// in meaning, slot in list will be replaced;
|
||||
// min indicate this slot value is minimal in list.
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) unpack(idxs uint8) (head, min uint8) {
|
||||
head = uint8((idxs >> counterBits) & counterMask)
|
||||
// we set head is 4 bits
|
||||
min = uint8(idxs & counterMask)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) pack(head, min uint8) uint8 {
|
||||
return uint8(head<<counterBits) |
|
||||
uint8(min&counterMask)
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) add(value float64) {
|
||||
head, min := Self.unpack(Self.headMin)
|
||||
Self.buf[head] = value
|
||||
if head == min {
|
||||
min = Self.minimal()
|
||||
//if head equals min, means the min slot already be replaced,
|
||||
// so we need to find another minimal value in the list,
|
||||
// and change the min indicator
|
||||
}
|
||||
if Self.buf[min] > value {
|
||||
min = head
|
||||
}
|
||||
head++
|
||||
Self.headMin = Self.pack(head, min)
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) minimal() (min uint8) {
|
||||
var val float64
|
||||
var i uint8
|
||||
for i = 0; i < counterMask; i++ {
|
||||
if Self.buf[i] > 0 {
|
||||
if val > Self.buf[i] {
|
||||
val = Self.buf[i]
|
||||
min = i
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *latencyCounter) Latency(value float64) (latency float64) {
|
||||
Self.add(value)
|
||||
_, min := Self.unpack(Self.headMin)
|
||||
latency = Self.buf[min] * Self.countSuccess()
|
||||
return
|
||||
}
|
||||
|
||||
const lossRatio = 1.6
|
||||
|
||||
func (Self *latencyCounter) countSuccess() (successRate float64) {
|
||||
var success, loss, i uint8
|
||||
_, min := Self.unpack(Self.headMin)
|
||||
for i = 0; i < counterMask; i++ {
|
||||
if Self.buf[i] > lossRatio*Self.buf[min] && Self.buf[i] > 0 {
|
||||
loss++
|
||||
}
|
||||
if Self.buf[i] <= lossRatio*Self.buf[min] && Self.buf[i] > 0 {
|
||||
success++
|
||||
}
|
||||
}
|
||||
// counting all the data in the ring buf, except zero
|
||||
successRate = float64(success) / float64(loss+success)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/goroutine"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
_ "net/http/pprof"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
var conn1 net.Conn
|
||||
var conn2 net.Conn
|
||||
|
||||
func TestNewMux(t *testing.T) {
|
||||
go func() {
|
||||
http.ListenAndServe("0.0.0.0:8889", nil)
|
||||
}()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
server()
|
||||
client()
|
||||
//poolConnCopy, _ := ants.NewPoolWithFunc(200000, common.copyConn, ants.WithNonblocking(false))
|
||||
time.Sleep(time.Second * 3)
|
||||
go func() {
|
||||
m2 := NewMux(conn2, "tcp")
|
||||
for {
|
||||
//logs.Warn("npc starting accept")
|
||||
c, err := m2.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
//logs.Warn("npc accept success ")
|
||||
c2, err := net.Dial("tcp", "127.0.0.1:80")
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
c.Close()
|
||||
continue
|
||||
}
|
||||
//c2.(*net.TCPConn).SetReadBuffer(0)
|
||||
//c2.(*net.TCPConn).SetReadBuffer(0)
|
||||
_ = goroutine.CopyConnsPool.Invoke(goroutine.NewConns(c, c2, nil))
|
||||
//go func(c2 net.Conn, c *conn) {
|
||||
// wg := new(sync.WaitGroup)
|
||||
// wg.Add(2)
|
||||
// _ = poolConnCopy.Invoke(common.newConnGroup(c2, c, wg))
|
||||
// //go func() {
|
||||
// // _, err = common.CopyBuffer(c2, c)
|
||||
// // if err != nil {
|
||||
// // c2.Close()
|
||||
// // c.Close()
|
||||
// // //logs.Warn("close npc by copy from nps", err, c.connId)
|
||||
// // }
|
||||
// // wg.Done()
|
||||
// //}()
|
||||
// //wg.Add(1)
|
||||
// _ = poolConnCopy.Invoke(common.newConnGroup(c, c2, wg))
|
||||
// //go func() {
|
||||
// // _, err = common.CopyBuffer(c, c2)
|
||||
// // if err != nil {
|
||||
// // c2.Close()
|
||||
// // c.Close()
|
||||
// // //logs.Warn("close npc by copy from server", err, c.connId)
|
||||
// // }
|
||||
// // wg.Done()
|
||||
// //}()
|
||||
// //logs.Warn("npc wait")
|
||||
// wg.Wait()
|
||||
//}(c2, c.(*conn))
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
m1 := NewMux(conn1, "tcp")
|
||||
l, err := net.Listen("tcp", "127.0.0.1:7777")
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
}
|
||||
for {
|
||||
//logs.Warn("nps starting accept")
|
||||
conns, err := l.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
continue
|
||||
}
|
||||
//conns.(*net.TCPConn).SetReadBuffer(0)
|
||||
//conns.(*net.TCPConn).SetReadBuffer(0)
|
||||
//logs.Warn("nps accept success starting new conn")
|
||||
tmpCpnn, err := m1.NewConn()
|
||||
if err != nil {
|
||||
logs.Warn("nps new conn err ", err)
|
||||
continue
|
||||
}
|
||||
//logs.Warn("nps new conn success ", tmpCpnn.connId)
|
||||
_ = goroutine.CopyConnsPool.Invoke(goroutine.NewConns(tmpCpnn, conns, nil))
|
||||
//go func(tmpCpnn *conn, conns net.Conn) {
|
||||
// wg := new(sync.WaitGroup)
|
||||
// wg.Add(2)
|
||||
// _ = poolConnCopy.Invoke(common.newConnGroup(tmpCpnn, conns, wg))
|
||||
// //go func() {
|
||||
// // _, err := common.CopyBuffer(tmpCpnn, conns)
|
||||
// // if err != nil {
|
||||
// // conns.Close()
|
||||
// // tmpCpnn.Close()
|
||||
// // //logs.Warn("close nps by copy from user", tmpCpnn.connId, err)
|
||||
// // }
|
||||
// //}()
|
||||
// //wg.Add(1)
|
||||
// _ = poolConnCopy.Invoke(common.newConnGroup(conns, tmpCpnn, wg))
|
||||
// //time.Sleep(time.Second)
|
||||
// //_, err = common.CopyBuffer(conns, tmpCpnn)
|
||||
// //if err != nil {
|
||||
// // conns.Close()
|
||||
// // tmpCpnn.Close()
|
||||
// // //logs.Warn("close nps by copy from npc ", tmpCpnn.connId, err)
|
||||
// //}
|
||||
// wg.Wait()
|
||||
//}(tmpCpnn, conns)
|
||||
}
|
||||
}()
|
||||
|
||||
//go NewLogServer()
|
||||
time.Sleep(time.Second * 5)
|
||||
//for i := 0; i < 1; i++ {
|
||||
// go test_raw(i)
|
||||
//}
|
||||
//test_request()
|
||||
|
||||
for {
|
||||
time.Sleep(time.Second * 5)
|
||||
}
|
||||
}
|
||||
|
||||
func server() {
|
||||
var err error
|
||||
l, err := net.Listen("tcp", "127.0.0.1:9999")
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
}
|
||||
go func() {
|
||||
conn1, err = l.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
}
|
||||
}()
|
||||
return
|
||||
}
|
||||
|
||||
func client() {
|
||||
var err error
|
||||
conn2, err = net.Dial("tcp", "127.0.0.1:9999")
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
}
|
||||
}
|
||||
|
||||
func test_request() {
|
||||
conn, _ := net.Dial("tcp", "127.0.0.1:7777")
|
||||
for i := 0; i < 1000; i++ {
|
||||
conn.Write([]byte(`GET / HTTP/1.1
|
||||
Host: 127.0.0.1:7777
|
||||
Connection: keep-alive
|
||||
|
||||
|
||||
`))
|
||||
r, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
||||
if err != nil {
|
||||
logs.Warn("close by read response err", err)
|
||||
break
|
||||
}
|
||||
logs.Warn("read response success", r)
|
||||
b, err := httputil.DumpResponse(r, true)
|
||||
if err != nil {
|
||||
logs.Warn("close by dump response err", err)
|
||||
break
|
||||
}
|
||||
fmt.Println(string(b[:20]), err)
|
||||
//time.Sleep(time.Second)
|
||||
}
|
||||
logs.Warn("finish")
|
||||
}
|
||||
|
||||
func test_raw(k int) {
|
||||
for i := 0; i < 1000; i++ {
|
||||
ti := time.Now()
|
||||
conn, err := net.Dial("tcp", "127.0.0.1:7777")
|
||||
if err != nil {
|
||||
logs.Warn("conn dial err", err)
|
||||
}
|
||||
tid := time.Now()
|
||||
conn.Write([]byte(`GET /videojs5/video.js HTTP/1.1
|
||||
Host: 127.0.0.1:7777
|
||||
|
||||
|
||||
`))
|
||||
tiw := time.Now()
|
||||
buf := make([]byte, 3572)
|
||||
n, err := io.ReadFull(conn, buf)
|
||||
//n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
logs.Warn("close by read response err", err)
|
||||
break
|
||||
}
|
||||
logs.Warn(n, string(buf[:50]), "\n--------------\n", string(buf[n-50:n]))
|
||||
//time.Sleep(time.Second)
|
||||
err = conn.Close()
|
||||
if err != nil {
|
||||
logs.Warn("close conn err ", err)
|
||||
}
|
||||
now := time.Now()
|
||||
du := now.Sub(ti).Seconds()
|
||||
dud := now.Sub(tid).Seconds()
|
||||
duw := now.Sub(tiw).Seconds()
|
||||
if du > 1 {
|
||||
logs.Warn("duration long", du, dud, duw, k, i)
|
||||
}
|
||||
if n != 3572 {
|
||||
logs.Warn("n loss", n, string(buf))
|
||||
}
|
||||
}
|
||||
logs.Warn("finish")
|
||||
}
|
||||
|
||||
func TestNewConn(t *testing.T) {
|
||||
buf := common.GetBufPoolCopy()
|
||||
logs.Warn(len(buf), cap(buf))
|
||||
//b := pool.GetBufPoolCopy()
|
||||
//b[0] = 1
|
||||
//b[1] = 2
|
||||
//b[2] = 3
|
||||
b := []byte{1, 2, 3}
|
||||
logs.Warn(copy(buf[:3], b), len(buf), cap(buf))
|
||||
logs.Warn(len(buf), buf[0])
|
||||
}
|
||||
|
||||
func TestDQueue(t *testing.T) {
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
d := new(bufDequeue)
|
||||
d.vals = make([]unsafe.Pointer, 8)
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 10; i++ {
|
||||
logs.Warn(i)
|
||||
logs.Warn(d.popTail())
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 10; i++ {
|
||||
data := "test"
|
||||
go logs.Warn(i, unsafe.Pointer(&data), d.pushHead(unsafe.Pointer(&data)))
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
|
||||
func TestChain(t *testing.T) {
|
||||
go func() {
|
||||
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
|
||||
}()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
time.Sleep(time.Second * 5)
|
||||
d := new(bufChain)
|
||||
d.new(256)
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 30000; i++ {
|
||||
unsa, ok := d.popTail()
|
||||
str := (*string)(unsa)
|
||||
if ok {
|
||||
fmt.Println(i, str, *str, ok)
|
||||
//logs.Warn(i, str, *str, ok)
|
||||
} else {
|
||||
fmt.Println("nil", i, ok)
|
||||
//logs.Warn("nil", i, ok)
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 3000; i++ {
|
||||
go func(i int) {
|
||||
for n := 0; n < 10; n++ {
|
||||
data := "test " + strconv.Itoa(i) + strconv.Itoa(n)
|
||||
fmt.Println(data, unsafe.Pointer(&data))
|
||||
//logs.Warn(data, unsafe.Pointer(&data))
|
||||
d.pushHead(unsafe.Pointer(&data))
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 100000)
|
||||
}
|
||||
|
||||
func TestFIFO(t *testing.T) {
|
||||
go func() {
|
||||
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
|
||||
}()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
time.Sleep(time.Second * 5)
|
||||
d := new(ReceiveWindowQueue)
|
||||
d.New()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 1001; i++ {
|
||||
data, err := d.Pop()
|
||||
if err == nil {
|
||||
//fmt.Println(i, string(data.buf), err)
|
||||
logs.Warn(i, string(data.Buf), err)
|
||||
common.ListElementPool.Put(data)
|
||||
} else {
|
||||
//fmt.Println("err", err)
|
||||
logs.Warn("err", err)
|
||||
}
|
||||
//logs.Warn(d.Len())
|
||||
}
|
||||
logs.Warn("pop finish")
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(time.Second * 10)
|
||||
for i := 0; i < 1000; i++ {
|
||||
by := []byte("test " + strconv.Itoa(i) + " ") //
|
||||
data, _ := NewListElement(by, uint16(len(by)), true)
|
||||
//fmt.Println(string((*data).buf), data)
|
||||
//logs.Warn(string((*data).buf), data)
|
||||
d.Push(data)
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 100000)
|
||||
}
|
||||
|
||||
func TestPriority(t *testing.T) {
|
||||
go func() {
|
||||
log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
|
||||
}()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
time.Sleep(time.Second * 5)
|
||||
d := new(PriorityQueue)
|
||||
d.New()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
for i := 0; i < 360050; i++ {
|
||||
data := d.Pop()
|
||||
//fmt.Println(i, string(data.buf), err)
|
||||
logs.Warn(i, string(data.Content), data)
|
||||
}
|
||||
logs.Warn("pop finish")
|
||||
}()
|
||||
go func() {
|
||||
time.Sleep(time.Second * 10)
|
||||
for i := 0; i < 30000; i++ {
|
||||
go func(i int) {
|
||||
for n := 0; n < 10; n++ {
|
||||
data := new(common.MuxPackager)
|
||||
by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n))
|
||||
_ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by)
|
||||
//fmt.Println(string((*data).buf), data)
|
||||
logs.Warn(string((*data).Content), data)
|
||||
d.Push(data)
|
||||
}
|
||||
}(i)
|
||||
go func(i int) {
|
||||
data := new(common.MuxPackager)
|
||||
_ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil)
|
||||
//fmt.Println(string((*data).buf), data)
|
||||
logs.Warn(data)
|
||||
d.Push(data)
|
||||
}(i)
|
||||
go func(i int) {
|
||||
data := new(common.MuxPackager)
|
||||
_ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil)
|
||||
//fmt.Println(string((*data).buf), data)
|
||||
logs.Warn(data)
|
||||
d.Push(data)
|
||||
}(i)
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 100000)
|
||||
}
|
||||
|
||||
//func TestReceive(t *testing.T) {
|
||||
// go func() {
|
||||
// log.Println(http.ListenAndServe("0.0.0.0:8889", nil))
|
||||
// }()
|
||||
// logs.EnableFuncCallDepth(true)
|
||||
// logs.SetLogFuncCallDepth(3)
|
||||
// time.Sleep(time.Second * 5)
|
||||
// mux := new(Mux)
|
||||
// mux.bw.readBandwidth = float64(1*1024*1024)
|
||||
// mux.latency = float64(1/1000)
|
||||
// wind := new(ReceiveWindow)
|
||||
// wind.New(mux)
|
||||
// wind.
|
||||
// go func() {
|
||||
// time.Sleep(time.Second)
|
||||
// for i := 0; i < 36000; i++ {
|
||||
// data := d.Pop()
|
||||
// //fmt.Println(i, string(data.buf), err)
|
||||
// logs.Warn(i, string(data.Content), data)
|
||||
// }
|
||||
// }()
|
||||
// go func() {
|
||||
// time.Sleep(time.Second*10)
|
||||
// for i := 0; i < 3000; i++ {
|
||||
// go func(i int) {
|
||||
// for n := 0; n < 10; n++{
|
||||
// data := new(common.MuxPackager)
|
||||
// by := []byte("test " + strconv.Itoa(i) + strconv.Itoa(n))
|
||||
// _ = data.NewPac(common.MUX_NEW_MSG_PART, int32(i), by)
|
||||
// //fmt.Println(string((*data).buf), data)
|
||||
// logs.Warn(string((*data).Content), data)
|
||||
// d.Push(data)
|
||||
// }
|
||||
// }(i)
|
||||
// go func(i int) {
|
||||
// data := new(common.MuxPackager)
|
||||
// _ = data.NewPac(common.MUX_NEW_CONN, int32(i), nil)
|
||||
// //fmt.Println(string((*data).buf), data)
|
||||
// logs.Warn(data)
|
||||
// d.Push(data)
|
||||
// }(i)
|
||||
// go func(i int) {
|
||||
// data := new(common.MuxPackager)
|
||||
// _ = data.NewPac(common.MUX_NEW_CONN_OK, int32(i), nil)
|
||||
// //fmt.Println(string((*data).buf), data)
|
||||
// logs.Warn(data)
|
||||
// d.Push(data)
|
||||
// }(i)
|
||||
// }
|
||||
// }()
|
||||
// time.Sleep(time.Second * 100000)
|
||||
//}
|
||||
@@ -0,0 +1,63 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
type PortConn struct {
|
||||
Conn net.Conn
|
||||
rs []byte
|
||||
start int
|
||||
}
|
||||
|
||||
func newPortConn(conn net.Conn, rs []byte) *PortConn {
|
||||
return &PortConn{
|
||||
Conn: conn,
|
||||
rs: rs,
|
||||
}
|
||||
}
|
||||
|
||||
func (pConn *PortConn) Read(b []byte) (n int, err error) {
|
||||
if len(b) < len(pConn.rs)-pConn.start {
|
||||
defer func() {
|
||||
pConn.start = pConn.start + len(b)
|
||||
}()
|
||||
return copy(b, pConn.rs), nil
|
||||
}
|
||||
if pConn.start < len(pConn.rs) {
|
||||
defer func() {
|
||||
pConn.start = len(pConn.rs)
|
||||
}()
|
||||
return copy(b, pConn.rs[pConn.start:]), nil
|
||||
}
|
||||
return pConn.Conn.Read(b)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) Write(b []byte) (n int, err error) {
|
||||
return pConn.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) Close() error {
|
||||
return pConn.Conn.Close()
|
||||
}
|
||||
|
||||
func (pConn *PortConn) LocalAddr() net.Addr {
|
||||
return pConn.Conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (pConn *PortConn) RemoteAddr() net.Addr {
|
||||
return pConn.Conn.RemoteAddr()
|
||||
}
|
||||
|
||||
func (pConn *PortConn) SetDeadline(t time.Time) error {
|
||||
return pConn.Conn.SetDeadline(t)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) SetReadDeadline(t time.Time) error {
|
||||
return pConn.Conn.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (pConn *PortConn) SetWriteDeadline(t time.Time) error {
|
||||
return pConn.Conn.SetWriteDeadline(t)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
type PortListener struct {
|
||||
net.Listener
|
||||
connCh chan *PortConn
|
||||
addr net.Addr
|
||||
isClose bool
|
||||
}
|
||||
|
||||
func NewPortListener(connCh chan *PortConn, addr net.Addr) *PortListener {
|
||||
return &PortListener{
|
||||
connCh: connCh,
|
||||
addr: addr,
|
||||
}
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Accept() (net.Conn, error) {
|
||||
if pListener.isClose {
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
conn := <-pListener.connCh
|
||||
if conn != nil {
|
||||
return conn, nil
|
||||
}
|
||||
return nil, errors.New("the listener has closed")
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Close() error {
|
||||
//close
|
||||
if pListener.isClose {
|
||||
return errors.New("the listener has closed")
|
||||
}
|
||||
pListener.isClose = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pListener *PortListener) Addr() net.Addr {
|
||||
return pListener.addr
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
// This module is used for port reuse
|
||||
// Distinguish client, web manager , HTTP and HTTPS according to the difference of protocol
|
||||
package mux
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
HTTP_GET = 716984
|
||||
HTTP_POST = 807983
|
||||
HTTP_HEAD = 726965
|
||||
HTTP_PUT = 808585
|
||||
HTTP_DELETE = 686976
|
||||
HTTP_CONNECT = 677978
|
||||
HTTP_OPTIONS = 798084
|
||||
HTTP_TRACE = 848265
|
||||
CLIENT = 848384
|
||||
ACCEPT_TIME_OUT = 10
|
||||
)
|
||||
|
||||
type PortMux struct {
|
||||
net.Listener
|
||||
port int
|
||||
isClose bool
|
||||
managerHost string
|
||||
clientConn chan *PortConn
|
||||
httpConn chan *PortConn
|
||||
httpsConn chan *PortConn
|
||||
managerConn chan *PortConn
|
||||
}
|
||||
|
||||
func NewPortMux(port int, managerHost string) *PortMux {
|
||||
pMux := &PortMux{
|
||||
managerHost: managerHost,
|
||||
port: port,
|
||||
clientConn: make(chan *PortConn),
|
||||
httpConn: make(chan *PortConn),
|
||||
httpsConn: make(chan *PortConn),
|
||||
managerConn: make(chan *PortConn),
|
||||
}
|
||||
pMux.Start()
|
||||
return pMux
|
||||
}
|
||||
|
||||
func (pMux *PortMux) Start() error {
|
||||
// Port multiplexing is based on TCP only
|
||||
tcpAddr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:"+strconv.Itoa(pMux.port))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pMux.Listener, err = net.ListenTCP("tcp", tcpAddr)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
go func() {
|
||||
for {
|
||||
conn, err := pMux.Listener.Accept()
|
||||
if err != nil {
|
||||
logs.Warn(err)
|
||||
//close
|
||||
pMux.Close()
|
||||
}
|
||||
go pMux.process(conn)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pMux *PortMux) process(conn net.Conn) {
|
||||
// Recognition according to different signs
|
||||
// read 3 byte
|
||||
buf := make([]byte, 3)
|
||||
if n, err := io.ReadFull(conn, buf); err != nil || n != 3 {
|
||||
return
|
||||
}
|
||||
var ch chan *PortConn
|
||||
var rs []byte
|
||||
var buffer bytes.Buffer
|
||||
switch common.BytesToNum(buf) {
|
||||
case HTTP_CONNECT, HTTP_DELETE, HTTP_GET, HTTP_HEAD, HTTP_OPTIONS, HTTP_POST, HTTP_PUT, HTTP_TRACE: //http and manager
|
||||
buffer.Reset()
|
||||
r := bufio.NewReader(conn)
|
||||
buffer.Write(buf)
|
||||
for {
|
||||
b, _, err := r.ReadLine()
|
||||
if err != nil {
|
||||
logs.Warn("read line error", err.Error())
|
||||
conn.Close()
|
||||
break
|
||||
}
|
||||
buffer.Write(b)
|
||||
buffer.Write([]byte("\r\n"))
|
||||
if strings.Index(string(b), "Host:") == 0 || strings.Index(string(b), "host:") == 0 {
|
||||
// Remove host and space effects
|
||||
str := strings.Replace(string(b), "Host:", "", -1)
|
||||
str = strings.Replace(str, "host:", "", -1)
|
||||
str = strings.TrimSpace(str)
|
||||
// Determine whether it is the same as the manager domain name
|
||||
if common.GetIpByAddr(str) == pMux.managerHost {
|
||||
ch = pMux.managerConn
|
||||
} else {
|
||||
ch = pMux.httpConn
|
||||
}
|
||||
b, _ := r.Peek(r.Buffered())
|
||||
buffer.Write(b)
|
||||
rs = buffer.Bytes()
|
||||
break
|
||||
}
|
||||
}
|
||||
case CLIENT: // client connection
|
||||
ch = pMux.clientConn
|
||||
default: // https
|
||||
ch = pMux.httpsConn
|
||||
}
|
||||
if len(rs) == 0 {
|
||||
rs = buf
|
||||
}
|
||||
timer := time.NewTimer(ACCEPT_TIME_OUT)
|
||||
select {
|
||||
case <-timer.C:
|
||||
case ch <- newPortConn(conn, rs):
|
||||
}
|
||||
}
|
||||
|
||||
func (pMux *PortMux) Close() error {
|
||||
if pMux.isClose {
|
||||
return errors.New("the port mux has closed")
|
||||
}
|
||||
pMux.isClose = true
|
||||
close(pMux.clientConn)
|
||||
close(pMux.httpsConn)
|
||||
close(pMux.httpConn)
|
||||
close(pMux.managerConn)
|
||||
return pMux.Listener.Close()
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetClientListener() net.Listener {
|
||||
return NewPortListener(pMux.clientConn, pMux.Listener.Addr())
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetHttpListener() net.Listener {
|
||||
return NewPortListener(pMux.httpConn, pMux.Listener.Addr())
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetHttpsListener() net.Listener {
|
||||
return NewPortListener(pMux.httpsConn, pMux.Listener.Addr())
|
||||
}
|
||||
|
||||
func (pMux *PortMux) GetManagerListener() net.Listener {
|
||||
return NewPortListener(pMux.managerConn, pMux.Listener.Addr())
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
)
|
||||
|
||||
func TestPortMux_Close(t *testing.T) {
|
||||
logs.Reset()
|
||||
logs.EnableFuncCallDepth(true)
|
||||
logs.SetLogFuncCallDepth(3)
|
||||
|
||||
pMux := NewPortMux(8888, "Ds")
|
||||
go func() {
|
||||
if pMux.Start() != nil {
|
||||
logs.Warn("Error")
|
||||
}
|
||||
}()
|
||||
time.Sleep(time.Second * 3)
|
||||
go func() {
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}()
|
||||
go func() {
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}()
|
||||
go func() {
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}()
|
||||
l := pMux.GetHttpListener()
|
||||
conn, err := l.Accept()
|
||||
logs.Warn(conn, err)
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"io"
|
||||
"math"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type PriorityQueue struct {
|
||||
highestChain *bufChain
|
||||
middleChain *bufChain
|
||||
lowestChain *bufChain
|
||||
starving uint8
|
||||
stop bool
|
||||
cond *sync.Cond
|
||||
}
|
||||
|
||||
func (Self *PriorityQueue) New() {
|
||||
Self.highestChain = new(bufChain)
|
||||
Self.highestChain.new(4)
|
||||
Self.middleChain = new(bufChain)
|
||||
Self.middleChain.new(32)
|
||||
Self.lowestChain = new(bufChain)
|
||||
Self.lowestChain.new(256)
|
||||
locker := new(sync.Mutex)
|
||||
Self.cond = sync.NewCond(locker)
|
||||
}
|
||||
|
||||
func (Self *PriorityQueue) Push(packager *common.MuxPackager) {
|
||||
//logs.Warn("push start")
|
||||
Self.push(packager)
|
||||
Self.cond.Broadcast()
|
||||
//logs.Warn("push finish")
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *PriorityQueue) push(packager *common.MuxPackager) {
|
||||
switch packager.Flag {
|
||||
case common.MUX_PING_FLAG, common.MUX_PING_RETURN:
|
||||
Self.highestChain.pushHead(unsafe.Pointer(packager))
|
||||
// the ping package need highest priority
|
||||
// prevent ping calculation error
|
||||
case common.MUX_NEW_CONN, common.MUX_NEW_CONN_OK, common.MUX_NEW_CONN_Fail:
|
||||
// the new conn package need some priority too
|
||||
Self.middleChain.pushHead(unsafe.Pointer(packager))
|
||||
default:
|
||||
Self.lowestChain.pushHead(unsafe.Pointer(packager))
|
||||
}
|
||||
}
|
||||
|
||||
const maxStarving uint8 = 8
|
||||
|
||||
func (Self *PriorityQueue) Pop() (packager *common.MuxPackager) {
|
||||
var iter bool
|
||||
for {
|
||||
packager = Self.TryPop()
|
||||
if packager != nil {
|
||||
return
|
||||
}
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
if iter {
|
||||
break
|
||||
// trying to pop twice
|
||||
}
|
||||
iter = true
|
||||
runtime.Gosched()
|
||||
}
|
||||
Self.cond.L.Lock()
|
||||
defer Self.cond.L.Unlock()
|
||||
for packager = Self.TryPop(); packager == nil; {
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
//logs.Warn("queue into wait")
|
||||
Self.cond.Wait()
|
||||
// wait for it with no more iter
|
||||
packager = Self.TryPop()
|
||||
//logs.Warn("queue wait finish", packager)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *PriorityQueue) TryPop() (packager *common.MuxPackager) {
|
||||
ptr, ok := Self.highestChain.popTail()
|
||||
if ok {
|
||||
packager = (*common.MuxPackager)(ptr)
|
||||
return
|
||||
}
|
||||
if Self.starving < maxStarving {
|
||||
// not pop too much, lowestChain will wait too long
|
||||
ptr, ok = Self.middleChain.popTail()
|
||||
if ok {
|
||||
packager = (*common.MuxPackager)(ptr)
|
||||
Self.starving++
|
||||
return
|
||||
}
|
||||
}
|
||||
ptr, ok = Self.lowestChain.popTail()
|
||||
if ok {
|
||||
packager = (*common.MuxPackager)(ptr)
|
||||
if Self.starving > 0 {
|
||||
Self.starving = uint8(Self.starving / 2)
|
||||
}
|
||||
return
|
||||
}
|
||||
if Self.starving > 0 {
|
||||
ptr, ok = Self.middleChain.popTail()
|
||||
if ok {
|
||||
packager = (*common.MuxPackager)(ptr)
|
||||
Self.starving++
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *PriorityQueue) Stop() {
|
||||
Self.stop = true
|
||||
Self.cond.Broadcast()
|
||||
}
|
||||
|
||||
type ConnQueue struct {
|
||||
chain *bufChain
|
||||
starving uint8
|
||||
stop bool
|
||||
cond *sync.Cond
|
||||
}
|
||||
|
||||
func (Self *ConnQueue) New() {
|
||||
Self.chain = new(bufChain)
|
||||
Self.chain.new(32)
|
||||
locker := new(sync.Mutex)
|
||||
Self.cond = sync.NewCond(locker)
|
||||
}
|
||||
|
||||
func (Self *ConnQueue) Push(connection *conn) {
|
||||
Self.chain.pushHead(unsafe.Pointer(connection))
|
||||
Self.cond.Broadcast()
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ConnQueue) Pop() (connection *conn) {
|
||||
var iter bool
|
||||
for {
|
||||
connection = Self.TryPop()
|
||||
if connection != nil {
|
||||
return
|
||||
}
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
if iter {
|
||||
break
|
||||
// trying to pop twice
|
||||
}
|
||||
iter = true
|
||||
runtime.Gosched()
|
||||
}
|
||||
Self.cond.L.Lock()
|
||||
defer Self.cond.L.Unlock()
|
||||
for connection = Self.TryPop(); connection == nil; {
|
||||
if Self.stop {
|
||||
return
|
||||
}
|
||||
//logs.Warn("queue into wait")
|
||||
Self.cond.Wait()
|
||||
// wait for it with no more iter
|
||||
connection = Self.TryPop()
|
||||
//logs.Warn("queue wait finish", packager)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ConnQueue) TryPop() (connection *conn) {
|
||||
ptr, ok := Self.chain.popTail()
|
||||
if ok {
|
||||
connection = (*conn)(ptr)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ConnQueue) Stop() {
|
||||
Self.stop = true
|
||||
Self.cond.Broadcast()
|
||||
}
|
||||
|
||||
func NewListElement(buf []byte, l uint16, part bool) (element *common.ListElement, err error) {
|
||||
if uint16(len(buf)) != l {
|
||||
err = errors.New("ListElement: buf length not match")
|
||||
return
|
||||
}
|
||||
//if l == 0 {
|
||||
// logs.Warn("push zero")
|
||||
//}
|
||||
element = common.ListElementPool.Get()
|
||||
element.Buf = buf
|
||||
element.L = l
|
||||
element.Part = part
|
||||
return
|
||||
}
|
||||
|
||||
type ReceiveWindowQueue struct {
|
||||
chain *bufChain
|
||||
stopOp chan struct{}
|
||||
readOp chan struct{}
|
||||
lengthWait uint64 // really strange ???? need put here
|
||||
// https://golang.org/pkg/sync/atomic/#pkg-note-BUG
|
||||
// On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core.
|
||||
// On ARM, x86-32, and 32-bit MIPS, it is the caller's responsibility
|
||||
// to arrange for 64-bit alignment of 64-bit words accessed atomically.
|
||||
// The first word in a variable or in an allocated struct, array, or slice can be relied upon to be 64-bit aligned.
|
||||
timeout time.Time
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) New() {
|
||||
Self.readOp = make(chan struct{})
|
||||
Self.chain = new(bufChain)
|
||||
Self.chain.new(64)
|
||||
Self.stopOp = make(chan struct{}, 2)
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) Push(element *common.ListElement) {
|
||||
var length, wait uint32
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&Self.lengthWait)
|
||||
length, wait = Self.chain.head.unpack(ptrs)
|
||||
length += uint32(element.L)
|
||||
if atomic.CompareAndSwapUint64(&Self.lengthWait, ptrs, Self.chain.head.pack(length, 0)) {
|
||||
break
|
||||
}
|
||||
// another goroutine change the length or into wait, make sure
|
||||
}
|
||||
//logs.Warn("window push before", Self.Len(), uint32(element.l), len(element.buf))
|
||||
Self.chain.pushHead(unsafe.Pointer(element))
|
||||
//logs.Warn("window push", Self.Len())
|
||||
if wait == 1 {
|
||||
Self.allowPop()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) Pop() (element *common.ListElement, err error) {
|
||||
var length uint32
|
||||
startPop:
|
||||
ptrs := atomic.LoadUint64(&Self.lengthWait)
|
||||
length, _ = Self.chain.head.unpack(ptrs)
|
||||
if length == 0 {
|
||||
if !atomic.CompareAndSwapUint64(&Self.lengthWait, ptrs, Self.chain.head.pack(0, 1)) {
|
||||
goto startPop // another goroutine is pushing
|
||||
}
|
||||
err = Self.waitPush()
|
||||
// there is no more data in queue, wait for it
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
goto startPop // wait finish, trying to get the new status
|
||||
}
|
||||
// length is not zero, so try to pop
|
||||
for {
|
||||
element = Self.TryPop()
|
||||
if element != nil {
|
||||
return
|
||||
}
|
||||
runtime.Gosched() // another goroutine is still pushing
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) TryPop() (element *common.ListElement) {
|
||||
ptr, ok := Self.chain.popTail()
|
||||
if ok {
|
||||
//logs.Warn("window pop before", Self.Len())
|
||||
element = (*common.ListElement)(ptr)
|
||||
atomic.AddUint64(&Self.lengthWait, ^(uint64(element.L)<<dequeueBits - 1))
|
||||
//logs.Warn("window pop", Self.Len(), uint32(element.l))
|
||||
return
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) allowPop() (closed bool) {
|
||||
//logs.Warn("allow pop", Self.Len())
|
||||
select {
|
||||
case Self.readOp <- struct{}{}:
|
||||
return false
|
||||
case <-Self.stopOp:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) waitPush() (err error) {
|
||||
//logs.Warn("wait push")
|
||||
//defer logs.Warn("wait push finish")
|
||||
t := Self.timeout.Sub(time.Now())
|
||||
if t <= 0 {
|
||||
t = time.Minute * 5
|
||||
}
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
//logs.Warn("queue into wait")
|
||||
select {
|
||||
case <-Self.readOp:
|
||||
//logs.Warn("queue wait finish")
|
||||
return nil
|
||||
case <-Self.stopOp:
|
||||
err = io.EOF
|
||||
return
|
||||
case <-timer.C:
|
||||
err = errors.New("mux.queue: read time out")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) Len() (n uint32) {
|
||||
ptrs := atomic.LoadUint64(&Self.lengthWait)
|
||||
n, _ = Self.chain.head.unpack(ptrs)
|
||||
return
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) Stop() {
|
||||
Self.stopOp <- struct{}{}
|
||||
Self.stopOp <- struct{}{}
|
||||
}
|
||||
|
||||
func (Self *ReceiveWindowQueue) SetTimeOut(t time.Time) {
|
||||
Self.timeout = t
|
||||
}
|
||||
|
||||
// https://golang.org/src/sync/poolqueue.go
|
||||
|
||||
type bufDequeue struct {
|
||||
// headTail packs together a 32-bit head index and a 32-bit
|
||||
// tail index. Both are indexes into vals modulo len(vals)-1.
|
||||
//
|
||||
// tail = index of oldest data in queue
|
||||
// head = index of next slot to fill
|
||||
//
|
||||
// Slots in the range [tail, head) are owned by consumers.
|
||||
// A consumer continues to own a slot outside this range until
|
||||
// it nils the slot, at which point ownership passes to the
|
||||
// producer.
|
||||
//
|
||||
// The head index is stored in the most-significant bits so
|
||||
// that we can atomically add to it and the overflow is
|
||||
// harmless.
|
||||
headTail uint64
|
||||
|
||||
// vals is a ring buffer of interface{} values stored in this
|
||||
// dequeue. The size of this must be a power of 2.
|
||||
//
|
||||
// A slot is still in use until *both* the tail
|
||||
// index has moved beyond it and typ has been set to nil. This
|
||||
// is set to nil atomically by the consumer and read
|
||||
// atomically by the producer.
|
||||
vals []unsafe.Pointer
|
||||
starving uint32
|
||||
}
|
||||
|
||||
const dequeueBits = 32
|
||||
|
||||
// dequeueLimit is the maximum size of a bufDequeue.
|
||||
//
|
||||
// This must be at most (1<<dequeueBits)/2 because detecting fullness
|
||||
// depends on wrapping around the ring buffer without wrapping around
|
||||
// the index. We divide by 4 so this fits in an int on 32-bit.
|
||||
const dequeueLimit = (1 << dequeueBits) / 4
|
||||
|
||||
func (d *bufDequeue) unpack(ptrs uint64) (head, tail uint32) {
|
||||
const mask = 1<<dequeueBits - 1
|
||||
head = uint32((ptrs >> dequeueBits) & mask)
|
||||
tail = uint32(ptrs & mask)
|
||||
return
|
||||
}
|
||||
|
||||
func (d *bufDequeue) pack(head, tail uint32) uint64 {
|
||||
const mask = 1<<dequeueBits - 1
|
||||
return (uint64(head) << dequeueBits) |
|
||||
uint64(tail&mask)
|
||||
}
|
||||
|
||||
// pushHead adds val at the head of the queue. It returns false if the
|
||||
// queue is full.
|
||||
func (d *bufDequeue) pushHead(val unsafe.Pointer) bool {
|
||||
var slot *unsafe.Pointer
|
||||
var starve uint8
|
||||
if atomic.LoadUint32(&d.starving) > 0 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
for {
|
||||
ptrs := atomic.LoadUint64(&d.headTail)
|
||||
head, tail := d.unpack(ptrs)
|
||||
if (tail+uint32(len(d.vals)))&(1<<dequeueBits-1) == head {
|
||||
// Queue is full.
|
||||
return false
|
||||
}
|
||||
ptrs2 := d.pack(head+1, tail)
|
||||
if atomic.CompareAndSwapUint64(&d.headTail, ptrs, ptrs2) {
|
||||
slot = &d.vals[head&uint32(len(d.vals)-1)]
|
||||
if starve >= 3 && atomic.LoadUint32(&d.starving) > 0 {
|
||||
atomic.StoreUint32(&d.starving, 0)
|
||||
}
|
||||
break
|
||||
}
|
||||
starve++
|
||||
if starve >= 3 {
|
||||
atomic.StoreUint32(&d.starving, 1)
|
||||
}
|
||||
}
|
||||
// The head slot is free, so we own it.
|
||||
*slot = val
|
||||
return true
|
||||
}
|
||||
|
||||
// popTail removes and returns the element at the tail of the queue.
|
||||
// It returns false if the queue is empty. It may be called by any
|
||||
// number of consumers.
|
||||
func (d *bufDequeue) popTail() (unsafe.Pointer, bool) {
|
||||
ptrs := atomic.LoadUint64(&d.headTail)
|
||||
head, tail := d.unpack(ptrs)
|
||||
if tail == head {
|
||||
// Queue is empty.
|
||||
return nil, false
|
||||
}
|
||||
slot := &d.vals[tail&uint32(len(d.vals)-1)]
|
||||
var val unsafe.Pointer
|
||||
for {
|
||||
val = atomic.LoadPointer(slot)
|
||||
if val != nil {
|
||||
// We now own slot.
|
||||
break
|
||||
}
|
||||
// Another goroutine is still pushing data on the tail.
|
||||
}
|
||||
|
||||
// Tell pushHead that we're done with this slot. Zeroing the
|
||||
// slot is also important so we don't leave behind references
|
||||
// that could keep this object live longer than necessary.
|
||||
//
|
||||
// We write to val first and then publish that we're done with
|
||||
atomic.StorePointer(slot, nil)
|
||||
// At this point pushHead owns the slot.
|
||||
if tail < math.MaxUint32 {
|
||||
atomic.AddUint64(&d.headTail, 1)
|
||||
} else {
|
||||
atomic.AddUint64(&d.headTail, ^uint64(math.MaxUint32-1))
|
||||
}
|
||||
return val, true
|
||||
}
|
||||
|
||||
// bufChain is a dynamically-sized version of bufDequeue.
|
||||
//
|
||||
// This is implemented as a doubly-linked list queue of poolDequeues
|
||||
// where each dequeue is double the size of the previous one. Once a
|
||||
// dequeue fills up, this allocates a new one and only ever pushes to
|
||||
// the latest dequeue. Pops happen from the other end of the list and
|
||||
// once a dequeue is exhausted, it gets removed from the list.
|
||||
type bufChain struct {
|
||||
// head is the bufDequeue to push to. This is only accessed
|
||||
// by the producer, so doesn't need to be synchronized.
|
||||
head *bufChainElt
|
||||
|
||||
// tail is the bufDequeue to popTail from. This is accessed
|
||||
// by consumers, so reads and writes must be atomic.
|
||||
tail *bufChainElt
|
||||
newChain uint32
|
||||
}
|
||||
|
||||
type bufChainElt struct {
|
||||
bufDequeue
|
||||
|
||||
// next and prev link to the adjacent poolChainElts in this
|
||||
// bufChain.
|
||||
//
|
||||
// next is written atomically by the producer and read
|
||||
// atomically by the consumer. It only transitions from nil to
|
||||
// non-nil.
|
||||
//
|
||||
// prev is written atomically by the consumer and read
|
||||
// atomically by the producer. It only transitions from
|
||||
// non-nil to nil.
|
||||
next, prev *bufChainElt
|
||||
}
|
||||
|
||||
func storePoolChainElt(pp **bufChainElt, v *bufChainElt) {
|
||||
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(pp)), unsafe.Pointer(v))
|
||||
}
|
||||
|
||||
func loadPoolChainElt(pp **bufChainElt) *bufChainElt {
|
||||
return (*bufChainElt)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(pp))))
|
||||
}
|
||||
|
||||
func (c *bufChain) new(initSize int) {
|
||||
// Initialize the chain.
|
||||
// initSize must be a power of 2
|
||||
d := new(bufChainElt)
|
||||
d.vals = make([]unsafe.Pointer, initSize)
|
||||
storePoolChainElt(&c.head, d)
|
||||
storePoolChainElt(&c.tail, d)
|
||||
}
|
||||
|
||||
func (c *bufChain) pushHead(val unsafe.Pointer) {
|
||||
startPush:
|
||||
for {
|
||||
if atomic.LoadUint32(&c.newChain) > 0 {
|
||||
runtime.Gosched()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
d := loadPoolChainElt(&c.head)
|
||||
|
||||
if d.pushHead(val) {
|
||||
return
|
||||
}
|
||||
|
||||
// The current dequeue is full. Allocate a new one of twice
|
||||
// the size.
|
||||
if atomic.CompareAndSwapUint32(&c.newChain, 0, 1) {
|
||||
newSize := len(d.vals) * 2
|
||||
if newSize >= dequeueLimit {
|
||||
// Can't make it any bigger.
|
||||
newSize = dequeueLimit
|
||||
}
|
||||
|
||||
d2 := &bufChainElt{prev: d}
|
||||
d2.vals = make([]unsafe.Pointer, newSize)
|
||||
d2.pushHead(val)
|
||||
storePoolChainElt(&c.head, d2)
|
||||
storePoolChainElt(&d.next, d2)
|
||||
atomic.StoreUint32(&c.newChain, 0)
|
||||
return
|
||||
}
|
||||
goto startPush
|
||||
}
|
||||
|
||||
func (c *bufChain) popTail() (unsafe.Pointer, bool) {
|
||||
d := loadPoolChainElt(&c.tail)
|
||||
if d == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
for {
|
||||
// It's important that we load the next pointer
|
||||
// *before* popping the tail. In general, d may be
|
||||
// transiently empty, but if next is non-nil before
|
||||
// the TryPop and the TryPop fails, then d is permanently
|
||||
// empty, which is the only condition under which it's
|
||||
// safe to drop d from the chain.
|
||||
d2 := loadPoolChainElt(&d.next)
|
||||
|
||||
if val, ok := d.popTail(); ok {
|
||||
return val, ok
|
||||
}
|
||||
|
||||
if d2 == nil {
|
||||
// This is the only dequeue. It's empty right
|
||||
// now, but could be pushed to in the future.
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// The tail of the chain has been drained, so move on
|
||||
// to the next dequeue. Try to drop it from the chain
|
||||
// so the next TryPop doesn't have to look at the empty
|
||||
// dequeue again.
|
||||
if atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&c.tail)), unsafe.Pointer(d), unsafe.Pointer(d2)) {
|
||||
// We won the race. Clear the prev pointer so
|
||||
// the garbage collector can collect the empty
|
||||
// dequeue and so popHead doesn't back up
|
||||
// further than necessary.
|
||||
storePoolChainElt(&d2.prev, nil)
|
||||
}
|
||||
d = d2
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package mux
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type connLog struct {
|
||||
startTime time.Time
|
||||
isClose bool
|
||||
logs []string
|
||||
}
|
||||
|
||||
var logms map[int]*connLog
|
||||
var logmc map[int]*connLog
|
||||
|
||||
var copyMaps map[int]*connLog
|
||||
var copyMapc map[int]*connLog
|
||||
var stashTimeNow time.Time
|
||||
var mutex sync.Mutex
|
||||
|
||||
func deepCopyMaps() {
|
||||
copyMaps = make(map[int]*connLog)
|
||||
for k, v := range logms {
|
||||
copyMaps[k] = &connLog{
|
||||
startTime: v.startTime,
|
||||
isClose: v.isClose,
|
||||
logs: v.logs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func deepCopyMapc() {
|
||||
copyMapc = make(map[int]*connLog)
|
||||
for k, v := range logmc {
|
||||
copyMapc[k] = &connLog{
|
||||
startTime: v.startTime,
|
||||
isClose: v.isClose,
|
||||
logs: v.logs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
logms = make(map[int]*connLog)
|
||||
logmc = make(map[int]*connLog)
|
||||
}
|
||||
|
||||
type IntSlice []int
|
||||
|
||||
func (s IntSlice) Len() int { return len(s) }
|
||||
|
||||
func (s IntSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
|
||||
func (s IntSlice) Less(i, j int) bool { return s[i] < s[j] }
|
||||
|
||||
func NewLogServer() {
|
||||
http.HandleFunc("/", index)
|
||||
http.HandleFunc("/detail", detail)
|
||||
http.HandleFunc("/stash", stash)
|
||||
fmt.Println(http.ListenAndServe(":8899", nil))
|
||||
}
|
||||
|
||||
func stash(w http.ResponseWriter, r *http.Request) {
|
||||
stashTimeNow = time.Now()
|
||||
deepCopyMaps()
|
||||
deepCopyMapc()
|
||||
w.Write([]byte("ok"))
|
||||
}
|
||||
|
||||
func getM(label string, id int) (cL *connLog) {
|
||||
label = strings.TrimSpace(label)
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
if label == "nps" {
|
||||
cL = logms[id]
|
||||
}
|
||||
if label == "npc" {
|
||||
cL = logmc[id]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func setM(label string, id int, cL *connLog) {
|
||||
label = strings.TrimSpace(label)
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
if label == "nps" {
|
||||
logms[id] = cL
|
||||
}
|
||||
if label == "npc" {
|
||||
logmc[id] = cL
|
||||
}
|
||||
}
|
||||
|
||||
func index(w http.ResponseWriter, r *http.Request) {
|
||||
var keys []int
|
||||
for k := range copyMaps {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Sort(IntSlice(keys))
|
||||
var s string
|
||||
s += "<h1>nps</h1>"
|
||||
for _, v := range keys {
|
||||
connL := copyMaps[v]
|
||||
s += "<a href='/detail?id=" + strconv.Itoa(v) + "&label=nps" + "'>" + strconv.Itoa(v) + "</a>----------"
|
||||
s += strconv.Itoa(int(stashTimeNow.Sub(connL.startTime).Milliseconds())) + "ms----------"
|
||||
s += strconv.FormatBool(connL.isClose)
|
||||
s += "<br>"
|
||||
}
|
||||
|
||||
keys = keys[:0]
|
||||
s += "<h1>npc</h1>"
|
||||
for k := range copyMapc {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Sort(IntSlice(keys))
|
||||
|
||||
for _, v := range keys {
|
||||
connL := copyMapc[v]
|
||||
s += "<a href='/detail?id=" + strconv.Itoa(v) + "&label=npc" + "'>" + strconv.Itoa(v) + "</a>----------"
|
||||
s += strconv.Itoa(int(stashTimeNow.Sub(connL.startTime).Milliseconds())) + "ms----------"
|
||||
s += strconv.FormatBool(connL.isClose)
|
||||
s += "<br>"
|
||||
}
|
||||
w.Write([]byte(s))
|
||||
}
|
||||
|
||||
func detail(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.FormValue("id")
|
||||
label := r.FormValue("label")
|
||||
logs.Warn(label)
|
||||
i, _ := strconv.Atoi(id)
|
||||
var v *connLog
|
||||
if label == "nps" {
|
||||
v, _ = copyMaps[i]
|
||||
}
|
||||
if label == "npc" {
|
||||
v, _ = copyMapc[i]
|
||||
}
|
||||
var s string
|
||||
if v != nil {
|
||||
for i, vv := range v.logs {
|
||||
s += "<p>" + strconv.Itoa(i+1) + ":" + vv + "</p>"
|
||||
}
|
||||
}
|
||||
w.Write([]byte(s))
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package mux
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestWeb(t *testing.T) {
|
||||
NewLogServer()
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package rate
|
||||
|
||||
import (
|
||||
"io"
|
||||
)
|
||||
|
||||
type rateConn struct {
|
||||
conn io.ReadWriteCloser
|
||||
rate *Rate
|
||||
}
|
||||
|
||||
func NewRateConn(conn io.ReadWriteCloser, rate *Rate) io.ReadWriteCloser {
|
||||
return &rateConn{
|
||||
conn: conn,
|
||||
rate: rate,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *rateConn) Read(b []byte) (n int, err error) {
|
||||
n, err = s.conn.Read(b)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *rateConn) Write(b []byte) (n int, err error) {
|
||||
n, err = s.conn.Write(b)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *rateConn) Close() error {
|
||||
return s.conn.Close()
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package utils
|
||||
package rate
|
||||
|
||||
import (
|
||||
"sync/atomic"
|
||||
@@ -6,10 +6,11 @@ import (
|
||||
)
|
||||
|
||||
type Rate struct {
|
||||
bucketSize int64 //木桶容量
|
||||
bucketSurplusSize int64 //当前桶中体积
|
||||
bucketAddSize int64 //每次加水大小
|
||||
stopChan chan bool //停止
|
||||
bucketSize int64
|
||||
bucketSurplusSize int64
|
||||
bucketAddSize int64
|
||||
stopChan chan bool
|
||||
NowRate int64
|
||||
}
|
||||
|
||||
func NewRate(addSize int64) *Rate {
|
||||
@@ -26,7 +27,8 @@ func (s *Rate) Start() {
|
||||
}
|
||||
|
||||
func (s *Rate) add(size int64) {
|
||||
if (s.bucketSize - s.bucketSurplusSize) < s.bucketAddSize {
|
||||
if res := s.bucketSize - s.bucketSurplusSize; res < s.bucketAddSize {
|
||||
atomic.AddInt64(&s.bucketSurplusSize, res)
|
||||
return
|
||||
}
|
||||
atomic.AddInt64(&s.bucketSurplusSize, size)
|
||||
@@ -65,6 +67,11 @@ func (s *Rate) session() {
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if rs := s.bucketAddSize - s.bucketSurplusSize; rs > 0 {
|
||||
s.NowRate = rs
|
||||
} else {
|
||||
s.NowRate = s.bucketSize - s.bucketSurplusSize
|
||||
}
|
||||
s.add(s.bucketAddSize)
|
||||
case <-s.stopChan:
|
||||
ticker.Stop()
|
||||
@@ -0,0 +1,21 @@
|
||||
package sheap
|
||||
|
||||
type IntHeap []int64
|
||||
|
||||
func (h IntHeap) Len() int { return len(h) }
|
||||
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
|
||||
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
|
||||
func (h *IntHeap) Push(x interface{}) {
|
||||
// Push and Pop use pointer receivers because they modify the slice's length,
|
||||
// not just its contents.
|
||||
*h = append(*h, x.(int64))
|
||||
}
|
||||
|
||||
func (h *IntHeap) Pop() interface{} {
|
||||
old := *h
|
||||
n := len(old)
|
||||
x := old[n-1]
|
||||
*h = old[0 : n-1]
|
||||
return x
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package version
|
||||
|
||||
const VERSION = "0.24.0"
|
||||
|
||||
// Compulsory minimum version, Minimum downward compatibility to this version
|
||||
func GetVersion() string {
|
||||
return "0.24.0"
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/easyProxy/bridge"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
//server base struct
|
||||
type server struct {
|
||||
id int
|
||||
bridge *bridge.Bridge
|
||||
task *utils.Tunnel
|
||||
config *utils.Config
|
||||
errorContent []byte
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (s *server) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.task.Flow.ExportFlow += out
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
func (s *server) FlowAddHost(host *utils.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
host.Flow.ExportFlow += out
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
//热更新配置
|
||||
func (s *server) ResetConfig() bool {
|
||||
//获取最新数据
|
||||
task, err := CsvDb.GetTask(s.task.Id)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if s.task.Client.Flow.FlowLimit > 0 && (s.task.Client.Flow.FlowLimit<<20) < (s.task.Client.Flow.ExportFlow+s.task.Client.Flow.InletFlow) {
|
||||
return false
|
||||
}
|
||||
s.task.UseClientCnf = task.UseClientCnf
|
||||
//使用客户端配置
|
||||
client, err := CsvDb.GetClient(s.task.Client.Id)
|
||||
if s.task.UseClientCnf {
|
||||
if err == nil {
|
||||
s.config.U = client.Cnf.U
|
||||
s.config.P = client.Cnf.P
|
||||
s.config.Compress = client.Cnf.Compress
|
||||
s.config.Crypt = client.Cnf.Crypt
|
||||
}
|
||||
} else {
|
||||
if err == nil {
|
||||
s.config.U = task.Config.U
|
||||
s.config.P = task.Config.P
|
||||
s.config.Compress = task.Config.Compress
|
||||
s.config.Crypt = task.Config.Crypt
|
||||
}
|
||||
}
|
||||
s.task.Client.Rate = client.Rate
|
||||
s.config.CompressDecode, s.config.CompressEncode = utils.GetCompressType(s.config.Compress)
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *server) linkCopy(link *utils.Link, c *utils.Conn, rb []byte, tunnel *utils.Conn, flow *utils.Flow) {
|
||||
if rb != nil {
|
||||
if _, err := tunnel.SendMsg(rb, link); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
flow.Add(len(rb), 0)
|
||||
}
|
||||
for {
|
||||
buf := utils.BufPoolCopy.Get().([]byte)
|
||||
if n, err := c.Read(buf); err != nil {
|
||||
tunnel.SendMsg([]byte(utils.IO_EOF), link)
|
||||
break
|
||||
} else {
|
||||
if _, err := tunnel.SendMsg(buf[:n], link); err != nil {
|
||||
utils.PutBufPoolCopy(buf)
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
utils.PutBufPoolCopy(buf)
|
||||
flow.Add(n, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(utils.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
//权限认证
|
||||
func (s *server) auth(r *http.Request, c *utils.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !utils.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(utils.UnauthorizedBytes))
|
||||
c.Close()
|
||||
return errors.New("401 Unauthorized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package connection
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/mux"
|
||||
)
|
||||
|
||||
var pMux *mux.PortMux
|
||||
var bridgePort string
|
||||
var httpsPort string
|
||||
var httpPort string
|
||||
var webPort string
|
||||
|
||||
func InitConnectionService() {
|
||||
bridgePort = beego.AppConfig.String("bridge_port")
|
||||
httpsPort = beego.AppConfig.String("https_proxy_port")
|
||||
httpPort = beego.AppConfig.String("http_proxy_port")
|
||||
webPort = beego.AppConfig.String("web_port")
|
||||
|
||||
if httpPort == bridgePort || httpsPort == bridgePort || webPort == bridgePort {
|
||||
port, err := strconv.Atoi(bridgePort)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
pMux = mux.NewPortMux(port, beego.AppConfig.String("web_host"))
|
||||
}
|
||||
}
|
||||
|
||||
func GetBridgeListener(tp string) (net.Listener, error) {
|
||||
logs.Info("server start, the bridge type is %s, the bridge port is %s", tp, bridgePort)
|
||||
var p int
|
||||
var err error
|
||||
if p, err = strconv.Atoi(bridgePort); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pMux != nil {
|
||||
return pMux.GetClientListener(), nil
|
||||
}
|
||||
return net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP(beego.AppConfig.String("bridge_ip")), p, ""})
|
||||
}
|
||||
|
||||
func GetHttpListener() (net.Listener, error) {
|
||||
if pMux != nil && httpPort == bridgePort {
|
||||
logs.Info("start http listener, port is", bridgePort)
|
||||
return pMux.GetHttpListener(), nil
|
||||
}
|
||||
logs.Info("start http listener, port is", httpPort)
|
||||
return getTcpListener(beego.AppConfig.String("http_proxy_ip"), httpPort)
|
||||
}
|
||||
|
||||
func GetHttpsListener() (net.Listener, error) {
|
||||
if pMux != nil && httpsPort == bridgePort {
|
||||
logs.Info("start https listener, port is", bridgePort)
|
||||
return pMux.GetHttpsListener(), nil
|
||||
}
|
||||
logs.Info("start https listener, port is", httpsPort)
|
||||
return getTcpListener(beego.AppConfig.String("http_proxy_ip"), httpsPort)
|
||||
}
|
||||
|
||||
func GetWebManagerListener() (net.Listener, error) {
|
||||
if pMux != nil && webPort == bridgePort {
|
||||
logs.Info("Web management start, access port is", bridgePort)
|
||||
return pMux.GetManagerListener(), nil
|
||||
}
|
||||
logs.Info("web management start, access port is", webPort)
|
||||
return getTcpListener(beego.AppConfig.String("web_ip"), webPort)
|
||||
}
|
||||
|
||||
func getTcpListener(ip, p string) (net.Listener, error) {
|
||||
port, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
if ip == "" {
|
||||
ip = "0.0.0.0"
|
||||
}
|
||||
return net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP(ip), port, ""})
|
||||
}
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/cnlh/easyProxy/bridge"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
server
|
||||
httpPort int //http端口
|
||||
httpsPort int //https监听端口
|
||||
pemPath string
|
||||
keyPath string
|
||||
stop chan bool
|
||||
}
|
||||
|
||||
func NewHttp(bridge *bridge.Bridge, c *utils.Tunnel) *httpServer {
|
||||
httpPort, _ := beego.AppConfig.Int("httpProxyPort")
|
||||
httpsPort, _ := beego.AppConfig.Int("httpsProxyPort")
|
||||
pemPath := beego.AppConfig.String("pemPath")
|
||||
keyPath := beego.AppConfig.String("keyPath")
|
||||
return &httpServer{
|
||||
server: server{
|
||||
task: c,
|
||||
bridge: bridge,
|
||||
Mutex: sync.Mutex{},
|
||||
},
|
||||
httpPort: httpPort,
|
||||
httpsPort: httpsPort,
|
||||
pemPath: pemPath,
|
||||
keyPath: keyPath,
|
||||
stop: make(chan bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) Start() error {
|
||||
var err error
|
||||
var http, https *http.Server
|
||||
if s.errorContent, err = utils.ReadAllFromFile(beego.AppPath + "/web/static/page/error.html"); err != nil {
|
||||
s.errorContent = []byte("easyProxy 404")
|
||||
}
|
||||
|
||||
if s.httpPort > 0 {
|
||||
if !s.TestTcpPort(s.httpPort) {
|
||||
utils.Fatalln("http端口", s.httpPort, "被占用!")
|
||||
}
|
||||
http = s.NewServer(s.httpPort)
|
||||
go func() {
|
||||
utils.Println("启动http监听,端口为", s.httpPort)
|
||||
err := http.ListenAndServe()
|
||||
if err != nil {
|
||||
utils.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if s.httpsPort > 0 {
|
||||
if !s.TestTcpPort(s.httpsPort) {
|
||||
utils.Fatalln("https端口", s.httpsPort, "被占用!")
|
||||
}
|
||||
if !utils.FileExists(s.pemPath) {
|
||||
utils.Fatalf("ssl certFile文件%s不存在", s.pemPath)
|
||||
}
|
||||
if !utils.FileExists(s.keyPath) {
|
||||
utils.Fatalf("ssl keyFile文件%s不存在", s.keyPath)
|
||||
}
|
||||
https = s.NewServer(s.httpsPort)
|
||||
go func() {
|
||||
utils.Println("启动https监听,端口为", s.httpsPort)
|
||||
err := https.ListenAndServeTLS(s.pemPath, s.keyPath)
|
||||
if err != nil {
|
||||
utils.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
startFinish <- true
|
||||
select {
|
||||
case <-s.stop:
|
||||
if http != nil {
|
||||
http.Close()
|
||||
}
|
||||
if https != nil {
|
||||
https.Close()
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Close() {
|
||||
s.stop <- true
|
||||
}
|
||||
|
||||
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
hijacker, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
conn, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
s.process(utils.NewConn(conn), r)
|
||||
}
|
||||
|
||||
func (s *httpServer) process(c *utils.Conn, r *http.Request) {
|
||||
//多客户端域名代理
|
||||
var (
|
||||
isConn = true
|
||||
link *utils.Link
|
||||
host *utils.Host
|
||||
tunnel *utils.Conn
|
||||
err error
|
||||
)
|
||||
for {
|
||||
//首次获取conn
|
||||
if isConn {
|
||||
if host, err = GetInfoByHost(r.Host); err != nil {
|
||||
utils.Printf("the host %s is not found !", r.Host)
|
||||
break
|
||||
}
|
||||
//流量限制
|
||||
if host.Client.Flow.FlowLimit > 0 && (host.Client.Flow.FlowLimit<<20) < (host.Client.Flow.ExportFlow+host.Client.Flow.InletFlow) {
|
||||
break
|
||||
}
|
||||
host.Client.Cnf.CompressDecode, host.Client.Cnf.CompressEncode = utils.GetCompressType(host.Client.Cnf.Compress)
|
||||
//权限控制
|
||||
if err = s.auth(r, c, host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
|
||||
break
|
||||
}
|
||||
link = utils.NewLink(host.Client.GetId(), utils.CONN_TCP, host.GetRandomTarget(), host.Client.Cnf.CompressEncode, host.Client.Cnf.CompressDecode, host.Client.Cnf.Crypt, c, host.Flow, nil, host.Client.Rate, nil)
|
||||
if tunnel, err = s.bridge.SendLinkInfo(host.Client.Id, link); err != nil {
|
||||
break
|
||||
}
|
||||
isConn = false
|
||||
} else {
|
||||
r, err = http.ReadRequest(bufio.NewReader(c))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
//根据设定,修改header和host
|
||||
utils.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
|
||||
b, err := httputil.DumpRequest(r, true)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
host.Flow.Add(len(b), 0)
|
||||
if _, err := tunnel.SendMsg(b, link); err != nil {
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if isConn {
|
||||
s.writeConnFail(c.Conn)
|
||||
} else {
|
||||
tunnel.SendMsg([]byte(utils.IO_EOF), link)
|
||||
}
|
||||
|
||||
c.Close()
|
||||
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServer(port int) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: ":" + strconv.Itoa(port),
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
s.handleTunneling(w, r)
|
||||
}),
|
||||
// Disable HTTP/2.
|
||||
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *httpServer) TestTcpPort(port int) bool {
|
||||
l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
|
||||
defer l.Close()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
)
|
||||
|
||||
type Service interface {
|
||||
Start() error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type NetBridge interface {
|
||||
SendLinkInfo(clientId int, link *conn.Link, t *file.Tunnel) (target net.Conn, err error)
|
||||
}
|
||||
|
||||
//BaseServer struct
|
||||
type BaseServer struct {
|
||||
id int
|
||||
bridge NetBridge
|
||||
task *file.Tunnel
|
||||
errorContent []byte
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func NewBaseServer(bridge *bridge.Bridge, task *file.Tunnel) *BaseServer {
|
||||
return &BaseServer{
|
||||
bridge: bridge,
|
||||
task: task,
|
||||
errorContent: nil,
|
||||
Mutex: sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
//add the flow
|
||||
func (s *BaseServer) FlowAdd(in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.task.Flow.ExportFlow += out
|
||||
s.task.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
//change the flow
|
||||
func (s *BaseServer) FlowAddHost(host *file.Host, in, out int64) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
host.Flow.ExportFlow += out
|
||||
host.Flow.InletFlow += in
|
||||
}
|
||||
|
||||
//write fail bytes to the connection
|
||||
func (s *BaseServer) writeConnFail(c net.Conn) {
|
||||
c.Write([]byte(common.ConnectionFailBytes))
|
||||
c.Write(s.errorContent)
|
||||
}
|
||||
|
||||
//auth check
|
||||
func (s *BaseServer) auth(r *http.Request, c *conn.Conn, u, p string) error {
|
||||
if u != "" && p != "" && !common.CheckAuth(r, u, p) {
|
||||
c.Write([]byte(common.UnauthorizedBytes))
|
||||
c.Close()
|
||||
return errors.New("401 Unauthorized")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//check flow limit of the client ,and decrease the allow num of client
|
||||
func (s *BaseServer) CheckFlowAndConnNum(client *file.Client) error {
|
||||
if client.Flow.FlowLimit > 0 && (client.Flow.FlowLimit<<20) < (client.Flow.ExportFlow+client.Flow.InletFlow) {
|
||||
return errors.New("Traffic exceeded")
|
||||
}
|
||||
if !client.GetConn() {
|
||||
return errors.New("Connections exceed the current client limit")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//create a new connection and start bytes copying
|
||||
func (s *BaseServer) DealClient(c *conn.Conn, client *file.Client, addr string, rb []byte, tp string, f func(), flow *file.Flow, localProxy bool) error {
|
||||
link := conn.NewLink(tp, addr, client.Cnf.Crypt, client.Cnf.Compress, c.Conn.RemoteAddr().String(), localProxy)
|
||||
if target, err := s.bridge.SendLinkInfo(client.Id, link, s.task); err != nil {
|
||||
logs.Warn("get connection from client id %d error %s", client.Id, err.Error())
|
||||
c.Close()
|
||||
return err
|
||||
} else {
|
||||
if f != nil {
|
||||
f()
|
||||
}
|
||||
conn.CopyWaitGroup(target, c.Conn, link.Crypt, link.Compress, client.Rate, flow, true, rb)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/cache"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
)
|
||||
|
||||
type httpServer struct {
|
||||
BaseServer
|
||||
httpPort int
|
||||
httpsPort int
|
||||
httpServer *http.Server
|
||||
httpsServer *http.Server
|
||||
httpsListener net.Listener
|
||||
useCache bool
|
||||
cache *cache.Cache
|
||||
cacheLen int
|
||||
}
|
||||
|
||||
func NewHttp(bridge *bridge.Bridge, c *file.Tunnel, httpPort, httpsPort int, useCache bool, cacheLen int) *httpServer {
|
||||
httpServer := &httpServer{
|
||||
BaseServer: BaseServer{
|
||||
task: c,
|
||||
bridge: bridge,
|
||||
Mutex: sync.Mutex{},
|
||||
},
|
||||
httpPort: httpPort,
|
||||
httpsPort: httpsPort,
|
||||
useCache: useCache,
|
||||
cacheLen: cacheLen,
|
||||
}
|
||||
if useCache {
|
||||
httpServer.cache = cache.New(cacheLen)
|
||||
}
|
||||
return httpServer
|
||||
}
|
||||
|
||||
func (s *httpServer) Start() error {
|
||||
var err error
|
||||
if s.errorContent, err = common.ReadAllFromFile(filepath.Join(common.GetRunPath(), "web", "static", "page", "error.html")); err != nil {
|
||||
s.errorContent = []byte("easyProxy 404")
|
||||
}
|
||||
if s.httpPort > 0 {
|
||||
s.httpServer = s.NewServer(s.httpPort, "http")
|
||||
go func() {
|
||||
l, err := connection.GetHttpListener()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
err = s.httpServer.Serve(l)
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
}
|
||||
if s.httpsPort > 0 {
|
||||
s.httpsServer = s.NewServer(s.httpsPort, "https")
|
||||
go func() {
|
||||
s.httpsListener, err = connection.GetHttpsListener()
|
||||
if err != nil {
|
||||
logs.Error(err)
|
||||
os.Exit(0)
|
||||
}
|
||||
logs.Error(NewHttpsServer(s.httpsListener, s.bridge, s.useCache, s.cacheLen).Start())
|
||||
}()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) Close() error {
|
||||
if s.httpsListener != nil {
|
||||
s.httpsListener.Close()
|
||||
}
|
||||
if s.httpsServer != nil {
|
||||
s.httpsServer.Close()
|
||||
}
|
||||
if s.httpServer != nil {
|
||||
s.httpServer.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *httpServer) handleTunneling(w http.ResponseWriter, r *http.Request) {
|
||||
hijacker, ok := w.(http.Hijacker)
|
||||
if !ok {
|
||||
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
}
|
||||
s.handleHttp(conn.NewConn(c), r)
|
||||
}
|
||||
|
||||
func (s *httpServer) handleHttp(c *conn.Conn, r *http.Request) {
|
||||
var (
|
||||
host *file.Host
|
||||
target net.Conn
|
||||
lastHost *file.Host
|
||||
err error
|
||||
connClient io.ReadWriteCloser
|
||||
scheme = r.URL.Scheme
|
||||
lk *conn.Link
|
||||
targetAddr string
|
||||
lenConn *conn.LenConn
|
||||
isReset bool
|
||||
wg sync.WaitGroup
|
||||
)
|
||||
defer func() {
|
||||
if connClient != nil {
|
||||
s.writeConnFail(c.Conn)
|
||||
connClient.Close()
|
||||
}
|
||||
c.Close()
|
||||
}()
|
||||
if host, err = file.GetDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
return
|
||||
}
|
||||
if err := s.CheckFlowAndConnNum(host.Client); err != nil {
|
||||
logs.Warn("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
|
||||
return
|
||||
}
|
||||
defer host.Client.AddConn()
|
||||
if err = s.auth(r, c, host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
|
||||
logs.Warn("auth error", err, r.RemoteAddr)
|
||||
return
|
||||
}
|
||||
reset:
|
||||
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
|
||||
logs.Warn(err.Error())
|
||||
return
|
||||
}
|
||||
lk = conn.NewLink("http", targetAddr, host.Client.Cnf.Crypt, host.Client.Cnf.Compress, r.RemoteAddr, host.Target.LocalProxy)
|
||||
if target, err = s.bridge.SendLinkInfo(host.Client.Id, lk, nil); err != nil {
|
||||
logs.Notice("connect to target %s error %s", lk.Host, err)
|
||||
return
|
||||
}
|
||||
connClient = conn.GetConn(target, lk.Crypt, lk.Compress, host.Client.Rate, true)
|
||||
lastHost = host
|
||||
|
||||
//read from inc-client
|
||||
go func() {
|
||||
wg.Add(1)
|
||||
isReset = false
|
||||
defer connClient.Close()
|
||||
defer func() {
|
||||
wg.Done()
|
||||
if !isReset {
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
for {
|
||||
if resp, err := http.ReadResponse(bufio.NewReader(connClient), r); err != nil {
|
||||
return
|
||||
} else {
|
||||
//if the cache is start and the response is in the extension,store the response to the cache list
|
||||
if s.useCache && strings.Contains(r.URL.Path, ".") {
|
||||
b, err := httputil.DumpResponse(resp, true)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.Write(b)
|
||||
host.Flow.Add(0, int64(len(b)))
|
||||
s.cache.Add(filepath.Join(host.Host, r.URL.Path), b)
|
||||
} else {
|
||||
lenConn := conn.NewLenConn(c)
|
||||
if err := resp.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
return
|
||||
}
|
||||
host.Flow.Add(0, int64(lenConn.Len))
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
//if the cache start and the request is in the cache list, return the cache
|
||||
if s.useCache {
|
||||
if v, ok := s.cache.Get(filepath.Join(host.Host, r.URL.Path)); ok {
|
||||
n, err := c.Write(v.([]byte))
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, return cache", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String())
|
||||
host.Flow.Add(0, int64(n))
|
||||
//if return cache and does not create a new conn with client and Connection is not set or close, close the connection.
|
||||
if strings.ToLower(r.Header.Get("Connection")) == "close" || strings.ToLower(r.Header.Get("Connection")) == "" {
|
||||
break
|
||||
}
|
||||
goto readReq
|
||||
}
|
||||
}
|
||||
|
||||
//change the host and header and set proxy setting
|
||||
common.ChangeHostAndHeader(r, host.HostChange, host.HeaderChange, c.Conn.RemoteAddr().String())
|
||||
logs.Trace("%s request, method %s, host %s, url %s, remote address %s, target %s", r.URL.Scheme, r.Method, r.Host, r.URL.Path, c.RemoteAddr().String(), lk.Host)
|
||||
//write
|
||||
lenConn = conn.NewLenConn(connClient)
|
||||
if err := r.Write(lenConn); err != nil {
|
||||
logs.Error(err)
|
||||
break
|
||||
}
|
||||
host.Flow.Add(int64(lenConn.Len), 0)
|
||||
|
||||
readReq:
|
||||
//read req from connection
|
||||
if r, err = http.ReadRequest(bufio.NewReader(c)); err != nil {
|
||||
break
|
||||
}
|
||||
r.URL.Scheme = scheme
|
||||
//What happened ,Why one character less???
|
||||
r.Method = resetReqMethod(r.Method)
|
||||
if hostTmp, err := file.GetDb().GetInfoByHost(r.Host, r); err != nil {
|
||||
logs.Notice("the url %s %s %s can't be parsed!", r.URL.Scheme, r.Host, r.RequestURI)
|
||||
break
|
||||
} else if host != lastHost {
|
||||
host = hostTmp
|
||||
lastHost = host
|
||||
isReset = true
|
||||
connClient.Close()
|
||||
goto reset
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func resetReqMethod(method string) string {
|
||||
if method == "ET" {
|
||||
return "GET"
|
||||
}
|
||||
if method == "OST" {
|
||||
return "POST"
|
||||
}
|
||||
return method
|
||||
}
|
||||
|
||||
func (s *httpServer) NewServer(port int, scheme string) *http.Server {
|
||||
return &http.Server{
|
||||
Addr: ":" + strconv.Itoa(port),
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
r.URL.Scheme = scheme
|
||||
s.handleTunneling(w, r)
|
||||
}),
|
||||
// Disable HTTP/2.
|
||||
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/cache"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/crypt"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type HttpsServer struct {
|
||||
httpServer
|
||||
listener net.Listener
|
||||
httpsListenerMap sync.Map
|
||||
}
|
||||
|
||||
func NewHttpsServer(l net.Listener, bridge NetBridge, useCache bool, cacheLen int) *HttpsServer {
|
||||
https := &HttpsServer{listener: l}
|
||||
https.bridge = bridge
|
||||
https.useCache = useCache
|
||||
if useCache {
|
||||
https.cache = cache.New(cacheLen)
|
||||
}
|
||||
return https
|
||||
}
|
||||
|
||||
//start https server
|
||||
func (https *HttpsServer) Start() error {
|
||||
if b, err := beego.AppConfig.Bool("https_just_proxy"); err == nil && b {
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
https.handleHttps(c)
|
||||
})
|
||||
} else {
|
||||
//start the default listener
|
||||
certFile := beego.AppConfig.String("https_default_cert_file")
|
||||
keyFile := beego.AppConfig.String("https_default_key_file")
|
||||
if common.FileExists(certFile) && common.FileExists(keyFile) {
|
||||
l := NewHttpsListener(https.listener)
|
||||
https.NewHttps(l, certFile, keyFile)
|
||||
https.httpsListenerMap.Store("default", l)
|
||||
}
|
||||
conn.Accept(https.listener, func(c net.Conn) {
|
||||
serverName, rb := GetServerNameFromClientHello(c)
|
||||
//if the clientHello does not contains sni ,use the default ssl certificate
|
||||
if serverName == "" {
|
||||
serverName = "default"
|
||||
}
|
||||
var l *HttpsListener
|
||||
if v, ok := https.httpsListenerMap.Load(serverName); ok {
|
||||
l = v.(*HttpsListener)
|
||||
} else {
|
||||
r := buildHttpsRequest(serverName)
|
||||
if host, err := file.GetDb().GetInfoByHost(serverName, r); err != nil {
|
||||
c.Close()
|
||||
logs.Notice("the url %s can't be parsed!,remote addr %s", serverName, c.RemoteAddr().String())
|
||||
return
|
||||
} else {
|
||||
if !common.FileExists(host.CertFilePath) || !common.FileExists(host.KeyFilePath) {
|
||||
//if the host cert file or key file is not set ,use the default file
|
||||
if v, ok := https.httpsListenerMap.Load("default"); ok {
|
||||
l = v.(*HttpsListener)
|
||||
} else {
|
||||
c.Close()
|
||||
logs.Error("the key %s cert %s file is not exist", host.KeyFilePath, host.CertFilePath)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
l = NewHttpsListener(https.listener)
|
||||
https.NewHttps(l, host.CertFilePath, host.KeyFilePath)
|
||||
https.httpsListenerMap.Store(serverName, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
acceptConn := conn.NewConn(c)
|
||||
acceptConn.Rb = rb
|
||||
l.acceptConn <- acceptConn
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// close
|
||||
func (https *HttpsServer) Close() error {
|
||||
return https.listener.Close()
|
||||
}
|
||||
|
||||
// new https server by cert and key file
|
||||
func (https *HttpsServer) NewHttps(l net.Listener, certFile string, keyFile string) {
|
||||
go func() {
|
||||
logs.Error(https.NewServer(0, "https").ServeTLS(l, certFile, keyFile))
|
||||
}()
|
||||
}
|
||||
|
||||
//handle the https which is just proxy to other client
|
||||
func (https *HttpsServer) handleHttps(c net.Conn) {
|
||||
hostName, rb := GetServerNameFromClientHello(c)
|
||||
var targetAddr string
|
||||
r := buildHttpsRequest(hostName)
|
||||
var host *file.Host
|
||||
var err error
|
||||
if host, err = file.GetDb().GetInfoByHost(hostName, r); err != nil {
|
||||
c.Close()
|
||||
logs.Notice("the url %s can't be parsed!", hostName)
|
||||
return
|
||||
}
|
||||
if err := https.CheckFlowAndConnNum(host.Client); err != nil {
|
||||
logs.Warn("client id %d, host id %d, error %s, when https connection", host.Client.Id, host.Id, err.Error())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
defer host.Client.AddConn()
|
||||
if err = https.auth(r, conn.NewConn(c), host.Client.Cnf.U, host.Client.Cnf.P); err != nil {
|
||||
logs.Warn("auth error", err, r.RemoteAddr)
|
||||
return
|
||||
}
|
||||
if targetAddr, err = host.Target.GetRandomTarget(); err != nil {
|
||||
logs.Warn(err.Error())
|
||||
}
|
||||
logs.Trace("new https connection,clientId %d,host %s,remote address %s", host.Client.Id, r.Host, c.RemoteAddr().String())
|
||||
https.DealClient(conn.NewConn(c), host.Client, targetAddr, rb, common.CONN_TCP, nil, host.Flow, host.Target.LocalProxy)
|
||||
}
|
||||
|
||||
type HttpsListener struct {
|
||||
acceptConn chan *conn.Conn
|
||||
parentListener net.Listener
|
||||
}
|
||||
|
||||
// https listener
|
||||
func NewHttpsListener(l net.Listener) *HttpsListener {
|
||||
return &HttpsListener{parentListener: l, acceptConn: make(chan *conn.Conn)}
|
||||
}
|
||||
|
||||
// accept
|
||||
func (httpsListener *HttpsListener) Accept() (net.Conn, error) {
|
||||
httpsConn := <-httpsListener.acceptConn
|
||||
if httpsConn == nil {
|
||||
return nil, errors.New("get connection error")
|
||||
}
|
||||
return httpsConn, nil
|
||||
}
|
||||
|
||||
// close
|
||||
func (httpsListener *HttpsListener) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// addr
|
||||
func (httpsListener *HttpsListener) Addr() net.Addr {
|
||||
return httpsListener.parentListener.Addr()
|
||||
}
|
||||
|
||||
// get server name from connection by read client hello bytes
|
||||
func GetServerNameFromClientHello(c net.Conn) (string, []byte) {
|
||||
buf := make([]byte, 4096)
|
||||
data := make([]byte, 4096)
|
||||
n, err := c.Read(buf)
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
if n < 42 {
|
||||
return "", nil
|
||||
}
|
||||
copy(data, buf[:n])
|
||||
clientHello := new(crypt.ClientHelloMsg)
|
||||
clientHello.Unmarshal(data[5:n])
|
||||
return clientHello.GetServerName(), buf[:n]
|
||||
}
|
||||
|
||||
// build https request
|
||||
func buildHttpsRequest(hostName string) *http.Request {
|
||||
r := new(http.Request)
|
||||
r.RequestURI = "/"
|
||||
r.URL = new(url.URL)
|
||||
r.URL.Scheme = "https"
|
||||
r.Host = hostName
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
)
|
||||
|
||||
type P2PServer struct {
|
||||
BaseServer
|
||||
p2pPort int
|
||||
p2p map[string]*p2p
|
||||
listener *net.UDPConn
|
||||
}
|
||||
|
||||
type p2p struct {
|
||||
visitorAddr *net.UDPAddr
|
||||
providerAddr *net.UDPAddr
|
||||
}
|
||||
|
||||
func NewP2PServer(p2pPort int) *P2PServer {
|
||||
return &P2PServer{
|
||||
p2pPort: p2pPort,
|
||||
p2p: make(map[string]*p2p),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *P2PServer) Start() error {
|
||||
logs.Info("start p2p server port", s.p2pPort)
|
||||
var err error
|
||||
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.p2pPort, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
buf := common.BufPoolUdp.Get().([]byte)
|
||||
n, addr, err := s.listener.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
go s.handleP2P(addr, string(buf[:n]))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *P2PServer) handleP2P(addr *net.UDPAddr, str string) {
|
||||
var (
|
||||
v *p2p
|
||||
ok bool
|
||||
)
|
||||
arr := strings.Split(str, common.CONN_DATA_SEQ)
|
||||
if len(arr) < 2 {
|
||||
return
|
||||
}
|
||||
if v, ok = s.p2p[arr[0]]; !ok {
|
||||
v = new(p2p)
|
||||
s.p2p[arr[0]] = v
|
||||
}
|
||||
logs.Trace("new p2p connection ,role %s , password %s ,local address %s", arr[1], arr[0], addr.String())
|
||||
if arr[1] == common.WORK_P2P_VISITOR {
|
||||
v.visitorAddr = addr
|
||||
for i := 20; i > 0; i-- {
|
||||
if v.providerAddr != nil {
|
||||
s.listener.WriteTo([]byte(v.providerAddr.String()), v.visitorAddr)
|
||||
s.listener.WriteTo([]byte(v.visitorAddr.String()), v.providerAddr)
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
delete(s.p2p, arr[0])
|
||||
} else {
|
||||
v.providerAddr = addr
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
package server
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/cnlh/easyProxy/bridge"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -45,8 +47,7 @@ const (
|
||||
)
|
||||
|
||||
type Sock5ModeServer struct {
|
||||
server
|
||||
isVerify bool
|
||||
BaseServer
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
@@ -65,7 +66,7 @@ func (s *Sock5ModeServer) handleRequest(c net.Conn) {
|
||||
_, err := io.ReadFull(c, header)
|
||||
|
||||
if err != nil {
|
||||
utils.Println("illegal request", err)
|
||||
logs.Warn("illegal request", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -135,19 +136,13 @@ func (s *Sock5ModeServer) doConnect(c net.Conn, command uint8) {
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(int(port)))
|
||||
var ltype string
|
||||
if command == associateMethod {
|
||||
ltype = utils.CONN_UDP
|
||||
ltype = common.CONN_UDP
|
||||
} else {
|
||||
ltype = utils.CONN_TCP
|
||||
ltype = common.CONN_TCP
|
||||
}
|
||||
link := utils.NewLink(s.task.Client.GetId(), ltype, addr, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, utils.NewConn(c), s.task.Flow, nil, s.task.Client.Rate, nil)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
|
||||
c.Close()
|
||||
return
|
||||
} else {
|
||||
s.DealClient(conn.NewConn(c), s.task.Client, addr, nil, ltype, func() {
|
||||
s.sendReply(c, succeeded)
|
||||
s.linkCopy(link, utils.NewConn(c), nil, tunnel, s.task.Flow)
|
||||
}
|
||||
}, s.task.Flow, s.task.Target.LocalProxy)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -162,7 +157,6 @@ func (s *Sock5ModeServer) handleBind(c net.Conn) {
|
||||
|
||||
//udp
|
||||
func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
utils.Println("UDP Associate")
|
||||
/*
|
||||
+----+------+------+----------+----------+----------+
|
||||
|RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
|
||||
@@ -175,7 +169,7 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
// relay udp datagram silently, without any notification to the requesting client
|
||||
if buf[2] != 0 {
|
||||
// does not support fragmentation, drop it
|
||||
utils.Println("does not support fragmentation, drop")
|
||||
logs.Warn("does not support fragmentation, drop")
|
||||
dummy := make([]byte, maxUDPPacketSize)
|
||||
c.Read(dummy)
|
||||
}
|
||||
@@ -187,13 +181,13 @@ func (s *Sock5ModeServer) handleUDP(c net.Conn) {
|
||||
func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := io.ReadFull(c, buf); err != nil {
|
||||
utils.Println("negotiation err", err)
|
||||
logs.Warn("negotiation err", err)
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if version := buf[0]; version != 5 {
|
||||
utils.Println("only support socks5, request from: ", c.RemoteAddr())
|
||||
logs.Warn("only support socks5, request from: ", c.RemoteAddr())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
@@ -201,16 +195,16 @@ func (s *Sock5ModeServer) handleConn(c net.Conn) {
|
||||
|
||||
methods := make([]byte, nMethods)
|
||||
if len, err := c.Read(methods); len != int(nMethods) || err != nil {
|
||||
utils.Println("wrong method")
|
||||
logs.Warn("wrong method")
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
if s.isVerify {
|
||||
if (s.task.Client.Cnf.U != "" && s.task.Client.Cnf.P != "") || (s.task.MultiAccount != nil && len(s.task.MultiAccount.AccountMap) > 0) {
|
||||
buf[1] = UserPassAuth
|
||||
c.Write(buf)
|
||||
if err := s.Auth(c); err != nil {
|
||||
c.Close()
|
||||
utils.Println("验证失败:", err)
|
||||
logs.Warn("Validation failed:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -242,7 +236,22 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
if _, err := io.ReadAtLeast(c, pass, passLen); err != nil {
|
||||
return err
|
||||
}
|
||||
if string(pass) == s.config.U && string(user) == s.config.P {
|
||||
|
||||
var U, P string
|
||||
if s.task.MultiAccount != nil {
|
||||
// enable multi user auth
|
||||
U = string(user)
|
||||
var ok bool
|
||||
P, ok = s.task.MultiAccount.AccountMap[U]
|
||||
if !ok {
|
||||
return errors.New("验证不通过")
|
||||
}
|
||||
} else {
|
||||
U = s.task.Client.Cnf.U
|
||||
P = s.task.Client.Cnf.P
|
||||
}
|
||||
|
||||
if string(user) == U && string(pass) == P {
|
||||
if _, err := c.Write([]byte{userAuthVersion, authSuccess}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -253,48 +262,31 @@ func (s *Sock5ModeServer) Auth(c net.Conn) error {
|
||||
}
|
||||
return errors.New("验证不通过")
|
||||
}
|
||||
return errors.New("未知错误")
|
||||
}
|
||||
|
||||
//start
|
||||
func (s *Sock5ModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.Listen("tcp", ":"+strconv.Itoa(s.task.TcpPort))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
conn, err := s.listener.Accept()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
utils.Fatalln("accept error: ", err)
|
||||
return conn.NewTcpListenerAndProcess(s.task.ServerIp+":"+strconv.Itoa(s.task.Port), func(c net.Conn) {
|
||||
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
|
||||
logs.Warn("client id %d, task id %d, error %s, when socks5 connection", s.task.Client.Id, s.task.Id, err.Error())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
if !s.ResetConfig() {
|
||||
conn.Close()
|
||||
continue
|
||||
}
|
||||
go s.handleConn(conn)
|
||||
}
|
||||
return nil
|
||||
logs.Trace("New socks5 connection,client %d,remote address %s", s.task.Client.Id, c.RemoteAddr())
|
||||
s.handleConn(c)
|
||||
s.task.Client.AddConn()
|
||||
}, &s.listener)
|
||||
}
|
||||
|
||||
//new
|
||||
func NewSock5ModeServer(bridge NetBridge, task *file.Tunnel) *Sock5ModeServer {
|
||||
s := new(Sock5ModeServer)
|
||||
s.bridge = bridge
|
||||
s.task = task
|
||||
return s
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *Sock5ModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
//new
|
||||
func NewSock5ModeServer(bridge *bridge.Bridge, task *utils.Tunnel) *Sock5ModeServer {
|
||||
s := new(Sock5ModeServer)
|
||||
s.bridge = bridge
|
||||
s.task = task
|
||||
s.config = utils.DeepCopyConfig(task.Config)
|
||||
if s.config.U != "" && s.config.P != "" {
|
||||
s.isVerify = true
|
||||
} else {
|
||||
s.isVerify = false
|
||||
}
|
||||
return s
|
||||
}
|
||||
Executable
+117
@@ -0,0 +1,117 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server/connection"
|
||||
)
|
||||
|
||||
type TunnelModeServer struct {
|
||||
BaseServer
|
||||
process process
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
//tcp|http|host
|
||||
func NewTunnelModeServer(process process, bridge NetBridge, task *file.Tunnel) *TunnelModeServer {
|
||||
s := new(TunnelModeServer)
|
||||
s.bridge = bridge
|
||||
s.process = process
|
||||
s.task = task
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *TunnelModeServer) Start() error {
|
||||
return conn.NewTcpListenerAndProcess(s.task.ServerIp+":"+strconv.Itoa(s.task.Port), func(c net.Conn) {
|
||||
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
|
||||
logs.Warn("client id %d, task id %d,error %s, when tcp connection", s.task.Client.Id, s.task.Id, err.Error())
|
||||
c.Close()
|
||||
return
|
||||
}
|
||||
logs.Trace("new tcp connection,local port %d,client %d,remote address %s", s.task.Port, s.task.Client.Id, c.RemoteAddr())
|
||||
s.process(conn.NewConn(c), s)
|
||||
s.task.Client.AddConn()
|
||||
}, &s.listener)
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *TunnelModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
//web管理方式
|
||||
type WebServer struct {
|
||||
BaseServer
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *WebServer) Start() error {
|
||||
p, _ := beego.AppConfig.Int("web_port")
|
||||
if p == 0 {
|
||||
stop := make(chan struct{})
|
||||
<-stop
|
||||
}
|
||||
beego.BConfig.WebConfig.Session.SessionOn = true
|
||||
beego.SetStaticPath("/static", filepath.Join(common.GetRunPath(), "web", "static"))
|
||||
beego.SetViewsPath(filepath.Join(common.GetRunPath(), "web", "views"))
|
||||
if l, err := connection.GetWebManagerListener(); err == nil {
|
||||
beego.InitBeforeHTTPRun()
|
||||
http.Serve(l, beego.BeeApp.Handlers)
|
||||
} else {
|
||||
logs.Error(err)
|
||||
}
|
||||
return errors.New("Web management startup failure")
|
||||
}
|
||||
|
||||
func (s *WebServer) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
//new
|
||||
func NewWebServer(bridge *bridge.Bridge) *WebServer {
|
||||
s := new(WebServer)
|
||||
s.bridge = bridge
|
||||
return s
|
||||
}
|
||||
|
||||
type process func(c *conn.Conn, s *TunnelModeServer) error
|
||||
|
||||
//tcp proxy
|
||||
func ProcessTunnel(c *conn.Conn, s *TunnelModeServer) error {
|
||||
targetAddr, err := s.task.Target.GetRandomTarget()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
logs.Warn("tcp port %d ,client id %d,task id %d connect error %s", s.task.Port, s.task.Client.Id, s.task.Id, err.Error())
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, targetAddr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
|
||||
//http proxy
|
||||
func ProcessHttp(c *conn.Conn, s *TunnelModeServer) error {
|
||||
_, addr, rb, err, r := c.GetHost()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
logs.Info(err)
|
||||
return err
|
||||
}
|
||||
if r.Method == "CONNECT" {
|
||||
c.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||
rb = nil
|
||||
}
|
||||
if err := s.auth(r, c, s.task.Client.Cnf.U, s.task.Client.Cnf.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.DealClient(c, s.task.Client, addr, rb, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// +build !windows
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
)
|
||||
|
||||
func HandleTrans(c *conn.Conn, s *TunnelModeServer) error {
|
||||
if addr, err := getAddress(c.Conn); err != nil {
|
||||
return err
|
||||
} else {
|
||||
return s.DealClient(c, s.task.Client, addr, nil, common.CONN_TCP, nil, s.task.Flow, s.task.Target.LocalProxy)
|
||||
}
|
||||
}
|
||||
|
||||
const SO_ORIGINAL_DST = 80
|
||||
|
||||
func getAddress(conn net.Conn) (string, error) {
|
||||
sysrawconn, f := conn.(syscall.Conn)
|
||||
if !f {
|
||||
return "", nil
|
||||
}
|
||||
rawConn, err := sysrawconn.SyscallConn()
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
var ip string
|
||||
var port uint16
|
||||
err = rawConn.Control(func(fd uintptr) {
|
||||
addr, err := syscall.GetsockoptIPv6Mreq(int(fd), syscall.IPPROTO_IP, SO_ORIGINAL_DST)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ip = net.IP(addr.Multiaddr[4:8]).String()
|
||||
port = uint16(addr.Multiaddr[2])<<8 + uint16(addr.Multiaddr[3])
|
||||
})
|
||||
return ip + ":" + strconv.Itoa(int(port)), nil
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// +build windows
|
||||
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
)
|
||||
|
||||
func HandleTrans(c *conn.Conn, s *TunnelModeServer) error {
|
||||
return nil
|
||||
}
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/conn"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
)
|
||||
|
||||
type UdpModeServer struct {
|
||||
BaseServer
|
||||
listener *net.UDPConn
|
||||
}
|
||||
|
||||
func NewUdpModeServer(bridge *bridge.Bridge, task *file.Tunnel) *UdpModeServer {
|
||||
s := new(UdpModeServer)
|
||||
s.bridge = bridge
|
||||
s.task = task
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *UdpModeServer) Start() error {
|
||||
var err error
|
||||
if s.task.ServerIp == "" {
|
||||
s.task.ServerIp = "0.0.0.0"
|
||||
}
|
||||
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP(s.task.ServerIp), s.task.Port, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buf := common.BufPoolUdp.Get().([]byte)
|
||||
for {
|
||||
n, addr, err := s.listener.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
logs.Trace("New udp connection,client %d,remote address %s", s.task.Client.Id, addr)
|
||||
go s.process(addr, buf[:n])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
if err := s.CheckFlowAndConnNum(s.task.Client); err != nil {
|
||||
logs.Warn("client id %d, task id %d,error %s, when udp connection", s.task.Client.Id, s.task.Id, err.Error())
|
||||
return
|
||||
}
|
||||
defer s.task.Client.AddConn()
|
||||
link := conn.NewLink(common.CONN_UDP, s.task.Target.TargetStr, s.task.Client.Cnf.Crypt, s.task.Client.Cnf.Compress, addr.String(), s.task.Target.LocalProxy)
|
||||
if target, err := s.bridge.SendLinkInfo(s.task.Client.Id, link, s.task); err != nil {
|
||||
return
|
||||
} else {
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
buf := common.BufPoolUdp.Get().([]byte)
|
||||
defer common.BufPoolUdp.Put(buf)
|
||||
target.Write(data)
|
||||
s.task.Flow.Add(int64(len(data)), 0)
|
||||
if n, err := target.Read(buf); err != nil {
|
||||
logs.Warn(err)
|
||||
return
|
||||
} else {
|
||||
s.listener.WriteTo(buf[:n], addr)
|
||||
s.task.Flow.Add(0, int64(n))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UdpModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
+308
-135
@@ -2,267 +2,440 @@ package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/cnlh/easyProxy/bridge"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/astaxie/beego/logs"
|
||||
"github.com/cnlh/nps/bridge"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
"github.com/cnlh/nps/server/proxy"
|
||||
"github.com/cnlh/nps/server/tool"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/load"
|
||||
"github.com/shirou/gopsutil/mem"
|
||||
"github.com/shirou/gopsutil/net"
|
||||
)
|
||||
|
||||
var (
|
||||
Bridge *bridge.Bridge
|
||||
RunList map[int]interface{} //运行中的任务
|
||||
CsvDb = utils.GetCsvDb()
|
||||
startFinish chan bool
|
||||
Bridge *bridge.Bridge
|
||||
RunList map[int]interface{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
RunList = make(map[int]interface{})
|
||||
startFinish = make(chan bool)
|
||||
}
|
||||
|
||||
//从csv文件中恢复任务
|
||||
//init task from db
|
||||
func InitFromCsv() {
|
||||
for _, v := range CsvDb.Tasks {
|
||||
if v.Status {
|
||||
utils.Println("启动模式:", v.Mode, "监听端口:", v.TcpPort)
|
||||
AddTask(v)
|
||||
//Add a public password
|
||||
if vkey := beego.AppConfig.String("public_vkey"); vkey != "" {
|
||||
c := file.NewClient(vkey, true, true)
|
||||
file.GetDb().NewClient(c)
|
||||
RunList[c.Id] = nil
|
||||
}
|
||||
//Initialize services in server-side files
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
if value.(*file.Tunnel).Status {
|
||||
AddTask(value.(*file.Tunnel))
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
//get bridge command
|
||||
func DealBridgeTask() {
|
||||
for {
|
||||
select {
|
||||
case t := <-Bridge.OpenTask:
|
||||
AddTask(t)
|
||||
case t := <-Bridge.CloseTask:
|
||||
StopServer(t.Id)
|
||||
case id := <-Bridge.CloseClient:
|
||||
DelTunnelAndHostByClientId(id, true)
|
||||
if v, ok := file.GetDb().JsonDb.Clients.Load(id); ok {
|
||||
if v.(*file.Client).NoStore {
|
||||
file.GetDb().DelClient(id)
|
||||
}
|
||||
}
|
||||
case tunnel := <-Bridge.OpenTask:
|
||||
StartTask(tunnel.Id)
|
||||
case s := <-Bridge.SecretChan:
|
||||
logs.Trace("New secret connection, addr", s.Conn.Conn.RemoteAddr())
|
||||
if t := file.GetDb().GetTaskByMd5Password(s.Password); t != nil {
|
||||
if t.Status {
|
||||
go proxy.NewBaseServer(Bridge, t).DealClient(s.Conn, t.Client, t.Target.TargetStr, nil, common.CONN_TCP, nil, t.Flow, t.Target.LocalProxy)
|
||||
} else {
|
||||
s.Conn.Close()
|
||||
logs.Trace("This key %s cannot be processed,status is close", s.Password)
|
||||
}
|
||||
} else {
|
||||
logs.Trace("This key %s cannot be processed", s.Password)
|
||||
s.Conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//start a new server
|
||||
func StartNewServer(bridgePort int, cnf *utils.Tunnel, test bool) {
|
||||
func StartNewServer(bridgePort int, cnf *file.Tunnel, bridgeType string) {
|
||||
Bridge = bridge.NewTunnel(bridgePort, bridgeType, common.GetBoolByStr(beego.AppConfig.String("ip_limit")), RunList)
|
||||
go func() {
|
||||
Bridge = bridge.NewTunnel(bridgePort, RunList)
|
||||
if err := Bridge.StartTunnel(); err != nil {
|
||||
utils.Fatalln("服务端开启失败", err)
|
||||
}
|
||||
if svr := NewMode(Bridge, cnf); svr != nil {
|
||||
RunList[cnf.Id] = svr
|
||||
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
|
||||
if err.Interface() != nil {
|
||||
utils.Fatalln(err)
|
||||
}
|
||||
} else {
|
||||
utils.Fatalln("启动模式不正确")
|
||||
logs.Error("start server bridge error", err)
|
||||
os.Exit(0)
|
||||
}
|
||||
}()
|
||||
if p, err := beego.AppConfig.Int("p2p_port"); err == nil {
|
||||
go proxy.NewP2PServer(p).Start()
|
||||
go proxy.NewP2PServer(p + 1).Start()
|
||||
go proxy.NewP2PServer(p + 2).Start()
|
||||
}
|
||||
go DealBridgeTask()
|
||||
go dealClientFlow()
|
||||
if svr := NewMode(Bridge, cnf); svr != nil {
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error(err)
|
||||
}
|
||||
RunList[cnf.Id] = svr
|
||||
} else {
|
||||
logs.Error("Incorrect startup mode %s", cnf.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func dealClientFlow() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
for {
|
||||
select {
|
||||
case <-startFinish:
|
||||
if test {
|
||||
log.Println("测试完成,未发现错误")
|
||||
os.Exit(0)
|
||||
}
|
||||
case <-ticker.C:
|
||||
dealClientData()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//new a server by mode name
|
||||
func NewMode(Bridge *bridge.Bridge, c *utils.Tunnel) interface{} {
|
||||
func NewMode(Bridge *bridge.Bridge, c *file.Tunnel) proxy.Service {
|
||||
var service proxy.Service
|
||||
switch c.Mode {
|
||||
case "tunnelServer":
|
||||
return NewTunnelModeServer(ProcessTunnel, Bridge, c)
|
||||
case "socks5Server":
|
||||
return NewSock5ModeServer(Bridge, c)
|
||||
case "httpProxyServer":
|
||||
return NewTunnelModeServer(ProcessHttp, Bridge, c)
|
||||
case "udpServer":
|
||||
return NewUdpModeServer(Bridge, c)
|
||||
case "tcp", "file":
|
||||
service = proxy.NewTunnelModeServer(proxy.ProcessTunnel, Bridge, c)
|
||||
case "socks5":
|
||||
service = proxy.NewSock5ModeServer(Bridge, c)
|
||||
case "httpProxy":
|
||||
service = proxy.NewTunnelModeServer(proxy.ProcessHttp, Bridge, c)
|
||||
case "tcpTrans":
|
||||
service = proxy.NewTunnelModeServer(proxy.HandleTrans, Bridge, c)
|
||||
case "udp":
|
||||
service = proxy.NewUdpModeServer(Bridge, c)
|
||||
case "webServer":
|
||||
InitFromCsv()
|
||||
t := &utils.Tunnel{
|
||||
TcpPort: 0,
|
||||
Mode: "httpHostServer",
|
||||
Target: "",
|
||||
Config: &utils.Config{},
|
||||
Status: true,
|
||||
t := &file.Tunnel{
|
||||
Port: 0,
|
||||
Mode: "httpHostServer",
|
||||
Status: true,
|
||||
}
|
||||
AddTask(t)
|
||||
return NewWebServer(Bridge)
|
||||
case "hostServer":
|
||||
return NewHostServer(c)
|
||||
service = proxy.NewWebServer(Bridge)
|
||||
case "httpHostServer":
|
||||
return NewHttp(Bridge, c)
|
||||
httpPort, _ := beego.AppConfig.Int("http_proxy_port")
|
||||
httpsPort, _ := beego.AppConfig.Int("https_proxy_port")
|
||||
useCache, _ := beego.AppConfig.Bool("http_cache")
|
||||
cacheLen, _ := beego.AppConfig.Int("http_cache_length")
|
||||
service = proxy.NewHttp(Bridge, c, httpPort, httpsPort, useCache, cacheLen)
|
||||
}
|
||||
return nil
|
||||
return service
|
||||
}
|
||||
|
||||
//stop server
|
||||
func StopServer(id int) error {
|
||||
if v, ok := RunList[id]; ok {
|
||||
reflect.ValueOf(v).MethodByName("Close").Call(nil)
|
||||
if t, err := CsvDb.GetTask(id); err != nil {
|
||||
if svr, ok := v.(proxy.Service); ok {
|
||||
if err := svr.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
logs.Info("stop server id %d", id)
|
||||
} else {
|
||||
logs.Warn("stop server id %d error", id)
|
||||
}
|
||||
if t, err := file.GetDb().GetTask(id); err != nil {
|
||||
return err
|
||||
} else {
|
||||
t.Status = false
|
||||
CsvDb.UpdateTask(t)
|
||||
file.GetDb().UpdateTask(t)
|
||||
}
|
||||
delete(RunList, id)
|
||||
return nil
|
||||
}
|
||||
return errors.New("未在运行中")
|
||||
return errors.New("task is not running")
|
||||
}
|
||||
|
||||
//add task
|
||||
func AddTask(t *utils.Tunnel) error {
|
||||
func AddTask(t *file.Tunnel) error {
|
||||
if t.Mode == "secret" || t.Mode == "p2p" {
|
||||
logs.Info("secret task %s start ", t.Remark)
|
||||
RunList[t.Id] = nil
|
||||
return nil
|
||||
}
|
||||
if b := tool.TestServerPort(t.Port, t.Mode); !b && t.Mode != "httpHostServer" {
|
||||
logs.Error("taskId %d start error port %d open failed", t.Id, t.Port)
|
||||
return errors.New("the port open error")
|
||||
}
|
||||
if minute, err := beego.AppConfig.Int("flow_store_interval"); err == nil && minute > 0 {
|
||||
go flowSession(time.Minute * time.Duration(minute))
|
||||
}
|
||||
if svr := NewMode(Bridge, t); svr != nil {
|
||||
logs.Info("tunnel task %s start mode:%s port %d", t.Remark, t.Mode, t.Port)
|
||||
RunList[t.Id] = svr
|
||||
go func() {
|
||||
err := reflect.ValueOf(svr).MethodByName("Start").Call(nil)[0]
|
||||
if err.Interface() != nil {
|
||||
utils.Fatalln("服务端", t.Id, "启动失败,错误:", err)
|
||||
if err := svr.Start(); err != nil {
|
||||
logs.Error("clientId %d taskId %d start error %s", t.Client.Id, t.Id, err)
|
||||
delete(RunList, t.Id)
|
||||
return
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
return errors.New("启动模式不正确")
|
||||
return errors.New("the mode is not correct")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//start task
|
||||
func StartTask(id int) error {
|
||||
if t, err := CsvDb.GetTask(id); err != nil {
|
||||
if t, err := file.GetDb().GetTask(id); err != nil {
|
||||
return err
|
||||
} else {
|
||||
AddTask(t)
|
||||
t.Status = true
|
||||
CsvDb.UpdateTask(t)
|
||||
file.GetDb().UpdateTask(t)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//delete task
|
||||
func DelTask(id int) error {
|
||||
if err := StopServer(id); err != nil {
|
||||
return err
|
||||
}
|
||||
return CsvDb.DelTask(id)
|
||||
}
|
||||
|
||||
//get key by host from x
|
||||
func GetInfoByHost(host string) (h *utils.Host, err error) {
|
||||
for _, v := range CsvDb.Hosts {
|
||||
s := strings.Split(host, ":")
|
||||
if s[0] == v.Host {
|
||||
h = v
|
||||
return
|
||||
if _, ok := RunList[id]; ok {
|
||||
if err := StopServer(id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = errors.New("未找到host对应的内网目标")
|
||||
return
|
||||
return file.GetDb().DelTask(id)
|
||||
}
|
||||
|
||||
//get task list by page num
|
||||
func GetTunnel(start, length int, typeVal string, clientId int) ([]*utils.Tunnel, int) {
|
||||
list := make([]*utils.Tunnel, 0)
|
||||
func GetTunnel(start, length int, typeVal string, clientId int, search string) ([]*file.Tunnel, int) {
|
||||
list := make([]*file.Tunnel, 0)
|
||||
var cnt int
|
||||
for _, v := range CsvDb.Tasks {
|
||||
if (typeVal != "" && v.Mode != typeVal) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client[v.Client.Id]; ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
if _, ok := RunList[v.Id]; ok {
|
||||
v.Client.Status = true
|
||||
} else {
|
||||
v.Client.Status = false
|
||||
keys := file.GetMapKeys(file.GetDb().JsonDb.Tasks, false, "", "")
|
||||
for _, key := range keys {
|
||||
if value, ok := file.GetDb().JsonDb.Tasks.Load(key); ok {
|
||||
v := value.(*file.Tunnel)
|
||||
if (typeVal != "" && v.Mode != typeVal || (clientId != 0 && v.Client.Id != clientId)) || (typeVal == "" && clientId != v.Client.Id) {
|
||||
continue
|
||||
}
|
||||
if search != "" && !(v.Id == common.GetIntNoErrByStr(search) || v.Port == common.GetIntNoErrByStr(search) || strings.Contains(v.Password, search) || strings.Contains(v.Remark, search)) {
|
||||
continue
|
||||
}
|
||||
cnt++
|
||||
if _, ok := Bridge.Client.Load(v.Client.Id); ok {
|
||||
v.Client.IsConnect = true
|
||||
} else {
|
||||
v.Client.IsConnect = false
|
||||
}
|
||||
if start--; start < 0 {
|
||||
if length--; length >= 0 {
|
||||
if _, ok := RunList[v.Id]; ok {
|
||||
v.RunStatus = true
|
||||
} else {
|
||||
v.RunStatus = false
|
||||
}
|
||||
list = append(list, v)
|
||||
}
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, cnt
|
||||
}
|
||||
|
||||
//获取客户端列表
|
||||
func GetClientList(start, length int) (list []*utils.Client, cnt int) {
|
||||
list, cnt = CsvDb.GetClientList(start, length)
|
||||
dealClientData(list)
|
||||
//get client list
|
||||
func GetClientList(start, length int, search, sort, order string, clientId int) (list []*file.Client, cnt int) {
|
||||
list, cnt = file.GetDb().GetClientList(start, length, search, sort, order, clientId)
|
||||
dealClientData()
|
||||
return
|
||||
}
|
||||
|
||||
func dealClientData(list []*utils.Client) {
|
||||
for _, v := range list {
|
||||
if _, ok := Bridge.Client[v.Id]; ok {
|
||||
func dealClientData() {
|
||||
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Client)
|
||||
if _, ok := Bridge.Client.Load(v.Id); ok {
|
||||
v.IsConnect = true
|
||||
} else {
|
||||
v.IsConnect = false
|
||||
}
|
||||
v.Flow.InletFlow = 0
|
||||
v.Flow.ExportFlow = 0
|
||||
for _, h := range CsvDb.Hosts {
|
||||
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
h := value.(*file.Host)
|
||||
if h.Client.Id == v.Id {
|
||||
v.Flow.InletFlow += h.Flow.InletFlow
|
||||
v.Flow.ExportFlow += h.Flow.ExportFlow
|
||||
}
|
||||
}
|
||||
for _, t := range CsvDb.Tasks {
|
||||
return true
|
||||
})
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
t := value.(*file.Tunnel)
|
||||
if t.Client.Id == v.Id {
|
||||
v.Flow.InletFlow += t.Flow.InletFlow
|
||||
v.Flow.ExportFlow += t.Flow.ExportFlow
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
return true
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
//根据客户端id删除其所属的所有隧道和域名
|
||||
func DelTunnelAndHostByClientId(clientId int) {
|
||||
for _, v := range CsvDb.Tasks {
|
||||
if v.Client.Id == clientId {
|
||||
DelTask(v.Id)
|
||||
//delete all host and tasks by client id
|
||||
func DelTunnelAndHostByClientId(clientId int, justDelNoStore bool) {
|
||||
var ids []int
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if justDelNoStore && !v.NoStore {
|
||||
return true
|
||||
}
|
||||
if v.Client.Id == clientId {
|
||||
ids = append(ids, v.Id)
|
||||
}
|
||||
return true
|
||||
})
|
||||
for _, id := range ids {
|
||||
DelTask(id)
|
||||
}
|
||||
for _, v := range CsvDb.Hosts {
|
||||
if v.Client.Id == clientId {
|
||||
CsvDb.DelHost(v.Host)
|
||||
ids = ids[:0]
|
||||
file.GetDb().JsonDb.Hosts.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Host)
|
||||
if justDelNoStore && !v.NoStore {
|
||||
return true
|
||||
}
|
||||
if v.Client.Id == clientId {
|
||||
ids = append(ids, v.Id)
|
||||
}
|
||||
return true
|
||||
})
|
||||
for _, id := range ids {
|
||||
file.GetDb().DelHost(id)
|
||||
}
|
||||
}
|
||||
|
||||
//关闭客户端连接
|
||||
//close the client
|
||||
func DelClientConnect(clientId int) {
|
||||
Bridge.DelClient(clientId)
|
||||
}
|
||||
|
||||
func GetDashboardData() map[string]int {
|
||||
data := make(map[string]int)
|
||||
data["hostCount"] = len(CsvDb.Hosts)
|
||||
data["clientCount"] = len(CsvDb.Clients)
|
||||
list := CsvDb.Clients
|
||||
dealClientData(list)
|
||||
func GetDashboardData() map[string]interface{} {
|
||||
data := make(map[string]interface{})
|
||||
data["hostCount"] = common.GeSynctMapLen(file.GetDb().JsonDb.Hosts)
|
||||
data["clientCount"] = common.GeSynctMapLen(file.GetDb().JsonDb.Clients) - 1 //Remove the public key client
|
||||
dealClientData()
|
||||
c := 0
|
||||
var in, out int64
|
||||
for _, v := range list {
|
||||
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Client)
|
||||
if v.IsConnect {
|
||||
c += 1
|
||||
}
|
||||
in += v.Flow.InletFlow
|
||||
out += v.Flow.ExportFlow
|
||||
}
|
||||
return true
|
||||
})
|
||||
data["clientOnlineCount"] = c
|
||||
data["inletFlowCount"] = int(in)
|
||||
data["exportFlowCount"] = int(out)
|
||||
for _, v := range CsvDb.Tasks {
|
||||
switch v.Mode {
|
||||
case "tunnelServer":
|
||||
data["tunnelServerCount"] += 1
|
||||
case "socks5Server":
|
||||
data["socks5ServerCount"] += 1
|
||||
case "httpProxyServer":
|
||||
data["httpProxyServerCount"] += 1
|
||||
case "udpServer":
|
||||
data["udpServerCount"] += 1
|
||||
var tcp, udp, secret, socks5, p2p, http int
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
switch value.(*file.Tunnel).Mode {
|
||||
case "tcp":
|
||||
tcp += 1
|
||||
case "socks5":
|
||||
socks5 += 1
|
||||
case "httpProxy":
|
||||
http += 1
|
||||
case "udp":
|
||||
udp += 1
|
||||
case "p2p":
|
||||
p2p += 1
|
||||
case "secret":
|
||||
secret += 1
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
data["tcpC"] = tcp
|
||||
data["udpCount"] = udp
|
||||
data["socks5Count"] = socks5
|
||||
data["httpProxyCount"] = http
|
||||
data["secretCount"] = secret
|
||||
data["p2pCount"] = p2p
|
||||
data["bridgeType"] = beego.AppConfig.String("bridge_type")
|
||||
data["httpProxyPort"] = beego.AppConfig.String("http_proxy_port")
|
||||
data["httpsProxyPort"] = beego.AppConfig.String("https_proxy_port")
|
||||
data["ipLimit"] = beego.AppConfig.String("ip_limit")
|
||||
data["flowStoreInterval"] = beego.AppConfig.String("flow_store_interval")
|
||||
data["serverIp"] = beego.AppConfig.String("p2p_ip")
|
||||
data["p2pPort"] = beego.AppConfig.String("p2p_port")
|
||||
data["logLevel"] = beego.AppConfig.String("log_level")
|
||||
tcpCount := 0
|
||||
|
||||
file.GetDb().JsonDb.Clients.Range(func(key, value interface{}) bool {
|
||||
tcpCount += int(value.(*file.Client).NowConn)
|
||||
return true
|
||||
})
|
||||
data["tcpCount"] = tcpCount
|
||||
cpuPercet, _ := cpu.Percent(0, true)
|
||||
var cpuAll float64
|
||||
for _, v := range cpuPercet {
|
||||
cpuAll += v
|
||||
}
|
||||
loads, _ := load.Avg()
|
||||
data["load"] = loads.String()
|
||||
data["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
|
||||
swap, _ := mem.SwapMemory()
|
||||
data["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
data["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
data["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
data["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
}
|
||||
for _, v := range conn {
|
||||
data[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
//chart
|
||||
var fg int
|
||||
if len(tool.ServerStatus) >= 10 {
|
||||
fg = len(tool.ServerStatus) / 10
|
||||
for i := 0; i <= 9; i++ {
|
||||
data["sys"+strconv.Itoa(i+1)] = tool.ServerStatus[i*fg]
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func flowSession(m time.Duration) {
|
||||
ticker := time.NewTicker(m)
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
file.GetDb().JsonDb.StoreHostToJsonFile()
|
||||
file.GetDb().JsonDb.StoreTasksToJsonFile()
|
||||
file.GetDb().JsonDb.StoreClientsToJsonFile()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-137
@@ -1,137 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/cnlh/easyProxy/bridge"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type TunnelModeServer struct {
|
||||
server
|
||||
process process
|
||||
listener *net.TCPListener
|
||||
}
|
||||
|
||||
//tcp|http|host
|
||||
func NewTunnelModeServer(process process, bridge *bridge.Bridge, task *utils.Tunnel) *TunnelModeServer {
|
||||
s := new(TunnelModeServer)
|
||||
s.bridge = bridge
|
||||
s.process = process
|
||||
s.task = task
|
||||
s.config = utils.DeepCopyConfig(task.Config)
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *TunnelModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), s.task.TcpPort, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
conn, err := s.listener.AcceptTCP()
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
utils.Println(err)
|
||||
continue
|
||||
}
|
||||
go s.process(utils.NewConn(conn), s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//与客户端建立通道
|
||||
func (s *TunnelModeServer) dealClient(c *utils.Conn, cnf *utils.Config, addr string, method string, rb []byte) error {
|
||||
link := utils.NewLink(s.task.Client.GetId(), utils.CONN_TCP, addr, cnf.CompressEncode, cnf.CompressDecode, cnf.Crypt, c, s.task.Flow, nil, s.task.Client.Rate, nil)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
|
||||
c.Close()
|
||||
return err
|
||||
} else {
|
||||
s.linkCopy(link, c, rb, tunnel, s.task.Flow)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *TunnelModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
|
||||
//web管理方式
|
||||
type WebServer struct {
|
||||
server
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *WebServer) Start() error {
|
||||
beego.BConfig.WebConfig.Session.SessionOn = true
|
||||
utils.Println("web管理启动,访问端口为", beego.AppConfig.String("httpport"))
|
||||
beego.SetViewsPath(beego.AppPath + "/web/views")
|
||||
beego.SetStaticPath("/static", beego.AppPath+"/web/static")
|
||||
beego.Run()
|
||||
return errors.New("web管理启动失败")
|
||||
}
|
||||
|
||||
//new
|
||||
func NewWebServer(bridge *bridge.Bridge) *WebServer {
|
||||
s := new(WebServer)
|
||||
s.bridge = bridge
|
||||
return s
|
||||
}
|
||||
|
||||
//host
|
||||
type HostServer struct {
|
||||
server
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *HostServer) Start() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewHostServer(task *utils.Tunnel) *HostServer {
|
||||
s := new(HostServer)
|
||||
s.task = task
|
||||
s.config = utils.DeepCopyConfig(task.Config)
|
||||
return s
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *HostServer) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type process func(c *utils.Conn, s *TunnelModeServer) error
|
||||
|
||||
//tcp隧道模式
|
||||
func ProcessTunnel(c *utils.Conn, s *TunnelModeServer) error {
|
||||
if !s.ResetConfig() {
|
||||
c.Close()
|
||||
return errors.New("流量超出")
|
||||
}
|
||||
return s.dealClient(c, s.config, s.task.Target, "", nil)
|
||||
}
|
||||
|
||||
//http代理模式
|
||||
func ProcessHttp(c *utils.Conn, s *TunnelModeServer) error {
|
||||
if !s.ResetConfig() {
|
||||
c.Close()
|
||||
return errors.New("流量超出")
|
||||
}
|
||||
method, addr, rb, err, r := c.GetHost()
|
||||
if err != nil {
|
||||
c.Close()
|
||||
return err
|
||||
}
|
||||
if err := s.auth(r, c, s.config.U, s.config.P); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.dealClient(c, s.config, addr, method, rb)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"log"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/cnlh/nps/lib/file"
|
||||
)
|
||||
|
||||
func TestServerConfig() {
|
||||
var postTcpArr []int
|
||||
var postUdpArr []int
|
||||
file.GetDb().JsonDb.Tasks.Range(func(key, value interface{}) bool {
|
||||
v := value.(*file.Tunnel)
|
||||
if v.Mode == "udp" {
|
||||
isInArr(&postUdpArr, v.Port, v.Remark, "udp")
|
||||
} else if v.Port != 0 {
|
||||
|
||||
isInArr(&postTcpArr, v.Port, v.Remark, "tcp")
|
||||
}
|
||||
return true
|
||||
})
|
||||
p, err := beego.AppConfig.Int("web_port")
|
||||
if err != nil {
|
||||
log.Fatalln("Getting web management port error :", err)
|
||||
} else {
|
||||
isInArr(&postTcpArr, p, "Web Management port", "tcp")
|
||||
}
|
||||
|
||||
if p := beego.AppConfig.String("bridge_port"); p != "" {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get Server and client communication portserror:", err)
|
||||
} else if beego.AppConfig.String("bridge_type") == "kcp" {
|
||||
isInArr(&postUdpArr, port, "Server and client communication ports", "udp")
|
||||
} else {
|
||||
isInArr(&postTcpArr, port, "Server and client communication ports", "tcp")
|
||||
}
|
||||
}
|
||||
|
||||
if p := beego.AppConfig.String("httpProxyPort"); p != "" {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get http port error:", err)
|
||||
} else {
|
||||
isInArr(&postTcpArr, port, "https port", "tcp")
|
||||
}
|
||||
}
|
||||
if p := beego.AppConfig.String("https_proxy_port"); p != "" {
|
||||
if b, err := beego.AppConfig.Bool("https_just_proxy"); !(err == nil && b) {
|
||||
if port, err := strconv.Atoi(p); err != nil {
|
||||
log.Fatalln("get https port error", err)
|
||||
} else {
|
||||
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("pemPath"))) {
|
||||
log.Fatalf("ssl certFile %s is not exist", beego.AppConfig.String("pemPath"))
|
||||
}
|
||||
if !common.FileExists(filepath.Join(common.GetRunPath(), beego.AppConfig.String("ketPath"))) {
|
||||
log.Fatalf("ssl keyFile %s is not exist", beego.AppConfig.String("pemPath"))
|
||||
}
|
||||
isInArr(&postTcpArr, port, "http port", "tcp")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isInArr(arr *[]int, val int, remark string, tp string) {
|
||||
for _, v := range *arr {
|
||||
if v == val {
|
||||
log.Fatalf("the port %d is reused,remark: %s", val, remark)
|
||||
}
|
||||
}
|
||||
if tp == "tcp" {
|
||||
if !common.TestTcpPort(val) {
|
||||
log.Fatalf("open the %d port error ,remark: %s", val, remark)
|
||||
}
|
||||
} else {
|
||||
if !common.TestUdpPort(val) {
|
||||
log.Fatalf("open the %d port error ,remark: %s", val, remark)
|
||||
}
|
||||
}
|
||||
*arr = append(*arr, val)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/astaxie/beego"
|
||||
"github.com/cnlh/nps/lib/common"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/load"
|
||||
"github.com/shirou/gopsutil/mem"
|
||||
"github.com/shirou/gopsutil/net"
|
||||
)
|
||||
|
||||
var (
|
||||
ports []int
|
||||
ServerStatus []map[string]interface{}
|
||||
)
|
||||
|
||||
func StartSystemInfo() {
|
||||
if b, err := beego.AppConfig.Bool("system_info_display"); err == nil && b {
|
||||
ServerStatus = make([]map[string]interface{}, 0, 1500)
|
||||
go getSeverStatus()
|
||||
}
|
||||
}
|
||||
|
||||
func InitAllowPort() {
|
||||
p := beego.AppConfig.String("allow_ports")
|
||||
ports = common.GetPorts(p)
|
||||
}
|
||||
|
||||
func TestServerPort(p int, m string) (b bool) {
|
||||
if p > 65535 || p < 0 {
|
||||
return false
|
||||
}
|
||||
if len(ports) != 0 {
|
||||
if !common.InIntArr(ports, p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if m == "udp" {
|
||||
b = common.TestUdpPort(p)
|
||||
} else {
|
||||
b = common.TestTcpPort(p)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func getSeverStatus() {
|
||||
for {
|
||||
if len(ServerStatus) < 10 {
|
||||
time.Sleep(time.Second)
|
||||
} else {
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
cpuPercet, _ := cpu.Percent(0, true)
|
||||
var cpuAll float64
|
||||
for _, v := range cpuPercet {
|
||||
cpuAll += v
|
||||
}
|
||||
m := make(map[string]interface{})
|
||||
loads, _ := load.Avg()
|
||||
m["load1"] = loads.Load1
|
||||
m["load5"] = loads.Load5
|
||||
m["load15"] = loads.Load15
|
||||
m["cpu"] = math.Round(cpuAll / float64(len(cpuPercet)))
|
||||
swap, _ := mem.SwapMemory()
|
||||
m["swap_mem"] = math.Round(swap.UsedPercent)
|
||||
vir, _ := mem.VirtualMemory()
|
||||
m["virtual_mem"] = math.Round(vir.UsedPercent)
|
||||
conn, _ := net.ProtoCounters(nil)
|
||||
io1, _ := net.IOCounters(false)
|
||||
time.Sleep(time.Millisecond * 500)
|
||||
io2, _ := net.IOCounters(false)
|
||||
if len(io2) > 0 && len(io1) > 0 {
|
||||
m["io_send"] = (io2[0].BytesSent - io1[0].BytesSent) * 2
|
||||
m["io_recv"] = (io2[0].BytesRecv - io1[0].BytesRecv) * 2
|
||||
}
|
||||
t := time.Now()
|
||||
m["time"] = strconv.Itoa(t.Hour()) + ":" + strconv.Itoa(t.Minute()) + ":" + strconv.Itoa(t.Second())
|
||||
|
||||
for _, v := range conn {
|
||||
m[v.Protocol] = v.Stats["CurrEstab"]
|
||||
}
|
||||
if len(ServerStatus) >= 1440 {
|
||||
ServerStatus = ServerStatus[1:]
|
||||
}
|
||||
ServerStatus = append(ServerStatus, m)
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/cnlh/easyProxy/bridge"
|
||||
"github.com/cnlh/easyProxy/utils"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type UdpModeServer struct {
|
||||
server
|
||||
listener *net.UDPConn
|
||||
udpMap map[string]*utils.Conn
|
||||
}
|
||||
|
||||
func NewUdpModeServer(bridge *bridge.Bridge, task *utils.Tunnel) *UdpModeServer {
|
||||
s := new(UdpModeServer)
|
||||
s.bridge = bridge
|
||||
s.udpMap = make(map[string]*utils.Conn)
|
||||
s.task = task
|
||||
s.config = utils.DeepCopyConfig(task.Config)
|
||||
return s
|
||||
}
|
||||
|
||||
//开始
|
||||
func (s *UdpModeServer) Start() error {
|
||||
var err error
|
||||
s.listener, err = net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), s.task.TcpPort, ""})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buf := utils.BufPoolUdp.Get().([]byte)
|
||||
for {
|
||||
n, addr, err := s.listener.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "use of closed network connection") {
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !s.ResetConfig() {
|
||||
continue
|
||||
}
|
||||
go s.process(addr, buf[:n])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UdpModeServer) process(addr *net.UDPAddr, data []byte) {
|
||||
link := utils.NewLink(s.task.Client.GetId(), utils.CONN_UDP, s.task.Target, s.config.CompressEncode, s.config.CompressDecode, s.config.Crypt, nil, s.task.Flow, s.listener, s.task.Client.Rate, addr)
|
||||
|
||||
if tunnel, err := s.bridge.SendLinkInfo(s.task.Client.Id, link); err != nil {
|
||||
return
|
||||
} else {
|
||||
s.task.Flow.Add(len(data), 0)
|
||||
tunnel.SendMsg(data, link)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *UdpModeServer) Close() error {
|
||||
return s.listener.Close()
|
||||
}
|
||||
-438
@@ -1,438 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/golang/snappy"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const cryptKey = "1234567812345678"
|
||||
|
||||
type CryptConn struct {
|
||||
conn net.Conn
|
||||
crypt bool
|
||||
rate *Rate
|
||||
}
|
||||
|
||||
func NewCryptConn(conn net.Conn, crypt bool, rate *Rate) *CryptConn {
|
||||
c := new(CryptConn)
|
||||
c.conn = conn
|
||||
c.crypt = crypt
|
||||
c.rate = rate
|
||||
return c
|
||||
}
|
||||
|
||||
//加密写
|
||||
func (s *CryptConn) Write(b []byte) (n int, err error) {
|
||||
n = len(b)
|
||||
if s.crypt {
|
||||
if b, err = AesEncrypt(b, []byte(cryptKey)); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if b, err = GetLenBytes(b); err != nil {
|
||||
return
|
||||
}
|
||||
_, err = s.conn.Write(b)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//解密读
|
||||
func (s *CryptConn) Read(b []byte) (n int, err error) {
|
||||
var lens int
|
||||
var buf []byte
|
||||
var rb []byte
|
||||
c := NewConn(s.conn)
|
||||
if lens, err = c.GetLen(); err != nil {
|
||||
return
|
||||
}
|
||||
if buf, err = c.ReadLen(lens); err != nil {
|
||||
return
|
||||
}
|
||||
if s.crypt {
|
||||
if rb, err = AesDecrypt(buf, []byte(cryptKey)); err != nil {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
rb = buf
|
||||
}
|
||||
copy(b, rb)
|
||||
n = len(rb)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type SnappyConn struct {
|
||||
w *snappy.Writer
|
||||
r *snappy.Reader
|
||||
crypt bool
|
||||
rate *Rate
|
||||
}
|
||||
|
||||
func NewSnappyConn(conn net.Conn, crypt bool, rate *Rate) *SnappyConn {
|
||||
c := new(SnappyConn)
|
||||
c.w = snappy.NewBufferedWriter(conn)
|
||||
c.r = snappy.NewReader(conn)
|
||||
c.crypt = crypt
|
||||
c.rate = rate
|
||||
return c
|
||||
}
|
||||
|
||||
//snappy压缩写 包含加密
|
||||
func (s *SnappyConn) Write(b []byte) (n int, err error) {
|
||||
n = len(b)
|
||||
if s.crypt {
|
||||
if b, err = AesEncrypt(b, []byte(cryptKey)); err != nil {
|
||||
Println("encode crypt error:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if _, err = s.w.Write(b); err != nil {
|
||||
return
|
||||
}
|
||||
if err = s.w.Flush(); err != nil {
|
||||
return
|
||||
}
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//snappy压缩读 包含解密
|
||||
func (s *SnappyConn) Read(b []byte) (n int, err error) {
|
||||
buf := BufPool.Get().([]byte)
|
||||
defer BufPool.Put(buf)
|
||||
if n, err = s.r.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
var bs []byte
|
||||
if s.crypt {
|
||||
if bs, err = AesDecrypt(buf[:n], []byte(cryptKey)); err != nil {
|
||||
Println("decode crypt error:", err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
bs = buf[:n]
|
||||
}
|
||||
n = len(bs)
|
||||
copy(b, bs)
|
||||
if s.rate != nil {
|
||||
s.rate.Get(int64(n))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type Conn struct {
|
||||
Conn net.Conn
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
//new conn
|
||||
func NewConn(conn net.Conn) *Conn {
|
||||
c := new(Conn)
|
||||
c.Conn = conn
|
||||
return c
|
||||
}
|
||||
|
||||
//从tcp报文中解析出host,连接类型等
|
||||
func (s *Conn) GetHost() (method, address string, rb []byte, err error, r *http.Request) {
|
||||
var b [32 * 1024]byte
|
||||
var n int
|
||||
if n, err = s.Read(b[:]); err != nil {
|
||||
return
|
||||
}
|
||||
rb = b[:n]
|
||||
r, err = http.ReadRequest(bufio.NewReader(bytes.NewReader(rb)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
hostPortURL, err := url.Parse(r.Host)
|
||||
if err != nil {
|
||||
address = r.Host
|
||||
err = nil
|
||||
return
|
||||
}
|
||||
if hostPortURL.Opaque == "443" { //https访问
|
||||
if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
|
||||
address = r.Host + ":443"
|
||||
} else {
|
||||
address = r.Host
|
||||
}
|
||||
} else { //http访问
|
||||
if strings.Index(r.Host, ":") == -1 { //host不带端口, 默认80
|
||||
address = r.Host + ":80"
|
||||
} else {
|
||||
address = r.Host
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//读取指定长度内容
|
||||
func (s *Conn) ReadLen(cLen int) ([]byte, error) {
|
||||
if cLen > poolSize {
|
||||
return nil, errors.New("长度错误" + strconv.Itoa(cLen))
|
||||
}
|
||||
var buf []byte
|
||||
if cLen <= poolSizeSmall {
|
||||
buf = BufPoolSmall.Get().([]byte)[:cLen]
|
||||
defer BufPoolSmall.Put(buf)
|
||||
} else {
|
||||
buf = BufPoolMax.Get().([]byte)[:cLen]
|
||||
defer BufPoolMax.Put(buf)
|
||||
}
|
||||
if n, err := io.ReadFull(s, buf); err != nil || n != cLen {
|
||||
return buf, errors.New("读取指定长度错误" + err.Error())
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
//read length or id (content length=4)
|
||||
func (s *Conn) GetLen() (int, error) {
|
||||
val, err := s.ReadLen(4)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return GetLenByBytes(val)
|
||||
}
|
||||
|
||||
//read flag
|
||||
func (s *Conn) ReadFlag() (string, error) {
|
||||
val, err := s.ReadLen(4)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(val), err
|
||||
}
|
||||
|
||||
//read connect status
|
||||
func (s *Conn) GetConnStatus() (id int, status bool, err error) {
|
||||
id, err = s.GetLen()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var b []byte
|
||||
if b, err = s.ReadLen(1); err != nil {
|
||||
return
|
||||
} else {
|
||||
status = GetBoolByStr(string(b[0]))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//设置连接为长连接
|
||||
func (s *Conn) SetAlive() {
|
||||
conn := s.Conn.(*net.TCPConn)
|
||||
conn.SetReadDeadline(time.Time{})
|
||||
conn.SetKeepAlive(true)
|
||||
conn.SetKeepAlivePeriod(time.Duration(2 * time.Second))
|
||||
}
|
||||
|
||||
//set read dead time
|
||||
func (s *Conn) SetReadDeadline(t time.Duration) {
|
||||
s.Conn.(*net.TCPConn).SetReadDeadline(time.Now().Add(time.Duration(t) * time.Second))
|
||||
}
|
||||
|
||||
//单独读(加密|压缩)
|
||||
func (s *Conn) ReadFrom(b []byte, compress int, crypt bool, rate *Rate) (int, error) {
|
||||
if COMPRESS_SNAPY_DECODE == compress {
|
||||
return NewSnappyConn(s.Conn, crypt, rate).Read(b)
|
||||
}
|
||||
return NewCryptConn(s.Conn, crypt, rate).Read(b)
|
||||
}
|
||||
|
||||
//单独写(加密|压缩)
|
||||
func (s *Conn) WriteTo(b []byte, compress int, crypt bool, rate *Rate) (n int, err error) {
|
||||
if COMPRESS_SNAPY_ENCODE == compress {
|
||||
return NewSnappyConn(s.Conn, crypt, rate).Write(b)
|
||||
}
|
||||
return NewCryptConn(s.Conn, crypt, rate).Write(b)
|
||||
}
|
||||
|
||||
//send msg
|
||||
func (s *Conn) SendMsg(content []byte, link *Link) (n int, err error) {
|
||||
/*
|
||||
The msg info is formed as follows:
|
||||
+----+--------+
|
||||
|id | content |
|
||||
+----+--------+
|
||||
| 4 | ... |
|
||||
+----+--------+
|
||||
*/
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(link.Id))
|
||||
if n, err = s.Write(raw.Bytes()); err != nil {
|
||||
return
|
||||
}
|
||||
raw.Reset()
|
||||
binary.Write(raw, binary.LittleEndian, content)
|
||||
n, err = s.WriteTo(raw.Bytes(), link.En, link.Crypt, link.Rate)
|
||||
return
|
||||
}
|
||||
|
||||
//get msg content from conn
|
||||
func (s *Conn) GetMsgContent(link *Link) (content []byte, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
buf := BufPoolCopy.Get().([]byte)
|
||||
if n, err := s.ReadFrom(buf, link.De, link.Crypt, link.Rate); err == nil && n > 4 {
|
||||
content = buf[:n]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//send info for link
|
||||
func (s *Conn) SendLinkInfo(link *Link) (int, error) {
|
||||
/*
|
||||
The link info is formed as follows:
|
||||
+----------+------+----------+------+----------+-----+
|
||||
| id | len | type | hostlen | host | en | de |crypt |
|
||||
+----------+------+----------+------+---------+------+
|
||||
| 4 | 4 | 3 | 4 | host | 1 | 1 | 1 |
|
||||
+----------+------+----------+------+----+----+------+
|
||||
*/
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, []byte(NEW_CONN))
|
||||
binary.Write(raw, binary.LittleEndian, int32(14+len(link.Host)))
|
||||
binary.Write(raw, binary.LittleEndian, int32(link.Id))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(link.ConnType))
|
||||
binary.Write(raw, binary.LittleEndian, int32(len(link.Host)))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(link.Host))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.En)))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(strconv.Itoa(link.De)))
|
||||
binary.Write(raw, binary.LittleEndian, []byte(GetStrByBool(link.Crypt)))
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
func (s *Conn) GetLinkInfo() (link *Link, err error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
var hostLen, n int
|
||||
var buf []byte
|
||||
if n, err = s.GetLen(); err != nil {
|
||||
return
|
||||
}
|
||||
link = new(Link)
|
||||
if buf, err = s.ReadLen(n); err != nil {
|
||||
return
|
||||
}
|
||||
if link.Id, err = GetLenByBytes(buf[:4]); err != nil {
|
||||
return
|
||||
}
|
||||
link.ConnType = string(buf[4:7])
|
||||
if hostLen, err = GetLenByBytes(buf[7:11]); err != nil {
|
||||
return
|
||||
} else {
|
||||
link.Host = string(buf[11 : 11+hostLen])
|
||||
link.En = GetIntNoErrByStr(string(buf[11+hostLen]))
|
||||
link.De = GetIntNoErrByStr(string(buf[12+hostLen]))
|
||||
link.Crypt = GetBoolByStr(string(buf[13+hostLen]))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
//write connect success
|
||||
func (s *Conn) WriteSuccess(id int) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(id))
|
||||
binary.Write(raw, binary.LittleEndian, []byte("1"))
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//write connect fail
|
||||
func (s *Conn) WriteFail(id int) (int, error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
binary.Write(raw, binary.LittleEndian, int32(id))
|
||||
binary.Write(raw, binary.LittleEndian, []byte("0"))
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write(raw.Bytes())
|
||||
}
|
||||
|
||||
//close
|
||||
func (s *Conn) Close() error {
|
||||
return s.Conn.Close()
|
||||
}
|
||||
|
||||
//write
|
||||
func (s *Conn) Write(b []byte) (int, error) {
|
||||
return s.Conn.Write(b)
|
||||
}
|
||||
|
||||
//read
|
||||
func (s *Conn) Read(b []byte) (int, error) {
|
||||
return s.Conn.Read(b)
|
||||
}
|
||||
|
||||
//write error
|
||||
func (s *Conn) WriteError() (int, error) {
|
||||
return s.Write([]byte(RES_MSG))
|
||||
}
|
||||
|
||||
//write sign flag
|
||||
func (s *Conn) WriteSign() (int, error) {
|
||||
return s.Write([]byte(RES_SIGN))
|
||||
}
|
||||
|
||||
//write sign flag
|
||||
func (s *Conn) WriteClose() (int, error) {
|
||||
return s.Write([]byte(RES_CLOSE))
|
||||
}
|
||||
|
||||
//write main
|
||||
func (s *Conn) WriteMain() (int, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write([]byte(WORK_MAIN))
|
||||
}
|
||||
|
||||
//write chan
|
||||
func (s *Conn) WriteChan() (int, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.Write([]byte(WORK_CHAN))
|
||||
}
|
||||
|
||||
//获取长度+内容
|
||||
func GetLenBytes(buf []byte) (b []byte, err error) {
|
||||
raw := bytes.NewBuffer([]byte{})
|
||||
if err = binary.Write(raw, binary.LittleEndian, int32(len(buf))); err != nil {
|
||||
return
|
||||
}
|
||||
if err = binary.Write(raw, binary.LittleEndian, buf); err != nil {
|
||||
return
|
||||
}
|
||||
b = raw.Bytes()
|
||||
return
|
||||
}
|
||||
|
||||
//解析出长度
|
||||
func GetLenByBytes(buf []byte) (int, error) {
|
||||
nlen := binary.LittleEndian.Uint32(buf)
|
||||
if nlen <= 0 {
|
||||
return 0, errors.New("数据长度错误")
|
||||
}
|
||||
return int(nlen), nil
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func InitDaemon(f string) {
|
||||
if len(os.Args) < 2 {
|
||||
return
|
||||
}
|
||||
var args []string
|
||||
args = append(args, os.Args[0])
|
||||
if len(os.Args) >= 2 {
|
||||
args = append(args, os.Args[2:]...)
|
||||
}
|
||||
args = append(args, "-log=file")
|
||||
switch os.Args[1] {
|
||||
case "start":
|
||||
start(args, f)
|
||||
os.Exit(0)
|
||||
case "stop":
|
||||
stop(f, args[0])
|
||||
os.Exit(0)
|
||||
case "restart":
|
||||
stop(f, args[0])
|
||||
start(args, f)
|
||||
os.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
func start(osArgs []string, f string) {
|
||||
cmd := exec.Command(osArgs[0], osArgs[1:]...)
|
||||
cmd.Start()
|
||||
log.Println("执行启动成功")
|
||||
if cmd.Process.Pid > 0 {
|
||||
d1 := []byte(strconv.Itoa(cmd.Process.Pid))
|
||||
ioutil.WriteFile(beego.AppPath+"/proxy_"+f+".pid", d1, 0600)
|
||||
}
|
||||
}
|
||||
|
||||
func stop(f string, p string) {
|
||||
var c *exec.Cmd
|
||||
var err error
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
p := strings.Split(p, `\`)
|
||||
c = exec.Command("taskkill", "/F", "/IM", p[len(p)-1])
|
||||
case "linux", "darwin":
|
||||
b, err := ioutil.ReadFile(beego.AppPath + "/proxy_" + f + ".pid")
|
||||
if err == nil {
|
||||
c = exec.Command("/bin/bash", "-c", `kill -9 `+string(b))
|
||||
} else {
|
||||
log.Println("停止服务失败,pid文件不存在")
|
||||
}
|
||||
}
|
||||
err = c.Run()
|
||||
if err != nil {
|
||||
log.Println("停止服务失败,", err)
|
||||
} else {
|
||||
log.Println("停止服务成功")
|
||||
}
|
||||
}
|
||||
-426
@@ -1,426 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"errors"
|
||||
"github.com/astaxie/beego"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var (
|
||||
CsvDb *Csv
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
func NewCsv() *Csv {
|
||||
return new(Csv)
|
||||
}
|
||||
|
||||
type Csv struct {
|
||||
Tasks []*Tunnel
|
||||
Path string
|
||||
Hosts []*Host //域名列表
|
||||
Clients []*Client //客户端
|
||||
ClientIncreaseId int //客户端id
|
||||
TaskIncreaseId int //任务自增ID
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (s *Csv) Init() {
|
||||
s.LoadClientFromCsv()
|
||||
s.LoadTaskFromCsv()
|
||||
s.LoadHostFromCsv()
|
||||
}
|
||||
|
||||
func (s *Csv) StoreTasksToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(beego.AppPath + "/conf/tasks.csv")
|
||||
if err != nil {
|
||||
Fatalf(err.Error())
|
||||
}
|
||||
defer csvFile.Close()
|
||||
writer := csv.NewWriter(csvFile)
|
||||
for _, task := range s.Tasks {
|
||||
record := []string{
|
||||
strconv.Itoa(task.TcpPort),
|
||||
task.Mode,
|
||||
task.Target,
|
||||
task.Config.U,
|
||||
task.Config.P,
|
||||
task.Config.Compress,
|
||||
GetStrByBool(task.Status),
|
||||
GetStrByBool(task.Config.Crypt),
|
||||
strconv.Itoa(task.Config.CompressEncode),
|
||||
strconv.Itoa(task.Config.CompressDecode),
|
||||
strconv.Itoa(task.Id),
|
||||
strconv.Itoa(task.Client.Id),
|
||||
strconv.FormatBool(task.UseClientCnf),
|
||||
task.Remark,
|
||||
}
|
||||
err := writer.Write(record)
|
||||
if err != nil {
|
||||
Fatalf(err.Error())
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
}
|
||||
|
||||
func (s *Csv) openFile(path string) ([][]string, error) {
|
||||
// 打开文件
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 获取csv的reader
|
||||
reader := csv.NewReader(file)
|
||||
|
||||
// 设置FieldsPerRecord为-1
|
||||
reader.FieldsPerRecord = -1
|
||||
|
||||
// 读取文件中所有行保存到slice中
|
||||
return reader.ReadAll()
|
||||
}
|
||||
|
||||
func (s *Csv) LoadTaskFromCsv() {
|
||||
path := beego.AppPath + "/conf/tasks.csv"
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
Fatalln("配置文件打开错误:", path)
|
||||
}
|
||||
var tasks []*Tunnel
|
||||
// 将每一行数据保存到内存slice中
|
||||
for _, item := range records {
|
||||
post := &Tunnel{
|
||||
TcpPort: GetIntNoErrByStr(item[0]),
|
||||
Mode: item[1],
|
||||
Target: item[2],
|
||||
Config: &Config{
|
||||
U: item[3],
|
||||
P: item[4],
|
||||
Compress: item[5],
|
||||
Crypt: GetBoolByStr(item[7]),
|
||||
CompressEncode: GetIntNoErrByStr(item[8]),
|
||||
CompressDecode: GetIntNoErrByStr(item[9]),
|
||||
},
|
||||
Status: GetBoolByStr(item[6]),
|
||||
Id: GetIntNoErrByStr(item[10]),
|
||||
UseClientCnf: GetBoolByStr(item[12]),
|
||||
Remark: item[13],
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
if post.Client, err = s.GetClient(GetIntNoErrByStr(item[11])); err != nil {
|
||||
continue
|
||||
}
|
||||
tasks = append(tasks, post)
|
||||
if post.Id > s.TaskIncreaseId {
|
||||
s.TaskIncreaseId = post.Id
|
||||
}
|
||||
}
|
||||
s.Tasks = tasks
|
||||
}
|
||||
|
||||
func (s *Csv) GetTaskId() int {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.TaskIncreaseId++
|
||||
return s.TaskIncreaseId
|
||||
}
|
||||
|
||||
func (s *Csv) GetIdByVerifyKey(vKey string, addr string) (int, error) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Clients {
|
||||
if Getverifyval(v.VerifyKey) == vKey && v.Status {
|
||||
if arr := strings.Split(addr, ":"); len(arr) > 0 {
|
||||
v.Addr = arr[0]
|
||||
}
|
||||
return v.Id, nil
|
||||
}
|
||||
}
|
||||
return 0, errors.New("not found")
|
||||
}
|
||||
|
||||
func (s *Csv) NewTask(t *Tunnel) {
|
||||
t.Flow = new(Flow)
|
||||
s.Tasks = append(s.Tasks, t)
|
||||
s.StoreTasksToCsv()
|
||||
}
|
||||
|
||||
func (s *Csv) UpdateTask(t *Tunnel) error {
|
||||
for k, v := range s.Tasks {
|
||||
if v.Id == t.Id {
|
||||
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
|
||||
s.Tasks = append(s.Tasks, t)
|
||||
s.StoreTasksToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) DelTask(id int) error {
|
||||
for k, v := range s.Tasks {
|
||||
if v.Id == id {
|
||||
s.Tasks = append(s.Tasks[:k], s.Tasks[k+1:]...)
|
||||
s.StoreTasksToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) GetTask(id int) (v *Tunnel, err error) {
|
||||
for _, v = range s.Tasks {
|
||||
if v.Id == id {
|
||||
return
|
||||
}
|
||||
}
|
||||
err = errors.New("未找到")
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Csv) StoreHostToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(beego.AppPath + "/conf/hosts.csv")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer csvFile.Close()
|
||||
// 获取csv的Writer
|
||||
writer := csv.NewWriter(csvFile)
|
||||
// 将map中的Post转换成slice,因为csv的Write需要slice参数
|
||||
// 并写入csv文件
|
||||
for _, host := range s.Hosts {
|
||||
record := []string{
|
||||
host.Host,
|
||||
host.Target,
|
||||
strconv.Itoa(host.Client.Id),
|
||||
host.HeaderChange,
|
||||
host.HostChange,
|
||||
host.Remark,
|
||||
}
|
||||
err1 := writer.Write(record)
|
||||
if err1 != nil {
|
||||
panic(err1)
|
||||
}
|
||||
}
|
||||
// 确保所有内存数据刷到csv文件
|
||||
writer.Flush()
|
||||
}
|
||||
|
||||
func (s *Csv) LoadClientFromCsv() {
|
||||
path := beego.AppPath + "/conf/clients.csv"
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
Fatalln("配置文件打开错误:", path)
|
||||
}
|
||||
var clients []*Client
|
||||
// 将每一行数据保存到内存slice中
|
||||
for _, item := range records {
|
||||
post := &Client{
|
||||
Id: GetIntNoErrByStr(item[0]),
|
||||
VerifyKey: item[1],
|
||||
Remark: item[2],
|
||||
Status: GetBoolByStr(item[3]),
|
||||
RateLimit: GetIntNoErrByStr(item[8]),
|
||||
Cnf: &Config{
|
||||
U: item[4],
|
||||
P: item[5],
|
||||
Crypt: GetBoolByStr(item[6]),
|
||||
Compress: item[7],
|
||||
},
|
||||
}
|
||||
if post.Id > s.ClientIncreaseId {
|
||||
s.ClientIncreaseId = post.Id
|
||||
}
|
||||
if post.RateLimit > 0 {
|
||||
post.Rate = NewRate(int64(post.RateLimit * 1024))
|
||||
post.Rate.Start()
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
post.Flow.FlowLimit = int64(GetIntNoErrByStr(item[9]))
|
||||
clients = append(clients, post)
|
||||
}
|
||||
s.Clients = clients
|
||||
}
|
||||
|
||||
func (s *Csv) LoadHostFromCsv() {
|
||||
path := beego.AppPath + "/conf/hosts.csv"
|
||||
records, err := s.openFile(path)
|
||||
if err != nil {
|
||||
Fatalln("配置文件打开错误:", path)
|
||||
}
|
||||
var hosts []*Host
|
||||
// 将每一行数据保存到内存slice中
|
||||
for _, item := range records {
|
||||
post := &Host{
|
||||
Host: item[0],
|
||||
Target: item[1],
|
||||
HeaderChange: item[3],
|
||||
HostChange: item[4],
|
||||
Remark: item[5],
|
||||
}
|
||||
if post.Client, err = s.GetClient(GetIntNoErrByStr(item[2])); err != nil {
|
||||
continue
|
||||
}
|
||||
post.Flow = new(Flow)
|
||||
hosts = append(hosts, post)
|
||||
}
|
||||
s.Hosts = hosts
|
||||
}
|
||||
|
||||
func (s *Csv) DelHost(host string) error {
|
||||
for k, v := range s.Hosts {
|
||||
if v.Host == host {
|
||||
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
|
||||
s.StoreHostToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) NewHost(t *Host) {
|
||||
t.Flow = new(Flow)
|
||||
s.Hosts = append(s.Hosts, t)
|
||||
s.StoreHostToCsv()
|
||||
|
||||
}
|
||||
|
||||
func (s *Csv) UpdateHost(t *Host) error {
|
||||
for k, v := range s.Hosts {
|
||||
if v.Host == t.Host {
|
||||
s.Hosts = append(s.Hosts[:k], s.Hosts[k+1:]...)
|
||||
s.Hosts = append(s.Hosts, t)
|
||||
s.StoreHostToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) GetHost(start, length int, id int) ([]*Host, int) {
|
||||
list := make([]*Host, 0)
|
||||
var cnt int
|
||||
for _, v := range s.Hosts {
|
||||
if id == 0 || v.Client.Id == id {
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, cnt
|
||||
}
|
||||
|
||||
func (s *Csv) DelClient(id int) error {
|
||||
for k, v := range s.Clients {
|
||||
if v.Id == id {
|
||||
s.Clients = append(s.Clients[:k], s.Clients[k+1:]...)
|
||||
s.StoreClientsToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) NewClient(c *Client) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
c.Flow = new(Flow)
|
||||
s.Clients = append(s.Clients, c)
|
||||
s.StoreClientsToCsv()
|
||||
}
|
||||
|
||||
func (s *Csv) GetClientId() int {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.ClientIncreaseId++
|
||||
return s.ClientIncreaseId
|
||||
}
|
||||
|
||||
func (s *Csv) UpdateClient(t *Client) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
for _, v := range s.Clients {
|
||||
if v.Id == t.Id {
|
||||
v.Cnf = t.Cnf
|
||||
v.VerifyKey = t.VerifyKey
|
||||
v.Remark = t.Remark
|
||||
v.RateLimit = t.RateLimit
|
||||
v.Flow = t.Flow
|
||||
v.Rate = t.Rate
|
||||
s.StoreClientsToCsv()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("不存在")
|
||||
}
|
||||
|
||||
func (s *Csv) GetClientList(start, length int) ([]*Client, int) {
|
||||
list := make([]*Client, 0)
|
||||
var cnt int
|
||||
for _, v := range s.Clients {
|
||||
cnt++
|
||||
if start--; start < 0 {
|
||||
if length--; length > 0 {
|
||||
list = append(list, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
return list, cnt
|
||||
}
|
||||
|
||||
func (s *Csv) GetClient(id int) (v *Client, err error) {
|
||||
for _, v = range s.Clients {
|
||||
if v.Id == id {
|
||||
return
|
||||
}
|
||||
}
|
||||
err = errors.New("未找到")
|
||||
return
|
||||
}
|
||||
func (s *Csv) StoreClientsToCsv() {
|
||||
// 创建文件
|
||||
csvFile, err := os.Create(beego.AppPath + "/conf/clients.csv")
|
||||
if err != nil {
|
||||
Fatalln(err.Error())
|
||||
}
|
||||
defer csvFile.Close()
|
||||
writer := csv.NewWriter(csvFile)
|
||||
for _, client := range s.Clients {
|
||||
record := []string{
|
||||
strconv.Itoa(client.Id),
|
||||
client.VerifyKey,
|
||||
client.Remark,
|
||||
strconv.FormatBool(client.Status),
|
||||
client.Cnf.U,
|
||||
client.Cnf.P,
|
||||
GetStrByBool(client.Cnf.Crypt),
|
||||
client.Cnf.Compress,
|
||||
strconv.Itoa(client.RateLimit),
|
||||
strconv.Itoa(int(client.Flow.FlowLimit)),
|
||||
}
|
||||
err := writer.Write(record)
|
||||
if err != nil {
|
||||
Fatalln(err.Error())
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
}
|
||||
|
||||
//init csv from file
|
||||
func GetCsvDb() *Csv {
|
||||
once.Do(func() {
|
||||
CsvDb = NewCsv()
|
||||
CsvDb.Init()
|
||||
})
|
||||
return CsvDb
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Link struct {
|
||||
Id int //id
|
||||
ConnType string //连接类型
|
||||
Host string //目标
|
||||
En int //加密
|
||||
De int //解密
|
||||
Crypt bool //加密
|
||||
Conn *Conn
|
||||
Flow *Flow
|
||||
UdpListener *net.UDPConn
|
||||
Rate *Rate
|
||||
UdpRemoteAddr *net.UDPAddr
|
||||
}
|
||||
|
||||
func NewLink(id int, connType string, host string, en, de int, crypt bool, conn *Conn, flow *Flow, udpListener *net.UDPConn, rate *Rate, UdpRemoteAddr *net.UDPAddr) *Link {
|
||||
return &Link{
|
||||
Id: id,
|
||||
ConnType: connType,
|
||||
Host: host,
|
||||
En: en,
|
||||
De: de,
|
||||
Crypt: crypt,
|
||||
Conn: conn,
|
||||
Flow: flow,
|
||||
UdpListener: udpListener,
|
||||
Rate: rate,
|
||||
UdpRemoteAddr: UdpRemoteAddr,
|
||||
}
|
||||
}
|
||||
|
||||
type Flow struct {
|
||||
ExportFlow int64 //出口流量
|
||||
InletFlow int64 //入口流量
|
||||
FlowLimit int64 //流量限制,出口+入口 /M
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Flow) Add(in, out int) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.InletFlow += int64(in)
|
||||
s.ExportFlow += int64(out)
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
Cnf *Config
|
||||
Id int //id
|
||||
VerifyKey string //验证密钥
|
||||
Addr string //客户端ip地址
|
||||
Remark string //备注
|
||||
Status bool //是否开启
|
||||
IsConnect bool //是否连接
|
||||
RateLimit int //速度限制 /kb
|
||||
Flow *Flow //流量
|
||||
Rate *Rate //速度控制
|
||||
id int
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Client) GetId() int {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.id++
|
||||
return s.id
|
||||
}
|
||||
|
||||
type Tunnel struct {
|
||||
Id int //Id
|
||||
TcpPort int //服务端与客户端通信端口
|
||||
Mode string //启动方式
|
||||
Target string //目标
|
||||
Status bool //是否开启
|
||||
Client *Client //所属客户端id
|
||||
Flow *Flow
|
||||
Config *Config
|
||||
UseClientCnf bool //是否继承客户端配置
|
||||
Remark string //备注
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
U string //socks5验证用户名
|
||||
P string //socks5验证密码
|
||||
Compress string //压缩方式
|
||||
Crypt bool //是否加密
|
||||
CompressEncode int //加密方式
|
||||
CompressDecode int //解密方式
|
||||
}
|
||||
|
||||
type Host struct {
|
||||
Host string //启动方式
|
||||
Target string //目标
|
||||
HeaderChange string //host修改
|
||||
HostChange string //host修改
|
||||
Flow *Flow
|
||||
Client *Client
|
||||
Remark string //备注
|
||||
NowIndex int
|
||||
TargetArr []string
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Host) GetRandomTarget() string {
|
||||
if s.TargetArr == nil {
|
||||
s.TargetArr = strings.Split(s.Target, "\n")
|
||||
}
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
if s.NowIndex >= len(s.TargetArr)-1 {
|
||||
s.NowIndex = 0
|
||||
} else {
|
||||
s.NowIndex++
|
||||
}
|
||||
return s.TargetArr[s.NowIndex]
|
||||
}
|
||||
|
||||
//深拷贝Config
|
||||
func DeepCopyConfig(c *Config) *Config {
|
||||
return &Config{
|
||||
U: c.U,
|
||||
P: c.P,
|
||||
Compress: c.Compress,
|
||||
Crypt: c.Crypt,
|
||||
CompressEncode: c.CompressEncode,
|
||||
CompressDecode: c.CompressDecode,
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
var Log *log.Logger
|
||||
|
||||
func InitLogFile(f string, isStdout bool) {
|
||||
var prefix string
|
||||
if !isStdout {
|
||||
logFile, err := os.OpenFile(beego.AppPath+"/proxy_"+f+"_log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0766)
|
||||
if err != nil {
|
||||
log.Fatalln("open file error !")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
prefix = "\r\n"
|
||||
}
|
||||
Log = log.New(logFile, prefix, log.Ldate|log.Ltime)
|
||||
} else {
|
||||
Log = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
}
|
||||
}
|
||||
|
||||
func Println(v ...interface{}) {
|
||||
Log.Println(v ...)
|
||||
}
|
||||
|
||||
func Fatalln(v ...interface{}) {
|
||||
Log.SetPrefix("error ")
|
||||
Log.Fatalln(v ...)
|
||||
Log.SetPrefix("")
|
||||
}
|
||||
func Fatalf(format string, v ...interface{}) {
|
||||
Log.SetPrefix("error ")
|
||||
Log.Fatalf(format, v...)
|
||||
Log.SetPrefix("")
|
||||
}
|
||||
|
||||
func Printf(format string, v ...interface{}) {
|
||||
Log.Printf(format, v...)
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const poolSize = 64 * 1024
|
||||
const poolSizeSmall = 100
|
||||
const poolSizeUdp = 1472
|
||||
const poolSizeCopy = 32 * 1024
|
||||
|
||||
var BufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, poolSize)
|
||||
},
|
||||
}
|
||||
|
||||
var BufPoolUdp = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, poolSizeUdp)
|
||||
},
|
||||
}
|
||||
var BufPoolMax = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, poolSize)
|
||||
},
|
||||
}
|
||||
var BufPoolSmall = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, poolSizeSmall)
|
||||
},
|
||||
}
|
||||
var BufPoolCopy = sync.Pool{
|
||||
New: func() interface{} {
|
||||
return make([]byte, poolSizeCopy)
|
||||
},
|
||||
}
|
||||
|
||||
func PutBufPoolCopy(buf []byte) {
|
||||
if cap(buf) == poolSizeCopy {
|
||||
BufPoolCopy.Put(buf[:poolSizeCopy])
|
||||
}
|
||||
}
|
||||
-163
@@ -1,163 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
COMPRESS_NONE_ENCODE = iota
|
||||
COMPRESS_NONE_DECODE
|
||||
COMPRESS_SNAPY_ENCODE
|
||||
COMPRESS_SNAPY_DECODE
|
||||
VERIFY_EER = "vkey"
|
||||
WORK_MAIN = "main"
|
||||
WORK_CHAN = "chan"
|
||||
RES_SIGN = "sign"
|
||||
RES_MSG = "msg0"
|
||||
RES_CLOSE = "clse"
|
||||
NEW_CONN = "conn" //新连接标志
|
||||
CONN_SUCCESS = "sucs"
|
||||
CONN_TCP = "tcp"
|
||||
CONN_UDP = "udp"
|
||||
UnauthorizedBytes = `HTTP/1.1 401 Unauthorized
|
||||
Content-Type: text/plain; charset=utf-8
|
||||
WWW-Authenticate: Basic realm="easyProxy"
|
||||
|
||||
401 Unauthorized`
|
||||
IO_EOF = "PROXYEOF"
|
||||
ConnectionFailBytes = `HTTP/1.1 404 Not Found
|
||||
|
||||
`
|
||||
)
|
||||
|
||||
//判断压缩方式
|
||||
func GetCompressType(compress string) (int, int) {
|
||||
switch compress {
|
||||
case "":
|
||||
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
|
||||
case "snappy":
|
||||
return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
|
||||
default:
|
||||
Fatalln("数据压缩格式错误")
|
||||
}
|
||||
return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
|
||||
}
|
||||
|
||||
//通过host获取对应的ip地址
|
||||
func GetHostByName(hostname string) string {
|
||||
if !DomainCheck(hostname) {
|
||||
return hostname
|
||||
}
|
||||
ips, _ := net.LookupIP(hostname)
|
||||
if ips != nil {
|
||||
for _, v := range ips {
|
||||
if v.To4() != nil {
|
||||
return v.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
//检查是否是域名
|
||||
func DomainCheck(domain string) bool {
|
||||
var match bool
|
||||
IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
|
||||
NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
|
||||
match, _ = regexp.MatchString(IsLine, domain)
|
||||
if !match {
|
||||
match, _ = regexp.MatchString(NotLine, domain)
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
//检查basic认证
|
||||
func CheckAuth(r *http.Request, user, passwd string) bool {
|
||||
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
||||
if len(s) != 2 {
|
||||
return false
|
||||
}
|
||||
|
||||
b, err := base64.StdEncoding.DecodeString(s[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pair := strings.SplitN(string(b), ":", 2)
|
||||
if len(pair) != 2 {
|
||||
return false
|
||||
}
|
||||
return pair[0] == user && pair[1] == passwd
|
||||
}
|
||||
|
||||
//get bool by str
|
||||
func GetBoolByStr(s string) bool {
|
||||
switch s {
|
||||
case "1", "true":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//get str by bool
|
||||
func GetStrByBool(b bool) string {
|
||||
if b {
|
||||
return "1"
|
||||
}
|
||||
return "0"
|
||||
}
|
||||
|
||||
//int
|
||||
func GetIntNoErrByStr(str string) int {
|
||||
i, _ := strconv.Atoi(str)
|
||||
return i
|
||||
}
|
||||
|
||||
//简单的一个校验值
|
||||
func Getverifyval(vkey string) string {
|
||||
return Md5(vkey)
|
||||
}
|
||||
|
||||
func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
|
||||
if host != "" {
|
||||
r.Host = host
|
||||
}
|
||||
if header != "" {
|
||||
h := strings.Split(header, "\n")
|
||||
for _, v := range h {
|
||||
hd := strings.Split(v, ":")
|
||||
if len(hd) == 2 {
|
||||
r.Header.Set(hd[0], hd[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
addr = strings.Split(addr, ":")[0]
|
||||
r.Header.Set("X-Forwarded-For", addr)
|
||||
r.Header.Set("X-Real-IP", addr)
|
||||
}
|
||||
|
||||
func ReadAllFromFile(filePath string) ([]byte, error) {
|
||||
f, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ioutil.ReadAll(f)
|
||||
}
|
||||
|
||||
|
||||
// FileExists reports whether the named file or directory exists.
|
||||
func FileExists(name string) bool {
|
||||
if _, err := os.Stat(name); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user