eopll rewrite

This commit is contained in:
aixiao 2020-01-21 19:48:05 +08:00
parent 6f7a666bf3
commit 8a44d18f0e
27 changed files with 1910 additions and 2617 deletions

22
CProxy.ini Normal file
View File

@ -0,0 +1,22 @@
[server]
uid=3004;
process=2;
timer=60;
local_port=9606;
pid_file=CProxy.pid;
[http]
http_ip=192.168.1.102;
http_port=1080;
http_del="x-online-host,X-Online-Host,host,Host";
http_first="[M] [U] [V]\r\nHost: [host]\r\n";
;strrep = "Windows NT 10.0; Win64; x64->Linux";
;regrep = "Host*.+?->Host: iread.wo.cn:443";
[https]
https_ip=192.168.1.102;
https_port=1080;
https_del="Host,host";
https_first="[M] [U]?aixiao.me [V]\r\nHost: [U]\r\n";
;strrep = "Windows NT 10.0; Win64; x64->Linux";
;regrep = "Host*.+?->Host: hu60.cn:443";

View File

@ -3,6 +3,8 @@
[server]模块
uid 设置进程UID
process 进程数
timer 超时
local_port 端口
pid_file PID文件

674
LICENSE
View File

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

View File

@ -2,16 +2,15 @@ CROSS_COMPILE ?=
CC := $(CROSS_COMPILE)gcc
STRIP := $(CROSS_COMPILE)strip
CFLAGS += -g -O2 -Wall -I../iniparser/src -L../iniparser
LIBS = -liniparser -static
OBJ := cproxy
LIBS = -liniparser -pthread -static
OBJ := CProxy
all: cproxy.o conf.o cproxy_request.o cproxy_help.o kill.o
all: proxy.o http.o request.o picohttpparser.o conf.o timeout.o help.o
$(CC) $(CFLAGS) -o $(OBJ) $^ $(LIBS)
$(STRIP) $(OBJ)
-chmod a+x $(OBJ)
.c.o:
$(CC) $(CFLAGS) -c $< $(LIBS)
clean:
rm -rf *.o
rm $(OBJ)

View File

@ -1,10 +1,10 @@
# cproxy
Android本地二级代理.
### CProxy
EPOLL多路复用IO, Android/Linux本地二级代理.
可以修改HTTP协议消息头(request).
可以修改HTTP协议CONNECT方法消息头.
# Build
### Build
git clone https://github.com/niuyuling/cproxy.git
git clone https://github.com/ndevilla/iniparser.git
cd iniparser
@ -12,15 +12,33 @@
cd ../cproxy
make clean; make
# Help Information
cproxy proxy server
windows 10子系统交叉编译:
apt-get install gcc-aarch64-linux-gnu
make clean; CROSS_COMPILE=aarch64-linux-gnu- make
### Help Information
./CProxy -h
CProxy proxy server
Author: aixiao@aixiao.me
Usage: [-?hdsc] [-s signal] [-c filename]
Usage: [-?hpt] [-s signal] [-c filename]
Options:
-?,-h : help information
-d : daemon
-s signal : send signal to a master process: stop, resatrt, reload, status
-c filename : set configuration file (default: conf/cproxy.ini)
-p : process number, default 2 process
-t : timeout minute, default is no timeout
-s signal : send signal to a master process: stop, quit, restart, reload, status
-c filename : set configuration file (default: cproxy.ini)
Jan 13 2020 19:56:06 Compile、link.
#启动
./CProxy -c CProxy.ini
#关闭
./CProxy -s stop
#重启
./CProxy -s reload -c CProxy.ini
or
./CProxy -s restart -c CProxy.ini
#状态
./CProxy -s status
Dec 9 2019 13:36:43 Compile、link.

244
conf.c
View File

@ -1,5 +1,20 @@
#include "conf.h"
char *strncpy_(char *dest, const char *src, size_t n)
{
int size = sizeof(char) * (n + 1);
char *tmp = (char *)malloc(size); // 开辟大小为n+1的临时内存tmp
if (tmp) {
memset(tmp, '\0', size); // 将内存初始化为0
memcpy(tmp, src, size - 1); // 将src的前n个字节拷贝到tmp
memcpy(dest, tmp, size); // 将临时空间tmp的内容拷贝到dest
free(tmp); // 释放内存
return dest;
} else {
return NULL;
}
}
void read_conf(char *file, conf * p)
{
if (access(file, F_OK)) {
@ -12,155 +27,90 @@ void read_conf(char *file, conf * p)
// server module
// uid
p->uid = iniparser_getint(ini, "server:uid", 0);
// process
p->process = iniparser_getint(ini, "server:process", 0);
// timer
p->timer = iniparser_getint(ini, "server:timer", 0);
//local_port
p->server_port = iniparser_getint(ini, "server:local_port", 0);
//pid_file
p->len_server_pid_file =
strlen(iniparser_getstring(ini, "server:pid_file", NULL)) + 1;
p->server_pid_file = (char *)malloc(p->len_server_pid_file);
p->server_pid_file_len = strlen(iniparser_getstring(ini, "server:pid_file", NULL)) + 1;
p->server_pid_file = (char *)malloc(p->server_pid_file_len);
if (p->server_pid_file == NULL) {
goto err;
}
memset(p->server_pid_file, 0, p->len_server_pid_file);
memcpy(p->server_pid_file,
iniparser_getstring(ini, "server:pid_file", NULL),
p->len_server_pid_file);
//printf("%s\n", p->server_pid_file);
memset(p->server_pid_file, 0, p->server_pid_file_len);
memcpy(p->server_pid_file, iniparser_getstring(ini, "server:pid_file", NULL), p->server_pid_file_len);
// http module
// http ip
p->len_http_ip = strlen(iniparser_getstring(ini, "http:http_ip", NULL)) + 1;
p->http_ip = (char *)malloc(p->len_http_ip);
p->http_ip_len = strlen(iniparser_getstring(ini, "http:http_ip", NULL)) + 1;
p->http_ip = (char *)malloc(p->http_ip_len);
if (p->http_ip == NULL) {
goto err;
}
memset(p->http_ip, 0, p->len_http_ip);
memcpy(p->http_ip, iniparser_getstring(ini, "http:http_ip", NULL),
p->len_http_ip);
memset(p->http_ip, 0, p->http_ip_len);
memcpy(p->http_ip, iniparser_getstring(ini, "http:http_ip", NULL), p->http_ip_len);
// http port
p->http_port = iniparser_getint(ini, "http:http_port", 0);
// http del
p->len_http_del =
strlen(iniparser_getstring(ini, "http:http_del", NULL)) + 1;
p->http_del = (char *)malloc(p->len_http_del);
p->http_del_len = strlen(iniparser_getstring(ini, "http:http_del", NULL)) + 1;
p->http_del = (char *)malloc(p->http_del_len);
if (p->http_del == NULL) {
goto err;
}
memset(p->http_del, 0, p->len_http_del);
memcpy(p->http_del, iniparser_getstring(ini, "http:http_del", NULL),
p->len_http_del);
memset(p->http_del, 0, p->http_del_len);
memcpy(p->http_del, iniparser_getstring(ini, "http:http_del", NULL), p->http_del_len);
// http first
p->len_http_first =
strlen(iniparser_getstring(ini, "http:http_first", NULL)) + 1;
p->http_first = (char *)malloc(p->len_http_first);
p->http_first_len = strlen(iniparser_getstring(ini, "http:http_first", NULL)) + 1;
p->http_first = (char *)malloc(p->http_first_len);
if (p->http_first == NULL) {
goto err;
}
memset(p->http_first, 0, p->len_http_first);
memcpy(p->http_first, iniparser_getstring(ini, "http:http_first", NULL),
p->len_http_first);
// https module
// https ip
p->len_https_ip =
strlen(iniparser_getstring(ini, "https:https_ip", NULL)) + 1;
p->https_ip = (char *)malloc(p->len_https_ip);
if (p->https_ip == NULL) {
goto err;
}
memset(p->https_ip, 0, p->len_http_ip);
memcpy(p->https_ip, iniparser_getstring(ini, "https:https_ip", NULL),
p->len_https_ip);
//https port
p->https_port = iniparser_getint(ini, "https:https_port", 0);
// https del
p->len_https_del =
strlen(iniparser_getstring(ini, "https:https_del", NULL)) + 1;
p->https_del = (char *)malloc(p->len_https_del);
if (p->https_del == NULL) {
goto err;
}
memset(p->https_del, 0, p->len_https_del);
memcpy(p->https_del, iniparser_getstring(ini, "https:https_del", NULL),
p->len_https_del);
// https first
p->len_https_first =
strlen(iniparser_getstring(ini, "https:https_first", NULL)) + 1;
p->https_first = (char *)malloc(p->len_https_first);
if (p->https_first == NULL) {
goto err;
}
memset(p->https_first, 0, p->len_https_first);
memcpy(p->https_first, iniparser_getstring(ini, "https:https_first", NULL),
p->len_https_first);
memset(p->http_first, 0, p->http_first_len);
memcpy(p->http_first, iniparser_getstring(ini, "http:http_first", NULL), p->http_first_len);
// http strrep
if (iniparser_find_entry(ini, "http:strrep") == 1) {
p->len_http_strrep =
strlen(iniparser_getstring(ini, "http:strrep", NULL)) + 1;
p->http_strrep = (char *)malloc(p->len_http_strrep);
p->http_strrep_len = strlen(iniparser_getstring(ini, "http:strrep", NULL)) + 1;
p->http_strrep = (char *)malloc(p->http_strrep_len);
if (p->http_strrep == NULL) {
free(p->http_strrep);
}
memset(p->http_strrep, 0, p->len_http_strrep);
memcpy(p->http_strrep, iniparser_getstring(ini, "http:strrep", NULL),
p->len_http_strrep);
memset(p->http_strrep, 0, p->http_strrep_len);
memcpy(p->http_strrep, iniparser_getstring(ini, "http:strrep", NULL), p->http_strrep_len);
char *p1 = strstr(p->http_strrep, "->");
p->http_strrep_aim =
(char *)malloc(strlen(p->http_strrep) - strlen(p1 + 2) - 2 + 1);
p->http_strrep_aim = (char *)malloc(strlen(p->http_strrep) - strlen(p1 + 2) - 2 + 1);
if (p->http_strrep_aim == NULL) {
free(p->http_strrep_aim);
}
strncpy_(p->http_strrep_aim, p->http_strrep,
strlen(p->http_strrep) - strlen(p1 + 2) - 2);
strncpy_(p->http_strrep_aim, p->http_strrep, strlen(p->http_strrep) - strlen(p1 + 2) - 2);
p->http_strrep_obj = (char *)malloc(strlen(p1 + 2) + 1);
if (p->http_strrep_obj == NULL) {
free(p->http_strrep_obj);
}
strncpy_(p->http_strrep_obj, p1 + 2, strlen(p1 + 2));
p->http_strrep_aim_len = strlen(p->http_strrep_aim);
p->http_strrep_obj_len = strlen(p->http_strrep_obj);
}
// https strrep
if (iniparser_find_entry(ini, "https:strrep") == 1) {
p->len_https_strrep =
strlen(iniparser_getstring(ini, "https:strrep", NULL)) + 1;
p->https_strrep = (char *)malloc(p->len_https_strrep);
if (p->https_strrep == NULL) {
free(p->https_strrep);
}
memset(p->https_strrep, 0, p->len_https_strrep);
memcpy(p->https_strrep, iniparser_getstring(ini, "https:strrep", NULL),
p->len_https_strrep);
char *p2 = strstr(p->https_strrep, "->");
p->https_strrep_aim =
(char *)malloc(strlen(p->https_strrep) - strlen(p2 + 2) - 2 + 1);
if (p->https_strrep_aim == NULL) {
free(p->https_strrep_aim);
}
strncpy_(p->https_strrep_aim, p->https_strrep,
strlen(p->https_strrep) - strlen(p2 + 2) - 2);
p->https_strrep_obj = (char *)malloc(strlen(p2 + 2) + 1);
if (p->https_strrep_obj == NULL) {
free(p->https_strrep_obj);
}
strncpy_(p->https_strrep_obj, p2 + 2, strlen(p2 + 2));
}
// http regrep
if (iniparser_find_entry(ini, "http:regrep") == 1) {
p->len_http_regrep =
strlen(iniparser_getstring(ini, "http:regrep", NULL)) + 1;
p->http_regrep = (char *)malloc(p->len_http_regrep);
p->http_regrep_len = strlen(iniparser_getstring(ini, "http:regrep", NULL)) + 1;
p->http_regrep = (char *)malloc(p->http_regrep_len);
if (p->http_regrep == NULL) {
free(p->http_regrep);
}
memset(p->http_regrep, 0, p->len_http_regrep);
memcpy(p->http_regrep, iniparser_getstring(ini, "http:regrep", NULL),
p->len_http_regrep);
memset(p->http_regrep, 0, p->http_regrep_len);
memcpy(p->http_regrep, iniparser_getstring(ini, "http:regrep", NULL), p->http_regrep_len);
char *p3 = strstr(p->http_regrep, "->");
p->http_regrep_aim =
(char *)malloc(strlen(p->http_regrep) - strlen(p3 + 2) - 2 + 1);
@ -174,31 +124,86 @@ void read_conf(char *file, conf * p)
free(p->http_regrep_obj);
}
strncpy_(p->http_regrep_obj, p3 + 2, strlen(p3 + 2));
p->http_regrep_aim_len = strlen(p->http_regrep_aim);
p->http_regrep_obj_len = strlen(p->http_regrep_obj);
}
// https module
// https ip
p->https_ip_len = strlen(iniparser_getstring(ini, "https:https_ip", NULL)) + 1;
p->https_ip = (char *)malloc(p->https_ip_len);
if (p->https_ip == NULL) {
goto err;
}
memset(p->https_ip, 0, p->https_ip_len);
memcpy(p->https_ip, iniparser_getstring(ini, "https:https_ip", NULL), p->https_ip_len);
//https port
p->https_port = iniparser_getint(ini, "https:https_port", 0);
// https del
p->https_del_len = strlen(iniparser_getstring(ini, "https:https_del", NULL)) + 1;
p->https_del = (char *)malloc(p->https_del_len);
if (p->https_del == NULL) {
goto err;
}
memset(p->https_del, 0, p->https_del_len);
memcpy(p->https_del, iniparser_getstring(ini, "https:https_del", NULL), p->https_del_len);
// https first
p->https_first_len = strlen(iniparser_getstring(ini, "https:https_first", NULL)) + 1;
p->https_first = (char *)malloc(p->https_first_len);
if (p->https_first == NULL) {
goto err;
}
memset(p->https_first, 0, p->https_first_len);
memcpy(p->https_first, iniparser_getstring(ini, "https:https_first", NULL), p->https_first_len);
// https strrep
if (iniparser_find_entry(ini, "https:strrep") == 1) {
p->https_strrep_len = strlen(iniparser_getstring(ini, "https:strrep", NULL)) + 1;
p->https_strrep = (char *)malloc(p->https_strrep_len);
if (p->https_strrep == NULL) {
free(p->https_strrep);
}
memset(p->https_strrep, 0, p->https_strrep_len);
memcpy(p->https_strrep, iniparser_getstring(ini, "https:strrep", NULL), p->https_strrep_len);
char *p2 = strstr(p->https_strrep, "->");
p->https_strrep_aim = (char *)malloc(strlen(p->https_strrep) - strlen(p2 + 2) - 2 + 1);
if (p->https_strrep_aim == NULL) {
free(p->https_strrep_aim);
}
strncpy_(p->https_strrep_aim, p->https_strrep, strlen(p->https_strrep) - strlen(p2 + 2) - 2);
p->https_strrep_obj = (char *)malloc(strlen(p2 + 2) + 1);
if (p->https_strrep_obj == NULL) {
free(p->https_strrep_obj);
}
strncpy_(p->https_strrep_obj, p2 + 2, strlen(p2 + 2));
p->https_strrep_aim_len = strlen(p->https_strrep_aim);
p->https_strrep_obj_len = strlen(p->https_strrep_obj);
}
// https regrep
if (iniparser_find_entry(ini, "https:regrep") == 1) {
p->len_https_regrep =
strlen(iniparser_getstring(ini, "https:regrep", NULL)) + 1;
p->https_regrep = (char *)malloc(p->len_https_regrep);
if (p->https_regrep == NULL) {
p->https_regrep_len = strlen(iniparser_getstring(ini, "https:regrep", NULL)) + 1;
p->https_regrep = (char *)malloc(p->https_regrep_len);
if (p->https_regrep == NULL)
free(p->https_regrep);
}
memset(p->https_regrep, 0, p->len_https_regrep);
memcpy(p->https_regrep, iniparser_getstring(ini, "https:regrep", NULL),
p->len_https_regrep);
memset(p->https_regrep, 0, p->https_regrep_len);
memcpy(p->https_regrep, iniparser_getstring(ini, "https:regrep", NULL), p->https_regrep_len);
char *p4 = strstr(p->https_regrep, "->");
p->https_regrep_aim =
(char *)malloc(strlen(p->https_regrep) - strlen(p4 + 2) - 2 + 1);
if (p->https_regrep_aim == NULL) {
p->https_regrep_aim = (char *)malloc(strlen(p->https_regrep) - strlen(p4 + 2) - 2 + 1);
if (p->https_regrep_aim == NULL)
free(p->https_regrep_aim);
}
strncpy_(p->https_regrep_aim, p->https_regrep,
strlen(p->https_regrep) - strlen(p4 + 2) - 2);
strncpy_(p->https_regrep_aim, p->https_regrep, strlen(p->https_regrep) - strlen(p4 + 2) - 2);
p->https_regrep_obj = (char *)malloc(strlen(p4 + 2) + 1);
if (p->https_regrep_obj == NULL) {
if (p->https_regrep_obj == NULL)
free(p->https_regrep_obj);
}
strncpy_(p->https_regrep_obj, p4 + 2, strlen(p4 + 2));
p->https_regrep_aim_len = strlen(p->https_regrep_aim);
p->https_regrep_obj_len = strlen(p->https_regrep_obj);
}
err:
@ -224,6 +229,7 @@ err:
void free_conf(conf * p)
{
free(p->server_pid_file);
free(p->http_ip);
free(p->http_del);
free(p->http_first);

38
conf.h
View File

@ -2,9 +2,45 @@
#define CONF_H
#include "iniparser.h"
#include "cproxy.h"
#include <unistd.h>
// 配置文件结构
typedef struct CONF {
// server module
int uid;
int process;
int timer;
int server_port;
char *server_pid_file;
int server_pid_file_len; // length
// http module
int http_port;
char *http_ip, *http_del, *http_first;
int http_ip_len, http_del_len, http_first_len;
char *http_strrep, *http_regrep;
int http_strrep_len, http_regrep_len;
char *http_strrep_aim, *http_strrep_obj;
int http_strrep_aim_len, http_strrep_obj_len;
char *http_regrep_aim, *http_regrep_obj;
int http_regrep_aim_len, http_regrep_obj_len;
// https module
int https_port;
char *https_ip, *https_del, *https_first;
int https_ip_len, https_del_len, https_first_len;
char *https_strrep, *https_regrep;
int https_strrep_len, https_regrep_len;
char *https_strrep_aim, *https_strrep_obj;
int https_strrep_aim_len, https_strrep_obj_len;
char *https_regrep_aim, *https_regrep_obj;
int https_regrep_aim_len, https_regrep_obj_len;
} conf;
char *strncpy_(char *dest, const char *src, size_t n);
void read_conf(char *file, conf * p);
void free_conf(conf * p);

View File

@ -1,19 +0,0 @@
[server]
uid=3004;
local_port=9606;
pid_file=log/cproxy.pid;
[http]
http_ip=10.0.0.172;
http_port=80;
http_del="x-online-host,X-Online-Host,host,Host";
http_first="[M] [U] [V]\r\n.aixiao.me\rx-online-host: [host]\r\nhost: iread.wo.cn\r\n";
strrep = "Mi MIX 2->Linux";
[https]
https_ip=10.0.0.172;
https_port=80;
https_del=",Host";
https_first="[M] iread.wo.cn//https://[host]:[port]#iread.wo.cn [V]\r\nhost: iread.wo.cn:443\r\n";
strrep = "Mi MIX 2->Linux";
regrep = "Host*.+?->Host: iread.wo.cn:443";

View File

@ -1,17 +0,0 @@
[server]
uid=3004;
local_port=9606;
pid_file=log/cproxy.pid;
[http]
http_ip=10.0.0.172;
http_port=80;
http_del="x-online-host,X-Online-Host,host,Host";
http_first="[M] [U] [V]\r\nhost: [host]\r\n";
[https]
https_ip=192.168.1.102;
https_port=1080;
https_del="Host";
https_first="[M] [U] [V]\r\nhost: [H]\r\n";

438
cproxy.c
View File

@ -1,438 +0,0 @@
#include "cproxy.h"
#include "kill.h"
char *read_data(int client_sock, char *data, int *data_len)
{
char *new_data;
int read_len;
do {
new_data = (char *)realloc(data, *data_len + BUF_SIZE + 1);
if (new_data == NULL) {
free(data);
return NULL;
}
data = new_data;
read_len = read(client_sock, data + *data_len, BUF_SIZE);
if (read_len <= 0) {
if (read_len == 0 || *data_len == 0 || errno != EAGAIN) {
free(data);
return NULL;
}
break;
}
*data_len += read_len;
} while (read_len == BUF_SIZE);
*(data + *data_len) = '\0';
return data;
}
void servertoclient(int remote_sock, int client_sock, char *complete_data,
int *len_complete_data)
{
while ((*len_complete_data =
read(remote_sock, complete_data, BUF_SIZE)) > 0) {
write(client_sock, complete_data, *len_complete_data);
}
return;
}
void clienttoserver(int remote_sock, char *complete_data,
int *len_complete_data)
{
write(remote_sock, complete_data, *len_complete_data);
complete_data = NULL;
complete_data = 0;
return;
}
// 处理客户端的连接
void handle_client(int client_sock, struct sockaddr_in client_addr,
conf * configure)
{
read_data(client_sock, header_buffer, &len_header_buffer); // 第一次读取客户端(浏览器)数据
SIGN = request_type(header_buffer); // 获取请求消息类型
extract_host(header_buffer); // 提取真实Host
replacement_http_head(header_buffer, remote_host, &remote_port, &SIGN,
configure);
//printf("%s", header_buffer);
if ((remote_sock = create_connection(configure, SIGN)) < 0) {
return;
}
if (fork() == 0) {
if (SIGN == HTTP_CONNECT) {
clienttoserver(remote_sock, header_buffer, &len_header_buffer);
forward_data(client_sock, remote_sock);
} else if (SIGN == HTTP_OTHERS || SIGN == HTTP) {
forward_header(remote_sock); //普通的http请求先转发header
forward_data(client_sock, remote_sock);
}
_exit(0);
}
if (fork() == 0) {
if (SIGN == HTTP_CONNECT) {
//servertoclient(remote_sock, client_sock, complete_data, &len_complete_data);
forward_data(remote_sock, client_sock);
} else if (SIGN == HTTP_OTHERS || SIGN == HTTP) {
forward_data(remote_sock, client_sock);
}
_exit(0);
}
close(client_sock);
close(remote_sock);
return;
}
int send_data(int socket, char *buffer, int len)
{
return send(socket, buffer, len, 0);
}
int receive_data(int socket, char *buffer, int len)
{
int n = recv(socket, buffer, len, 0);
return n;
}
void forward_data(int source_sock, int destination_sock)
{
char buffer[BUF_SIZE];
int n;
while ((n = receive_data(source_sock, buffer, BUF_SIZE)) > 0) {
send_data(destination_sock, buffer, n);
}
shutdown(destination_sock, SHUT_RDWR);
shutdown(source_sock, SHUT_RDWR);
return;
}
int create_connection(conf * configure, int SIGN)
{
struct sockaddr_in server_addr;
struct hostent *server = NULL;
int sock;
int optval;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return CLIENT_SOCKET_ERROR;
}
if (SIGN == HTTP_CONNECT) {
if ((server = gethostbyname(configure->https_ip)) == NULL) {
errno = EFAULT;
return CLIENT_RESOLVE_ERROR;
}
} else if (SIGN == HTTP_OTHERS || SIGN == HTTP) {
if ((server = gethostbyname(configure->http_ip)) == NULL) {
errno = EFAULT;
return CLIENT_RESOLVE_ERROR;
}
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
if (SIGN == HTTP_CONNECT) {
server_addr.sin_port = htons(configure->https_port);
} else if (SIGN == HTTP_OTHERS || SIGN == HTTP) {
server_addr.sin_port = htons(configure->http_port);
}
struct linger so_linger;
so_linger.l_onoff = 1;
so_linger.l_linger = 0;
if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &so_linger, sizeof so_linger) <
0) {
return SERVER_SETSOCKOPT_ERROR;
}
if (setsockopt
(server_sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) {
return SERVER_SETSOCKOPT_ERROR;
}
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
return CLIENT_CONNECT_ERROR;
}
return sock;
}
int create_server_socket(int port)
{
int server_sock;
int optval;
struct sockaddr_in server_addr;
if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
return SERVER_SOCKET_ERROR;
}
struct linger so_linger;
so_linger.l_onoff = 1;
so_linger.l_linger = 0;
if (setsockopt
(server_sock, SOL_SOCKET, SO_LINGER, &so_linger,
sizeof so_linger) < 0) {
return SERVER_SETSOCKOPT_ERROR;
}
if (setsockopt
(server_sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) {
return SERVER_SETSOCKOPT_ERROR;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr))
!= 0) {
return SERVER_BIND_ERROR;
}
if (listen(server_sock, 20) < 0) {
return SERVER_LISTEN_ERROR;
}
return server_sock;
}
// 守护
int init_daemon(int nochdir, int noclose, conf * configure, char *path)
{
char *p = strcat(path, configure->server_pid_file);
FILE *fp = fopen(p, "w");
if (fp == NULL) {
fclose(fp);
printf("%s Open Failed\n", p);
exit(1);
}
int pid;
if ((pid = fork()) < 0) {
return -1;
} else if (0 != pid) {
exit(0);
}
//child 1 continues...
//become session leader
if (setsid() < 0) {
return -1;
}
signal(SIGHUP, SIG_IGN);
if ((pid = fork()) < 0) {
return -1;
} else if (0 != pid) {
fprintf(fp, "%d", pid);
exit(0);
}
//child 2 continues...
//change working directory
if (0 == nochdir) {
chdir("/");
}
//redirect stdin,stdout,stderror to "/dev/null"
if (0 == noclose) {
open("/dev/null", O_RDONLY);
open("/dev/null", O_RDWR);
open("/dev/null", O_RDWR);
}
fclose(fp);
return 0;
}
// 处理僵尸进程
void sigchld_handler(int signal)
{
while (waitpid(-1, NULL, WNOHANG) > 0) ;
return;
}
void server_loop(conf * configure)
{
struct sockaddr_in client_addr;
socklen_t addrlen = sizeof(client_addr);
while (1) {
client_sock =
accept(server_sock, (struct sockaddr *)&client_addr, &addrlen);
if (fork() == 0) { // 创建子进程处理客户端连接请求
close(server_sock);
handle_client(client_sock, client_addr, configure);
exit(0);
}
close(client_sock);
}
close(server_sock);
return;
}
void start_server(conf * configure)
{
signal(SIGCHLD, sigchld_handler); // 防止子进程变成僵尸进程
if ((server_sock = create_server_socket(local_port)) < 0) {
exit(server_sock);
}
server_loop(configure);
return;
}
void get_pid(char *proces_name)
{
char bufer[PATH_SIZE];
char comm[PATH_SIZE];
char proc_comm_name[PATH_SIZE];
int num[PATH_SIZE] = { 0 };
int n = 0;
FILE *fp;
DIR *dir;
struct dirent *ptr;
dir = opendir("/proc");
while ((ptr = readdir(dir)) != NULL) {
if (ptr->d_type == 4 && strcasecmp(ptr->d_name, ".")
&& strcasecmp(ptr->d_name, "..")) {
bzero(bufer, 0);
sprintf(comm, "/proc/%s/comm", ptr->d_name);
if (access(comm, F_OK) == 0) {
fp = fopen(comm, "r");
if (fgets(bufer, PATH_SIZE - 1, fp) == NULL) {
fclose(fp);
continue;
}
sscanf(bufer, "%s", proc_comm_name);
if (!strcmp(proces_name, proc_comm_name)) {
num[n] = atoi(ptr->d_name);
n += 1;
}
fclose(fp);
}
}
}
n -= 2; // 去除最后一个搜索时的本身进程
for (; n >= 0; n--) {
printf("\t%d\n", num[n]);
}
closedir(dir);
return;
}
int stop(int signal, char *program_name)
{
if (signal == 1) {
struct passwd *pwent = NULL;
pwent = getpwnam("root");
return kill_all(15, 1, &program_name, pwent);
}
if (signal == 2) {
get_pid(program_name);
return 0;
}
return 0;
}
int get_executable_path(char *processdir, char *processname, int len)
{
char *filename;
if (readlink("/proc/self/exe", processdir, len) <= 0) {
return -1;
}
filename = strrchr(processdir, '/');
if (filename == NULL)
return -1;
++filename;
strcpy(processname, filename);
*filename = '\0';
return (int)(filename - processdir);
}
int _main(int argc, char *argv[])
{
// 初始化全局变量
header_buffer = (char *)malloc(BUF_SIZE);
len_header_buffer = strlen(header_buffer);
char *inifile = "conf/cproxy.ini";
char path[PATH_SIZE] = { 0 };
char executable_filename[PATH_SIZE] = { 0 };
(void)get_executable_path(path, executable_filename, sizeof(path));
inifile = strcat(path, inifile);
conf *configure = (struct CONF *)malloc(sizeof(struct CONF));
read_conf(inifile, configure);
local_port = configure->server_port;
int opt;
char optstrs[] = ":l:ds:c:h?";
while (-1 != (opt = getopt(argc, argv, optstrs))) {
switch (opt) {
case 'l':
local_port = atoi(optarg);
break;
case 'd':
(void)get_executable_path(path, executable_filename, sizeof(path));
init_daemon(1, 1, configure, path);
break;
case 's':
if (strcasecmp(optarg, "stop") == 0
|| strcasecmp(optarg, "quit") == 0) {
free_conf(configure);
free(header_buffer);
exit(stop(1, executable_filename));
}
if (strcasecmp(optarg, "restart") == 0
|| strcasecmp(optarg, "reload") == 0) {
stop(1, executable_filename);
}
if (strcasecmp(optarg, "status") == 0) {
exit(stop(2, executable_filename));
}
break;
case 'c':
free_conf(configure); // 如果指定-c参数就释放上次分配的内存
inifile = optarg;
read_conf(inifile, configure);
break;
case 'h':
case '?':
help_information();
exit(0);
break;
default:
;
}
}
if (setegid(configure->uid) == -1 || seteuid(configure->uid) == -1) // 设置uid
exit(1);
start_server(configure);
free_conf(configure);
free(header_buffer);
return 0;
}
int main(int argc, char *argv[])
{
return _main(argc, argv);
}

104
cproxy.h
View File

@ -1,104 +0,0 @@
#ifndef CPROXY_H
#define CPROXY_H
#include <arpa/inet.h>
#include <errno.h>
#include <libgen.h>
#include <netdb.h>
#include <resolv.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#define PATH_SIZE 270
#define BUF_SIZE 8192
#define BUF_SIZES 1024
#define SERVER_SOCKET_ERROR -1
#define SERVER_SETSOCKOPT_ERROR -2
#define SERVER_BIND_ERROR -3
#define SERVER_LISTEN_ERROR -4
#define CLIENT_SOCKET_ERROR -5
#define CLIENT_RESOLVE_ERROR -6
#define CLIENT_CONNECT_ERROR -7
char remote_host[128];
int remote_port;
int local_port;
int server_sock;
int client_sock;
int remote_sock;
char *header_buffer;
int len_header_buffer;
int SIGN;
// 配置文件结构
typedef struct CONF {
int uid;
int server_port; // server module
char *server_pid_file;
int http_port; // http module
char *http_ip, *http_del, *http_first;
int https_port; // https module
char *https_ip, *https_del, *https_first;
int len_server_pid_file; // length
int len_http_ip, len_http_del, len_http_first;
int len_https_ip, len_https_del, len_https_first;
char *http_strrep, *http_regrep, *https_strrep, *https_regrep;
char *http_strrep_aim, *http_strrep_obj;
char *https_strrep_aim, *https_strrep_obj;
char *http_regrep_aim, *http_regrep_obj;
char *https_regrep_aim, *https_regrep_obj;
int len_http_strrep, len_http_regrep;
int len_https_strrep, len_https_regrep;
} conf;
// 请求类型
#define OTHER 1
#define HTTP 2
#define HTTP_OTHERS 3
#define HTTP_CONNECT 4
char *read_data(int client_sock, char *data, int *data_len);
void servertoclient(int remote_sock, int client_sock, char *complete_data, int *len_complete_data);
void clienttoserver(int remote_sock, char *complete_data, int *len_complete_data);
void handle_client(int client_sock, struct sockaddr_in client_addr, conf *configure);
int send_data(int socket, char *buffer, int len);
int receive_data(int socket, char *buffer, int len);
void forward_data(int source_sock, int destination_sock);
int create_connection(conf *configure, int SIGN);
int create_server_socket(int port);
int init_daemon(int nochdir, int noclose, conf *configure, char *path);
void sigchld_handler(int signal);
void server_loop(conf *configure);
void start_server(conf *configure);
int _main(int argc, char *argv[]);
void read_conf(char *file, conf *p);
void free_conf(conf *p);
int extract_host(char *header);
int replacement_http_head(char *header_buffer, char *remote_host, int *remote_port, int *SIGN, conf *p);
uint8_t request_type(char *req);
void forward_header(int destination_sock);
void rewrite_header();
char help_information(void);
#endif

View File

@ -1,637 +0,0 @@
#include "cproxy_request.h"
// 字符串替换
char *replace(char *replace_memory, int *replace_memory_len, const char *src,
const int src_len, const char *dest, const int dest_len)
{
if (!replace_memory || !src || !dest)
return replace_memory;
char *p;
int diff;
if (src_len == dest_len) {
for (p = memmem(replace_memory, *replace_memory_len, src, src_len); p;
p =
memmem(p, *replace_memory_len - (p - replace_memory), src,
src_len)) {
memcpy(p, dest, dest_len);
p += dest_len;
}
} else if (src_len < dest_len) {
int before_len;
char *before_end, *new_replace_memory;
diff = dest_len - src_len;
for (p = memmem(replace_memory, *replace_memory_len, src, src_len); p;
p =
memmem(p, *replace_memory_len - (p - replace_memory), src,
src_len)) {
*replace_memory_len += diff;
before_len = p - replace_memory;
new_replace_memory =
(char *)realloc(replace_memory, *replace_memory_len + 1);
if (new_replace_memory == NULL) {
free(replace_memory);
return NULL;
}
replace_memory = new_replace_memory;
before_end = replace_memory + before_len;
p = before_end + dest_len;
memmove(p, p - diff, *replace_memory_len - (p - replace_memory));
memcpy(before_end, dest, dest_len);
}
} else if (src_len > dest_len) {
diff = src_len - dest_len;
for (p = memmem(replace_memory, *replace_memory_len, src, src_len); p;
p =
memmem(p, *replace_memory_len - (p - replace_memory), src,
src_len)) {
*replace_memory_len -= diff;
memcpy(p, dest, dest_len);
p += dest_len;
memmove(p, p + diff, *replace_memory_len - (p - replace_memory));
}
}
replace_memory[*replace_memory_len] = '\0';
return replace_memory;
}
/* 正则表达式字符串替换str为可用free释放的指针 */
static char *regrep(char *str, int *str_len, const char *src, char *dest,
int dest_len)
{
if (!str || !src || !dest)
return NULL;
regmatch_t pm[10];
regex_t reg;
char child_num[2] = { '\\', '0' }, *p, *real_dest;
int match_len, real_dest_len, i;
p = str;
regcomp(&reg, src, REG_NEWLINE | REG_ICASE | REG_EXTENDED);
while (regexec(&reg, p, 10, pm, 0) == 0) {
real_dest = (char *)malloc(dest_len);
if (real_dest == NULL) {
regfree(&reg);
free(str);
return NULL;
}
memcpy(real_dest, dest, dest_len);
real_dest_len = dest_len;
//不进行不必要的字符串操作
if (pm[1].rm_so >= 0) {
/* 替换目标字符串中的子表达式 */
for (i = 1; i < 10 && pm[i].rm_so > -1; i++) {
child_num[1] = i + 48;
real_dest =
replace(real_dest, &real_dest_len, child_num, 2,
p + pm[i].rm_so, pm[i].rm_eo - pm[i].rm_so);
if (real_dest == NULL) {
regfree(&reg);
free(str);
return NULL;
}
}
}
match_len = pm[0].rm_eo - pm[0].rm_so;
p += pm[0].rm_so;
//目标字符串不大于匹配字符串则不用分配新内存
if (match_len >= real_dest_len) {
memcpy(p, real_dest, real_dest_len);
if (match_len > real_dest_len)
//strcpy(p + real_dest_len, p + match_len);
memmove(p + real_dest_len, p + match_len,
*str_len - (p + match_len - str));
p += real_dest_len;
*str_len -= match_len - real_dest_len;
} else {
int diff;
char *before_end, *new_str;
diff = real_dest_len - match_len;
*str_len += diff;
new_str = (char *)realloc(str, *str_len + 1);
if (new_str == NULL) {
free(str);
free(real_dest);
regfree(&reg);
return NULL;
}
str = new_str;
before_end = str + pm[0].rm_so;
p = before_end + real_dest_len;
memmove(p, p - diff, *str_len - (p - str) + 1);
memcpy(before_end, real_dest, real_dest_len);
}
free(real_dest);
}
regfree(&reg);
return str;
}
// 删除单个字符
void del_chr(char *s, char ch)
{
char *t = s; // 目标指针先指向原串头
while (*s != '\0') // 遍历字符串s
{
if (*s != ch) // 如果当前字符不是要删除的,则保存到目标串中
*t++ = *s;
s++; // 检查下一个字符
}
*t = '\0'; // 置目标串结束符。
}
// strncpy()封装
char *strncpy_(char *dest, const char *src, size_t n)
{
int size = sizeof(char) * (n + 1);
char *tmp = (char *)malloc(size); // 开辟大小为n+1的临时内存tmp
if (tmp) {
memset(tmp, '\0', size); // 将内存初始化为0
memcpy(tmp, src, size - 1); // 将src的前n个字节拷贝到tmp
memcpy(dest, tmp, size); // 将临时空间tmp的内容拷贝到dest
free(tmp); // 释放内存
return dest;
} else {
return NULL;
}
}
uint8_t request_type(char *req)
{
if (strncmp(req, "GET", 3) == 0 || strncmp(req, "POST", 4) == 0)
return HTTP;
else if (strncmp(req, "CONNECT", 7) == 0)
return HTTP_CONNECT;
else if (strncmp(req, "HEAD", 4) == 0 ||
strncmp(req, "PUT", 3) == 0 ||
strncmp(req, "OPTIONS", 7) == 0 ||
strncmp(req, "MOVE", 4) == 0 ||
strncmp(req, "COPY", 4) == 0 ||
strncmp(req, "TRACE", 5) == 0 ||
strncmp(req, "DELETE", 6) == 0 ||
strncmp(req, "LINK", 4) == 0 ||
strncmp(req, "UNLINK", 6) == 0 ||
strncmp(req, "PATCH", 5) == 0 || strncmp(req, "WRAPPED", 7) == 0)
return HTTP_OTHERS;
else
return OTHER;
}
int extract_host(char *header)
{
char *_p = strstr(header, "CONNECT"); // 在 CONNECT 方法中解析 隧道主机名称及端口号
if (_p) {
char *_p1 = strchr(_p, ' ');
char *_p2 = strchr(_p1 + 1, ':');
char *_p3 = strchr(_p1 + 1, ' ');
if (_p2) {
char s_port[10];
bzero(s_port, 10);
strncpy(remote_host, _p1 + 1, (int)(_p2 - _p1) - 1);
strncpy(s_port, _p2 + 1, (int)(_p3 - _p2) - 1);
remote_port = atoi(s_port);
} else {
strncpy(remote_host, _p1 + 1, (int)(_p3 - _p1) - 1);
remote_port = 80;
}
return 0;
}
char *p = strstr(header, "Host:");
if (!p) {
return -1;
}
char *p1 = strchr(p, '\n');
if (!p1) {
return -1;
}
char *p2 = strchr(p + 5, ':'); // 5是指'Host:'的长度
if (p2 && p2 < p1) {
int p_len = (int)(p1 - p2 - 1);
char s_port[p_len];
strncpy(s_port, p2 + 1, p_len);
s_port[p_len] = '\0';
remote_port = atoi(s_port);
int h_len = (int)(p2 - p - 5 - 1);
strncpy(remote_host, p + 5 + 1, h_len); // Host:
remote_host[h_len] = '\0';
} else {
int h_len = (int)(p1 - p - 5 - 1 - 1);
strncpy(remote_host, p + 5 + 1, h_len);
remote_host[h_len] = '\0';
remote_port = 80;
}
return 0;
}
// 转发头字符串到destination_sock
void forward_header(int destination_sock)
{
rewrite_header();
int len = strlen(header_buffer);
send_data(destination_sock, header_buffer, len);
return;
}
// 代理中的完整URL转发前需改成 path 的形式
void rewrite_header()
{
char *p = strstr(header_buffer, "http://");
char *p0 = strchr(p, '\0');
char *p5 = strstr(header_buffer, "HTTP/"); // "HTTP/" 是协议标识 如 "HTTP/1.1"
int len = strlen(header_buffer);
if (p) {
char *p1 = strchr(p + 7, '/');
if (p1 && (p5 > p1)) {
// 转换url到 path
memcpy(p, p1, (int)(p0 - p1));
int l = len - (p1 - p);
header_buffer[l] = '\0';
} else {
char *p2 = strchr(p, ' '); // GET http://3g.sina.com.cn HTTP/1.1
memcpy(p + 1, p2, (int)(p0 - p2));
*p = '/'; // url 没有路径使用根
int l = len - (p2 - p) + 1;
header_buffer[l] = '\0';
}
}
return;
}
// 判断数字有几位
int numbin(int n)
{
int sum = 0;
while (n) {
sum++;
n /= 10;
}
return sum;
}
// 删除字符串header_buffer中第一位到character处,并拼接string,character为空返回原字符串.(string替换第一个字符到character处)
char *splice_head(char *header_buffer, const char *character, char *string)
{
int len_first = strlen(string);
char *p1 = strstr(header_buffer, character);
if (p1 == NULL) {
return header_buffer;
}
p1 = p1 + 1;
char new_string[len_first + strlen(p1) + 1];
strcpy(new_string, string); // 拼接
return strcat(new_string, p1);
}
// 删除字符串header_buffer中character到string处,character为空返回原字符串.
char *delete_header(char *header_buffer, const char *character, int string)
{
int len_header_buffer = strlen(header_buffer);
char *p1 = strstr(header_buffer, character);
if (p1 == NULL) {
return header_buffer;
}
char *p2 = strchr(p1, string);
int l = len_header_buffer - strlen(p1);
header_buffer[l] = '\0';
return strcat(header_buffer, p2 + 1);
}
char *splice_host_port(char *tmp, char *host, char *port)
{
//memset(tmp, 0, strlen(tmp));
bzero(tmp, strlen(tmp));
strcat(tmp, host);
strcat(tmp, ":");
return strcat(tmp, port);
}
int replacement_http_head(char *header_buffer, char *remote_host,
int *remote_port, int *SIGN, conf * p)
{
char *http_firsts = (char *)malloc(strlen(p->http_first) + 1);
if (http_firsts) {
strcpy(http_firsts, p->http_first); // 拷贝http_first
} else {
free(http_firsts);
return 0;
}
char *https_firsts = (char *)malloc(strlen(p->https_first) + 1);
if (https_firsts) {
strcpy(https_firsts, p->https_first); // 拷贝https_first
} else {
free(https_firsts);
return 0;
}
char *header_buffer_backup = (char *)malloc(strlen(header_buffer) + 1); // 拷贝原字符串
if (header_buffer_backup) {
strcpy(header_buffer_backup, header_buffer);
} else {
free(header_buffer_backup);
return 0;
}
char *new_http_del = malloc(strlen(p->http_del) + 1); // 拷贝http_del
if (new_http_del) {
strcpy(new_http_del, p->http_del);
} else {
free(new_http_del);
return 0;
}
char *new_https_del = malloc(strlen(p->https_del) + 1); // 拷贝https_del
if (new_https_del) {
strcpy(new_https_del, p->https_del);
} else {
free(new_https_del);
return 0;
}
if (*SIGN == HTTP) {
char *result = NULL;
result = strtok(new_http_del, ",");
while (result != NULL) {
delete_header(header_buffer_backup, result, '\n');
result = strtok(NULL, ",");
}
char *p2 = strstr(header_buffer_backup, "\n");
p2 = p2 + 1;
int len_http_head = strlen(header_buffer_backup) - strlen(p2);
char *HTTP_HEAD = (char *)malloc(len_http_head + 1); // http头第一行
if (HTTP_HEAD) {
strncpy_(HTTP_HEAD, header_buffer_backup, len_http_head);
} else {
free(HTTP_HEAD);
return 0;
}
// M
char *p3 = strstr(HTTP_HEAD, " ");
int l = strlen(HTTP_HEAD) - strlen(p3);
char *M = malloc(l + 1);
if (M) {
strncpy_(M, HTTP_HEAD, l);
//printf("%s", M);
} else {
free(M);
return 0;
}
// U
p3 = p3 + 1;
char *p4 = strstr(p3, " ");
l = strlen(p3) - strlen(p4);
char *U = (char *)malloc(l + 1);
if (U) {
strncpy_(U, p3, l);
//printf("%s", U);
} else {
free(U);
return 0;
}
// V
p4 = p4 + 1;
del_chr(p4, '\r');
del_chr(p4, '\n');
l = strlen(p4);
char *V = (char *)malloc(l);
if (V) {
strcpy(V, p4);
//printf("%s", V);
} else {
free(V);
return 0;
}
char *new_header_buffer =
(char *)
malloc(strlen(splice_head(header_buffer_backup, "\n", http_firsts))
+ 1);
if (new_header_buffer) {
strcpy(new_header_buffer,
splice_head(header_buffer_backup, "\n", http_firsts));
} else {
free(new_header_buffer);
return 0;
}
int len = strlen(new_header_buffer);
int len_m = strlen(M);
int len_u = strlen(U);
int len_v = strlen(V);
int len_remote_host = strlen(remote_host);
new_header_buffer =
replace(new_header_buffer, &len, "[M]", 3, M, len_m);
new_header_buffer =
replace(new_header_buffer, &len, "[U]", 3, U, len_u);
new_header_buffer =
replace(new_header_buffer, &len, "[V]", 3, V, len_v);
new_header_buffer =
replace(new_header_buffer, &len, "[host]", 6, remote_host,
len_remote_host);
char port_copy[(numbin(*remote_port) + 2)];
sprintf(port_copy, "%d", *remote_port);
int len_remote_port = strlen(port_copy);
new_header_buffer =
replace(new_header_buffer, &len, "[port]", 6, port_copy,
len_remote_port);
char H[(len_remote_port + len_remote_host) + 1];
splice_host_port(H, remote_host, port_copy);
int len_h = strlen(H);
new_header_buffer =
replace(new_header_buffer, &len, "[H]", 3, H, len_h);
new_header_buffer = replace(new_header_buffer, &len, "\\r", 2, "\r", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\n", 2, "\n", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\b", 2, "\b", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\v", 2, "\v", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\f", 2, "\f", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\a", 2, "\a", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\t", 2, "\t", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\r", 2, "\r", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\n", 2, "\n", 1);
if (p->http_strrep) {
int regrep_aim_len = strlen(p->http_strrep_aim);
int regrep_obj_len = strlen(p->http_strrep_obj);
new_header_buffer =
replace(new_header_buffer, &len, p->http_strrep_aim,
regrep_aim_len, p->http_strrep_obj, regrep_obj_len);
}
if (p->http_regrep) {
len = strlen(new_header_buffer) + 1;
new_header_buffer =
regrep(new_header_buffer, &len, p->http_regrep_aim,
p->http_regrep_obj, strlen(p->http_regrep_obj));
}
//stpcpy(p->http_ip, remote_host);
//p->http_port = *remote_port;
memset(header_buffer, 0, strlen(header_buffer));
strcpy(header_buffer, new_header_buffer);
len_header_buffer = strlen(header_buffer);
free(HTTP_HEAD);
free(M);
free(U);
free(V);
free(new_header_buffer);
} else if (*SIGN == HTTP_CONNECT) {
char *result = NULL;
result = strtok(new_https_del, ",");
while (result != NULL) {
delete_header(header_buffer_backup, result, '\n');
result = strtok(NULL, ",");
}
char *p2 = strstr(header_buffer_backup, "\n");
p2 = p2 + 1;
int len_https_head = strlen(header_buffer_backup) - strlen(p2);
char *HTTPS_HEAD = (char *)malloc(len_https_head + 1); // https头第一行
if (HTTPS_HEAD) {
strncpy_(HTTPS_HEAD, header_buffer_backup, len_https_head);
} else {
free(HTTPS_HEAD);
return 0;
}
// M
char *p3 = strstr(HTTPS_HEAD, " ");
int l = strlen(HTTPS_HEAD) - strlen(p3);
char *M = malloc(l + 1);
if (M) {
strncpy_(M, HTTPS_HEAD, l);
} else {
free(M);
return 0;
}
// U
p3 = p3 + 1;
char *p4 = strstr(p3, " ");
l = strlen(p3) - strlen(p4);
char *U = (char *)malloc(l + 1);
if (U) {
strncpy_(U, p3, l);
//printf("%s", U);
} else {
free(U);
return 0;
}
// V
p4 = p4 + 1;
l = strlen(p4);
char *V = (char *)malloc(l);
if (V) {
strncpy_(V, p4, 8);
//printf("%s", V);
} else {
free(V);
return 0;
}
char *new_header_buffer =
(char *)
malloc(strlen(splice_head(header_buffer_backup, "\n", https_firsts))
+ 1);
if (new_header_buffer) {
strcpy(new_header_buffer,
splice_head(header_buffer_backup, "\n", https_firsts));
} else {
free(new_header_buffer);
return 0;
}
int len = strlen(new_header_buffer);
int len_m = strlen(M);
int len_u = strlen(U);
int len_v = strlen(V);
int len_remote_host = strlen(remote_host);
new_header_buffer =
replace(new_header_buffer, &len, "[M]", 3, M, len_m);
new_header_buffer =
replace(new_header_buffer, &len, "[U]", 3, U, len_u);
new_header_buffer =
replace(new_header_buffer, &len, "[V]", 3, V, len_v);
new_header_buffer =
replace(new_header_buffer, &len, "[host]", 6, remote_host,
len_remote_host);
char port_copy[(numbin(*remote_port) + 2)];
sprintf(port_copy, "%d", *remote_port);
int len_remote_port = strlen(port_copy);
new_header_buffer =
replace(new_header_buffer, &len, "[port]", 6, port_copy,
len_remote_port);
char H[(len_remote_port + len_remote_host) + 1];
splice_host_port(H, remote_host, port_copy);
int len_h = strlen(H);
new_header_buffer =
replace(new_header_buffer, &len, "[H]", 3, H, len_h);
new_header_buffer = replace(new_header_buffer, &len, "\\r", 2, "\r", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\n", 2, "\n", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\b", 2, "\b", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\v", 2, "\v", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\f", 2, "\f", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\a", 2, "\a", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\t", 2, "\t", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\r", 2, "\r", 1);
new_header_buffer = replace(new_header_buffer, &len, "\\n", 2, "\n", 1);
if (p->https_strrep) {
int regrep_aim_len = strlen(p->https_strrep_aim);
int regrep_obj_len = strlen(p->https_strrep_obj);
new_header_buffer =
replace(new_header_buffer, &len, p->https_strrep_aim,
regrep_aim_len, p->https_strrep_obj, regrep_obj_len);
}
if (p->https_regrep) {
len = strlen(new_header_buffer) + 1;
new_header_buffer =
regrep(new_header_buffer, &len, p->https_regrep_aim,
p->https_regrep_obj, strlen(p->https_regrep_obj));
}
//stpcpy(p->https_ip, remote_host); // 走真实IP非代理
//p->https_port = *remote_port;
memset(header_buffer, 0, strlen(header_buffer));
memcpy(header_buffer, new_header_buffer, strlen(new_header_buffer));
len_header_buffer = strlen(header_buffer);
free(HTTPS_HEAD);
free(M);
free(U);
free(V);
free(new_header_buffer);
}
free(http_firsts);
free(https_firsts);
free(new_http_del);
free(new_https_del);
free(header_buffer_backup);
return 1;
}

View File

@ -1,25 +0,0 @@
#ifndef CPROXY_REQUEST_H
#define CPROXY_REQUEST_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include "cproxy.h"
void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen);
char *replace(char *replace_memory, int *replace_memory_len, const char *src, const int src_len, const char *dest, const int dest_len);
void del_chr(char *s, char ch);
char *strncpy_(char *dest, const char *src, size_t n);
uint8_t request_type(char *req);
int extract_host(char *header);
void forward_header(int destination_sock);
void rewrite_header();
int numbin(int n);
char *splice_head(char *header_buffer, const char *character, char *string);
char *delete_header(char *header_buffer, const char *character, int string);
char *splice_host_port(char *tmp, char *host, char *port);
int replacement_http_head(char *header_buffer, char *remote_host, int *remote_port, int *SIGN, conf *p);
#endif

View File

@ -1,31 +1,30 @@
#include "cproxy_help.h"
#include "help.h"
char help_information(void)
{
static const char name[] = "cproxy";
static const char name[] = "CProxy";
static const char subject[] = "proxy server";
static const struct {
const char *a, *b, *c, *d;
const char *email;
} author = {
"aixiao@aixiao.me", "aixiao", "Author:", "Email :",
"aixiao@aixiao.me",
};
static const char usage[] = "Usage: [-?hd] [-s signal] [-c filename]";
static const char usage[] = "Usage: [-?hpt] [-s signal] [-c filename]";
static const char *s_help[] = {
"",
"Options:",
" -?,-h : help information",
" -d : daemon",
" -p : process number, default 2 process",
" -t : timeout minute, default is no timeout",
" -s signal : send signal to a master process: stop, quit, restart, reload, status",
" -c filename : set configuration file (default: conf/cproxy.ini)",
" -c filename : set configuration file, default CProxy.ini",
"",
0
};
//fprintf(stderr, "%s %s\n", author.c, author.b);
fprintf(stderr, "%s %s\n", name, subject);
fprintf(stderr, "%s %s\n", author.c, author.a);
fprintf(stderr, "Author: %s\n", author.email);
fprintf(stderr, "%s\n", usage);
int l;

View File

@ -1,8 +1,7 @@
#ifndef CPROXY_HELP
#define CPROXY_HELP
#ifndef HELP_H
#define HELP_H
#include <stdio.h>
#include "cproxy.h"
#define BUILD(fmt...) do { fprintf(stderr,"%s %s ",__DATE__,__TIME__); fprintf(stderr, ##fmt); } while(0)
char help_information(void);

191
http.c Normal file
View File

@ -0,0 +1,191 @@
#include "http.h"
#include "proxy.h"
static char *read_data(conn *in, char *data, int *data_len)
{
char *new_data;
int read_len;
do {
new_data = (char *)realloc(data, *data_len + BUFFER_SIZE + 1);
if (new_data == NULL) {
free(data);
return NULL;
}
data = new_data;
read_len = read(in->fd, data + *data_len, BUFFER_SIZE);
// 判断是否关闭连接
if (read_len <= 0) {
if (read_len == 0 || *data_len == 0 || errno != EAGAIN) {
free(data);
return NULL;
}
break;
}
*data_len += read_len;
} while (read_len == BUFFER_SIZE);
*(data + *data_len) = '\0';
return data;
}
void close_connection(conn *conn)
{
epoll_ctl(epollfd, EPOLL_CTL_DEL, conn->fd, NULL);
close(conn->fd);
if ((conn - cts) & 1) {
char *server_data;
server_data = conn->header_buffer;
memset(conn, 0, sizeof(*conn));
conn->header_buffer = server_data;
conn--->fd = -1;
} else {
free(conn->header_buffer);
memset(conn, 0, sizeof(*conn));
conn++->fd = -1;
}
if (conn->fd >= 0)
close_connection(conn);
}
static void serverToClient(conn *server)
{
int write_len;
conn *client;
client = server - 1;
while ((server->header_buffer_len = read(server->fd, server->header_buffer, BUFFER_SIZE)) > 0) {
write_len = write(client->fd, server->header_buffer, server->header_buffer_len);
if (write_len <= 0) {
if (write_len == 0 || errno != EAGAIN)
close_connection(server);
else
server->sent_len = 0;
return;
} else if (write_len < server->header_buffer_len) {
server->sent_len = write_len;
ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
ev.data.ptr = client;
epoll_ctl(epollfd, EPOLL_CTL_MOD, client->fd, &ev);
return;
}
if (server->header_buffer_len < BUFFER_SIZE)
break;
}
if (server->header_buffer_len == 0
|| (server->header_buffer_len == -1 && errno != EAGAIN))
close_connection(server);
else
server->header_buffer_len = server->sent_len = 0;
}
void clienttoserver(conn *in)
{
int write_len;
conn *remote;
remote = in + 1;
write_len = write(remote->fd, in->header_buffer, in->header_buffer_len);
if (write_len == in->header_buffer_len) {
in->header_buffer_len = 0;
in->header_buffer = NULL;
} else {
close_connection(remote);
}
return;
}
// 判断请求类型
static int8_t request_type(char *data)
{
if (strncmp(data, "GET", 3) == 0 ||
strncmp(data, "POST", 4) == 0 ||
strncmp(data, "CONNECT", 7) == 0 ||
strncmp(data, "HEAD", 4) == 0 ||
strncmp(data, "PUT", 3) == 0 ||
strncmp(data, "OPTIONS", 7) == 0 ||
strncmp(data, "MOVE", 4) == 0 ||
strncmp(data, "COPY", 4) == 0 ||
strncmp(data, "TRACE", 5) == 0 ||
strncmp(data, "DELETE", 6) == 0 ||
strncmp(data, "LINK", 4) == 0 ||
strncmp(data, "UNLINK", 6) == 0 ||
strncmp(data, "PATCH", 5) == 0 ||
strncmp(data, "WRAPPED", 7) == 0)
return HTTP_TYPE;
return OTHER_TYPE;
}
void tcp_in(conn *in, conf *configure)
{
if (in->fd < 0)
return;
// 如果in - cts是奇数,那么是服务端触发事件
if ((in - cts) & 1) {
in->timer = (in-1)->timer = 0;
serverToClient(in);
return;
}
in->timer = (in+1)->timer = 0;
in->header_buffer = read_data(in, in->header_buffer, &in->header_buffer_len);
if (in->header_buffer != NULL) {
if (request_type(in->header_buffer) == HTTP_TYPE) {
in->header_buffer = request_head(in, configure);
struct epoll_event epollEvent;
conn *remote;
remote = in + 1;
remote->fd = create_connection(remote_host, remote_port);
epollEvent.events = EPOLLIN|EPOLLOUT|EPOLLET;
epollEvent.data.ptr = remote;
epoll_ctl(epollfd, EPOLL_CTL_ADD, remote->fd, &epollEvent);
}
}
clienttoserver(in);
return;
}
void tcp_out(conn *out)
{
conn *from;
int write_len;
if (out->fd == -1)
return;
else if ((out - cts) & 1)
from = out - 1;
else
from = out + 1;
from->timer = out->timer = 0;
write_len = write(out->fd, from->header_buffer + from->sent_len, from->header_buffer_len - from->sent_len);
if (write_len == from->header_buffer_len - from->sent_len) {
// 服务端的数据可能没全部写入到客户端
if ((from - cts) & 1) {
serverToClient(from);
if (from->fd >= 0 && from->header_buffer == 0) {
ev.events = EPOLLIN | EPOLLET;
ev.data.ptr = out;
epoll_ctl(epollfd, EPOLL_CTL_MOD, out->fd, &ev);
}
} else {
ev.events = EPOLLIN | EPOLLET;
ev.data.ptr = out;
epoll_ctl(epollfd, EPOLL_CTL_MOD, out->fd, &ev);
free(from->header_buffer);
from->header_buffer = NULL;
from->header_buffer_len = 0;
}
} else if (write_len > 0) {
from->sent_len += write_len;
ev.events = EPOLLIN | EPOLLOUT | EPOLLET;
ev.data.ptr = out;
epoll_ctl(epollfd, EPOLL_CTL_MOD, out->fd, &ev);
} else if (errno != EAGAIN) {
close_connection(out);
}
return;
}

28
http.h Normal file
View File

@ -0,0 +1,28 @@
#ifndef HTTP_H
#define HTTP_H
#include "conf.h"
#include "proxy.h"
#define HTTP_TYPE 0
#define OTHER_TYPE 1
int remote_port;
char remote_host[128];
typedef struct conn_t {
int fd;
char *header_buffer;
int header_buffer_len, sent_len, timer;
} conn;
extern conn cts[MAX_CONNECTION];
extern void tcp_in(conn *in, conf *configure);
extern void tcp_out(conn *out);
extern void clienttoserver(conn *in);
extern void close_connection(conn *conn);
extern char *request_head(conn *in, conf *configure);
#endif

489
kill.c
View File

@ -1,489 +0,0 @@
#include "kill.h"
static pid_t opt_ns_pid = 0;
static int exact = 1, reg = 0, wait_until_dead = 1, process_group =
0, ignore_case = 0;
static long younger_than = 0, older_than = 0;
typedef struct NAMEINFO {
const char *name;
int name_length;
struct stat st;
} NAMEINFO;
static double uptime()
{
char *savelocale;
char buf[2048];
FILE *file;
if (!(file = fopen(PROC_BASE "/uptime", "r"))) {
exit(1);
}
savelocale = setlocale(LC_NUMERIC, "C");
if (fscanf(file, "%2047s", buf) == EOF)
perror("uptime");
fclose(file);
setlocale(LC_NUMERIC, savelocale);
return atof(buf);
}
static double process_age(const unsigned long long jf)
{
double age;
double sc_clk_tck = sysconf(_SC_CLK_TCK);
assert(sc_clk_tck > 0);
age = uptime() - jf / sc_clk_tck;
if (age < 0L)
return 0L;
return age;
}
enum ns_type {
IPCNS = 0,
MNTNS,
NETNS,
PIDNS,
USERNS,
UTSNS
};
static const char *ns_names[] = {
[IPCNS] = "ipc",
[MNTNS] = "mnt",
[NETNS] = "net",
[PIDNS] = "pid",
[USERNS] = "user",
[UTSNS] = "uts",
};
const char *get_ns_name(int id)
{
if (id >= 6)
return NULL;
return ns_names[id];
}
static int get_ns(pid_t pid, int id)
{
struct stat st;
char buff[50];
snprintf(buff, sizeof(buff), "/proc/%i/ns/%s", pid, get_ns_name(id));
if (stat(buff, &st))
return 0;
else
return st.st_ino;
}
static int match_process_uid(pid_t pid, uid_t uid)
{
char buf[128];
uid_t puid;
FILE *f;
int re = -1;
snprintf(buf, sizeof buf, PROC_BASE "/%d/status", pid);
if (!(f = fopen(buf, "r")))
return 0;
while (fgets(buf, sizeof buf, f)) {
if (sscanf(buf, "Uid:\t%d", &puid)) {
re = uid == puid;
break;
}
}
fclose(f);
if (re == -1) {
exit(1);
}
return re;
}
static void free_regexp_list(regex_t * reglist, int names)
{
int i;
for (i = 0; i < names; i++)
regfree(&reglist[i]);
free(reglist);
}
static regex_t *build_regexp_list(int names, char **namelist)
{
int i;
regex_t *reglist;
int flag = REG_EXTENDED | REG_NOSUB;
if (!(reglist = malloc(sizeof(regex_t) * names))) {
perror("malloc");
exit(1);
}
if (ignore_case)
flag |= REG_ICASE;
for (i = 0; i < names; i++) {
if (regcomp(&reglist[i], namelist[i], flag) != 0) {
free_regexp_list(reglist, i);
exit(1);
}
}
return reglist;
}
static NAMEINFO *build_nameinfo(const int names, char **namelist)
{
int i;
NAMEINFO *ni = NULL;
if ((ni = malloc(sizeof(NAMEINFO) * names)) == NULL)
return NULL;
for (i = 0; i < names; i++) {
ni[i].name = namelist[i];
ni[i].st.st_dev = 0;
if (!strchr(namelist[i], '/')) {
ni[i].name_length = strlen(namelist[i]);
} else if (stat(namelist[i], &(ni[i].st)) < 0) {
perror(namelist[i]);
free(ni);
return NULL;
}
}
return ni;
}
static int
load_process_name_and_age(char *comm, double *process_age_sec,
const pid_t pid, int load_age)
{
FILE *file;
char *path;
char buf[1024];
char *startcomm, *endcomm;
unsigned lencomm;
*process_age_sec = 0;
if (asprintf(&path, PROC_BASE "/%d/stat", pid) < 0)
return -1;
if (!(file = fopen(path, "r"))) {
free(path);
return -1;
}
free(path);
if (fgets(buf, 1024, file) == NULL) {
fclose(file);
return -1;
}
fclose(file);
startcomm = strchr(buf, '(') + 1;
endcomm = strrchr(startcomm, ')');
lencomm = endcomm - startcomm;
if (lencomm < 0)
lencomm = 0;
if (lencomm > COMM_LEN - 1)
lencomm = COMM_LEN - 1;
strncpy(comm, startcomm, lencomm);
comm[lencomm] = '\0';
endcomm += 2; // skip ") "
if (load_age) {
unsigned long long proc_stt_jf = 0;
if (sscanf
(endcomm,
"%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %Lu",
&proc_stt_jf) != 1) {
return -1;
}
*process_age_sec = process_age(proc_stt_jf);
}
return lencomm;
}
static int
load_proc_cmdline(const pid_t pid, const char *comm, char **command,
int *got_long)
{
FILE *file;
char *path, *p, *command_buf;
int cmd_size = 128;
int okay;
if (asprintf(&path, PROC_BASE "/%d/cmdline", pid) < 0)
return -1;
if (!(file = fopen(path, "r"))) {
free(path);
return -1;
}
free(path);
if ((command_buf = (char *)malloc(cmd_size)) == NULL)
exit(1);
while (1) {
for (p = command_buf;; p++) {
int c;
if (p == (command_buf + cmd_size)) {
char *new_command_buf;
int cur_size = cmd_size;
cmd_size *= 2;
new_command_buf = (char *)realloc(command_buf, cmd_size);
if (!new_command_buf) {
if (command_buf)
free(command_buf);
exit(1);
}
command_buf = new_command_buf;
p = command_buf + cur_size;
}
c = fgetc(file);
if (c == EOF || c == '\0') {
*p = '\0';
break;
} else {
*p = c;
}
}
if (strlen(command_buf) == 0) {
okay = 0;
break;
}
p = strrchr(command_buf, '/');
p = p ? p + 1 : command_buf;
if (strncmp(p, comm, COMM_LEN - 1) == 0) {
okay = 1;
if (!(*command = strdup(p))) {
free(command_buf);
exit(1);
}
break;
}
}
(void)fclose(file);
free(command_buf);
command_buf = NULL;
if (exact && !okay) {
*got_long = okay;
return -1;
}
*got_long = okay;
return 0;
}
static pid_t *create_pid_table(int *max_pids, int *pids)
{
pid_t self, *pid_table;
int pid;
DIR *dir;
struct dirent *de;
self = getpid();
if (!(dir = opendir(PROC_BASE))) {
perror(PROC_BASE);
exit(1);
}
*max_pids = 256;
pid_table = malloc(*max_pids * sizeof(pid_t));
if (!pid_table) {
perror("malloc");
exit(1);
}
*pids = 0;
while ((de = readdir(dir)) != NULL) {
if (!(pid = (pid_t) atoi(de->d_name)) || pid == self)
continue;
if (*pids == *max_pids) {
if (!(pid_table = realloc(pid_table, 2 * *pids * sizeof(pid_t)))) {
perror("realloc");
exit(1);
}
*max_pids *= 2;
}
pid_table[(*pids)++] = pid;
}
(void)closedir(dir);
return pid_table;
}
#define strcmp2(A,B,I) (I? strcasecmp((A),(B)):strcmp((A),(B)))
#define strncmp2(A,B,L,I) (I? strncasecmp((A),(B),(L)):strncmp((A),(B),(L)))
static int match_process_name(const char *proc_comm,
const int comm_len,
const char *proc_cmdline,
const char *match_name,
const int match_len, const int got_long)
{
if (comm_len == OLD_COMM_LEN - 1 && match_len >= OLD_COMM_LEN - 1) {
if (got_long) {
return (0 == strncmp2(match_name, proc_cmdline, OLD_COMM_LEN - 1,
ignore_case));
} else {
return (0 == strncmp2(match_name, proc_comm, OLD_COMM_LEN - 1,
ignore_case));
}
}
if (comm_len == COMM_LEN - 1 && match_len >= COMM_LEN - 1) {
if (got_long) {
return (0 == strncmp2(match_name, proc_cmdline, COMM_LEN - 1,
ignore_case));
} else {
return (0 == strncmp2(match_name, proc_comm, COMM_LEN - 1,
ignore_case));
}
}
if (got_long) {
return (0 == strcmp2(match_name, proc_cmdline, ignore_case));
}
return (0 == strcmp2(match_name, proc_comm, ignore_case));
}
int kill_all(int signal, int name_count, char **namelist, struct passwd *pwent)
{
struct stat st;
NAMEINFO *name_info = NULL;
char *path, comm[COMM_LEN];
char *command = NULL;
pid_t *pid_table, *pid_killed;
pid_t *pgids = NULL;
int i, j, length, got_long, error;
int pids, max_pids, pids_killed;
unsigned long found;
regex_t *reglist = NULL;
long ns_ino = 0;
if (opt_ns_pid)
ns_ino = get_ns(opt_ns_pid, PIDNS);
if (name_count && reg)
reglist = build_regexp_list(name_count, namelist);
else if ((name_info = build_nameinfo(name_count, namelist)) == NULL)
exit(1);
pid_table = create_pid_table(&max_pids, &pids);
found = 0;
pids_killed = 0;
pid_killed = malloc(max_pids * sizeof(pid_t));
if (!pid_killed) {
perror("malloc");
exit(1);
}
if (process_group) {
pgids = calloc(pids, sizeof(pid_t));
if (!pgids) {
perror("malloc");
exit(1);
}
}
got_long = 0;
for (i = 0; i < pids; i++) {
pid_t id;
int found_name = -1;
double process_age_sec = 0;
if (pwent && match_process_uid(pid_table[i], pwent->pw_uid) == 0)
continue;
if (opt_ns_pid && ns_ino && ns_ino != get_ns(pid_table[i], PIDNS))
continue;
length =
load_process_name_and_age(comm, &process_age_sec, pid_table[i],
(younger_than || older_than));
if (length < 0)
continue;
if (younger_than && (process_age_sec > younger_than))
continue;
if (older_than && (process_age_sec < older_than))
continue;
got_long = 0;
if (command) {
free(command);
command = NULL;
}
if (length == COMM_LEN - 1)
if (load_proc_cmdline(pid_table[i], comm, &command, &got_long) < 0)
continue;
for (j = 0; j < name_count; j++) {
if (reg) {
if (regexec(&reglist[j], got_long ? command : comm, 0, NULL, 0)
!= 0)
continue;
} else {
if (!name_info[j].st.st_dev) {
if (!match_process_name(comm, length, command, namelist[j],
name_info[j].name_length, got_long))
continue;
} else {
int ok = 1;
if (asprintf(&path, PROC_BASE "/%d/exe", pid_table[i]) < 0)
continue;
if (stat(path, &st) < 0)
ok = 0;
else if (name_info[j].st.st_dev != st.st_dev ||
name_info[j].st.st_ino != st.st_ino) {
size_t len = strlen(namelist[j]);
char *linkbuf = malloc(len + 1);
if (!linkbuf ||
readlink(path, linkbuf, len + 1) != (ssize_t) len ||
memcmp(namelist[j], linkbuf, len))
ok = 0;
free(linkbuf);
}
free(path);
if (!ok)
continue;
}
}
found_name = j;
break;
}
if (name_count && found_name == -1)
continue;
if (!process_group)
id = pid_table[i];
else {
int j;
id = getpgid(pid_table[i]);
pgids[i] = id;
for (j = 0; j < i; j++)
if (pgids[j] == id)
break;
if (j < i)
continue;
}
if (kill(process_group ? -id : id, signal) >= 0) {
if (found_name >= 0)
found |= 1UL << found_name;
pid_killed[pids_killed++] = id;
}
}
if (command)
free(command);
if (reglist)
free_regexp_list(reglist, name_count);
free(pgids);
if (name_count)
error =
found ==
((1UL << (name_count - 1)) | ((1UL << (name_count - 1)) - 1)) ? 0 :
1;
else
error = pids_killed ? 0 : 1;
while (pids_killed && wait_until_dead) {
for (i = 0; i < pids_killed;) {
if (kill(process_group ? -pid_killed[i] : pid_killed[i], 0) < 0 &&
errno == ESRCH) {
pid_killed[i] = pid_killed[--pids_killed];
continue;
}
i++;
}
//sleep(1);
}
free(pid_killed);
free(pid_table);
free(name_info);
return error;
}

60
kill.h
View File

@ -1,60 +0,0 @@
#ifndef KILL_H
#define KILL_H
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <getopt.h>
#include <pwd.h>
#include <regex.h>
#include <ctype.h>
#include <assert.h>
#include <locale.h>
#define COMM_LEN 64
#define OLD_COMM_LEN 16
#define _(String) (String)
#define rpmatch(line) \
( (line == NULL)? -1 : \
(*line == 'y' || *line == 'Y')? 1 : \
(*line == 'n' || *line == 'N')? 0 : \
-1 )
#define PROC_BASE "/proc"
#define MAX_NAMES (int)(sizeof(unsigned long)*8)
#define TSECOND "s"
#define TMINUTE "m"
#define THOUR "h"
#define TDAY "d"
#define TWEEK "w"
#define TMONTH "M"
#define TYEAR "y"
#define TMAX_SECOND 31536000
#define TMAX_MINUTE 525600
#define TMAX_HOUR 8760
#define TMAX_DAY 365
#define TMAX_WEEK 48
#define TMAX_MONTH 12
#define TMAX_YEAR 1
#define ER_REGFAIL -1
#define ER_NOMEM -2
#define ER_UNKWN -3
#define ER_OOFRA -4
int kill_all(int signal, int name_count, char **namelist, struct passwd *pwent);
#endif

645
picohttpparser.c Normal file
View File

@ -0,0 +1,645 @@
/*
* Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase,
* Shigeo Mitsunari
*
* The software is licensed under either the MIT License (below) or the Perl
* license.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <assert.h>
#include <stddef.h>
#include <string.h>
#ifdef __SSE4_2__
#ifdef _MSC_VER
#include <nmmintrin.h>
#else
#include <x86intrin.h>
#endif
#endif
#include "picohttpparser.h"
#if __GNUC__ >= 3
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else
#define likely(x) (x)
#define unlikely(x) (x)
#endif
#ifdef _MSC_VER
#define ALIGNED(n) _declspec(align(n))
#else
#define ALIGNED(n) __attribute__((aligned(n)))
#endif
#define IS_PRINTABLE_ASCII(c) ((unsigned char)(c)-040u < 0137u)
#define CHECK_EOF() \
if (buf == buf_end) { \
*ret = -2; \
return NULL; \
}
#define EXPECT_CHAR_NO_CHECK(ch) \
if (*buf++ != ch) { \
*ret = -1; \
return NULL; \
}
#define EXPECT_CHAR(ch) \
CHECK_EOF(); \
EXPECT_CHAR_NO_CHECK(ch);
#define ADVANCE_TOKEN(tok, toklen) \
do { \
const char *tok_start = buf; \
static const char ALIGNED(16) ranges2[16] = "\000\040\177\177"; \
int found2; \
buf = findchar_fast(buf, buf_end, ranges2, 4, &found2); \
if (!found2) { \
CHECK_EOF(); \
} \
while (1) { \
if (*buf == ' ') { \
break; \
} else if (unlikely(!IS_PRINTABLE_ASCII(*buf))) { \
if ((unsigned char)*buf < '\040' || *buf == '\177') { \
*ret = -1; \
return NULL; \
} \
} \
++buf; \
CHECK_EOF(); \
} \
tok = tok_start; \
toklen = buf - tok_start; \
} while (0)
static const char *token_char_map = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\1\0\1\1\1\1\1\0\0\1\1\0\1\1\0\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0"
"\0\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\1\1"
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\1\0\1\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
static const char *findchar_fast(const char *buf, const char *buf_end, const char *ranges, size_t ranges_size, int *found)
{
*found = 0;
#if __SSE4_2__
if (likely(buf_end - buf >= 16)) {
__m128i ranges16 = _mm_loadu_si128((const __m128i *)ranges);
size_t left = (buf_end - buf) & ~15;
do {
__m128i b16 = _mm_loadu_si128((const __m128i *)buf);
int r = _mm_cmpestri(ranges16, ranges_size, b16, 16, _SIDD_LEAST_SIGNIFICANT | _SIDD_CMP_RANGES | _SIDD_UBYTE_OPS);
if (unlikely(r != 16)) {
buf += r;
*found = 1;
break;
}
buf += 16;
left -= 16;
} while (likely(left != 0));
}
#else
/* suppress unused parameter warning */
(void)buf_end;
(void)ranges;
(void)ranges_size;
#endif
return buf;
}
static const char *get_token_to_eol(const char *buf, const char *buf_end, const char **token, size_t *token_len, int *ret)
{
const char *token_start = buf;
#ifdef __SSE4_2__
static const char ALIGNED(16) ranges1[16] = "\0\010" /* allow HT */
"\012\037" /* allow SP and up to but not including DEL */
"\177\177"; /* allow chars w. MSB set */
int found;
buf = findchar_fast(buf, buf_end, ranges1, 6, &found);
if (found)
goto FOUND_CTL;
#else
/* find non-printable char within the next 8 bytes, this is the hottest code; manually inlined */
while (likely(buf_end - buf >= 8)) {
#define DOIT() \
do { \
if (unlikely(!IS_PRINTABLE_ASCII(*buf))) \
goto NonPrintable; \
++buf; \
} while (0)
DOIT();
DOIT();
DOIT();
DOIT();
DOIT();
DOIT();
DOIT();
DOIT();
#undef DOIT
continue;
NonPrintable:
if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) {
goto FOUND_CTL;
}
++buf;
}
#endif
for (;; ++buf) {
CHECK_EOF();
if (unlikely(!IS_PRINTABLE_ASCII(*buf))) {
if ((likely((unsigned char)*buf < '\040') && likely(*buf != '\011')) || unlikely(*buf == '\177')) {
goto FOUND_CTL;
}
}
}
FOUND_CTL:
if (likely(*buf == '\015')) {
++buf;
EXPECT_CHAR('\012');
*token_len = buf - 2 - token_start;
} else if (*buf == '\012') {
*token_len = buf - token_start;
++buf;
} else {
*ret = -1;
return NULL;
}
*token = token_start;
return buf;
}
static const char *is_complete(const char *buf, const char *buf_end, size_t last_len, int *ret)
{
int ret_cnt = 0;
buf = last_len < 3 ? buf : buf + last_len - 3;
while (1) {
CHECK_EOF();
if (*buf == '\015') {
++buf;
CHECK_EOF();
EXPECT_CHAR('\012');
++ret_cnt;
} else if (*buf == '\012') {
++buf;
++ret_cnt;
} else {
++buf;
ret_cnt = 0;
}
if (ret_cnt == 2) {
return buf;
}
}
*ret = -2;
return NULL;
}
#define PARSE_INT(valp_, mul_) \
if (*buf < '0' || '9' < *buf) { \
buf++; \
*ret = -1; \
return NULL; \
} \
*(valp_) = (mul_) * (*buf++ - '0');
#define PARSE_INT_3(valp_) \
do { \
int res_ = 0; \
PARSE_INT(&res_, 100) \
*valp_ = res_; \
PARSE_INT(&res_, 10) \
*valp_ += res_; \
PARSE_INT(&res_, 1) \
*valp_ += res_; \
} while (0)
/* returned pointer is always within [buf, buf_end), or null */
static const char *parse_http_version(const char *buf, const char *buf_end, int *minor_version, int *ret)
{
/* we want at least [HTTP/1.<two chars>] to try to parse */
if (buf_end - buf < 9) {
*ret = -2;
return NULL;
}
EXPECT_CHAR_NO_CHECK('H');
EXPECT_CHAR_NO_CHECK('T');
EXPECT_CHAR_NO_CHECK('T');
EXPECT_CHAR_NO_CHECK('P');
EXPECT_CHAR_NO_CHECK('/');
EXPECT_CHAR_NO_CHECK('1');
EXPECT_CHAR_NO_CHECK('.');
PARSE_INT(minor_version, 1);
return buf;
}
static const char *parse_headers(const char *buf, const char *buf_end, struct phr_header *headers, size_t *num_headers,
size_t max_headers, int *ret)
{
for (;; ++*num_headers) {
CHECK_EOF();
if (*buf == '\015') {
++buf;
EXPECT_CHAR('\012');
break;
} else if (*buf == '\012') {
++buf;
break;
}
if (*num_headers == max_headers) {
*ret = -1;
return NULL;
}
if (!(*num_headers != 0 && (*buf == ' ' || *buf == '\t'))) {
/* parsing name, but do not discard SP before colon, see
* http://www.mozilla.org/security/announce/2006/mfsa2006-33.html */
headers[*num_headers].name = buf;
static const char ALIGNED(16) ranges1[] = "\x00 " /* control chars and up to SP */
"\"\"" /* 0x22 */
"()" /* 0x28,0x29 */
",," /* 0x2c */
"//" /* 0x2f */
":@" /* 0x3a-0x40 */
"[]" /* 0x5b-0x5d */
"{\377"; /* 0x7b-0xff */
int found;
buf = findchar_fast(buf, buf_end, ranges1, sizeof(ranges1) - 1, &found);
if (!found) {
CHECK_EOF();
}
while (1) {
if (*buf == ':') {
break;
} else if (!token_char_map[(unsigned char)*buf]) {
*ret = -1;
return NULL;
}
++buf;
CHECK_EOF();
}
if ((headers[*num_headers].name_len = buf - headers[*num_headers].name) == 0) {
*ret = -1;
return NULL;
}
++buf;
for (;; ++buf) {
CHECK_EOF();
if (!(*buf == ' ' || *buf == '\t')) {
break;
}
}
} else {
headers[*num_headers].name = NULL;
headers[*num_headers].name_len = 0;
}
const char *value;
size_t value_len;
if ((buf = get_token_to_eol(buf, buf_end, &value, &value_len, ret)) == NULL) {
return NULL;
}
/* remove trailing SPs and HTABs */
const char *value_end = value + value_len;
for (; value_end != value; --value_end) {
const char c = *(value_end - 1);
if (!(c == ' ' || c == '\t')) {
break;
}
}
headers[*num_headers].value = value;
headers[*num_headers].value_len = value_end - value;
}
return buf;
}
static const char *parse_request(const char *buf, const char *buf_end, const char **method, size_t *method_len, const char **path,
size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers,
size_t max_headers, int *ret)
{
/* skip first empty line (some clients add CRLF after POST content) */
CHECK_EOF();
if (*buf == '\015') {
++buf;
EXPECT_CHAR('\012');
} else if (*buf == '\012') {
++buf;
}
/* parse request line */
ADVANCE_TOKEN(*method, *method_len);
do {
++buf;
} while (*buf == ' ');
ADVANCE_TOKEN(*path, *path_len);
do {
++buf;
} while (*buf == ' ');
if (*method_len == 0 || *path_len == 0) {
*ret = -1;
return NULL;
}
if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) {
return NULL;
}
if (*buf == '\015') {
++buf;
EXPECT_CHAR('\012');
} else if (*buf == '\012') {
++buf;
} else {
*ret = -1;
return NULL;
}
return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret);
}
int phr_parse_request(const char *buf_start, size_t len, const char **method, size_t *method_len, const char **path,
size_t *path_len, int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len)
{
const char *buf = buf_start, *buf_end = buf_start + len;
size_t max_headers = *num_headers;
int r;
*method = NULL;
*method_len = 0;
*path = NULL;
*path_len = 0;
*minor_version = -1;
*num_headers = 0;
/* if last_len != 0, check if the request is complete (a fast countermeasure
againt slowloris */
if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) {
return r;
}
if ((buf = parse_request(buf, buf_end, method, method_len, path, path_len, minor_version, headers, num_headers, max_headers,
&r)) == NULL) {
return r;
}
return (int)(buf - buf_start);
}
static const char *parse_response(const char *buf, const char *buf_end, int *minor_version, int *status, const char **msg,
size_t *msg_len, struct phr_header *headers, size_t *num_headers, size_t max_headers, int *ret)
{
/* parse "HTTP/1.x" */
if ((buf = parse_http_version(buf, buf_end, minor_version, ret)) == NULL) {
return NULL;
}
/* skip space */
if (*buf != ' ') {
*ret = -1;
return NULL;
}
do {
++buf;
} while (*buf == ' ');
/* parse status code, we want at least [:digit:][:digit:][:digit:]<other char> to try to parse */
if (buf_end - buf < 4) {
*ret = -2;
return NULL;
}
PARSE_INT_3(status);
/* get message includig preceding space */
if ((buf = get_token_to_eol(buf, buf_end, msg, msg_len, ret)) == NULL) {
return NULL;
}
if (*msg_len == 0) {
/* ok */
} else if (**msg == ' ') {
/* remove preceding space */
do {
++*msg;
--*msg_len;
} while (**msg == ' ');
} else {
/* garbage found after status code */
*ret = -1;
return NULL;
}
return parse_headers(buf, buf_end, headers, num_headers, max_headers, ret);
}
int phr_parse_response(const char *buf_start, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len,
struct phr_header *headers, size_t *num_headers, size_t last_len)
{
const char *buf = buf_start, *buf_end = buf + len;
size_t max_headers = *num_headers;
int r;
*minor_version = -1;
*status = 0;
*msg = NULL;
*msg_len = 0;
*num_headers = 0;
/* if last_len != 0, check if the response is complete (a fast countermeasure
against slowloris */
if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) {
return r;
}
if ((buf = parse_response(buf, buf_end, minor_version, status, msg, msg_len, headers, num_headers, max_headers, &r)) == NULL) {
return r;
}
return (int)(buf - buf_start);
}
int phr_parse_headers(const char *buf_start, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len)
{
const char *buf = buf_start, *buf_end = buf + len;
size_t max_headers = *num_headers;
int r;
*num_headers = 0;
/* if last_len != 0, check if the response is complete (a fast countermeasure
against slowloris */
if (last_len != 0 && is_complete(buf, buf_end, last_len, &r) == NULL) {
return r;
}
if ((buf = parse_headers(buf, buf_end, headers, num_headers, max_headers, &r)) == NULL) {
return r;
}
return (int)(buf - buf_start);
}
enum {
CHUNKED_IN_CHUNK_SIZE,
CHUNKED_IN_CHUNK_EXT,
CHUNKED_IN_CHUNK_DATA,
CHUNKED_IN_CHUNK_CRLF,
CHUNKED_IN_TRAILERS_LINE_HEAD,
CHUNKED_IN_TRAILERS_LINE_MIDDLE
};
static int decode_hex(int ch)
{
if ('0' <= ch && ch <= '9') {
return ch - '0';
} else if ('A' <= ch && ch <= 'F') {
return ch - 'A' + 0xa;
} else if ('a' <= ch && ch <= 'f') {
return ch - 'a' + 0xa;
} else {
return -1;
}
}
ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *_bufsz)
{
size_t dst = 0, src = 0, bufsz = *_bufsz;
ssize_t ret = -2; /* incomplete */
while (1) {
switch (decoder->_state) {
case CHUNKED_IN_CHUNK_SIZE:
for (;; ++src) {
int v;
if (src == bufsz)
goto Exit;
if ((v = decode_hex(buf[src])) == -1) {
if (decoder->_hex_count == 0) {
ret = -1;
goto Exit;
}
break;
}
if (decoder->_hex_count == sizeof(size_t) * 2) {
ret = -1;
goto Exit;
}
decoder->bytes_left_in_chunk = decoder->bytes_left_in_chunk * 16 + v;
++decoder->_hex_count;
}
decoder->_hex_count = 0;
decoder->_state = CHUNKED_IN_CHUNK_EXT;
/* fallthru */
case CHUNKED_IN_CHUNK_EXT:
/* RFC 7230 A.2 "Line folding in chunk extensions is disallowed" */
for (;; ++src) {
if (src == bufsz)
goto Exit;
if (buf[src] == '\012')
break;
}
++src;
if (decoder->bytes_left_in_chunk == 0) {
if (decoder->consume_trailer) {
decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD;
break;
} else {
goto Complete;
}
}
decoder->_state = CHUNKED_IN_CHUNK_DATA;
/* fallthru */
case CHUNKED_IN_CHUNK_DATA: {
size_t avail = bufsz - src;
if (avail < decoder->bytes_left_in_chunk) {
if (dst != src)
memmove(buf + dst, buf + src, avail);
src += avail;
dst += avail;
decoder->bytes_left_in_chunk -= avail;
goto Exit;
}
if (dst != src)
memmove(buf + dst, buf + src, decoder->bytes_left_in_chunk);
src += decoder->bytes_left_in_chunk;
dst += decoder->bytes_left_in_chunk;
decoder->bytes_left_in_chunk = 0;
decoder->_state = CHUNKED_IN_CHUNK_CRLF;
}
/* fallthru */
case CHUNKED_IN_CHUNK_CRLF:
for (;; ++src) {
if (src == bufsz)
goto Exit;
if (buf[src] != '\015')
break;
}
if (buf[src] != '\012') {
ret = -1;
goto Exit;
}
++src;
decoder->_state = CHUNKED_IN_CHUNK_SIZE;
break;
case CHUNKED_IN_TRAILERS_LINE_HEAD:
for (;; ++src) {
if (src == bufsz)
goto Exit;
if (buf[src] != '\015')
break;
}
if (buf[src++] == '\012')
goto Complete;
decoder->_state = CHUNKED_IN_TRAILERS_LINE_MIDDLE;
/* fallthru */
case CHUNKED_IN_TRAILERS_LINE_MIDDLE:
for (;; ++src) {
if (src == bufsz)
goto Exit;
if (buf[src] == '\012')
break;
}
++src;
decoder->_state = CHUNKED_IN_TRAILERS_LINE_HEAD;
break;
default:
assert(!"decoder is corrupt");
}
}
Complete:
ret = bufsz - src;
Exit:
if (dst != src)
memmove(buf + dst, buf + src, bufsz - src);
*_bufsz = dst;
return ret;
}
int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder)
{
return decoder->_state == CHUNKED_IN_CHUNK_DATA;
}
#undef CHECK_EOF
#undef EXPECT_CHAR
#undef ADVANCE_TOKEN

87
picohttpparser.h Normal file
View File

@ -0,0 +1,87 @@
/*
* Copyright (c) 2009-2014 Kazuho Oku, Tokuhiro Matsuno, Daisuke Murase,
* Shigeo Mitsunari
*
* The software is licensed under either the MIT License (below) or the Perl
* license.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef picohttpparser_h
#define picohttpparser_h
#include <sys/types.h>
#ifdef _MSC_VER
#define ssize_t intptr_t
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* contains name and value of a header (name == NULL if is a continuing line
* of a multiline header */
struct phr_header {
const char *name;
size_t name_len;
const char *value;
size_t value_len;
};
/* returns number of bytes consumed if successful, -2 if request is partial,
* -1 if failed */
int phr_parse_request(const char *buf, size_t len, const char **method, size_t *method_len, const char **path, size_t *path_len,
int *minor_version, struct phr_header *headers, size_t *num_headers, size_t last_len);
/* ditto */
int phr_parse_response(const char *_buf, size_t len, int *minor_version, int *status, const char **msg, size_t *msg_len,
struct phr_header *headers, size_t *num_headers, size_t last_len);
/* ditto */
int phr_parse_headers(const char *buf, size_t len, struct phr_header *headers, size_t *num_headers, size_t last_len);
/* should be zero-filled before start */
struct phr_chunked_decoder {
size_t bytes_left_in_chunk; /* number of bytes left in current chunk */
char consume_trailer; /* if trailing headers should be consumed */
char _hex_count;
char _state;
};
/* the function rewrites the buffer given as (buf, bufsz) removing the chunked-
* encoding headers. When the function returns without an error, bufsz is
* updated to the length of the decoded data available. Applications should
* repeatedly call the function while it returns -2 (incomplete) every time
* supplying newly arrived data. If the end of the chunked-encoded data is
* found, the function returns a non-negative number indicating the number of
* octets left undecoded at the tail of the supplied buffer. Returns -1 on
* error.
*/
ssize_t phr_decode_chunked(struct phr_chunked_decoder *decoder, char *buf, size_t *bufsz);
/* returns if the chunked decoder is in middle of chunked data */
int phr_decode_chunked_is_in_data(struct phr_chunked_decoder *decoder);
#ifdef __cplusplus
}
#endif
#endif

296
proxy.c Normal file
View File

@ -0,0 +1,296 @@
#include "proxy.h"
#include "http.h"
#include "request.h"
#include "timeout.h"
#include "conf.h"
#include "help.h"
#define SERVER_STOP 1
#define SERVER_RELOAD 2
#define SERVER_STATUS 3
struct epoll_event ev, events[MAX_CONNECTION + 1];
int epollfd, server_sock;
conn cts[MAX_CONNECTION];
int create_connection(char *remote_host, int remote_port) {
struct sockaddr_in server_addr;
struct hostent *server;
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
return -1;
}
if ((server = gethostbyname(remote_host)) == NULL) {
perror("gethostbyname");
errno = EFAULT;
return -1;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
server_addr.sin_port = htons(remote_port);
if (connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
perror("connect");
return -1;
}
fcntl(sock, F_SETFL, O_NONBLOCK);
return sock;
}
int create_server_socket(int port) {
int server_sock;
int optval = 1;
struct sockaddr_in server_addr;
if ((server_sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket");
return -1;
}
if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) {
perror("setsockopt");
return -1;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) != 0) {
perror("bind");
return -1;
}
if (listen(server_sock, 50) < 0) {
perror("listen");
return -1;
}
return server_sock;
}
void accept_client()
{
struct epoll_event epollEvent;
struct sockaddr_in addr;
conn *client;
socklen_t addr_len = sizeof(addr);
// 偶数为客户端,奇数为服务端
for (client = cts; client - cts < MAX_CONNECTION; client += 2)
if (client->fd < 0)
break;
if (client - cts >= MAX_CONNECTION)
return;
client->timer = (client+1)->timer = 0;
client->fd = accept(server_sock, (struct sockaddr *)&addr, &addr_len);
if (client->fd < 0)
return;
fcntl(client->fd, F_SETFL, O_NONBLOCK);
epollEvent.events = EPOLLIN|EPOLLET;
epollEvent.data.ptr = client;
epoll_ctl(epollfd, EPOLL_CTL_ADD, client->fd, &epollEvent);
}
void start_server(conf *configure)
{
int n;
pthread_t thId;
if (timeout_minute)
pthread_create(&thId, NULL, &close_timeout_connectionLoop, NULL);
while (1) {
n = epoll_wait(epollfd, events, MAX_CONNECTION, -1);
while (n-- > 0) {
if (events[n].data.fd == server_sock) {
accept_client();
} else {
if(events[n].events & EPOLLIN) {
tcp_in((conn *) events[n].data.ptr, configure);
}
if (events[n].events & EPOLLOUT) {
tcp_out((conn *) events[n].data.ptr);
}
}
}
}
close(epollfd);
}
int
process_signal(int signal, char *process_name)
{
char bufer[PATH_SIZE];
char comm[PATH_SIZE];
char proc_comm_name[PATH_SIZE];
int num[PATH_SIZE] = { 0 };
int n = 0;
FILE *fp;
DIR *dir;
struct dirent *ptr;
dir = opendir("/proc");
while ((ptr = readdir(dir)) != NULL) {
if (ptr->d_type == DT_DIR && strcasecmp(ptr->d_name, ".")
&& strcasecmp(ptr->d_name, "..")) {
bzero(bufer, 0);
sprintf(comm, "/proc/%s/comm", ptr->d_name);
if (access(comm, F_OK) == 0) {
fp = fopen(comm, "r");
if (fgets(bufer, PATH_SIZE - 1, fp) == NULL) {
fclose(fp);
continue;
}
sscanf(bufer, "%s", proc_comm_name);
if (!strcmp(process_name, proc_comm_name)) {
num[n] = atoi(ptr->d_name);
n += 1;
}
fclose(fp);
}
}
}
n -= 2; // 去除最后一个搜索时的本身进程
for (; n >= 0; n--) {
if (signal == SERVER_STATUS)
printf("\t%d\n", num[n]);
if (signal == SERVER_STOP || signal == SERVER_RELOAD)
kill(num[n], SIGTERM);
}
closedir(dir);
return 0;
}
int get_executable_path(char *processdir, char *processname, int len)
{
char *filename;
if (readlink("/proc/self/exe", processdir, len) <= 0)
return -1;
filename = strrchr(processdir, '/');
if (filename == NULL)
return -1;
++filename;
strcpy(processname, filename);
*filename = '\0';
return (int)(filename - processdir);
}
int _main(int argc, char *argv[])
{
int opt, i, process;
char path[PATH_SIZE] = { 0 };
char executable_filename[PATH_SIZE] = { 0 };
(void)get_executable_path(path, executable_filename, sizeof(path));
char *inifile = "/CProxy.ini";
inifile = strcat(path, inifile);
conf *configure = (struct CONF *)malloc(sizeof(struct CONF));
read_conf(inifile, configure);
timeout_minute = 0;
if (configure->timer > 0)
timeout_minute = configure->timer;
process = 2;
if (configure->process > 0)
process = configure->process;
char optstrs[] = ":l:f:t:p:c:s:h?";
char *p = NULL;
while (-1 != (opt = getopt(argc, argv, optstrs))) {
switch (opt) {
case 'l':
p = strchr(optarg, ':');
if (p) {
strncpy(local_host, optarg, p - optarg);
local_port = atoi(p + 1);
} else {
strncpy(local_host, optarg, strlen(local_host));
}
break;
case 'f':
p = strchr(optarg, ':');
if (p) {
strncpy(remote_host, optarg, p - optarg);
remote_port = atoi(p + 1);
} else {
strncpy(remote_host, optarg, strlen(remote_host));
}
break;
case 't':
timeout_minute = (time_t)atoi(optarg);
break;
case 'p':
process = atoi(optarg);
break;
case 'c':
free_conf(configure);
inifile = optarg;
read_conf(inifile, configure);
break;
case 's':
if (strcasecmp(optarg, "stop") == 0 || strcasecmp(optarg, "quit") == 0) {
free_conf(configure);
exit(process_signal(SERVER_STOP, executable_filename));
}
if (strcasecmp(optarg, "restart") == 0 || strcasecmp(optarg, "reload") == 0)
process_signal(SERVER_RELOAD, executable_filename);
if (strcasecmp(optarg, "status") == 0)
exit(process_signal(SERVER_STATUS, executable_filename));
break;
case 'h':
case '?':
help_information();
exit(0);
break;
default:
;
}
}
server_sock = create_server_socket(configure->server_port);
signal(SIGPIPE, SIG_IGN); //忽略PIPE信号
memset(cts, 0, sizeof(cts));
for (i = MAX_CONNECTION; i--; )
cts[i].fd = -1;
//为服务端的结构体分配内存
for (i = 1; i < MAX_CONNECTION; i += 2)
{
cts[i].header_buffer = (char *)malloc(BUFFER_SIZE);
if (cts[i].header_buffer == NULL)
{
fputs("out of memory.", stderr);
exit(1);
}
}
while (process-- > 0 && fork() == 0)
epollfd = epoll_create(MAX_CONNECTION);
if (epollfd == -1) {
perror("epoll_create");
exit(1);
}
static struct epoll_event event;
event.events = EPOLLIN;
event.data.fd = server_sock;
if (-1 == epoll_ctl(epollfd, EPOLL_CTL_ADD, server_sock, &event)) {
exit(1);
}
if (daemon(1, 1)) {
perror("daemon");
return 1;
}
if (setegid(configure->uid) == -1 || seteuid(configure->uid) == -1) // 设置uid
exit(1);
start_server(configure);
return 0;
}
int main(int argc, char *argv[])
{
return _main(argc, argv);
}

32
proxy.h Normal file
View File

@ -0,0 +1,32 @@
#ifndef PROXY_H
#define PROXY_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <pwd.h>
#include <dirent.h>
#include <pthread.h>
#define MAX_CONNECTION 1020
#define BUFFER_SIZE 10240
#define PATH_SIZE 270
int local_port;
char local_host[128];
extern int epollfd;
extern struct epoll_event ev, events[MAX_CONNECTION + 1];
int create_connection(char *remote_host, int remote_port);
#endif

349
request.c Normal file
View File

@ -0,0 +1,349 @@
#include "request.h"
// 字符串替换
char *replace(char *replace_memory, int *replace_memory_len, const char *src, const int src_len, const char *dest, const int dest_len)
{
if (!replace_memory || !src || !dest)
return replace_memory;
char *p;
int diff;
if (src_len == dest_len) {
for (p = memmem(replace_memory, *replace_memory_len, src, src_len); p; p = memmem(p, *replace_memory_len - (p - replace_memory), src, src_len)) {
memcpy(p, dest, dest_len);
p += dest_len;
}
} else if (src_len < dest_len) {
int before_len;
char *before_end, *new_replace_memory;
diff = dest_len - src_len;
for (p = memmem(replace_memory, *replace_memory_len, src, src_len); p; p = memmem(p, *replace_memory_len - (p - replace_memory), src, src_len)) {
*replace_memory_len += diff;
before_len = p - replace_memory;
new_replace_memory = (char *)realloc(replace_memory, *replace_memory_len + 1);
if (new_replace_memory == NULL) {
free(replace_memory);
return NULL;
}
replace_memory = new_replace_memory;
before_end = replace_memory + before_len;
p = before_end + dest_len;
memmove(p, p - diff, *replace_memory_len - (p - replace_memory));
memcpy(before_end, dest, dest_len);
}
} else if (src_len > dest_len) {
diff = src_len - dest_len;
for (p = memmem(replace_memory, *replace_memory_len, src, src_len); p; p = memmem(p, *replace_memory_len - (p - replace_memory), src, src_len)) {
*replace_memory_len -= diff;
memcpy(p, dest, dest_len);
p += dest_len;
memmove(p, p + diff, *replace_memory_len - (p - replace_memory));
}
}
replace_memory[*replace_memory_len] = '\0';
return replace_memory;
}
/* 正则表达式字符串替换str为可用free释放的指针 */
static char *regrep(char *str, int *str_len, const char *src, char *dest,
int dest_len)
{
if (!str || !src || !dest)
return NULL;
regmatch_t pm[10];
regex_t reg;
char child_num[2] = { '\\', '0' }, *p, *real_dest;
int match_len, real_dest_len, i;
p = str;
regcomp(&reg, src, REG_NEWLINE | REG_ICASE | REG_EXTENDED);
while (regexec(&reg, p, 10, pm, 0) == 0) {
real_dest = (char *)malloc(dest_len);
if (real_dest == NULL) {
regfree(&reg);
free(str);
return NULL;
}
memcpy(real_dest, dest, dest_len);
real_dest_len = dest_len;
//不进行不必要的字符串操作
if (pm[1].rm_so >= 0) {
/* 替换目标字符串中的子表达式 */
for (i = 1; i < 10 && pm[i].rm_so > -1; i++) {
child_num[1] = i + 48;
real_dest =
replace(real_dest, &real_dest_len, child_num, 2,
p + pm[i].rm_so, pm[i].rm_eo - pm[i].rm_so);
if (real_dest == NULL) {
regfree(&reg);
free(str);
return NULL;
}
}
}
match_len = pm[0].rm_eo - pm[0].rm_so;
p += pm[0].rm_so;
//目标字符串不大于匹配字符串则不用分配新内存
if (match_len >= real_dest_len) {
memcpy(p, real_dest, real_dest_len);
if (match_len > real_dest_len)
//strcpy(p + real_dest_len, p + match_len);
memmove(p + real_dest_len, p + match_len,
*str_len - (p + match_len - str));
p += real_dest_len;
*str_len -= match_len - real_dest_len;
} else {
int diff;
char *before_end, *new_str;
diff = real_dest_len - match_len;
*str_len += diff;
new_str = (char *)realloc(str, *str_len + 1);
if (new_str == NULL) {
free(str);
free(real_dest);
regfree(&reg);
return NULL;
}
str = new_str;
before_end = str + pm[0].rm_so;
p = before_end + real_dest_len;
memmove(p, p - diff, *str_len - (p - str) + 1);
memcpy(before_end, real_dest, real_dest_len);
}
free(real_dest);
}
regfree(&reg);
return str;
}
// 删除字符串head中第一位到character处并拼接string, character为空返回原字符串.(string字符替换第一个字符到character处)
char *splice_head(char *head, const char *character, char *string)
{
int len_first = strlen(string);
char *p1 = strstr(head, character);
if (p1 == NULL) {
return head;
}
p1 = p1 + 1;
char new_string[len_first + strlen(p1) + 1];
strcpy(new_string, string);
return strcat(new_string, p1);
}
// 删除字符串head中character到string处, character为空返回原字符串.
char *delete_head(char *head, const char *character, int string)
{
int head_len = strlen(head);
char *p1 = strstr(head, character);
if (p1 == NULL) {
return head;
}
char *p2 = strchr(p1, string);
if (p2 == NULL) {
return head;
}
char tmp[head_len];
strncpy_(tmp, head, head_len-strlen(p1)-1);
strcat(tmp, p2);
return strcpy(head, tmp);
}
int extract_host(char *header, char *host, char *port, char *H)
{
bzero(host, 0);
bzero(port, 0);
bzero(H, 0);
char *_p = strstr(header, "CONNECT"); // 在 CONNECT 方法中解析 隧道主机名称及端口号
if (_p) {
char *_p1 = strchr(_p, ' ');
char *_p2 = strchr(_p1 + 1, ':');
char *_p3 = strchr(_p1 + 1, ' ');
if (_p2) {
char s_port[10];
bzero(s_port, 10);
strncpy(host, _p1 + 1, (int)(_p2 - _p1) - 1);
strncpy(s_port, _p2 + 1, (int)(_p3 - _p2) - 1);
strcpy(port, s_port);
} else {
strncpy(host, _p1 + 1, (int)(_p3 - _p1) - 1);
strcpy(port, "80");
}
strcpy(H, host);
strcat(H, ":");
strcat(H, port);
return 0;
}
char *p = strstr(header, "Host:");
if (!p) {
return -1;
}
char *p1 = strchr(p, '\n');
if (!p1) {
return -1;
}
char *p2 = strchr(p + 5, ':'); // 5是指'Host:'的长度
if (p2 && p2 < p1) {
int p_len = (int)(p1 - p2 - 1);
char s_port[p_len];
strncpy(s_port, p2 + 1, p_len);
s_port[p_len] = '\0';
strcpy(port, s_port);
int h_len = (int)(p2 - p - 5 - 1);
strncpy(host, p + 5 + 1, h_len); // Host:
host[h_len] = '\0';
} else {
int h_len = (int)(p1 - p - 5 - 1 - 1);
strncpy(host, p + 5 + 1, h_len);
host[h_len] = '\0';
strcpy(port, "80");
}
strcpy(H, host);
strcat(H, ":");
strcat(H, port);
return 0;
}
char *request_head(conn *in, conf *configure)
{
const char *method, *path;
size_t method_len, path_len, num_headers;
int minor_version;
struct phr_header headers[32];
num_headers = sizeof(headers) / sizeof(headers[0]);
phr_parse_request(in->header_buffer, strlen(in->header_buffer) - 1, &method, &method_len, &path, &path_len, &minor_version, headers, &num_headers, 0);
char M[method_len+2];
strncpy_(M, method, method_len);
int M_len = strlen(M);
//printf("%s\n", M);
char U[path_len+1];
strncpy_(U, path, path_len);
int U_len = strlen(U);
//printf("%s\n", U);
char V[9];
sprintf(V, "HTTP/1.%.d", minor_version);
int V_len = strlen(V);
//printf("%s\n", V);
char host[path_len];
char port[path_len];
char H[path_len*2];
extract_host(in->header_buffer, host, port, H);
if (strncmp(M, "CONNECT", 7) == 0) {
char https_del_copy[configure->https_del_len];
char *result = NULL;
char *incomplete_head;
int incomplete_head_len;
if (configure->https_port > 0)
remote_port = configure->https_port;
if (configure->https_ip != NULL)
strcpy(remote_host, configure->https_ip);
incomplete_head = (char *)malloc(1024 + 10240);
strcpy(incomplete_head, in->header_buffer);
strcpy(https_del_copy, configure->https_del);
result = strtok(https_del_copy, ",");
while (result != NULL) {
delete_head(incomplete_head, result, '\n');
result = strtok(NULL, ",");
}
strcpy(incomplete_head, splice_head(incomplete_head, "\n", configure->https_first));
incomplete_head_len = strlen(incomplete_head);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\r", 2, "\r", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\n", 2, "\n", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\b", 2, "\b", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\v", 2, "\v", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\f", 2, "\f", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\a", 2, "\a", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\t", 2, "\t", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\r", 2, "\r", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\n", 2, "\n", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[M]", 3, M, M_len);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[U]", 3, U, U_len);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[V]", 3, V, V_len);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[host]", 6, host, (int)strlen(host));
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[port]", 6, port, (int)strlen(port));
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[H]", 3, H, (int)strlen(H));
if (configure->https_strrep) {
incomplete_head = replace(incomplete_head, &incomplete_head_len, configure->https_strrep_aim, configure->https_strrep_aim_len, configure->https_strrep_obj, configure->https_strrep_obj_len);
}
if (configure->https_regrep) {
incomplete_head = regrep(incomplete_head, &incomplete_head_len, configure->https_regrep_aim, configure->https_regrep_obj, configure->https_regrep_obj_len);
}
//printf("%s", incomplete_head);
memset(in->header_buffer, 0, strlen(in->header_buffer));
strcpy(in->header_buffer, incomplete_head);
in->header_buffer_len = strlen(in->header_buffer);
free(incomplete_head);
} else {
char *incomplete_head;
char https_del_copy[configure->http_del_len];
char *result = NULL;
int incomplete_head_len;
if (configure->http_port > 0)
remote_port = configure->http_port;
if (configure->https_ip != NULL)
strcpy(remote_host, configure->http_ip);
incomplete_head = (char *)malloc(1024 + 10240);
strcpy(incomplete_head, in->header_buffer);
strcpy(https_del_copy, configure->http_del);
result = strtok(https_del_copy, ",");
while (result != NULL) {
delete_head(incomplete_head, result, '\n');
result = strtok(NULL, ",");
}
strcpy(incomplete_head, splice_head(incomplete_head, "\n", configure->http_first));
incomplete_head_len = strlen(incomplete_head);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\r", 2, "\r", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\n", 2, "\n", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\b", 2, "\b", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\v", 2, "\v", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\f", 2, "\f", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\a", 2, "\a", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\t", 2, "\t", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\r", 2, "\r", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "\\n", 2, "\n", 1);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[M]", 3, M, M_len);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[U]", 3, U, U_len);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[V]", 3, V, V_len);
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[host]", 6, host, (int)strlen(host));
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[port]", 6, port, (int)strlen(port));
incomplete_head = replace(incomplete_head, &incomplete_head_len, "[H]", 3, H, (int)strlen(H));
if (configure->http_strrep) {
incomplete_head = replace(incomplete_head, &incomplete_head_len, configure->http_strrep_aim, configure->http_strrep_aim_len, configure->http_strrep_obj, configure->http_strrep_obj_len);
}
if (configure->http_regrep) {
incomplete_head = regrep(incomplete_head, &incomplete_head_len, configure->http_regrep_aim, configure->http_regrep_obj, configure->http_regrep_obj_len);
}
//printf("%s", incomplete_head);
memset(in->header_buffer, 0, strlen(in->header_buffer));
strcpy(in->header_buffer, incomplete_head);
in->header_buffer_len = strlen(in->header_buffer);
free(incomplete_head);
}
return in->header_buffer;
}

17
request.h Normal file
View File

@ -0,0 +1,17 @@
#ifndef REQUEST_H
#define REQUEST_H
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include "http.h"
#include "conf.h"
#include "picohttpparser.h"
void *memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen);
char *replace(char *replace_memory, int *replace_memory_len, const char *src, const int src_len, const char *dest, const int dest_len);
char *request_head(conn *in, conf *configure);
#endif

22
timeout.c Normal file
View File

@ -0,0 +1,22 @@
#include "proxy.h"
#include "http.h"
int timeout_minute;
void *close_timeout_connectionLoop(void *nullPtr)
{
int i;
while (1)
{
sleep(60);
for (i = 0; i < MAX_CONNECTION; i += 2)
if (cts[i].fd > -1)
{
if (cts[i].timer >= timeout_minute)
close_connection(cts + i);
else
cts[i].timer++;
}
}
}

8
timeout.h Normal file
View File

@ -0,0 +1,8 @@
#ifndef TIME_H
#define TIME_H
extern int timeout_minute;
void *close_timeout_connectionLoop(void *nullPtr);
#endif