Repository: linyacool/WebServer
Branch: master
Commit: 7e18602f15c5
Files: 190
Total size: 453.7 KB
Directory structure:
gitextract_ftjuqrgs/
├── .clang-format
├── .gitignore
├── .travis.yml
├── CMakeLists.txt
├── LICENSE
├── README.md
├── WebBench/
│ ├── LICENSE
│ ├── Makefile
│ ├── README.md
│ ├── bin/
│ │ └── webbench
│ ├── build.sh
│ ├── debian/
│ │ ├── changelog
│ │ ├── control
│ │ ├── copyright
│ │ ├── dirs
│ │ └── rules
│ ├── man/
│ │ └── man1/
│ │ └── webbench.1
│ ├── share/
│ │ └── doc/
│ │ └── webbench/
│ │ ├── changelog
│ │ └── copyright
│ ├── socket.c
│ ├── tags
│ ├── test.sh
│ ├── webbench
│ ├── webbench.1
│ └── webbench.c
├── WebServer/
│ ├── CMakeLists.txt
│ ├── Channel.cpp
│ ├── Channel.h
│ ├── Epoll.cpp
│ ├── Epoll.h
│ ├── EventLoop.cpp
│ ├── EventLoop.h
│ ├── EventLoopThread.cpp
│ ├── EventLoopThread.h
│ ├── EventLoopThreadPool.cpp
│ ├── EventLoopThreadPool.h
│ ├── HttpData.cpp
│ ├── HttpData.h
│ ├── Main.cpp
│ ├── Makefile
│ ├── Makefile.bak
│ ├── Server.cpp
│ ├── Server.h
│ ├── ThreadPool.cpp
│ ├── ThreadPool.h
│ ├── Timer.cpp
│ ├── Timer.h
│ ├── Util.cpp
│ ├── Util.h
│ ├── base/
│ │ ├── AsyncLogging.cpp
│ │ ├── AsyncLogging.h
│ │ ├── CMakeLists.txt
│ │ ├── Condition.h
│ │ ├── CountDownLatch.cpp
│ │ ├── CountDownLatch.h
│ │ ├── CurrentThread.h
│ │ ├── FileUtil.cpp
│ │ ├── FileUtil.h
│ │ ├── LogFile.cpp
│ │ ├── LogFile.h
│ │ ├── LogStream.cpp
│ │ ├── LogStream.h
│ │ ├── Logging.cpp
│ │ ├── Logging.h
│ │ ├── Log的设计.txt
│ │ ├── MutexLock.h
│ │ ├── Thread.cpp
│ │ ├── Thread.h
│ │ ├── noncopyable.h
│ │ └── tests/
│ │ ├── CMakeLists.txt
│ │ └── LoggingTest.cpp
│ ├── config.h
│ └── tests/
│ ├── CMakeLists.txt
│ └── HTTPClient.cpp
├── build.sh
├── old_version/
│ ├── old_version_0.1/
│ │ ├── Makefile
│ │ ├── Makefile1
│ │ ├── epoll.cpp
│ │ ├── epoll.h
│ │ ├── improvement.txt
│ │ ├── index.html
│ │ ├── main.cpp
│ │ ├── requestData.cpp
│ │ ├── requestData.h
│ │ ├── threadpool.cpp
│ │ ├── threadpool.h
│ │ ├── util.cpp
│ │ └── util.h
│ ├── old_version_0.2/
│ │ ├── Makefile
│ │ ├── Makefile1
│ │ ├── epoll.cpp
│ │ ├── epoll.h
│ │ ├── improvement.txt
│ │ ├── index.html
│ │ ├── main.cpp
│ │ ├── requestData.cpp
│ │ ├── requestData.h
│ │ ├── threadpool.cpp
│ │ ├── threadpool.h
│ │ ├── util.cpp
│ │ └── util.h
│ ├── old_version_0.3/
│ │ ├── Makefile
│ │ ├── Makefile1
│ │ ├── config.h
│ │ ├── epoll.cpp
│ │ ├── epoll.h
│ │ ├── improvement.txt
│ │ ├── index.html
│ │ ├── main.cpp
│ │ ├── requestData.cpp
│ │ ├── requestData.h
│ │ ├── threadpool.cpp
│ │ ├── threadpool.h
│ │ ├── util.cpp
│ │ └── util.h
│ ├── old_version_0.4/
│ │ ├── Makefile
│ │ ├── Makefile1
│ │ ├── base/
│ │ │ ├── mutexLock.hpp
│ │ │ └── nocopyable.hpp
│ │ ├── config.h
│ │ ├── epoll.cpp
│ │ ├── epoll.h
│ │ ├── improvement.txt
│ │ ├── index.html
│ │ ├── main.cpp
│ │ ├── requestData.cpp
│ │ ├── requestData.h
│ │ ├── threadpool.cpp
│ │ ├── threadpool.h
│ │ ├── timer.cpp
│ │ ├── timer.h
│ │ ├── util.cpp
│ │ └── util.h
│ ├── old_version_0.5/
│ │ ├── Makefile
│ │ ├── Makefile1
│ │ ├── base/
│ │ │ ├── condition.hpp
│ │ │ ├── mutexLock.hpp
│ │ │ └── nocopyable.hpp
│ │ ├── config.h
│ │ ├── epoll.cpp
│ │ ├── epoll.h
│ │ ├── index.html
│ │ ├── main.cpp
│ │ ├── requestData.cpp
│ │ ├── requestData.h
│ │ ├── threadpool.cpp
│ │ ├── threadpool.h
│ │ ├── timer.cpp
│ │ ├── timer.h
│ │ ├── util.cpp
│ │ └── util.h
│ └── old_version_0.6/
│ ├── AsyncLogging.cpp
│ ├── AsyncLogging.h
│ ├── Condition.h
│ ├── CountDownLatch.cpp
│ ├── CountDownLatch.h
│ ├── CurrentThread.hpp
│ ├── FileUtil.cpp
│ ├── FileUtil.h
│ ├── LogFile.cpp
│ ├── LogFile.h
│ ├── LogStream.cpp
│ ├── LogStream.h
│ ├── Logging.cpp
│ ├── Logging.h
│ ├── Makefile
│ ├── Makefile1
│ ├── MutexLock.h
│ ├── Thread.cpp
│ ├── Thread.h
│ ├── config.h
│ ├── epoll.cpp
│ ├── epoll.h
│ ├── index.html
│ ├── main.cpp
│ ├── noncopyable.h
│ ├── requestData.cpp
│ ├── requestData.h
│ ├── threadpool.cpp
│ ├── threadpool.h
│ ├── timer.cpp
│ ├── timer.h
│ ├── util.cpp
│ └── util.h
├── 并发模型.md
├── 测试及改进.md
├── 版本历史.md
├── 连接的维护.md
├── 遇到的困难.md
└── 项目目的.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .clang-format
================================================
Language: Cpp
BasedOnStyle: Google
================================================
FILE: .gitignore
================================================
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# Otheres
core
.vscode
================================================
FILE: .travis.yml
================================================
language: cpp
sudo: required
dist: trusty
compiler:
- g++
os:
- linux
install:
- sudo apt-get install cmake
env:
- BUILD_TYPE=debug
- BUILD_TYPE=release
script:
- ./build.sh
================================================
FILE: CMakeLists.txt
================================================
cmake_minimum_required(VERSION 2.8)
project(WebServer CXX)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Debug")
endif()
set(CXX_FLAGS
-g
-Wall
-std=c++11
-D_PTHREADS
-Wno-unused-parameter
)
set(CMAKE_CXX_COMPILER "g++")
set(CMAKE_CXX_FLAGS_DEBUG "-O0")
set(CMAKE_CXX_FLAGS_RELEASE "-O0")
string(REPLACE ";" " " CMAKE_CXX_FLAGS "${CXX_FLAGS}")
string(TOUPPER ${CMAKE_BUILD_TYPE} BUILD_TYPE)
message(STATUS "CXX_FLAGS = " ${CMAKE_CXX_FLAGS} " " ${CMAKE_CXX_FLAGS_${BUILD_TYPE}})
add_subdirectory(WebServer)
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018 林亚
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.
================================================
FILE: README.md
================================================
# A C++ High Performance Web Server
[](https://travis-ci.org/linyacool/WebServer)
[](https://opensource.org/licenses/MIT)
## Introduction
本项目为C++11编写的Web服务器,解析了get、head请求,可处理静态资源,支持HTTP长连接,支持管线化请求,并实现了异步日志,记录服务器运行状态。
| Part Ⅰ | Part Ⅱ | Part Ⅲ | Part Ⅳ | Part Ⅴ | Part Ⅵ |
| :--------: | :---------: | :---------: | :---------: | :---------: | :---------: |
| [并发模型](https://github.com/linyacool/WebServer/blob/master/并发模型.md)|[连接的维护](https://github.com/linyacool/WebServer/blob/master/连接的维护.md)|[版本历史](https://github.com/linyacool/WebServer/blob/master/%E7%89%88%E6%9C%AC%E5%8E%86%E5%8F%B2.md) | [测试及改进](https://github.com/linyacool/WebServer/blob/master/测试及改进.md) | [项目目的](https://github.com/linyacool/WebServer/blob/master/%E9%A1%B9%E7%9B%AE%E7%9B%AE%E7%9A%84.md) | [面试问题](https://github.com/linyacool/WebServer/blob/master/%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98.md)
## Envoirment
* OS: Ubuntu 14.04
* Complier: g++ 4.8
## Build
./build.sh
## Usage
./WebServer [-t thread_numbers] [-p port] [-l log_file_path(should begin with '/')]
## Technical points
* 使用Epoll边沿触发的IO多路复用技术,非阻塞IO,使用Reactor模式
* 使用多线程充分利用多核CPU,并使用线程池避免线程频繁创建销毁的开销
* 使用基于小根堆的定时器关闭超时请求
* 主线程只负责accept请求,并以Round Robin的方式分发给其它IO线程(兼计算线程),锁的争用只会出现在主线程和某一特定线程中
* 使用eventfd实现了线程的异步唤醒
* 使用双缓冲区技术实现了简单的异步日志系统
* 为减少内存泄漏的可能,使用智能指针等RAII机制
* 使用状态机解析了HTTP请求,支持管线化
* 支持优雅关闭连接
## Model
并发模型为Reactor+非阻塞IO+线程池,新连接Round Robin分配,详细介绍请参考[并发模型](https://github.com/linyacool/WebServer/blob/master/并发模型.md)

## 代码统计

## Others
除了项目基本的代码,进服务器进行压测时,对开源测试工具Webbench增加了Keep-Alive选项和测试功能: 改写后的[Webbench](https://github.com/linyacool/WebBench)
================================================
FILE: WebBench/LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
================================================
FILE: WebBench/Makefile
================================================
CFLAGS?= -Wall -ggdb -W -O
CC?= gcc
LIBS?=
LDFLAGS?=
PREFIX?= /usr/local/webbench
VERSION=1.5
TMPDIR=/tmp/webbench-$(VERSION)
all: webbench tags
tags: *.c
-ctags *.c
install: webbench
install -d $(DESTDIR)$(PREFIX)/bin
install -s webbench $(DESTDIR)$(PREFIX)/bin
ln -sf $(DESTDIR)$(PREFIX)/bin/webbench $(DESTDIR)/usr/local/bin/webbench
install -d $(DESTDIR)/usr/local/man/man1
install -d $(DESTDIR)$(PREFIX)/man/man1
install -m 644 webbench.1 $(DESTDIR)$(PREFIX)/man/man1
ln -sf $(DESTDIR)$(PREFIX)/man/man1/webbench.1 $(DESTDIR)/usr/local/man/man1/webbench.1
install -d $(DESTDIR)$(PREFIX)/share/doc/webbench
install -m 644 debian/copyright $(DESTDIR)$(PREFIX)/share/doc/webbench
install -m 644 debian/changelog $(DESTDIR)$(PREFIX)/share/doc/webbench
webbench: webbench.o Makefile
$(CC) $(CFLAGS) $(LDFLAGS) -o webbench webbench.o $(LIBS)
clean:
-rm -f *.o webbench *~ core *.core tags
tar: clean
-debian/rules clean
rm -rf $(TMPDIR)
install -d $(TMPDIR)
cp -p Makefile webbench.c socket.c webbench.1 $(TMPDIR)
install -d $(TMPDIR)/debian
-cp -p debian/* $(TMPDIR)/debian
ln -sf debian/copyright $(TMPDIR)/COPYRIGHT
ln -sf debian/changelog $(TMPDIR)/ChangeLog
-cd $(TMPDIR) && cd .. && tar cozf webbench-$(VERSION).tar.gz webbench-$(VERSION)
webbench.o: webbench.c socket.c Makefile
.PHONY: clean install all tar
================================================
FILE: WebBench/README.md
================================================
# WebBench
Webbench是一个在linux下使用的非常简单的网站压测工具。它使用fork()模拟多个客户端同时访问我们设定的URL,测试网站在压力下工作的性能,最多可以模拟3万个并发连接去测试网站的负载能力。
## 依赖
ctags
## 使用:
sudo make && sudo make install PREFIX=your_path_to_webbench
## 命令行选项:
| 短参 | 长参数 | 作用 |
| ------------- |:-------------:| -----:|
|-f |--force |不需要等待服务器响应 |
|-r |--reload |发送重新加载请求 |
|-t |--time |运行多长时间,单位:秒" |
|-p |--proxy |使用代理服务器来发送请求 |
|-c |--clients |创建多少个客户端,默认1个" |
|-9 |--http09 |使用 HTTP/0.9 |
|-1 |--http10 |使用 HTTP/1.0 协议 |
|-2 |--http11 |使用 HTTP/1.1 协议 |
| |--get |使用 GET请求方法 |
| |--head |使用 HEAD请求方法 |
| |--options |使用 OPTIONS请求方法 |
| |--trace |使用 TRACE请求方法 |
|-?/-h |--help |打印帮助信息 |
|-V |--version |显示版本号 |
================================================
FILE: WebBench/build.sh
================================================
sudo make && sudo make install PREFIX=.
================================================
FILE: WebBench/debian/changelog
================================================
webbench (1.5) unstable; urgency=low
* allow building with both Gnu and BSD make
-- Radim Kolar Fri, Jun 25 12:00:20 CEST 2004
webbench (1.4) unstable; urgency=low
* check if url is not too long
* report correct program version number
* use yield() when waiting for test start
* corrected error codes
* check availability of test server first
* do not abort test if first request failed
* report when some childrens are dead.
* use alarm, not time() for lower syscal use by bench
* use mode 644 for installed doc
* makefile cleaned for better freebsd ports integration
-- Radim Kolar Thu, 15 Jan 2004 11:15:52 +0100
webbench (1.3) unstable; urgency=low
* Build fixes for freeBSD
* Default benchmark time 60 -> 30
* generate tar with subdirectory
* added to freeBSD ports collection
-- Radim Kolar Mon, 12 Jan 2004 17:00:24 +0100
webbench (1.2) unstable; urgency=low
* Only debian-related bugfixes
* Updated Debian/rules
* Adapted to fit new directory system
* moved from debstd to dh_*
-- Radim Kolar Fri, 18 Jan 2002 12:33:04 +0100
webbench (1.1) unstable; urgency=medium
* Program debianized
* added support for multiple methods (GET, HEAD, OPTIONS, TRACE)
* added support for multiple HTTP versions (0.9 -- 1.1)
* added long options
* added multiple clients
* wait for start of second before test
* test time can be specified
* better error checking when reading reply from server
* FIX: tests was one second longer than expected
-- Radim Kolar Thu, 16 Sep 1999 18:48:00 +0200
Local variables:
mode: debian-changelog
End:
================================================
FILE: WebBench/debian/control
================================================
Source: webbench
Section: web
Priority: extra
Maintainer: Radim Kolar
Build-Depends: debhelper (>> 3.0.0)
Standards-Version: 3.5.2
Package: webbench
Architecture: any
Depends: ${shlibs:Depends}
Description: Simple forking Web benchmark
webbench is very simple program for benchmarking WWW or Proxy servers.
Uses fork() for simulating multiple clients load. Can use HTTP 0.9 - 1.1
requests, but Keep-Alive connections are not supported.
================================================
FILE: WebBench/debian/copyright
================================================
Webbench was written by Radim Kolar 1997-2004 (hsn@netmag.cz).
UNIX sockets code (socket.c) taken from popclient 1.5 4/1/94
public domain code, created by Virginia Tech Computing Center.
Copyright: GPL (see /usr/share/common-licenses/GPL)
================================================
FILE: WebBench/debian/dirs
================================================
usr/bin
================================================
FILE: WebBench/debian/rules
================================================
#!/usr/bin/make -f
# Sample debian/rules that uses debhelper.
# GNU copyright 1997 to 1999 by Joey Hess.
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
# This is the debhelper compatability version to use.
export DH_COMPAT=3
configure: configure-stamp
configure-stamp:
dh_testdir
touch configure-stamp
build: configure-stamp build-stamp
build-stamp:
dh_testdir
$(MAKE)
touch build-stamp
clean:
dh_testdir
rm -f build-stamp configure-stamp
# Add here commands to clean up after the build process.
-$(MAKE) clean
dh_clean
install: build
dh_testdir
dh_testroot
dh_clean -k
dh_installdirs
# Add here commands to install the package into debian/webbench.
$(MAKE) install DESTDIR=$(CURDIR)/debian/webbench
# Build architecture-independent files here.
binary-indep: build install
# We have nothing to do by default.
# Build architecture-dependent files here.
binary-arch: build install
dh_testdir
dh_testroot
dh_installdocs
dh_installman webbench.1
dh_installchangelogs
dh_link
dh_strip
dh_compress
dh_fixperms
# dh_makeshlibs
dh_installdeb
dh_shlibdeps
dh_gencontrol
dh_md5sums
dh_builddeb
binary: binary-indep binary-arch
.PHONY: build clean binary-indep binary-arch binary install configure
================================================
FILE: WebBench/man/man1/webbench.1
================================================
-.TH WEBBENCH 1 "14 Jan 2004"
-.\" NAME should be all caps, SECTION should be 1-8, maybe w/ subsection
-.\" other parms are allowed: see man(7), man(1)
-.SH NAME
-webbench \- simple forking web benchmark
-.SH SYNOPSIS
-.B webbench
-.I "[options] URL"
-.br
-.SH "AUTHOR"
-This program and manual page was written by Radim Kolar,
-for the
-.B Supreme Personality of Godhead
-(but may be used by others).
-.SH "DESCRIPTION"
-.B webbench
-is simple program for benchmarking HTTP servers or any
-other servers, which can be accessed via HTTP proxy. Unlike others
-benchmarks,
-.B webbench
-uses multiple processes for simulating traffic
-generated by multiple users. This allows better operating
-on SMP systems and on systems with slow or buggy implementation
-of select().
-.SH OPTIONS
-The programs follow the usual GNU command line syntax, with long
-options starting with two dashes (`-').
-A summary of options are included below.
-.TP
-.B \-?, \-h, \-\-help
-Show summary of options.
-.TP
-.B \-v, \-\-version
-Show version of program.
-.TP
-.B \-f, \-\-force
-Do not wait for any response from server. Close connection after
-request is send. This option produce quite a good denial of service
-attack.
-.TP
-.B \-9, \-\-http09
-Use HTTP/0.9 protocol, if possible.
-.TP
-.B \-1, \-\-http10
-Use HTTP/1.0 protocol, if possible.
-.TP
-.B \-2, \-\-http11
-Use HTTP/1.1 protocol (without
-.I Keep-Alive
-), if possible.
-.TP
-.B \-r, \-\-reload
-Forces proxy to reload document. If proxy is not
-set, option has no effect.
-.TP
-.B \-t, \-\-time
-Run benchmark for
-.I
-seconds. Default value is 30.
-.TP
-.B \-p, \-\-proxy
-Send request via proxy server. Needed for supporting others protocols
-than HTTP.
-.TP
-.B \-\-get
-Use GET request method.
-.TP
-.B \-\-head
-Use HEAD request method.
-.TP
-.B \-\-options
-Use OPTIONS request method.
-.TP
-.B \-\-trace
-Use TRACE request method.
-.TP
-.B \-c, \-\-clients
-Use
-.I
-multiple clients for benchmark. Default value
-is 1.
-.SH "EXIT STATUS"
-.TP
-0 - sucess
-.TP
-1 - benchmark failed, can not connect to server
-.TP
-2 - bad command line argument(s)
-.TP
-3 - internal error, i.e. fork failed
-.SH "TODO"
-Include support for using
-.I Keep-Alive
-HTTP/1.1 connections.
-.SH "COPYING"
-Webbench is distributed under GPL. Copyright 1997-2004
-Radim Kolar (hsn@netmag.cz).
-UNIX sockets code taken from popclient 1.5 4/1/94
-public domain code, created by Virginia Tech Computing Center.
-.BR
-This man page is public domain.
================================================
FILE: WebBench/share/doc/webbench/changelog
================================================
webbench (1.5) unstable; urgency=low
* allow building with both Gnu and BSD make
-- Radim Kolar Fri, Jun 25 12:00:20 CEST 2004
webbench (1.4) unstable; urgency=low
* check if url is not too long
* report correct program version number
* use yield() when waiting for test start
* corrected error codes
* check availability of test server first
* do not abort test if first request failed
* report when some childrens are dead.
* use alarm, not time() for lower syscal use by bench
* use mode 644 for installed doc
* makefile cleaned for better freebsd ports integration
-- Radim Kolar Thu, 15 Jan 2004 11:15:52 +0100
webbench (1.3) unstable; urgency=low
* Build fixes for freeBSD
* Default benchmark time 60 -> 30
* generate tar with subdirectory
* added to freeBSD ports collection
-- Radim Kolar Mon, 12 Jan 2004 17:00:24 +0100
webbench (1.2) unstable; urgency=low
* Only debian-related bugfixes
* Updated Debian/rules
* Adapted to fit new directory system
* moved from debstd to dh_*
-- Radim Kolar Fri, 18 Jan 2002 12:33:04 +0100
webbench (1.1) unstable; urgency=medium
* Program debianized
* added support for multiple methods (GET, HEAD, OPTIONS, TRACE)
* added support for multiple HTTP versions (0.9 -- 1.1)
* added long options
* added multiple clients
* wait for start of second before test
* test time can be specified
* better error checking when reading reply from server
* FIX: tests was one second longer than expected
-- Radim Kolar Thu, 16 Sep 1999 18:48:00 +0200
Local variables:
mode: debian-changelog
End:
================================================
FILE: WebBench/share/doc/webbench/copyright
================================================
Webbench was written by Radim Kolar 1997-2004 (hsn@netmag.cz).
UNIX sockets code (socket.c) taken from popclient 1.5 4/1/94
public domain code, created by Virginia Tech Computing Center.
Copyright: GPL (see /usr/share/common-licenses/GPL)
================================================
FILE: WebBench/socket.c
================================================
/* $Id: socket.c 1.1 1995/01/01 07:11:14 cthuang Exp $
*
* This module has been modified by Radim Kolar for OS/2 emx
*/
/***********************************************************************
module: socket.c
program: popclient
SCCS ID: @(#)socket.c 1.5 4/1/94
programmer: Virginia Tech Computing Center
compiler: DEC RISC C compiler (Ultrix 4.1)
environment: DEC Ultrix 4.3
description: UNIX sockets code.
***********************************************************************/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int Socket(const char *host, int clientPort)
{
int sock;
unsigned long inaddr;
struct sockaddr_in ad;
struct hostent *hp;
memset(&ad, 0, sizeof(ad));
ad.sin_family = AF_INET;
inaddr = inet_addr(host);
if (inaddr != INADDR_NONE)
memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
else
{
hp = gethostbyname(host);
if (hp == NULL)
return -1;
memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
}
ad.sin_port = htons(clientPort);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
return sock;
// int optval = 1;
// if(setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1)
// return -1;
if (connect(sock, (struct sockaddr *)&ad, sizeof(ad)) < 0)
{
close(sock);
return -1;
}
return sock;
}
================================================
FILE: WebBench/tags
================================================
!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/
!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/
!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/
!_TAG_PROGRAM_NAME Exuberant Ctags //
!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/
!_TAG_PROGRAM_VERSION 5.9~svn20110310 //
METHOD_GET webbench.c 38;" d file:
METHOD_GET webbench1.c 38;" d file:
METHOD_GET webbench2.c 38;" d file:
METHOD_HEAD webbench.c 39;" d file:
METHOD_HEAD webbench1.c 39;" d file:
METHOD_HEAD webbench2.c 39;" d file:
METHOD_OPTIONS webbench.c 40;" d file:
METHOD_OPTIONS webbench1.c 40;" d file:
METHOD_OPTIONS webbench2.c 40;" d file:
METHOD_TRACE webbench.c 41;" d file:
METHOD_TRACE webbench1.c 41;" d file:
METHOD_TRACE webbench2.c 41;" d file:
PROGRAM_VERSION webbench.c 42;" d file:
PROGRAM_VERSION webbench1.c 42;" d file:
PROGRAM_VERSION webbench2.c 42;" d file:
REQUEST_SIZE webbench.c 56;" d file:
REQUEST_SIZE webbench1.c 56;" d file:
REQUEST_SIZE webbench2.c 56;" d file:
Socket socket.c /^int Socket(const char *host, int clientPort)$/;" f
alarm_handler webbench.c /^static void alarm_handler(int signal)$/;" f file:
alarm_handler webbench1.c /^static void alarm_handler(int signal)$/;" f file:
alarm_handler webbench2.c /^static void alarm_handler(int signal)$/;" f file:
bench webbench.c /^static int bench(void)$/;" f file:
bench webbench1.c /^static int bench(void)$/;" f file:
bench webbench2.c /^static int bench(void)$/;" f file:
benchcore webbench.c /^void benchcore(const char *host,const int port,const char *req)$/;" f
benchcore webbench1.c /^void benchcore(const char *host,const int port,const char *req)$/;" f
benchcore webbench2.c /^void benchcore(const char *host,const int port,const char *req)$/;" f
benchtime webbench.c /^int benchtime=30;$/;" v
benchtime webbench1.c /^int benchtime=30;$/;" v
benchtime webbench2.c /^int benchtime=30;$/;" v
build_request webbench.c /^void build_request(const char *url)$/;" f
build_request webbench1.c /^void build_request(const char *url)$/;" f
build_request webbench2.c /^void build_request(const char *url)$/;" f
bytes webbench.c /^int bytes=0;$/;" v
bytes webbench1.c /^int bytes=0;$/;" v
bytes webbench2.c /^int bytes=0;$/;" v
clients webbench.c /^int clients=1;$/;" v
clients webbench1.c /^int clients=1;$/;" v
clients webbench2.c /^int clients=1;$/;" v
failed webbench.c /^int failed=0;$/;" v
failed webbench1.c /^int failed=0;$/;" v
failed webbench2.c /^int failed=0;$/;" v
force webbench.c /^int force=0;$/;" v
force webbench1.c /^int force=0;$/;" v
force webbench2.c /^int force=0;$/;" v
force_reload webbench.c /^int force_reload=0;$/;" v
force_reload webbench1.c /^int force_reload=0;$/;" v
force_reload webbench2.c /^int force_reload=0;$/;" v
host webbench.c /^char host[MAXHOSTNAMELEN];$/;" v
host webbench1.c /^char host[MAXHOSTNAMELEN];$/;" v
host webbench2.c /^char host[MAXHOSTNAMELEN];$/;" v
http10 webbench.c /^int http10=1; \/* 0 - http\/0.9, 1 - http\/1.0, 2 - http\/1.1 *\/$/;" v
http10 webbench1.c /^int http10=1; \/* 0 - http\/0.9, 1 - http\/1.0, 2 - http\/1.1 *\/$/;" v
http10 webbench2.c /^int http10=1; \/* 0 - http\/0.9, 1 - http\/1.0, 2 - http\/1.1 *\/$/;" v
keep_alive webbench.c /^bool keep_alive = false;$/;" v
keep_alive webbench1.c /^bool keep_alive = false;$/;" v
keep_alive webbench2.c /^bool keep_alive = false;$/;" v
long_options webbench.c /^static const struct option long_options[]=$/;" v typeref:struct:option file:
long_options webbench1.c /^static const struct option long_options[]=$/;" v typeref:struct:option file:
long_options webbench2.c /^static const struct option long_options[]=$/;" v typeref:struct:option file:
main webbench.c /^int main(int argc, char *argv[])$/;" f
main webbench1.c /^int main(int argc, char *argv[])$/;" f
main webbench2.c /^int main(int argc, char *argv[])$/;" f
method webbench.c /^int method=METHOD_GET;$/;" v
method webbench1.c /^int method=METHOD_GET;$/;" v
method webbench2.c /^int method=METHOD_GET;$/;" v
mypipe webbench.c /^int mypipe[2];$/;" v
mypipe webbench1.c /^int mypipe[2];$/;" v
mypipe webbench2.c /^int mypipe[2];$/;" v
proxyhost webbench.c /^char *proxyhost=NULL;$/;" v
proxyhost webbench1.c /^char *proxyhost=NULL;$/;" v
proxyhost webbench2.c /^char *proxyhost=NULL;$/;" v
proxyport webbench.c /^int proxyport=80;$/;" v
proxyport webbench1.c /^int proxyport=80;$/;" v
proxyport webbench2.c /^int proxyport=80;$/;" v
request webbench.c /^char request[REQUEST_SIZE];$/;" v
request webbench1.c /^char request[REQUEST_SIZE];$/;" v
request webbench2.c /^char request[REQUEST_SIZE];$/;" v
speed webbench.c /^int speed=0;$/;" v
speed webbench1.c /^int speed=0;$/;" v
speed webbench2.c /^int speed=0;$/;" v
timerexpired webbench.c /^volatile int timerexpired=0;$/;" v
timerexpired webbench1.c /^volatile int timerexpired=0;$/;" v
timerexpired webbench2.c /^volatile int timerexpired=0;$/;" v
usage webbench.c /^static void usage(void)$/;" f file:
usage webbench1.c /^static void usage(void)$/;" f file:
usage webbench2.c /^static void usage(void)$/;" f file:
================================================
FILE: WebBench/test.sh
================================================
./bin/webbench -t 60 -c 1000 -2 --get http://127.0.0.1:80/hello
================================================
FILE: WebBench/webbench.1
================================================
-.TH WEBBENCH 1 "14 Jan 2004"
-.\" NAME should be all caps, SECTION should be 1-8, maybe w/ subsection
-.\" other parms are allowed: see man(7), man(1)
-.SH NAME
-webbench \- simple forking web benchmark
-.SH SYNOPSIS
-.B webbench
-.I "[options] URL"
-.br
-.SH "AUTHOR"
-This program and manual page was written by Radim Kolar,
-for the
-.B Supreme Personality of Godhead
-(but may be used by others).
-.SH "DESCRIPTION"
-.B webbench
-is simple program for benchmarking HTTP servers or any
-other servers, which can be accessed via HTTP proxy. Unlike others
-benchmarks,
-.B webbench
-uses multiple processes for simulating traffic
-generated by multiple users. This allows better operating
-on SMP systems and on systems with slow or buggy implementation
-of select().
-.SH OPTIONS
-The programs follow the usual GNU command line syntax, with long
-options starting with two dashes (`-').
-A summary of options are included below.
-.TP
-.B \-?, \-h, \-\-help
-Show summary of options.
-.TP
-.B \-v, \-\-version
-Show version of program.
-.TP
-.B \-f, \-\-force
-Do not wait for any response from server. Close connection after
-request is send. This option produce quite a good denial of service
-attack.
-.TP
-.B \-9, \-\-http09
-Use HTTP/0.9 protocol, if possible.
-.TP
-.B \-1, \-\-http10
-Use HTTP/1.0 protocol, if possible.
-.TP
-.B \-2, \-\-http11
-Use HTTP/1.1 protocol (without
-.I Keep-Alive
-), if possible.
-.TP
-.B \-r, \-\-reload
-Forces proxy to reload document. If proxy is not
-set, option has no effect.
-.TP
-.B \-t, \-\-time
-Run benchmark for
-.I
-seconds. Default value is 30.
-.TP
-.B \-p, \-\-proxy
-Send request via proxy server. Needed for supporting others protocols
-than HTTP.
-.TP
-.B \-\-get
-Use GET request method.
-.TP
-.B \-\-head
-Use HEAD request method.
-.TP
-.B \-\-options
-Use OPTIONS request method.
-.TP
-.B \-\-trace
-Use TRACE request method.
-.TP
-.B \-c, \-\-clients
-Use
-.I
-multiple clients for benchmark. Default value
-is 1.
-.SH "EXIT STATUS"
-.TP
-0 - sucess
-.TP
-1 - benchmark failed, can not connect to server
-.TP
-2 - bad command line argument(s)
-.TP
-3 - internal error, i.e. fork failed
-.SH "TODO"
-Include support for using
-.I Keep-Alive
-HTTP/1.1 connections.
-.SH "COPYING"
-Webbench is distributed under GPL. Copyright 1997-2004
-Radim Kolar (hsn@netmag.cz).
-UNIX sockets code taken from popclient 1.5 4/1/94
-public domain code, created by Virginia Tech Computing Center.
-.BR
-This man page is public domain.
================================================
FILE: WebBench/webbench.c
================================================
/*
* (C) Radim Kolar 1997-2004
* This is free software, see GNU Public License version 2 for
* details.
*
* Simple forking WWW Server benchmark:
*
* Usage:
* webbench --help
*
* Return codes:
* 0 - sucess
* 1 - benchmark failed (server is not on-line)
* 2 - bad param
* 3 - internal error, fork failed
*
*/
#include "socket.c"
#include
#include
#include
#include
#include
#include
#include
#include
#include
/* values */
volatile int timerexpired=0;
int speed=0;
int failed=0;
int bytes=0;
/* globals */
int http10=1; /* 0 - http/0.9, 1 - http/1.0, 2 - http/1.1 */
/* Allow: GET, HEAD, OPTIONS, TRACE */
#define METHOD_GET 0
#define METHOD_HEAD 1
#define METHOD_OPTIONS 2
#define METHOD_TRACE 3
#define PROGRAM_VERSION "1.5"
int method=METHOD_GET;
int clients=1;
int force=0;
int force_reload=0;
int proxyport=80;
char *proxyhost=NULL;
int benchtime=30;
bool keep_alive = false;
/* internal */
int mypipe[2];
char host[MAXHOSTNAMELEN];
#define REQUEST_SIZE 2048
char request[REQUEST_SIZE];
static const struct option long_options[]=
{
{"force",no_argument,&force,1},
{"reload",no_argument,&force_reload,1},
{"time",required_argument,NULL,'t'},
{"help",no_argument,NULL,'?'},
{"http09",no_argument,NULL,'9'},
{"http10",no_argument,NULL,'1'},
{"http11",no_argument,NULL,'2'},
{"get",no_argument,&method,METHOD_GET},
{"head",no_argument,&method,METHOD_HEAD},
{"options",no_argument,&method,METHOD_OPTIONS},
{"trace",no_argument,&method,METHOD_TRACE},
{"version",no_argument,NULL,'V'},
{"proxy",required_argument,NULL,'p'},
{"clients",required_argument,NULL,'c'},
{NULL,0,NULL,0}
};
/* prototypes */
static void benchcore(const char* host,const int port, const char *request);
static int bench(void);
static void build_request(const char *url);
static void alarm_handler(int signal)
{
timerexpired=1;
}
static void usage(void)
{
fprintf(stderr,
"webbench [option]... URL\n"
" -f|--force Don't wait for reply from server.\n"
" -r|--reload Send reload request - Pragma: no-cache.\n"
" -t|--time Run benchmark for seconds. Default 30.\n"
" -p|--proxy Use proxy server for request.\n"
" -c|--clients Run HTTP clients at once. Default one.\n"
" -k|--keep Keep-Alive\n"
" -9|--http09 Use HTTP/0.9 style requests.\n"
" -1|--http10 Use HTTP/1.0 protocol.\n"
" -2|--http11 Use HTTP/1.1 protocol.\n"
" --get Use GET request method.\n"
" --head Use HEAD request method.\n"
" --options Use OPTIONS request method.\n"
" --trace Use TRACE request method.\n"
" -?|-h|--help This information.\n"
" -V|--version Display program version.\n"
);
}
int main(int argc, char *argv[])
{
int opt=0;
int options_index=0;
char *tmp=NULL;
if(argc==1)
{
usage();
return 2;
}
while((opt=getopt_long(argc,argv,"912Vfrt:p:c:?hk",long_options,&options_index))!=EOF )
{
switch(opt)
{
case 0 : break;
case 'f': force=1;break;
case 'r': force_reload=1;break;
case '9': http10=0;break;
case '1': http10=1;break;
case '2': http10=2;break;
case 'V': printf(PROGRAM_VERSION"\n");exit(0);
case 't': benchtime=atoi(optarg);break;
case 'k': keep_alive = true;break;
case 'p':
/* proxy server parsing server:port */
tmp=strrchr(optarg,':');
proxyhost=optarg;
if(tmp==NULL)
{
break;
}
if(tmp==optarg)
{
fprintf(stderr,"Error in option --proxy %s: Missing hostname.\n",optarg);
return 2;
}
if(tmp==optarg+strlen(optarg)-1)
{
fprintf(stderr,"Error in option --proxy %s Port number is missing.\n",optarg);
return 2;
}
*tmp='\0';
proxyport=atoi(tmp+1);break;
case ':':
case 'h':
case '?': usage();return 2;break;
case 'c': clients=atoi(optarg);break;
}
}
if(optind==argc) {
fprintf(stderr,"webbench: Missing URL!\n");
usage();
return 2;
}
if(clients==0) clients=1;
if(benchtime==0) benchtime=30;
/* Copyright */
fprintf(stderr,"Webbench - Simple Web Benchmark "PROGRAM_VERSION"\n"
"Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n"
);
build_request(argv[optind]);
// print request info ,do it in function build_request
/*printf("Benchmarking: ");
switch(method)
{
case METHOD_GET:
default:
printf("GET");break;
case METHOD_OPTIONS:
printf("OPTIONS");break;
case METHOD_HEAD:
printf("HEAD");break;
case METHOD_TRACE:
printf("TRACE");break;
}
printf(" %s",argv[optind]);
switch(http10)
{
case 0: printf(" (using HTTP/0.9)");break;
case 2: printf(" (using HTTP/1.1)");break;
}
printf("\n");
*/
printf("Runing info: ");
if(clients==1)
printf("1 client");
else
printf("%d clients",clients);
printf(", running %d sec", benchtime);
if(force) printf(", early socket close");
if(proxyhost!=NULL) printf(", via proxy server %s:%d",proxyhost,proxyport);
if(force_reload) printf(", forcing reload");
printf(".\n");
return bench();
}
void build_request(const char *url)
{
char tmp[10];
int i;
//bzero(host,MAXHOSTNAMELEN);
//bzero(request,REQUEST_SIZE);
memset(host,0,MAXHOSTNAMELEN);
memset(request,0,REQUEST_SIZE);
if(force_reload && proxyhost!=NULL && http10<1) http10=1;
if(method==METHOD_HEAD && http10<1) http10=1;
if(method==METHOD_OPTIONS && http10<2) http10=2;
if(method==METHOD_TRACE && http10<2) http10=2;
switch(method)
{
default:
case METHOD_GET: strcpy(request,"GET");break;
case METHOD_HEAD: strcpy(request,"HEAD");break;
case METHOD_OPTIONS: strcpy(request,"OPTIONS");break;
case METHOD_TRACE: strcpy(request,"TRACE");break;
}
strcat(request," ");
if(NULL==strstr(url,"://"))
{
fprintf(stderr, "\n%s: is not a valid URL.\n",url);
exit(2);
}
if(strlen(url)>1500)
{
fprintf(stderr,"URL is too long.\n");
exit(2);
}
if (0!=strncasecmp("http://",url,7))
{
fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");
exit(2);
}
/* protocol/host delimiter */
i=strstr(url,"://")-url+3;
if(strchr(url+i,'/')==NULL) {
fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");
exit(2);
}
if(proxyhost==NULL)
{
/* get port from hostname */
if(index(url+i,':')!=NULL && index(url+i,':')0)
strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n");
if(proxyhost==NULL && http10>0)
{
strcat(request,"Host: ");
strcat(request,host);
strcat(request,"\r\n");
}
if(force_reload && proxyhost!=NULL)
{
strcat(request,"Pragma: no-cache\r\n");
}
if(http10>1)
{
if (!keep_alive)
strcat(request,"Connection: close\r\n");
else
strcat(request,"Connection: Keep-Alive\r\n");
}
/* add empty line at end */
if(http10>0) strcat(request,"\r\n");
printf("\nRequest:\n%s\n",request);
}
/* vraci system rc error kod */
static int bench(void)
{
int i,j,k;
pid_t pid=0;
FILE *f;
/* check avaibility of target server */
i=Socket(proxyhost==NULL?host:proxyhost,proxyport);
if(i<0) {
fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n");
return 1;
}
close(i);
/* create pipe */
if(pipe(mypipe))
{
perror("pipe failed.");
return 3;
}
/* not needed, since we have alarm() in childrens */
/* wait 4 next system clock tick */
/*
cas=time(NULL);
while(time(NULL)==cas)
sched_yield();
*/
/* fork childs */
for(i=0;i0)
{
/* fprintf(stderr,"Correcting failed by signal\n"); */
failed--;
}
return;
}
if(s<0) { failed++;continue;}
if(rlen!=write(s,req,rlen)) {
failed++;
close(s);
while ((s = Socket(host,port)) == -1);
continue;
}
if(force==0)
{
/* read all available data from socket */
while(1)
{
if(timerexpired) break;
i=read(s,buf,1500);
/* fprintf(stderr,"%d\n",i); */
if(i<0)
{
failed++;
close(s);
//while ((s = Socket(host,port)) == -1);
goto nexttry1;
}
else
if(i==0) break;
else
bytes+=i;
// Supposed reveived bytes were less than 1500
//if (i < 1500)
break;
}
}
speed++;
}
}
else
{
nexttry:while(1)
{
if(timerexpired)
{
if(failed>0)
{
/* fprintf(stderr,"Correcting failed by signal\n"); */
failed--;
}
return;
}
s=Socket(host,port);
if(s<0) { failed++;continue;}
if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;}
if(http10==0)
if(shutdown(s,1)) { failed++;close(s);continue;}
if(force==0)
{
/* read all available data from socket */
while(1)
{
if(timerexpired) break;
i=read(s,buf,1500);
if(i<0)
{
failed++;
close(s);
goto nexttry;
}
else
if(i==0) break;
else
bytes+=i;
}
}
if(close(s)) {failed++; continue;}
speed++;
}
}
}
================================================
FILE: WebServer/CMakeLists.txt
================================================
set(SRCS
Channel.cpp
Epoll.cpp
EventLoop.cpp
EventLoopThread.cpp
EventLoopThreadPool.cpp
HttpData.cpp
Main.cpp
Server.cpp
#ThreadPool.cpp
Timer.cpp
Util.cpp
)
include_directories(${PROJECT_SOURCE_DIR}/base)
add_executable(WebServer ${SRCS})
target_link_libraries(WebServer libserver_base)
add_subdirectory(base)
add_subdirectory(tests)
================================================
FILE: WebServer/Channel.cpp
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "Channel.h"
#include
#include
#include
#include
#include "Epoll.h"
#include "EventLoop.h"
#include "Util.h"
using namespace std;
Channel::Channel(EventLoop *loop)
: loop_(loop), events_(0), lastEvents_(0), fd_(0) {}
Channel::Channel(EventLoop *loop, int fd)
: loop_(loop), fd_(fd), events_(0), lastEvents_(0) {}
Channel::~Channel() {
// loop_->poller_->epoll_del(fd, events_);
// close(fd_);
}
int Channel::getFd() { return fd_; }
void Channel::setFd(int fd) { fd_ = fd; }
void Channel::handleRead() {
if (readHandler_) {
readHandler_();
}
}
void Channel::handleWrite() {
if (writeHandler_) {
writeHandler_();
}
}
void Channel::handleConn() {
if (connHandler_) {
connHandler_();
}
}
================================================
FILE: WebServer/Channel.h
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#pragma once
#include
#include
#include
#include
#include
#include
#include "Timer.h"
class EventLoop;
class HttpData;
class Channel {
private:
typedef std::function CallBack;
EventLoop *loop_;
int fd_;
__uint32_t events_;
__uint32_t revents_;
__uint32_t lastEvents_;
// 方便找到上层持有该Channel的对象
std::weak_ptr holder_;
private:
int parse_URI();
int parse_Headers();
int analysisRequest();
CallBack readHandler_;
CallBack writeHandler_;
CallBack errorHandler_;
CallBack connHandler_;
public:
Channel(EventLoop *loop);
Channel(EventLoop *loop, int fd);
~Channel();
int getFd();
void setFd(int fd);
void setHolder(std::shared_ptr holder) { holder_ = holder; }
std::shared_ptr getHolder() {
std::shared_ptr ret(holder_.lock());
return ret;
}
void setReadHandler(CallBack &&readHandler) { readHandler_ = readHandler; }
void setWriteHandler(CallBack &&writeHandler) {
writeHandler_ = writeHandler;
}
void setErrorHandler(CallBack &&errorHandler) {
errorHandler_ = errorHandler;
}
void setConnHandler(CallBack &&connHandler) { connHandler_ = connHandler; }
void handleEvents() {
events_ = 0;
if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) {
events_ = 0;
return;
}
if (revents_ & EPOLLERR) {
if (errorHandler_) errorHandler_();
events_ = 0;
return;
}
if (revents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) {
handleRead();
}
if (revents_ & EPOLLOUT) {
handleWrite();
}
handleConn();
}
void handleRead();
void handleWrite();
void handleError(int fd, int err_num, std::string short_msg);
void handleConn();
void setRevents(__uint32_t ev) { revents_ = ev; }
void setEvents(__uint32_t ev) { events_ = ev; }
__uint32_t &getEvents() { return events_; }
bool EqualAndUpdateLastEvents() {
bool ret = (lastEvents_ == events_);
lastEvents_ = events_;
return ret;
}
__uint32_t getLastEvents() { return lastEvents_; }
};
typedef std::shared_ptr SP_Channel;
================================================
FILE: WebServer/Epoll.cpp
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "Epoll.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include "Util.h"
#include "base/Logging.h"
#include
#include
using namespace std;
const int EVENTSNUM = 4096;
const int EPOLLWAIT_TIME = 10000;
typedef shared_ptr SP_Channel;
Epoll::Epoll() : epollFd_(epoll_create1(EPOLL_CLOEXEC)), events_(EVENTSNUM) {
assert(epollFd_ > 0);
}
Epoll::~Epoll() {}
// 注册新描述符
void Epoll::epoll_add(SP_Channel request, int timeout) {
int fd = request->getFd();
if (timeout > 0) {
add_timer(request, timeout);
fd2http_[fd] = request->getHolder();
}
struct epoll_event event;
event.data.fd = fd;
event.events = request->getEvents();
request->EqualAndUpdateLastEvents();
fd2chan_[fd] = request;
if (epoll_ctl(epollFd_, EPOLL_CTL_ADD, fd, &event) < 0) {
perror("epoll_add error");
fd2chan_[fd].reset();
}
}
// 修改描述符状态
void Epoll::epoll_mod(SP_Channel request, int timeout) {
if (timeout > 0) add_timer(request, timeout);
int fd = request->getFd();
if (!request->EqualAndUpdateLastEvents()) {
struct epoll_event event;
event.data.fd = fd;
event.events = request->getEvents();
if (epoll_ctl(epollFd_, EPOLL_CTL_MOD, fd, &event) < 0) {
perror("epoll_mod error");
fd2chan_[fd].reset();
}
}
}
// 从epoll中删除描述符
void Epoll::epoll_del(SP_Channel request) {
int fd = request->getFd();
struct epoll_event event;
event.data.fd = fd;
event.events = request->getLastEvents();
// event.events = 0;
// request->EqualAndUpdateLastEvents()
if (epoll_ctl(epollFd_, EPOLL_CTL_DEL, fd, &event) < 0) {
perror("epoll_del error");
}
fd2chan_[fd].reset();
fd2http_[fd].reset();
}
// 返回活跃事件数
std::vector Epoll::poll() {
while (true) {
int event_count =
epoll_wait(epollFd_, &*events_.begin(), events_.size(), EPOLLWAIT_TIME);
if (event_count < 0) perror("epoll wait error");
std::vector req_data = getEventsRequest(event_count);
if (req_data.size() > 0) return req_data;
}
}
void Epoll::handleExpired() { timerManager_.handleExpiredEvent(); }
// 分发处理函数
std::vector Epoll::getEventsRequest(int events_num) {
std::vector req_data;
for (int i = 0; i < events_num; ++i) {
// 获取有事件产生的描述符
int fd = events_[i].data.fd;
SP_Channel cur_req = fd2chan_[fd];
if (cur_req) {
cur_req->setRevents(events_[i].events);
cur_req->setEvents(0);
// 加入线程池之前将Timer和request分离
// cur_req->seperateTimer();
req_data.push_back(cur_req);
} else {
LOG << "SP cur_req is invalid";
}
}
return req_data;
}
void Epoll::add_timer(SP_Channel request_data, int timeout) {
shared_ptr t = request_data->getHolder();
if (t)
timerManager_.addTimer(t, timeout);
else
LOG << "timer add fail";
}
================================================
FILE: WebServer/Epoll.h
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#pragma once
#include
#include
#include
#include
#include "Channel.h"
#include "HttpData.h"
#include "Timer.h"
class Epoll {
public:
Epoll();
~Epoll();
void epoll_add(SP_Channel request, int timeout);
void epoll_mod(SP_Channel request, int timeout);
void epoll_del(SP_Channel request);
std::vector> poll();
std::vector> getEventsRequest(int events_num);
void add_timer(std::shared_ptr request_data, int timeout);
int getEpollFd() { return epollFd_; }
void handleExpired();
private:
static const int MAXFDS = 100000;
int epollFd_;
std::vector events_;
std::shared_ptr fd2chan_[MAXFDS];
std::shared_ptr fd2http_[MAXFDS];
TimerManager timerManager_;
};
================================================
FILE: WebServer/EventLoop.cpp
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "EventLoop.h"
#include
#include
#include
#include "Util.h"
#include "base/Logging.h"
using namespace std;
__thread EventLoop* t_loopInThisThread = 0;
int createEventfd() {
int evtfd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (evtfd < 0) {
LOG << "Failed in eventfd";
abort();
}
return evtfd;
}
EventLoop::EventLoop()
: looping_(false),
poller_(new Epoll()),
wakeupFd_(createEventfd()),
quit_(false),
eventHandling_(false),
callingPendingFunctors_(false),
threadId_(CurrentThread::tid()),
pwakeupChannel_(new Channel(this, wakeupFd_)) {
if (t_loopInThisThread) {
// LOG << "Another EventLoop " << t_loopInThisThread << " exists in this
// thread " << threadId_;
} else {
t_loopInThisThread = this;
}
// pwakeupChannel_->setEvents(EPOLLIN | EPOLLET | EPOLLONESHOT);
pwakeupChannel_->setEvents(EPOLLIN | EPOLLET);
pwakeupChannel_->setReadHandler(bind(&EventLoop::handleRead, this));
pwakeupChannel_->setConnHandler(bind(&EventLoop::handleConn, this));
poller_->epoll_add(pwakeupChannel_, 0);
}
void EventLoop::handleConn() {
// poller_->epoll_mod(wakeupFd_, pwakeupChannel_, (EPOLLIN | EPOLLET |
// EPOLLONESHOT), 0);
updatePoller(pwakeupChannel_, 0);
}
EventLoop::~EventLoop() {
// wakeupChannel_->disableAll();
// wakeupChannel_->remove();
close(wakeupFd_);
t_loopInThisThread = NULL;
}
void EventLoop::wakeup() {
uint64_t one = 1;
ssize_t n = writen(wakeupFd_, (char*)(&one), sizeof one);
if (n != sizeof one) {
LOG << "EventLoop::wakeup() writes " << n << " bytes instead of 8";
}
}
void EventLoop::handleRead() {
uint64_t one = 1;
ssize_t n = readn(wakeupFd_, &one, sizeof one);
if (n != sizeof one) {
LOG << "EventLoop::handleRead() reads " << n << " bytes instead of 8";
}
// pwakeupChannel_->setEvents(EPOLLIN | EPOLLET | EPOLLONESHOT);
pwakeupChannel_->setEvents(EPOLLIN | EPOLLET);
}
void EventLoop::runInLoop(Functor&& cb) {
if (isInLoopThread())
cb();
else
queueInLoop(std::move(cb));
}
void EventLoop::queueInLoop(Functor&& cb) {
{
MutexLockGuard lock(mutex_);
pendingFunctors_.emplace_back(std::move(cb));
}
if (!isInLoopThread() || callingPendingFunctors_) wakeup();
}
void EventLoop::loop() {
assert(!looping_);
assert(isInLoopThread());
looping_ = true;
quit_ = false;
// LOG_TRACE << "EventLoop " << this << " start looping";
std::vector ret;
while (!quit_) {
// cout << "doing" << endl;
ret.clear();
ret = poller_->poll();
eventHandling_ = true;
for (auto& it : ret) it->handleEvents();
eventHandling_ = false;
doPendingFunctors();
poller_->handleExpired();
}
looping_ = false;
}
void EventLoop::doPendingFunctors() {
std::vector functors;
callingPendingFunctors_ = true;
{
MutexLockGuard lock(mutex_);
functors.swap(pendingFunctors_);
}
for (size_t i = 0; i < functors.size(); ++i) functors[i]();
callingPendingFunctors_ = false;
}
void EventLoop::quit() {
quit_ = true;
if (!isInLoopThread()) {
wakeup();
}
}
================================================
FILE: WebServer/EventLoop.h
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#pragma once
#include
#include
#include
#include "Channel.h"
#include "Epoll.h"
#include "Util.h"
#include "base/CurrentThread.h"
#include "base/Logging.h"
#include "base/Thread.h"
#include
using namespace std;
class EventLoop {
public:
typedef std::function Functor;
EventLoop();
~EventLoop();
void loop();
void quit();
void runInLoop(Functor&& cb);
void queueInLoop(Functor&& cb);
bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); }
void assertInLoopThread() { assert(isInLoopThread()); }
void shutdown(shared_ptr channel) { shutDownWR(channel->getFd()); }
void removeFromPoller(shared_ptr channel) {
// shutDownWR(channel->getFd());
poller_->epoll_del(channel);
}
void updatePoller(shared_ptr channel, int timeout = 0) {
poller_->epoll_mod(channel, timeout);
}
void addToPoller(shared_ptr channel, int timeout = 0) {
poller_->epoll_add(channel, timeout);
}
private:
// 声明顺序 wakeupFd_ > pwakeupChannel_
bool looping_;
shared_ptr poller_;
int wakeupFd_;
bool quit_;
bool eventHandling_;
mutable MutexLock mutex_;
std::vector pendingFunctors_;
bool callingPendingFunctors_;
const pid_t threadId_;
shared_ptr pwakeupChannel_;
void wakeup();
void handleRead();
void doPendingFunctors();
void handleConn();
};
================================================
FILE: WebServer/EventLoopThread.cpp
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "EventLoopThread.h"
#include
EventLoopThread::EventLoopThread()
: loop_(NULL),
exiting_(false),
thread_(bind(&EventLoopThread::threadFunc, this), "EventLoopThread"),
mutex_(),
cond_(mutex_) {}
EventLoopThread::~EventLoopThread() {
exiting_ = true;
if (loop_ != NULL) {
loop_->quit();
thread_.join();
}
}
EventLoop* EventLoopThread::startLoop() {
assert(!thread_.started());
thread_.start();
{
MutexLockGuard lock(mutex_);
// 一直等到threadFun在Thread里真正跑起来
while (loop_ == NULL) cond_.wait();
}
return loop_;
}
void EventLoopThread::threadFunc() {
EventLoop loop;
{
MutexLockGuard lock(mutex_);
loop_ = &loop;
cond_.notify();
}
loop.loop();
// assert(exiting_);
loop_ = NULL;
}
================================================
FILE: WebServer/EventLoopThread.h
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#pragma once
#include "EventLoop.h"
#include "base/Condition.h"
#include "base/MutexLock.h"
#include "base/Thread.h"
#include "base/noncopyable.h"
class EventLoopThread : noncopyable {
public:
EventLoopThread();
~EventLoopThread();
EventLoop* startLoop();
private:
void threadFunc();
EventLoop* loop_;
bool exiting_;
Thread thread_;
MutexLock mutex_;
Condition cond_;
};
================================================
FILE: WebServer/EventLoopThreadPool.cpp
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "EventLoopThreadPool.h"
EventLoopThreadPool::EventLoopThreadPool(EventLoop *baseLoop, int numThreads)
: baseLoop_(baseLoop), started_(false), numThreads_(numThreads), next_(0) {
if (numThreads_ <= 0) {
LOG << "numThreads_ <= 0";
abort();
}
}
void EventLoopThreadPool::start() {
baseLoop_->assertInLoopThread();
started_ = true;
for (int i = 0; i < numThreads_; ++i) {
std::shared_ptr t(new EventLoopThread());
threads_.push_back(t);
loops_.push_back(t->startLoop());
}
}
EventLoop *EventLoopThreadPool::getNextLoop() {
baseLoop_->assertInLoopThread();
assert(started_);
EventLoop *loop = baseLoop_;
if (!loops_.empty()) {
loop = loops_[next_];
next_ = (next_ + 1) % numThreads_;
}
return loop;
}
================================================
FILE: WebServer/EventLoopThreadPool.h
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#pragma once
#include
#include
#include "EventLoopThread.h"
#include "base/Logging.h"
#include "base/noncopyable.h"
class EventLoopThreadPool : noncopyable {
public:
EventLoopThreadPool(EventLoop* baseLoop, int numThreads);
~EventLoopThreadPool() { LOG << "~EventLoopThreadPool()"; }
void start();
EventLoop* getNextLoop();
private:
EventLoop* baseLoop_;
bool started_;
int numThreads_;
int next_;
std::vector> threads_;
std::vector loops_;
};
================================================
FILE: WebServer/HttpData.cpp
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#include "HttpData.h"
#include
#include
#include
#include
#include "Channel.h"
#include "EventLoop.h"
#include "Util.h"
#include "time.h"
using namespace std;
pthread_once_t MimeType::once_control = PTHREAD_ONCE_INIT;
std::unordered_map MimeType::mime;
const __uint32_t DEFAULT_EVENT = EPOLLIN | EPOLLET | EPOLLONESHOT;
const int DEFAULT_EXPIRED_TIME = 2000; // ms
const int DEFAULT_KEEP_ALIVE_TIME = 5 * 60 * 1000; // ms
char favicon[555] = {
'\x89', 'P', 'N', 'G', '\xD', '\xA', '\x1A', '\xA', '\x0',
'\x0', '\x0', '\xD', 'I', 'H', 'D', 'R', '\x0', '\x0',
'\x0', '\x10', '\x0', '\x0', '\x0', '\x10', '\x8', '\x6', '\x0',
'\x0', '\x0', '\x1F', '\xF3', '\xFF', 'a', '\x0', '\x0', '\x0',
'\x19', 't', 'E', 'X', 't', 'S', 'o', 'f', 't',
'w', 'a', 'r', 'e', '\x0', 'A', 'd', 'o', 'b',
'e', '\x20', 'I', 'm', 'a', 'g', 'e', 'R', 'e',
'a', 'd', 'y', 'q', '\xC9', 'e', '\x3C', '\x0', '\x0',
'\x1', '\xCD', 'I', 'D', 'A', 'T', 'x', '\xDA', '\x94',
'\x93', '9', 'H', '\x3', 'A', '\x14', '\x86', '\xFF', '\x5D',
'b', '\xA7', '\x4', 'R', '\xC4', 'm', '\x22', '\x1E', '\xA0',
'F', '\x24', '\x8', '\x16', '\x16', 'v', '\xA', '6', '\xBA',
'J', '\x9A', '\x80', '\x8', 'A', '\xB4', 'q', '\x85', 'X',
'\x89', 'G', '\xB0', 'I', '\xA9', 'Q', '\x24', '\xCD', '\xA6',
'\x8', '\xA4', 'H', 'c', '\x91', 'B', '\xB', '\xAF', 'V',
'\xC1', 'F', '\xB4', '\x15', '\xCF', '\x22', 'X', '\x98', '\xB',
'T', 'H', '\x8A', 'd', '\x93', '\x8D', '\xFB', 'F', 'g',
'\xC9', '\x1A', '\x14', '\x7D', '\xF0', 'f', 'v', 'f', '\xDF',
'\x7C', '\xEF', '\xE7', 'g', 'F', '\xA8', '\xD5', 'j', 'H',
'\x24', '\x12', '\x2A', '\x0', '\x5', '\xBF', 'G', '\xD4', '\xEF',
'\xF7', '\x2F', '6', '\xEC', '\x12', '\x20', '\x1E', '\x8F', '\xD7',
'\xAA', '\xD5', '\xEA', '\xAF', 'I', '5', 'F', '\xAA', 'T',
'\x5F', '\x9F', '\x22', 'A', '\x2A', '\x95', '\xA', '\x83', '\xE5',
'r', '9', 'd', '\xB3', 'Y', '\x96', '\x99', 'L', '\x6',
'\xE9', 't', '\x9A', '\x25', '\x85', '\x2C', '\xCB', 'T', '\xA7',
'\xC4', 'b', '1', '\xB5', '\x5E', '\x0', '\x3', 'h', '\x9A',
'\xC6', '\x16', '\x82', '\x20', 'X', 'R', '\x14', 'E', '6',
'S', '\x94', '\xCB', 'e', 'x', '\xBD', '\x5E', '\xAA', 'U',
'T', '\x23', 'L', '\xC0', '\xE0', '\xE2', '\xC1', '\x8F', '\x0',
'\x9E', '\xBC', '\x9', 'A', '\x7C', '\x3E', '\x1F', '\x83', 'D',
'\x22', '\x11', '\xD5', 'T', '\x40', '\x3F', '8', '\x80', 'w',
'\xE5', '3', '\x7', '\xB8', '\x5C', '\x2E', 'H', '\x92', '\x4',
'\x87', '\xC3', '\x81', '\x40', '\x20', '\x40', 'g', '\x98', '\xE9',
'6', '\x1A', '\xA6', 'g', '\x15', '\x4', '\xE3', '\xD7', '\xC8',
'\xBD', '\x15', '\xE1', 'i', '\xB7', 'C', '\xAB', '\xEA', 'x',
'\x2F', 'j', 'X', '\x92', '\xBB', '\x18', '\x20', '\x9F', '\xCF',
'3', '\xC3', '\xB8', '\xE9', 'N', '\xA7', '\xD3', 'l', 'J',
'\x0', 'i', '6', '\x7C', '\x8E', '\xE1', '\xFE', 'V', '\x84',
'\xE7', '\x3C', '\x9F', 'r', '\x2B', '\x3A', 'B', '\x7B', '7',
'f', 'w', '\xAE', '\x8E', '\xE', '\xF3', '\xBD', 'R', '\xA9',
'd', '\x2', 'B', '\xAF', '\x85', '2', 'f', 'F', '\xBA',
'\xC', '\xD9', '\x9F', '\x1D', '\x9A', 'l', '\x22', '\xE6', '\xC7',
'\x3A', '\x2C', '\x80', '\xEF', '\xC1', '\x15', '\x90', '\x7', '\x93',
'\xA2', '\x28', '\xA0', 'S', 'j', '\xB1', '\xB8', '\xDF', '\x29',
'5', 'C', '\xE', '\x3F', 'X', '\xFC', '\x98', '\xDA', 'y',
'j', 'P', '\x40', '\x0', '\x87', '\xAE', '\x1B', '\x17', 'B',
'\xB4', '\x3A', '\x3F', '\xBE', 'y', '\xC7', '\xA', '\x26', '\xB6',
'\xEE', '\xD9', '\x9A', '\x60', '\x14', '\x93', '\xDB', '\x8F', '\xD',
'\xA', '\x2E', '\xE9', '\x23', '\x95', '\x29', 'X', '\x0', '\x27',
'\xEB', 'n', 'V', 'p', '\xBC', '\xD6', '\xCB', '\xD6', 'G',
'\xAB', '\x3D', 'l', '\x7D', '\xB8', '\xD2', '\xDD', '\xA0', '\x60',
'\x83', '\xBA', '\xEF', '\x5F', '\xA4', '\xEA', '\xCC', '\x2', 'N',
'\xAE', '\x5E', 'p', '\x1A', '\xEC', '\xB3', '\x40', '9', '\xAC',
'\xFE', '\xF2', '\x91', '\x89', 'g', '\x91', '\x85', '\x21', '\xA8',
'\x87', '\xB7', 'X', '\x7E', '\x7E', '\x85', '\xBB', '\xCD', 'N',
'N', 'b', 't', '\x40', '\xFA', '\x93', '\x89', '\xEC', '\x1E',
'\xEC', '\x86', '\x2', 'H', '\x26', '\x93', '\xD0', 'u', '\x1D',
'\x7F', '\x9', '2', '\x95', '\xBF', '\x1F', '\xDB', '\xD7', 'c',
'\x8A', '\x1A', '\xF7', '\x5C', '\xC1', '\xFF', '\x22', 'J', '\xC3',
'\x87', '\x0', '\x3', '\x0', 'K', '\xBB', '\xF8', '\xD6', '\x2A',
'v', '\x98', 'I', '\x0', '\x0', '\x0', '\x0', 'I', 'E',
'N', 'D', '\xAE', 'B', '\x60', '\x82',
};
void MimeType::init() {
mime[".html"] = "text/html";
mime[".avi"] = "video/x-msvideo";
mime[".bmp"] = "image/bmp";
mime[".c"] = "text/plain";
mime[".doc"] = "application/msword";
mime[".gif"] = "image/gif";
mime[".gz"] = "application/x-gzip";
mime[".htm"] = "text/html";
mime[".ico"] = "image/x-icon";
mime[".jpg"] = "image/jpeg";
mime[".png"] = "image/png";
mime[".txt"] = "text/plain";
mime[".mp3"] = "audio/mp3";
mime["default"] = "text/html";
}
std::string MimeType::getMime(const std::string &suffix) {
pthread_once(&once_control, MimeType::init);
if (mime.find(suffix) == mime.end())
return mime["default"];
else
return mime[suffix];
}
HttpData::HttpData(EventLoop *loop, int connfd)
: loop_(loop),
channel_(new Channel(loop, connfd)),
fd_(connfd),
error_(false),
connectionState_(H_CONNECTED),
method_(METHOD_GET),
HTTPVersion_(HTTP_11),
nowReadPos_(0),
state_(STATE_PARSE_URI),
hState_(H_START),
keepAlive_(false) {
// loop_->queueInLoop(bind(&HttpData::setHandlers, this));
channel_->setReadHandler(bind(&HttpData::handleRead, this));
channel_->setWriteHandler(bind(&HttpData::handleWrite, this));
channel_->setConnHandler(bind(&HttpData::handleConn, this));
}
void HttpData::reset() {
// inBuffer_.clear();
fileName_.clear();
path_.clear();
nowReadPos_ = 0;
state_ = STATE_PARSE_URI;
hState_ = H_START;
headers_.clear();
// keepAlive_ = false;
if (timer_.lock()) {
shared_ptr my_timer(timer_.lock());
my_timer->clearReq();
timer_.reset();
}
}
void HttpData::seperateTimer() {
// cout << "seperateTimer" << endl;
if (timer_.lock()) {
shared_ptr my_timer(timer_.lock());
my_timer->clearReq();
timer_.reset();
}
}
void HttpData::handleRead() {
__uint32_t &events_ = channel_->getEvents();
do {
bool zero = false;
int read_num = readn(fd_, inBuffer_, zero);
LOG << "Request: " << inBuffer_;
if (connectionState_ == H_DISCONNECTING) {
inBuffer_.clear();
break;
}
// cout << inBuffer_ << endl;
if (read_num < 0) {
perror("1");
error_ = true;
handleError(fd_, 400, "Bad Request");
break;
}
// else if (read_num == 0)
// {
// error_ = true;
// break;
// }
else if (zero) {
// 有请求出现但是读不到数据,可能是Request
// Aborted,或者来自网络的数据没有达到等原因
// 最可能是对端已经关闭了,统一按照对端已经关闭处理
// error_ = true;
connectionState_ = H_DISCONNECTING;
if (read_num == 0) {
// error_ = true;
break;
}
// cout << "readnum == 0" << endl;
}
if (state_ == STATE_PARSE_URI) {
URIState flag = this->parseURI();
if (flag == PARSE_URI_AGAIN)
break;
else if (flag == PARSE_URI_ERROR) {
perror("2");
LOG << "FD = " << fd_ << "," << inBuffer_ << "******";
inBuffer_.clear();
error_ = true;
handleError(fd_, 400, "Bad Request");
break;
} else
state_ = STATE_PARSE_HEADERS;
}
if (state_ == STATE_PARSE_HEADERS) {
HeaderState flag = this->parseHeaders();
if (flag == PARSE_HEADER_AGAIN)
break;
else if (flag == PARSE_HEADER_ERROR) {
perror("3");
error_ = true;
handleError(fd_, 400, "Bad Request");
break;
}
if (method_ == METHOD_POST) {
// POST方法准备
state_ = STATE_RECV_BODY;
} else {
state_ = STATE_ANALYSIS;
}
}
if (state_ == STATE_RECV_BODY) {
int content_length = -1;
if (headers_.find("Content-length") != headers_.end()) {
content_length = stoi(headers_["Content-length"]);
} else {
// cout << "(state_ == STATE_RECV_BODY)" << endl;
error_ = true;
handleError(fd_, 400, "Bad Request: Lack of argument (Content-length)");
break;
}
if (static_cast(inBuffer_.size()) < content_length) break;
state_ = STATE_ANALYSIS;
}
if (state_ == STATE_ANALYSIS) {
AnalysisState flag = this->analysisRequest();
if (flag == ANALYSIS_SUCCESS) {
state_ = STATE_FINISH;
break;
} else {
// cout << "state_ == STATE_ANALYSIS" << endl;
error_ = true;
break;
}
}
} while (false);
// cout << "state_=" << state_ << endl;
if (!error_) {
if (outBuffer_.size() > 0) {
handleWrite();
// events_ |= EPOLLOUT;
}
// error_ may change
if (!error_ && state_ == STATE_FINISH) {
this->reset();
if (inBuffer_.size() > 0) {
if (connectionState_ != H_DISCONNECTING) handleRead();
}
// if ((keepAlive_ || inBuffer_.size() > 0) && connectionState_ ==
// H_CONNECTED)
// {
// this->reset();
// events_ |= EPOLLIN;
// }
} else if (!error_ && connectionState_ != H_DISCONNECTED)
events_ |= EPOLLIN;
}
}
void HttpData::handleWrite() {
if (!error_ && connectionState_ != H_DISCONNECTED) {
__uint32_t &events_ = channel_->getEvents();
if (writen(fd_, outBuffer_) < 0) {
perror("writen");
events_ = 0;
error_ = true;
}
if (outBuffer_.size() > 0) events_ |= EPOLLOUT;
}
}
void HttpData::handleConn() {
seperateTimer();
__uint32_t &events_ = channel_->getEvents();
if (!error_ && connectionState_ == H_CONNECTED) {
if (events_ != 0) {
int timeout = DEFAULT_EXPIRED_TIME;
if (keepAlive_) timeout = DEFAULT_KEEP_ALIVE_TIME;
if ((events_ & EPOLLIN) && (events_ & EPOLLOUT)) {
events_ = __uint32_t(0);
events_ |= EPOLLOUT;
}
// events_ |= (EPOLLET | EPOLLONESHOT);
events_ |= EPOLLET;
loop_->updatePoller(channel_, timeout);
} else if (keepAlive_) {
events_ |= (EPOLLIN | EPOLLET);
// events_ |= (EPOLLIN | EPOLLET | EPOLLONESHOT);
int timeout = DEFAULT_KEEP_ALIVE_TIME;
loop_->updatePoller(channel_, timeout);
} else {
// cout << "close normally" << endl;
// loop_->shutdown(channel_);
// loop_->runInLoop(bind(&HttpData::handleClose, shared_from_this()));
events_ |= (EPOLLIN | EPOLLET);
// events_ |= (EPOLLIN | EPOLLET | EPOLLONESHOT);
int timeout = (DEFAULT_KEEP_ALIVE_TIME >> 1);
loop_->updatePoller(channel_, timeout);
}
} else if (!error_ && connectionState_ == H_DISCONNECTING &&
(events_ & EPOLLOUT)) {
events_ = (EPOLLOUT | EPOLLET);
} else {
// cout << "close with errors" << endl;
loop_->runInLoop(bind(&HttpData::handleClose, shared_from_this()));
}
}
URIState HttpData::parseURI() {
string &str = inBuffer_;
string cop = str;
// 读到完整的请求行再开始解析请求
size_t pos = str.find('\r', nowReadPos_);
if (pos < 0) {
return PARSE_URI_AGAIN;
}
// 去掉请求行所占的空间,节省空间
string request_line = str.substr(0, pos);
if (str.size() > pos + 1)
str = str.substr(pos + 1);
else
str.clear();
// Method
int posGet = request_line.find("GET");
int posPost = request_line.find("POST");
int posHead = request_line.find("HEAD");
if (posGet >= 0) {
pos = posGet;
method_ = METHOD_GET;
} else if (posPost >= 0) {
pos = posPost;
method_ = METHOD_POST;
} else if (posHead >= 0) {
pos = posHead;
method_ = METHOD_HEAD;
} else {
return PARSE_URI_ERROR;
}
// filename
pos = request_line.find("/", pos);
if (pos < 0) {
fileName_ = "index.html";
HTTPVersion_ = HTTP_11;
return PARSE_URI_SUCCESS;
} else {
size_t _pos = request_line.find(' ', pos);
if (_pos < 0)
return PARSE_URI_ERROR;
else {
if (_pos - pos > 1) {
fileName_ = request_line.substr(pos + 1, _pos - pos - 1);
size_t __pos = fileName_.find('?');
if (__pos >= 0) {
fileName_ = fileName_.substr(0, __pos);
}
}
else
fileName_ = "index.html";
}
pos = _pos;
}
// cout << "fileName_: " << fileName_ << endl;
// HTTP 版本号
pos = request_line.find("/", pos);
if (pos < 0)
return PARSE_URI_ERROR;
else {
if (request_line.size() - pos <= 3)
return PARSE_URI_ERROR;
else {
string ver = request_line.substr(pos + 1, 3);
if (ver == "1.0")
HTTPVersion_ = HTTP_10;
else if (ver == "1.1")
HTTPVersion_ = HTTP_11;
else
return PARSE_URI_ERROR;
}
}
return PARSE_URI_SUCCESS;
}
HeaderState HttpData::parseHeaders() {
string &str = inBuffer_;
int key_start = -1, key_end = -1, value_start = -1, value_end = -1;
int now_read_line_begin = 0;
bool notFinish = true;
size_t i = 0;
for (; i < str.size() && notFinish; ++i) {
switch (hState_) {
case H_START: {
if (str[i] == '\n' || str[i] == '\r') break;
hState_ = H_KEY;
key_start = i;
now_read_line_begin = i;
break;
}
case H_KEY: {
if (str[i] == ':') {
key_end = i;
if (key_end - key_start <= 0) return PARSE_HEADER_ERROR;
hState_ = H_COLON;
} else if (str[i] == '\n' || str[i] == '\r')
return PARSE_HEADER_ERROR;
break;
}
case H_COLON: {
if (str[i] == ' ') {
hState_ = H_SPACES_AFTER_COLON;
} else
return PARSE_HEADER_ERROR;
break;
}
case H_SPACES_AFTER_COLON: {
hState_ = H_VALUE;
value_start = i;
break;
}
case H_VALUE: {
if (str[i] == '\r') {
hState_ = H_CR;
value_end = i;
if (value_end - value_start <= 0) return PARSE_HEADER_ERROR;
} else if (i - value_start > 255)
return PARSE_HEADER_ERROR;
break;
}
case H_CR: {
if (str[i] == '\n') {
hState_ = H_LF;
string key(str.begin() + key_start, str.begin() + key_end);
string value(str.begin() + value_start, str.begin() + value_end);
headers_[key] = value;
now_read_line_begin = i;
} else
return PARSE_HEADER_ERROR;
break;
}
case H_LF: {
if (str[i] == '\r') {
hState_ = H_END_CR;
} else {
key_start = i;
hState_ = H_KEY;
}
break;
}
case H_END_CR: {
if (str[i] == '\n') {
hState_ = H_END_LF;
} else
return PARSE_HEADER_ERROR;
break;
}
case H_END_LF: {
notFinish = false;
key_start = i;
now_read_line_begin = i;
break;
}
}
}
if (hState_ == H_END_LF) {
str = str.substr(i);
return PARSE_HEADER_SUCCESS;
}
str = str.substr(now_read_line_begin);
return PARSE_HEADER_AGAIN;
}
AnalysisState HttpData::analysisRequest() {
if (method_ == METHOD_POST) {
// ------------------------------------------------------
// My CV stitching handler which requires OpenCV library
// ------------------------------------------------------
// string header;
// header += string("HTTP/1.1 200 OK\r\n");
// if(headers_.find("Connection") != headers_.end() &&
// headers_["Connection"] == "Keep-Alive")
// {
// keepAlive_ = true;
// header += string("Connection: Keep-Alive\r\n") + "Keep-Alive:
// timeout=" + to_string(DEFAULT_KEEP_ALIVE_TIME) + "\r\n";
// }
// int length = stoi(headers_["Content-length"]);
// vector data(inBuffer_.begin(), inBuffer_.begin() + length);
// Mat src = imdecode(data, CV_LOAD_IMAGE_ANYDEPTH|CV_LOAD_IMAGE_ANYCOLOR);
// //imwrite("receive.bmp", src);
// Mat res = stitch(src);
// vector data_encode;
// imencode(".png", res, data_encode);
// header += string("Content-length: ") + to_string(data_encode.size()) +
// "\r\n\r\n";
// outBuffer_ += header + string(data_encode.begin(), data_encode.end());
// inBuffer_ = inBuffer_.substr(length);
// return ANALYSIS_SUCCESS;
} else if (method_ == METHOD_GET || method_ == METHOD_HEAD) {
string header;
header += "HTTP/1.1 200 OK\r\n";
if (headers_.find("Connection") != headers_.end() &&
(headers_["Connection"] == "Keep-Alive" ||
headers_["Connection"] == "keep-alive")) {
keepAlive_ = true;
header += string("Connection: Keep-Alive\r\n") + "Keep-Alive: timeout=" +
to_string(DEFAULT_KEEP_ALIVE_TIME) + "\r\n";
}
int dot_pos = fileName_.find('.');
string filetype;
if (dot_pos < 0)
filetype = MimeType::getMime("default");
else
filetype = MimeType::getMime(fileName_.substr(dot_pos));
// echo test
if (fileName_ == "hello") {
outBuffer_ =
"HTTP/1.1 200 OK\r\nContent-type: text/plain\r\n\r\nHello World";
return ANALYSIS_SUCCESS;
}
if (fileName_ == "favicon.ico") {
header += "Content-Type: image/png\r\n";
header += "Content-Length: " + to_string(sizeof favicon) + "\r\n";
header += "Server: LinYa's Web Server\r\n";
header += "\r\n";
outBuffer_ += header;
outBuffer_ += string(favicon, favicon + sizeof favicon);
;
return ANALYSIS_SUCCESS;
}
struct stat sbuf;
if (stat(fileName_.c_str(), &sbuf) < 0) {
header.clear();
handleError(fd_, 404, "Not Found!");
return ANALYSIS_ERROR;
}
header += "Content-Type: " + filetype + "\r\n";
header += "Content-Length: " + to_string(sbuf.st_size) + "\r\n";
header += "Server: LinYa's Web Server\r\n";
// 头部结束
header += "\r\n";
outBuffer_ += header;
if (method_ == METHOD_HEAD) return ANALYSIS_SUCCESS;
int src_fd = open(fileName_.c_str(), O_RDONLY, 0);
if (src_fd < 0) {
outBuffer_.clear();
handleError(fd_, 404, "Not Found!");
return ANALYSIS_ERROR;
}
void *mmapRet = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, src_fd, 0);
close(src_fd);
if (mmapRet == (void *)-1) {
munmap(mmapRet, sbuf.st_size);
outBuffer_.clear();
handleError(fd_, 404, "Not Found!");
return ANALYSIS_ERROR;
}
char *src_addr = static_cast(mmapRet);
outBuffer_ += string(src_addr, src_addr + sbuf.st_size);
;
munmap(mmapRet, sbuf.st_size);
return ANALYSIS_SUCCESS;
}
return ANALYSIS_ERROR;
}
void HttpData::handleError(int fd, int err_num, string short_msg) {
short_msg = " " + short_msg;
char send_buff[4096];
string body_buff, header_buff;
body_buff += "哎~出错了";
body_buff += "";
body_buff += to_string(err_num) + short_msg;
body_buff += "
LinYa's Web Server\n";
header_buff += "HTTP/1.1 " + to_string(err_num) + short_msg + "\r\n";
header_buff += "Content-Type: text/html\r\n";
header_buff += "Connection: Close\r\n";
header_buff += "Content-Length: " + to_string(body_buff.size()) + "\r\n";
header_buff += "Server: LinYa's Web Server\r\n";
;
header_buff += "\r\n";
// 错误处理不考虑writen不完的情况
sprintf(send_buff, "%s", header_buff.c_str());
writen(fd, send_buff, strlen(send_buff));
sprintf(send_buff, "%s", body_buff.c_str());
writen(fd, send_buff, strlen(send_buff));
}
void HttpData::handleClose() {
connectionState_ = H_DISCONNECTED;
shared_ptr guard(shared_from_this());
loop_->removeFromPoller(channel_);
}
void HttpData::newEvent() {
channel_->setEvents(DEFAULT_EVENT);
loop_->addToPoller(channel_, DEFAULT_EXPIRED_TIME);
}
================================================
FILE: WebServer/HttpData.h
================================================
// @Author Lin Ya
// @Email xxbbb@vip.qq.com
#pragma once
#include
#include
#include
#include